@lmctl-ai/lmctl 0.2.15 → 0.2.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +32 -31
- package/dist/cli/script.js +37 -36
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -798,16 +798,16 @@ var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDe
|
|
|
798
798
|
`);if(e[0]!=="---")throw new st("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 st(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!bw.has(c))throw new st(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Os.join(", ")}`);r[c]=d}if(n===-1)throw new st("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Os)if(r[o]===void 0)throw new st(`missing required frontmatter key "${o}" \u2014 required: ${Os.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 Os,bw,st,Ru=k(()=>{"use strict";Os=["title","description","members"],bw=new Set(Os),st=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as Iw,writeFileSync as j0,renameSync as B0,existsSync as Lu}from"node:fs";import{basename as xw,resolve as Cr,dirname as ea}from"node:path";function Aw(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 Rw(t){return/^\s*_MEMBER_\s+\S/.test(t)}function Nw(t){return/^\s*_SESSION_\s+\S/.test(t)}function Lw(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function ra(t){let e=xw(t);return e.endsWith(".lmctl")?e.slice(0,-6):e}function Ae(t){let e=Iw(t,"utf-8"),r=ea(Cr(t)),n=na(e,ra(t),{baseDir:r,sourcePath:Cr(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Cr(r,s.sessiondir));return n}function na(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
799
799
|
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=Au(i)}catch(l){if(l instanceof st)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
800
800
|
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(Nw(c))throw new Error(`line ${d}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(Lw(c)||!Rw(c))continue;let u=Aw(c);for(let p of Object.keys(u))if(!Nu.includes(p))throw new Error(`line ${d}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
801
|
-
allowed keys: ${Nu.join(", ")}`);if(!u.provider&&!u.teamfile){s.push(`line ${d}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!u.alias){s.push(`line ${d}: member line missing required alias: ${c.trim()}`);continue}let m={alias:u.alias,provider:u.provider||"",extra:{}};u.sessionid&&(m.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(m.sessiondir=u.sessiondir),u.teamfile&&(m.teamfile=u.teamfile),u.model&&(m.model=u.model),u.effort&&(m.effort=u.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function sa(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()===ta.toLowerCase());n.length>1&&r.push({field:ta,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?Cr(e,i.teamfile):Cr(i.teamfile);if(!Lu(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ae(a),c=Ot(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 kw.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 Ot(t){return t.members.find(e=>e.alias.toLowerCase()===ta.toLowerCase())}function ia(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=Cr(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),!Lu(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Ae(i),l=Ot(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return ia(l,ea(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||ea(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function Ds(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var ta,kw,Nu,Et=k(()=>{"use strict";Ru();ta="Lead",kw=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"]);Nu=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as Cw}from"node:crypto";import{existsSync as Cu,readFileSync as Ou,realpathSync as Ow}from"node:fs";import{dirname as Dw,resolve as Du}from"node:path";function ge(t,e){let r=Du(t);if(Cu(r))return Ow(r);if(e!==void 0){let n=$w(t,r,e);if(n!==null)return n}return r}function $s(t,e){let r=Dw(e),n=na(t,ra(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Du(r,s.sessiondir));return n}function
|
|
802
|
-
`)}){let n=ge(t,Mw(e)?e:void 0);if(Cu(n)){let i=Ou(n,"utf8"),o=$s(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&Fw(o)&&Uw(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 Mw(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function $w(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function Fw(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=oa)}function aa(t,e,r){let n=ge(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=oa);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=ge(i.teamfile_path),o===n)continue;a=Ou(o,"utf8")}catch(c){if(Pw(c))continue;throw c}let l=$s(a,o);for(let c of s){let d=l.members.find(u=>u.teamfile===void 0&&u.session===c.session&&(u.session?.length??0)>=oa);if(d!==void 0)throw new Ms(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${d.alias} both use sessionid "${c.session}"`)}}}function Pw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Uw(t,e,r,n,s){try{aa(t,e,r)}catch(o){if(!(o instanceof Ms))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:Cw("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var oa,Ms,Tt=k(()=>{"use strict";Et();oa=5,Ms=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{existsSync as jw}from"node:fs";import{dirname as Mu}from"node:path";function Xw(t){return Bw.test(t)||Ww.test(t)||Hw.test(t)}function $u(t){return Fs.test(t)}function Ps(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!r.endsWith(".lmctl")||!Fs.test(n)?null:{teamfile:r,alias:n}}function fe(t,e,r){if(!t.endsWith(".lmctl"))throw new ie(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl extension).`);if(!$u(e))throw new ie(`lmctl: "${e}" is not a valid alias (must match ${Fs.source}).`);let n=ge(t,r);if(r===void 0&&!jw(n))throw new ie(`lmctl: teamfile not found: ${t}`);let s;try{s=
|
|
801
|
+
allowed keys: ${Nu.join(", ")}`);if(!u.provider&&!u.teamfile){s.push(`line ${d}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!u.alias){s.push(`line ${d}: member line missing required alias: ${c.trim()}`);continue}let m={alias:u.alias,provider:u.provider||"",extra:{}};u.sessionid&&(m.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(m.sessiondir=u.sessiondir),u.teamfile&&(m.teamfile=u.teamfile),u.model&&(m.model=u.model),u.effort&&(m.effort=u.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function sa(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()===ta.toLowerCase());n.length>1&&r.push({field:ta,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?Cr(e,i.teamfile):Cr(i.teamfile);if(!Lu(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ae(a),c=Ot(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 kw.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 Ot(t){return t.members.find(e=>e.alias.toLowerCase()===ta.toLowerCase())}function ia(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=Cr(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),!Lu(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Ae(i),l=Ot(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return ia(l,ea(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||ea(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function Ds(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var ta,kw,Nu,Et=k(()=>{"use strict";Ru();ta="Lead",kw=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"]);Nu=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as Cw}from"node:crypto";import{existsSync as Cu,readFileSync as Ou,realpathSync as Ow}from"node:fs";import{dirname as Dw,resolve as Du}from"node:path";function ge(t,e){let r=Du(t);if(Cu(r))return Ow(r);if(e!==void 0){let n=$w(t,r,e);if(n!==null)return n}return r}function $s(t,e){let r=Dw(e),n=na(t,ra(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Du(r,s.sessiondir));return n}function Xe(t,e,r=n=>{process.stderr.write(`warning: ${n}
|
|
802
|
+
`)}){let n=ge(t,Mw(e)?e:void 0);if(Cu(n)){let i=Ou(n,"utf8"),o=$s(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&Fw(o)&&Uw(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 Mw(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function $w(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function Fw(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=oa)}function aa(t,e,r){let n=ge(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=oa);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=ge(i.teamfile_path),o===n)continue;a=Ou(o,"utf8")}catch(c){if(Pw(c))continue;throw c}let l=$s(a,o);for(let c of s){let d=l.members.find(u=>u.teamfile===void 0&&u.session===c.session&&(u.session?.length??0)>=oa);if(d!==void 0)throw new Ms(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${d.alias} both use sessionid "${c.session}"`)}}}function Pw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Uw(t,e,r,n,s){try{aa(t,e,r)}catch(o){if(!(o instanceof Ms))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:Cw("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var oa,Ms,Tt=k(()=>{"use strict";Et();oa=5,Ms=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{existsSync as jw}from"node:fs";import{dirname as Mu}from"node:path";function Xw(t){return Bw.test(t)||Ww.test(t)||Hw.test(t)}function $u(t){return Fs.test(t)}function Ps(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!r.endsWith(".lmctl")||!Fs.test(n)?null:{teamfile:r,alias:n}}function fe(t,e,r){if(!t.endsWith(".lmctl"))throw new ie(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl extension).`);if(!$u(e))throw new ie(`lmctl: "${e}" is not a valid alias (must match ${Fs.source}).`);let n=ge(t,r);if(r===void 0&&!jw(n))throw new ie(`lmctl: teamfile not found: ${t}`);let s;try{s=Xe(n,r)}catch(o){throw new ie(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new ie(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=Ds(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new ie(`lmctl: alias "${e}" not found in ${t}.
|
|
803
803
|
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=ia(i,Mu(n));return{teamfile:n,alias:i.alias,provider:o.provider,sessionid:o.session,sessiondir:o.sessiondir,isLead:!0,...o.model??i.model?{model:o.model??i.model}:{},...o.effort??i.effort?{effort:o.effort??i.effort}:{}}}if(i.session===void 0)throw new ie(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
804
804
|
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Mu(n),isLead:Ot(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function it(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=Ps(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(r.endsWith(".lmctl"))return n!==void 0?$u(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${Fs.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
805
805
|
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(Xw(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.
|
|
806
806
|
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}".
|
|
807
807
|
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.
|
|
808
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ie,Bw,Ww,Hw,Fs,Ue=k(()=>{"use strict";Et();Tt();ie=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},Bw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ww=/^ses_[A-Za-z0-9_-]+$/,Hw=/^session_[A-Za-z0-9_-]+$/,Fs=/^[A-Za-z][A-Za-z0-9_-]*$/});import{existsSync as qw,mkdirSync as Gw,readFileSync as Jw,renameSync as Vw,unlinkSync as Kw,writeFileSync as Yw}from"node:fs";import{homedir as Pu}from"node:os";import{dirname as _n,join as Re,resolve as zw}from"node:path";function Dr(t,e,r){let n=_n(zw(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())ot(Re(o,".mcp.json"),"mcpServers",[Dt(),Mt()]),a.has("opencode")&&ot(Re(o,".opencode","opencode.json"),"mcp",[Uu(),ju()]),a.has("kimi")&&ot(Re(o,".kimi-code","mcp.json"),"mcpServers",[Dt(),Mt()]);for(let o of s)rv(o)}function Zw(t=la??Pu()){return Re(t,".copilot","mcp-config.json")}function ev(t,e){
|
|
809
|
-
`,"utf8"),
|
|
810
|
-
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Fu(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function sv(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Bu(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=iv(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Us&&c[1]!==js)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=Wu(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=av(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===Us&&Xu(i.command,i.args)&&n.add(s),s===js&&qu(i.command,i.args)&&n.add(s);return n}function iv(t,e){if(t.startsWith("mcp_servers"))return Bs(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Bs(t);return r===null?null:[...e,...r]}function Bu(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Bs(e[1])}function ov(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 Bs(r)}function Bs(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 Wu(t){let e=Hu(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 av(t){let e=Hu(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=>Wu(s.trim()));return n.some(s=>s===null)?null:n}function Hu(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 lv(t){return Or(t)?t.type==="stdio"&&typeof t.command=="string"&&Xu(t.command,t.args):!1}function cv(t){return!Or(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Ju(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"&&Gu(t.command[0],[t.command[1],t.command[2]])}function dv(t){return Or(t)?t.type==="stdio"&&qu(t.command,t.args):!1}function uv(t){return!Or(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Vu(t.command[0])&&t.command[1]==="mcp"}function Xu(t,e){return Ju(t)&&Ku(e)||Gu(t,e)}function qu(t,e){return Vu(t)&&Ku(e)}function Gu(t,e){return mv(t)&&Array.isArray(e)&&e.length===2&&fv(e[0])&&e[1]==="mcp"}function Ju(t){return typeof t=="string"&&ca(t)==="lmctl"}function Vu(t){return typeof t=="string"&&ca(t)==="lmctl0"}function mv(t){if(typeof t!="string")return!1;let e=ca(t).toLowerCase();return e==="node"||e==="node.exe"}function fv(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 ca(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function Ku(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Or(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Us,js,Qw,
|
|
808
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ie,Bw,Ww,Hw,Fs,Ue=k(()=>{"use strict";Et();Tt();ie=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},Bw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ww=/^ses_[A-Za-z0-9_-]+$/,Hw=/^session_[A-Za-z0-9_-]+$/,Fs=/^[A-Za-z][A-Za-z0-9_-]*$/});import{existsSync as qw,mkdirSync as Gw,readFileSync as Jw,renameSync as Vw,unlinkSync as Kw,writeFileSync as Yw}from"node:fs";import{homedir as Pu}from"node:os";import{dirname as _n,join as Re,resolve as zw}from"node:path";function Dr(t,e,r){let n=_n(zw(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())ot(Re(o,".mcp.json"),"mcpServers",[Dt(),Mt()]),a.has("opencode")&&ot(Re(o,".opencode","opencode.json"),"mcp",[Uu(),ju()]),a.has("kimi")&&ot(Re(o,".kimi-code","mcp.json"),"mcpServers",[Dt(),Mt()]);for(let o of s)rv(o)}function Zw(t=la??Pu()){return Re(t,".copilot","mcp-config.json")}function ev(t,e){qe.mkdirSync(_n(t),{recursive:!0});let r=Re(_n(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{qe.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
809
|
+
`,"utf8"),qe.renameSync(r,t)}catch(n){try{qe.unlinkSync(r)}catch{}throw n}}function tv(t,e){qe.mkdirSync(_n(t),{recursive:!0});let r=Re(_n(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{qe.writeFileSync(r,e,"utf8"),qe.renameSync(r,t)}catch(n){try{qe.unlinkSync(r)}catch{}throw n}}function ot(t,e,r){try{if(!qe.existsSync(t))return;let n=JSON.parse(qe.readFileSync(t,"utf8"));if(!Or(n)||!Or(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,ev(t,n),L({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Dt(){return{name:js,shouldRemove:dv}}function Uu(){return{name:js,shouldRemove:uv}}function Mt(){return{name:Us,shouldRemove:lv}}function ju(){return{name:Us,shouldRemove:cv}}function rv(t){let e=la??Pu();switch(t){case"copilot":ot(Zw(e),"mcpServers",[Dt(),Mt()]);return;case"claude":ot(Re(e,".claude.json"),"mcpServers",[Dt(),Mt()]);return;case"gemini":ot(Re(e,".gemini","settings.json"),"mcpServers",[Dt(),Mt()]);return;case"qwen":ot(Re(e,".qwen","settings.json"),"mcpServers",[Dt(),Mt()]);return;case"agy":ot(Re(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Dt(),Mt()]);return;case"opencode":ot(Re(e,".config","opencode","opencode.json"),"mcp",[Uu(),ju()]);return;case"kimi":ot(Re(la===void 0?process.env.KIMI_CODE_HOME??Re(e,".kimi-code"):Re(e,".kimi-code"),"mcp.json"),"mcpServers",[Dt(),Mt()]);return;case"codex":nv(Re(e,".codex","config.toml"));return;default:return}}function nv(t){try{if(!qe.existsSync(t))return;let e=qe.readFileSync(t,"utf8"),r=sv(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=Bu(l);if(c===null)return;if(c!==void 0){if(Fu(c,r)){o=!0,a=c[1],i.add(a);continue}o=!1,a=void 0,s.push(l);continue}if(o){if(/^\s*(?:#.*)?$/.test(l)){s.push(l);continue}a!==void 0&&i.add(a);continue}let d=ov(l);if(d===null)return;if(d!==void 0&&Fu(d,r)){i.add(d[1]);continue}s.push(l)}if(i.size===0)return;tv(t,s.join(`
|
|
810
|
+
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Fu(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function sv(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Bu(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=iv(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Us&&c[1]!==js)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=Wu(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=av(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===Us&&Xu(i.command,i.args)&&n.add(s),s===js&&qu(i.command,i.args)&&n.add(s);return n}function iv(t,e){if(t.startsWith("mcp_servers"))return Bs(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Bs(t);return r===null?null:[...e,...r]}function Bu(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Bs(e[1])}function ov(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 Bs(r)}function Bs(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 Wu(t){let e=Hu(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 av(t){let e=Hu(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=>Wu(s.trim()));return n.some(s=>s===null)?null:n}function Hu(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 lv(t){return Or(t)?t.type==="stdio"&&typeof t.command=="string"&&Xu(t.command,t.args):!1}function cv(t){return!Or(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Ju(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"&&Gu(t.command[0],[t.command[1],t.command[2]])}function dv(t){return Or(t)?t.type==="stdio"&&qu(t.command,t.args):!1}function uv(t){return!Or(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Vu(t.command[0])&&t.command[1]==="mcp"}function Xu(t,e){return Ju(t)&&Ku(e)||Gu(t,e)}function qu(t,e){return Vu(t)&&Ku(e)}function Gu(t,e){return mv(t)&&Array.isArray(e)&&e.length===2&&fv(e[0])&&e[1]==="mcp"}function Ju(t){return typeof t=="string"&&ca(t)==="lmctl"}function Vu(t){return typeof t=="string"&&ca(t)==="lmctl0"}function mv(t){if(typeof t!="string")return!1;let e=ca(t).toLowerCase();return e==="node"||e==="node.exe"}function fv(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 ca(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function Ku(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Or(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Us,js,Qw,qe,la,Ws=k(()=>{"use strict";J();Us="lmctl",js="lmctl0",Qw={existsSync:qw,mkdirSync:Gw,readFileSync:Jw,writeFileSync:Yw,renameSync:Vw,unlinkSync:Kw},qe=Qw});function Qu(t){let e=Yu(t.registry,t.fromTeamfile);if(e===void 0)return Mr(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!zu(e,t.fromAlias))return Mr(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Yu(t.registry,t.toTeamfile);return r===void 0?Mr(`target team is not registered in policy graph: ${t.toTeamfile}`):zu(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Mr(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Mr(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Mr(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Yu(t,e){return t.teams.find(r=>r.teamfile===e)}function zu(t,e){return t.aliases.some(r=>r===e)}function Mr(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var Zu=k(()=>{"use strict"});import{basename as pv}from"node:path";function rm(t,e){let r=new Date(e.now.getTime()-at()).toISOString(),n=im(t,r).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=yv(e.sender,n),i=Ev(e.sender,n);i!==null&&i.teamfile===e.root&&!tm(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>tm(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,_)=>_-p)[0]??null,d=c!==null&&e.now.getTime()-c<hv,u=da(e.sender,n).length;return{stop:l.length>=1&&d&&u>=gv,chain:Tv(a)}}function nm(t,e){let r=new Date(e.now.getTime()-at()).toISOString(),n=im(t,r),s=da(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 at(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return em;let r=Number(e);return!Number.isFinite(r)||r<=0?em:r}function sm(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function _v(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 im(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(_v).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function yv(t,e,r={}){let n=new Map;for(let a of e)n.set(ar(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([ar(t)]);for(let a=0;a<64;a+=1){let l=n.get(ar(i));if(l===void 0)break;s[0]={...s[0],at:s[0].at??l.at};let c={...l.sender,at:l.at};if(l.sender.teamfile.startsWith("prompt:")&&r.includePromptSender!==!0)break;let d=ar(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function da(t,e){let r=ar(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=ar(l.sender),d=ar(l.receiver);c!==a&&d!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(d)||(n.add(d),s.push(d)))}}return i.sort((o,a)=>o.at-a.at)}function Ev(t,e){let r=da(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function tm(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function ar(t){return`${t.teamfile}\0${t.alias}`}function Tv(t){return t.map(e=>`${pv(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var hv,gv,em,yn=k(()=>{"use strict";hv=6e4,gv=2,em=8*60*60*1e3});function om(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(`
|
|
811
811
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
812
812
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
813
813
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
@@ -1023,7 +1023,7 @@ var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDe
|
|
|
1023
1023
|
AND holder_host IS ?
|
|
1024
1024
|
AND started_at = ?
|
|
1025
1025
|
AND last_heartbeat_at IS ?
|
|
1026
|
-
`)}}function
|
|
1026
|
+
`)}}function Ge(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(lm,"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")}${lm}`}var lm,dm=k(()=>{"use strict";lm=`
|
|
1027
1027
|
...[truncated]`});function wn(t,e){return JSON.stringify([t,e])}function um(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 En,Tn,mm=k(()=>{"use strict";En="terminal_lock",Tn="member"});function Ne(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 lr=k(()=>{"use strict"});import{hostname as $r}from"node:os";function Fr(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??wv);return r.unref?.(),r}function $t(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(!Hs(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 Ft(t){return t.status!=="running"?null:t.holder_host===$r()&&t.holder_pid!==null&&t.holder_pid>0?Ne(t.holder_pid)?"live":"dead":"unknown"}function lt(t,e,r){let n,s=t.getTerminalLock(e,r);if(s!==null){if(vv(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===$r()?"dead-pid":"stale"}}let i=Sv(t,e,r);if(i!==null){if(bv(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===$r())?"dead-pid":"stale"}}let o=t.getAgentInflight(e,r);if(o!==null){let a=new Date(Date.now()-Pr()).toISOString();if(!Hs(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:$r(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function vv(t){if(t.holder_host===$r())return Ne(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=xv():!1}function Sv(t,e,r){return t.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1028
1028
|
FROM tracked_invocation
|
|
1029
1029
|
WHERE target_teamfile = ?
|
|
@@ -1506,13 +1506,13 @@ var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDe
|
|
|
1506
1506
|
response = NULL
|
|
1507
1507
|
WHERE id = ?
|
|
1508
1508
|
AND status = 'running'
|
|
1509
|
-
`),...cm(t),...om(t)}}function nS(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Gv,jm,Jv,Vv,Js,Ut=k(()=>{"use strict";Ko();Cs();am();dm();mm();lr();qs();Rm();Om();Gv=3,jm=".recovery.lock",Jv=20,Vv=50;Js=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=rS(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let _=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 p=this.getJob(a.id);return p===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:p}}),this.resumeRunTxn=e.transaction((r,n,s)=>nS("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!==Cm)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Nm&&!a.includes(n))return{resumed:!1,reason:Lm};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=_m(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){Fm(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,D()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,D());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){Fm(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,D());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,D())}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,D());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,D()),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,D(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(D(),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,D());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,D());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,D(),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,D());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",D());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,D());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=D(),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,D(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,D(),e)??null}closeIssue(e,r,n){let s=D(),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,D(),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,D(),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=D();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,D(),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,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Dm(),s=D();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=D(),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,D())}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??D(),e.dedupe_key??null,e.concurrency_key??null,D());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=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=D(),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:D();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,D()),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,D()),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??D(),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,D());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=D(),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,D(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(D(),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 pa(this.db,n,e),Xs(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 pa(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}`);Xs(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{ma(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>fa(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??D(),n=e.holder_host??_a(),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,qe(e.command),r,e.holder_pid??null,n,s,qe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return bm(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(`
|
|
1509
|
+
`),...cm(t),...om(t)}}function nS(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Gv,jm,Jv,Vv,Js,Ut=k(()=>{"use strict";Ko();Cs();am();dm();mm();lr();qs();Rm();Om();Gv=3,jm=".recovery.lock",Jv=20,Vv=50;Js=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=rS(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let _=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 p=this.getJob(a.id);return p===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:p}}),this.resumeRunTxn=e.transaction((r,n,s)=>nS("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!==Cm)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Nm&&!a.includes(n))return{resumed:!1,reason:Lm};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=_m(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){Fm(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,D()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,D());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){Fm(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,D());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,D())}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,D());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,D()),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,D(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(D(),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,D());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,D());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,D(),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,D());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",D());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,D());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=D(),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,D(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,D(),e)??null}closeIssue(e,r,n){let s=D(),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,D(),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,D(),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=D();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,D(),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,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Dm(),s=D();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=D(),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,D())}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??D(),e.dedupe_key??null,e.concurrency_key??null,D());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=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=D(),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:D();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,D()),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,D()),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??D(),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,D());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=D(),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,D(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(D(),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 pa(this.db,n,e),Xs(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 pa(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}`);Xs(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{ma(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>fa(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??D(),n=e.holder_host??_a(),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,Ge(e.command),r,e.holder_pid??null,n,s,Ge(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return bm(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(`
|
|
1510
1510
|
SELECT * FROM tracked_invocation
|
|
1511
1511
|
WHERE parent_invocation_id IN (${n})
|
|
1512
1512
|
AND ended_at IS NOT NULL
|
|
1513
1513
|
AND ended_at >= ?
|
|
1514
1514
|
ORDER BY started_at ASC, id ASC
|
|
1515
|
-
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??D();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,
|
|
1515
|
+
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??D();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Ge(r.result_summary),Ge(r.error),r.team_chat_log_id??null,Ge(r.meta),Ge(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Gs(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??D();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Ge(n.result_summary),Ge(n.error),n.team_chat_log_id??null,Ge(n.meta),Ge(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 Gs(this.db,o),o})()}heartbeatTrackedInvocation(e,r=D()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return xm(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(km(this.db,e,r),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,e).changes!==1?null:(Am(this.db,e,wt(r)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,r,n){return this.db.transaction(()=>{let s=D();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Ge(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 Gs(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||Xs(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:D()})}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=D()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Im(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=D()){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:ym(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&&vn(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&&vn(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
|
|
1516
1516
|
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&&vn(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&&(vn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(En,wn(e,r),Tn);return n===void 0?null:um(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&ha(this.db,n,!0),this.stmts.upsertRuntimeState.run(En,wn(e.teamfile,e.alias),Tn,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Em(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(En,wn(e,r),Tn,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(En,wn(e,r),Tn);return i.changes===1&&ha(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:eS(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=D()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!tS(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Dm(),holder_pid:process.pid,holder_host:_a(),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,D(),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,D())}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,D());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,D(),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??D(),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,D());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,D()).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,D()),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,D());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(D(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=D();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??D());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,D())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,D())}}});var dt=cT(De=>{"use strict";function Ks(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 sS(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function jt(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 Bm(t,e,r){let n=" ".repeat(Math.max(0,e-jt(t)));return r?n+t:t+n}function iS(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 oS(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 aS(t,e,r="\u2026"){if(jt(t)<=e)return t;let n=jt(r)>e?"\u2026":r,s=jt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=jt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function lS(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 Hm(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=lS(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=iS(i);o.headers!==void 0&&Ks(o.headers).forEach((a,l)=>{s(l,jt(a))});for(let a of o.rows.map(Ks))a.forEach((l,c)=>{s(c,jt(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}De.measureColumns=Hm;function cS(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 Xm(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=cS(o),d=sS(n),u=oS(l),m=e??Hm([{rows:t,headers:r}],{max:a}),p=t.map(Ks);r!==void 0&&p.unshift(Ks(r));let _=p.map(h=>{let g=h.length-1;for(;g>=0&&h[g]==="";)g--;return h.slice(0,g+1).map((f,E)=>{let y=m[E]||0,T=s&&y>0&&(E!==g||i)?aS(f,y,u):f;return d[E]==="right"?Bm(T,y,!0):E===g?T:Bm(T,y,!1)}).join(" ")}).join(`
|
|
1517
1517
|
`);return _===""||c===""?_:`${c}${_.split(`
|
|
1518
1518
|
`).join(`
|
|
@@ -1520,13 +1520,13 @@ ${c}`)}`}De.renderGrid=Xm;function qm(t,{headers:e,align:r,truncate:n,truncateTr
|
|
|
1520
1520
|
`)}De.formatTable=qm;De.printTable=dS;function Wm(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function uS(t,{now:e=Date.now()}={}){let r=Wm(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=Wm(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":""}`}De.formatRelativeTime=uS;function mS(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`}De.formatCount=mS;var Ea=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function fS(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=Ea.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=Ea.slice(n).filter(([u])=>u!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,d=!1;for(let[u,m]of a){let p=Math.floor(c/m);if(c-=p*m,p>0&&!d){let _=u==="d"||u==="w"?`${p}${u}`:`${ct(p)}${u}`;l.push({text:_,zero:!1}),d=!0}else d&&l.push({text:`${ct(p)}${u}`,zero:p===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(u=>u.text).join("")}let i=s,o=[];for(let[a,l]of Ea.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(" ")}De.formatDuration=fS;function Gm(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function ct(t){return String(t).padStart(2,"0")}function Jm(t){let e=Gm(t);return Number.isNaN(e.getTime())?"unknown":`${ct(e.getHours())}:${ct(e.getMinutes())}:${ct(e.getSeconds())}`}De.formatClock=Jm;function pS(t){let e=Gm(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${ct(e.getMonth()+1)}-${ct(e.getDate())}`} ${Jm(e)}`}De.formatLocalTimestamp=pS;function hS(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}De.formatPercent=hS;function gS(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)||jt(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)}`}De.formatBar=gS;function _S(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=`${ct(n)}:${ct(s)}:${ct(e)}`;return r>0?`${r}d ${i}`:i}De.formatTimer=_S;function yS(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
1521
1521
|
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}De.escapeCell=yS});async function C(t,e){if(t.dal!==void 0)return e(t.dal);let r=Ze({path:he()});try{return await e(r)}finally{r.close()}}function oe(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 W(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function X(t,e){return t.flags[e]===!0}function re(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1522
1522
|
`)}function A(t,e){return t.stderr.write(`error: ${e}
|
|
1523
|
-
`),1}function Me(){return(0,Km.formatClock)()}function et(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
|
|
1523
|
+
`),1}function Me(){return(0,Km.formatClock)()}function et(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 Je(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1524
1524
|
`),2}function Bt(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}function Ys(t){if(t.stdout!==process.stdout||Vm)return;Vm=!0;let e=r=>{throw r.code==="EPIPE"&&process.exit(0),process.stdout.off("error",e),r};process.stdout.on("error",e)}var Km,Vm,_e=k(()=>{"use strict";Ut();Km=_t(dt(),1);nt();Vm=!1});function Ta(t,e){if(Ft(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 Br(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
1525
1525
|
FROM tracked_invocation
|
|
1526
1526
|
WHERE target_teamfile = ?
|
|
1527
1527
|
AND target_alias = ?
|
|
1528
1528
|
AND status = 'running'`,e,r),s=0;for(let i of n)Ta(t,i)!==null&&(s+=1);return s}var Sn=k(()=>{"use strict";Ue();Ut();Qe()});import{realpathSync as ES}from"node:fs";import{resolve as TS}from"node:path";function wa(t){let e=TS(t);try{return ES(e)}catch{return e}}var Ym=k(()=>{"use strict"});import{platform as zm}from"node:os";function Wt(t){let e=new bn;for(let r of t)e.registerAdapter(r);return e}var bn,va=k(()=>{"use strict";Ym();bn=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=wa(e.workspace);i=i.filter(a=>wa(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=zm()==="darwin"||zm()==="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 Qm}from"node:fs";import{createInterface as Zm}from"node:readline";import{stat as wS}from"node:fs/promises";import{homedir as vS}from"node:os";function ef(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*ce(t){let e=Qm(t,{encoding:"utf-8"}),r=Zm({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=ef(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function je(t,e){let r=[],n=Qm(t,{encoding:"utf-8"}),s=Zm({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=ef(o);if(a!==void 0&&r.push(a),r.length>=e)break}}finally{s.close(),n.destroy()}return r}async function ue(t){let e=await wS(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function Z(t){return t.replace(/\\n/g,`
|
|
1529
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function U(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function
|
|
1529
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function U(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ve(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var H,be=k(()=>{"use strict";H=vS()});import{readdir as zs,stat as tf,unlink as SS}from"node:fs/promises";import{join as Wr,basename as rf}from"node:path";function bS(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function IS(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return Z(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 nf(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of ce(t))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let d=c.message.content;if(typeof d=="string"){if(d.includes("<command-name>")||d.includes("<local-command-"))continue;e++,l=U(d.trim(),80)}}else if(c.type==="assistant"&&c.message){let d=c.message.content;if(Array.isArray(d))for(let m of d)m.type==="text"&&e++;let u=c.message.usage;if(u){let m=u.input_tokens||0,p=u.cache_creation_input_tokens||0,_=u.cache_read_input_tokens||0,h=u.output_tokens||0;r+=m+p+_,n+=_,s+=p,i+=h;let g=m+p+_;g&&(o=g),a={inputTokens:m,cacheWriteInputTokens:p,cachedInputTokens:_,outputTokens:h}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function xS(t){let e=kS(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 kS(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 Qs,sf=k(()=>{"use strict";be();Qs=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Wr(H,".claude"),this.projectsDir=Wr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await zs(this.projectsDir)}catch{return e}for(let n of r){let s=Wr(this.projectsDir,n);if(!(await tf(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await zs(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=rf(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Wr(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await je(e,50),s=await ue(e),i="",o,a,l,c,d,u;for(let p of n)if(!bS(p.type)&&(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!u&&p.timestamp&&(u=new Date(p.timestamp)),p.type==="assistant"&&p.message?.model&&(l=p.message.model),p.type==="user"&&!p.isMeta&&p.message)){let _=p.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;c||(c=U(_.trim(),80)),d=U(_.trim(),80)}}if(!i)return null;let m=await nf(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:m.lastUserMessage??d,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 ue(r),s=[],i="",o,a,l,c,d,u,m,p=e,_,h=[];for await(let f of ce(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&&(p=f.sessionId),f.type==="system"||f.type==="progress"||f.type==="queue-operation"){s.push({role:"system",timestamp:new Date(f.timestamp||0),content:IS(f)});continue}if(f.type==="user"&&f.message){if(f.isMeta)continue;let E=new Date(f.timestamp||0),y=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(y)&&y.some(T=>T.type==="tool_result"))){let T=typeof y=="string"?y:Array.isArray(y)?y.filter(b=>b.type==="text"&&typeof b.text=="string").map(b=>b.text).join(`
|
|
1530
1530
|
`):"";T&&!/^<(?:command-name>|local-command-)/u.test(T.trimStart())&&h.push(T)}if(typeof y=="string"){if(y.includes("<command-name>")||y.includes("<local-command-"))continue;d||(d=U(y.trim(),80)),u=U(y.trim(),80),_=void 0,s.push({role:"user",timestamp:E,content:Z(y.trim())})}else if(Array.isArray(y)){for(let T of y)if(T.type==="tool_result"){let b=typeof T.content=="string"?Z(T.content):JSON.stringify(T.content);s.push({role:"tool_result",timestamp:E,content:b,toolCallId:T.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 E=new Date(f.timestamp||0),y=f.message.content;if(Array.isArray(y))for(let T of y)T.type==="text"&&T.text?s.push({role:"assistant",timestamp:E,content:Z(T.text),model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):T.type==="tool_use"?s.push({role:"tool_use",timestamp:E,content:T.name||"unknown tool",toolName:T.name,toolInput:JSON.stringify(T.input,null,2),toolInputData:T.input,toolCallId:T.id,model:f.message.model,...typeof f.message.stop_reason=="string"?{stopReason:f.message.stop_reason}:{}}):T.type==="thinking"&&T.thinking&&s.push({role:"thinking",timestamp:E,content:T.thinking})}}if(!i)return null;xS(s);let g=await nf(r);return{provider:"claude",sessionId:p,slug:o,cwd:i,createdAt:m||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:_,firstUserMessage:d,lastUserMessage:u,messageCount:g.messageCount,filePath:r,totalInputTokens:g.totalInputTokens||void 0,totalCachedInputTokens:g.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:g.totalCacheWriteInputTokens||void 0,totalOutputTokens:g.totalOutputTokens||void 0,lastInputTokens:g.lastInputTokens||void 0,lastTokenUsage:g.lastTokenUsage,messages:s,userPrompts:h}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await SS(r),!0):!1}async resolveSessionFile(e){let r;try{r=await zs(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Wr(this.projectsDir,o);if(!(await tf(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await zs(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=rf(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Wr(a,d),fileSessionId:u})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await je(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as AS,writeFileSync as dM,mkdirSync as uM}from"node:fs";import{join as RS,dirname as fM}from"node:path";import{homedir as NS}from"node:os";function CS(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function OS(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=CS(t.slice(e+1).trim());return r?{key:r,value:n}:null}function DS(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Zs(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function MS(){return RS(NS(),".lmctl","config.toml")}function Hr(t){let e=t??MS(),r;try{r=AS(e,"utf-8")}catch{return{tools:{}}}return $S(r)}function of(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 $S(t){let e={},r={},n=t.split(`
|
|
1531
1531
|
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let m=u.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=m}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=of(i.min);m!==null&&(u.min=m)}if(i.max!==void 0){let m=of(i.max);m!==null&&(u.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let m=u.trim();if(!m||m.startsWith("#"))continue;let p=DS(m);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let h=".profile.",g=p.indexOf(h);g!==-1?s={kind:"tool",tool:p.slice(5,g),profile:p.slice(g+h.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let _=OS(m);_&&s.kind!=="none"?i[_.key]=_.value:_&&!o&&(a[_.key]=_.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let d=a.site_name;return d!==void 0&&d.length>0&&(c.site_name=d),c}function af(t){return t.site_name??null}function FS(t,e,r){if(!r)return"";let n=t.tools[e]??Sa[e],s=n?.profiles?.[r]?.flags??Sa[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 lf(t,e){return!!t.tools[e]}function cf(t,e,r,n,s){let i=t.tools[e]??Sa[e],o;if(i?.agent){let l=Zs(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=LS[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(d=>d.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let d=c.map(Zs).join(" ");o=`printf '%s\\n' ${Zs(n)} | ${d}`}else o=c.map(Zs).join(" ")}let a=FS(t,e,s);return a&&(o+=" "+a),o}var Sa,LS,In=k(()=>{"use strict";Sa={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:""}}}},LS={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 df(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 uf=k(()=>{"use strict"});var PS,G,ei,$e=k(()=>{"use strict";PS="ACK: waiting for explicit lmctl task.",G=`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: ${PS}`,ei=`send this exact lmctl seed instruction: "${G}"`});import{existsSync as US}from"node:fs";function mf(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&&!US(e);if(!r&&!n)return t;L({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 Xr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function BS(t,e){return e===void 0||e.length===0?t:{...t??process.env,[ba]:e}}function we(t,e,r,n="chat"){return{...BS(Xr(t,e),r),[jS]:n}}var ba,jS,ut=k(()=>{"use strict";J();ba="LMCTL_SELF_SESSIONID",jS="LMCTL_LAUNCH_SOURCE"});function xn(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Ia=k(()=>{"use strict"});import{spawn as ff}from"node:child_process";import{mkdirSync as WS}from"node:fs";var xa,ee,Be=k(()=>{"use strict";In();uf();$e();ut();Ia();xa=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},ee=class t{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===G?r:n)}turnOptsFor(e){return e}seed(e,r){return WS(e,{recursive:!0}),new Promise(n=>{let s;try{s=ff(this.binary,this.seedArgsFor(r),{cwd:e,env:Xr(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(l){return n({success:!1,error:l instanceof Error?l.message:String(l)})}let i="",o="";s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{o+=l.toString()});let a=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1532
1532
|
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",l=>{if(l===0||l===null)n({success:!0});else{let c=xn(o).trim(),d=xn(i).trim();n({success:!1,error:(c||d).slice(0,500)||`exit code ${l}`})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:ei,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&&lf(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,r,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),d(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},d=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let u={...n,binary:this.binary,signal:s.signal,onDelta:_=>{a+=_,c(),n.onDelta?.(_)},onProgress:_=>{_.kind!=="api_retry"&&c(),n.onProgress?.(_)}},m=this.transportFn(r,u).then(_=>(d(),{..._,status:_.status??"ok"})).catch(_=>{throw d(),o==="external"?new xa("Turn cancelled","external"):_}),p=new Promise(_=>{l=_});return Promise.race([m,p])}runOneShotAgent(e,r,n){let s=cf(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=df(r.env),c=ff(s,{shell:!0,cwd:r.cwd,env:we(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,m=setTimeout(()=>{u=!0,c.kill()},l),p="",_="";if(c.stdout?.on("data",h=>{let g=h.toString();p+=g,r.onDelta?.(g)}),c.stderr?.on("data",h=>{_+=h.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",h=>{if(d)return;d=!0,clearTimeout(m);let g=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:p.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(_.trim().slice(0,200)||`Agent command exited with code ${h}`))}),c.on("error",h=>{d||(d=!0,clearTimeout(m),a(h))})})}}});function Rn(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new An(t,r,e)}var Ht,te,kn,ti,An,dr=k(()=>{"use strict";Ht=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},te=class extends Ht{},kn=class extends Ht{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},ti=class extends Ht{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},An=class extends Ht{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as Aa from"node:child_process";function XS(t){if(typeof Aa.spawnSync=="function")try{Aa.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function pf(t){return t.exitCode!==null||t.signalCode!==null}function ka(t,e){return pf(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 ne(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??XS;if(pf(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await ka(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 ka(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await ka(t,HS)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var HS,Nn=k(()=>{"use strict";HS=1e3});function hf(t){z()&&Se({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Xt(t,e){let r=GS[t];if(r)return r[e]??r.yolo}function VS(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 Ie(t,e,r="yolo"){if(JS.has(t)){hf(`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"?Xt(t,"plan"):qS[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 L({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new te(s)}if(!VS(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 L({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new te(i)}hf(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var qS,GS,JS,vt=k(()=>{"use strict";dr();J();qS={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},GS={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"]}};JS=new Set(["codex","opencode","kimi","dsh","hermes","pi"])});async function ni(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(Ra),e),n.unref?.(),r!==void 0&&(s=()=>i(Ra),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function qt(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();ZS(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function ZS(t,e,r,n){let s=t.pollMs??KS,i=t.maxHoldMs??ri,o=t.settleMs??YS,a=t.backgroundGraceMs??zS,l=!1,c=null,d=u=>n({startedMs:r,held:l,reason:u});for(;;){if(e.isAborted())return d("aborted");if(e.hasChildExited())return d("child-exited");let u=i-(Date.now()-r);if(u<=0)return d("max-hold");let m;try{m=await ni(t.hasOutstandingWork(),u,e.signal)}catch{return d("check-error")}if(m===Ra)return d(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(m)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-r<a){let h=a-(Date.now()-r);await new Promise(g=>setTimeout(g,Math.max(0,Math.min(s,QS,h))).unref?.());continue}if(!l||o<=0)return d("cleared");c===null&&(c=Date.now(),Te(`${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 d("cleared")}if(l||(l=!0,t.onHold?.(),Te(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-r>=i)return L({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-r}),d("max-hold");let p=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(_=>setTimeout(_,p).unref?.())}}var KS,ri,YS,zS,QS,Ra,si=k(()=>{"use strict";J();KS=2e3,ri=8*60*60*1e3,YS=5e3,zS=1e3,QS=50,Ra=Symbol("check-timed-out")});function gf(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(`
|
|
@@ -1563,7 +1563,7 @@ ${r}`:r}function Cf(t){let e=t.binaryPath||"codex",r=["app-server","--listen","s
|
|
|
1563
1563
|
FROM session s
|
|
1564
1564
|
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)",d=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1565
1565
|
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,m,p,_,h=zf(),g=[];for(let E of d){let y;try{y=JSON.parse(E.data)}catch{continue}_||(_=y.model?.modelID||y.modelID),(y.role==="user"||y.role==="assistant")&&u++,y.role==="user"&&g.push(E.id),y.role==="assistant"&&Qf(h,y.tokens)}let f=[...g.length>0?[g[0]]:[],...g.length>1?[g[g.length-1]]:[]];for(let E of f){let y=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(E),T=this.extractText(y);T&&(m||(m=U(T,80)),p=U(T,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:p,messageCount:u,filePath:r,...Zf(h)})}}catch(s){L({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
|
|
1566
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,m,p=zf();for(let _ of o){let h;try{h=JSON.parse(_.data)}catch{continue}d||(d=h.model?.modelID||h.modelID);let g=h.model?.modelID||h.modelID,f=new Date(h.time?.created||_.time_created),E=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_.id);if(h.role==="user"){let y=this.extractText(E),T=this.extractText(E,!0);T&&l.push(T),y&&(u||(u=U(y,80)),m=U(y,80)),a.push({role:"user",timestamp:f,content:y||"(empty)"}),c++}else if(h.role==="assistant"){Qf(p,h.tokens);for(let y of E){let T;try{T=JSON.parse(y.data)}catch{continue}T.type==="text"&&T.text?a.push({role:"assistant",timestamp:f,content:T.text,model:g}):T.type==="reasoning"&&T.text?a.push({role:"thinking",timestamp:f,content:T.text}):T.type==="tool"&&T.tool&&(a.push({role:"tool_use",timestamp:f,content:`${T.tool}`,toolName:T.tool,toolCallId:T.callID,toolInput:T.state?.input?JSON.stringify(T.state.input):void 0,toolInputData:
|
|
1566
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,m,p=zf();for(let _ of o){let h;try{h=JSON.parse(_.data)}catch{continue}d||(d=h.model?.modelID||h.modelID);let g=h.model?.modelID||h.modelID,f=new Date(h.time?.created||_.time_created),E=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_.id);if(h.role==="user"){let y=this.extractText(E),T=this.extractText(E,!0);T&&l.push(T),y&&(u||(u=U(y,80)),m=U(y,80)),a.push({role:"user",timestamp:f,content:y||"(empty)"}),c++}else if(h.role==="assistant"){Qf(p,h.tokens);for(let y of E){let T;try{T=JSON.parse(y.data)}catch{continue}T.type==="text"&&T.text?a.push({role:"assistant",timestamp:f,content:T.text,model:g}):T.type==="reasoning"&&T.text?a.push({role:"thinking",timestamp:f,content:T.text}):T.type==="tool"&&T.tool&&(a.push({role:"tool_use",timestamp:f,content:`${T.tool}`,toolName:T.tool,toolCallId:T.callID,toolInput:T.state?.input?JSON.stringify(T.state.input):void 0,toolInputData:Ve(T.state?.input)}),T.state&&(T.state.status==="completed"||T.state.status==="error"||T.state.output!==void 0||T.state.error!==void 0)&&a.push({role:"tool_result",timestamp:f,content:T.state.error??T.state.output??"",toolCallId:T.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:d,startCommand:this.startCommand,firstUserMessage:u,lastUserMessage:m,messageCount:c,filePath:n,...Zf(p),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(`
|
|
1567
1567
|
`).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(Ba())(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,
|
|
1568
1568
|
s.time_created, s.time_updated
|
|
1569
1569
|
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,
|
|
@@ -1595,13 +1595,13 @@ ${r}`:r}function Bb(t,e){return jn(t)?.filterExpectedStderr?.(e)??e}function lp(
|
|
|
1595
1595
|
`).trim();S&&i.push({role:"thinking",timestamp:mr(v.timestamp,E),content:Z(S)})}i.push({role:"assistant",timestamp:E,content:T,model:f.model});continue}let b=y?`[${y}] `:"";i.push({role:"system",timestamp:E,content:`${b}${T}`.trim()})}let _=mr(n.startTime,s.createdAt),h=mr(n.lastUpdated,s.modifiedAt),g=Ap(a);return{provider:"gemini",sessionId:l,cwd:d,createdAt:_,modifiedAt:h,model:p,startCommand:"gemini",firstUserMessage:u,lastUserMessage:m,messageCount:i.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:r,totalInputTokens:g.totalInputTokens||void 0,totalCachedInputTokens:g.totalCachedInputTokens||void 0,totalOutputTokens:g.totalOutputTokens||void 0,totalReasoningOutputTokens:g.totalReasoningOutputTokens||void 0,lastInputTokens:g.lastInputTokens||void 0,lastTokenUsage:g.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await ue(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let p of s)if(kp(p.type)){u++;let _=nl(p.content).trim();_&&(l||(l=U(Z(_),80)),c=U(Z(_),80))}else sl(p.type)&&(u++,p.model&&(d=p.model));let m=Ap(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:mr(r.startTime,n.createdAt),modifiedAt:mr(r.lastUpdated,n.modifiedAt),model:d,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:u,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 xp(e,"utf-8");if(Hn(r)==="unknown")return L({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 Ti(r)}catch{return null}}extractSessionIdFromFilename(e){let r=nI(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 Xn(this.geminiTmpDir)}catch{return e}for(let n of r){let s=We(this.geminiTmpDir,n,"chats");if(!(await wi(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Xn(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(We(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await rI(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){let i=await this.readSessionFile(s).catch(()=>null),o=this.extractSessionIdFromFilename(s),a=i?.sessionId||o,l=a===e||a.startsWith(e),c=o===e||o.startsWith(e)||o.length>=8&&e.startsWith(o);if(!l&&!c)continue;let d=await ue(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:mr(i?.lastUpdated,d.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;qn(e,iI());for(let n of this.extraWorkspacePaths)qn(e,n);for(let n of await this.collectGeminiProjectPaths())qn(e,n);for(let n of await this.collectCodexCwds())qn(e,n);for(let n of await this.collectClaudeCwds())qn(e,n);let r=new Map;for(let n of e)r.set(lI(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await xp(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 je(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await Xn(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=We(this.claudeProjectsDir,n);if(!(await wi(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Xn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=We(s,a),d=(await je(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await wi(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await Xn(e)}catch{return r}for(let i of s){let o=We(e,i),a=await wi(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 cI,writeFileSync as dI,mkdirSync as uI}from"node:fs";import{join as mI,dirname as fI}from"node:path";import{randomUUID as pI}from"node:crypto";function ol(t){return new il(t)}var il,al=k(()=>{"use strict";Rp();Be();St();$e();rl();il=class extends ee{geminiDir;constructor(e){super({provider:new Si(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",G,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>mt(r,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return ft({...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(`
|
|
1596
1596
|
`)}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:ei,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=cI(n,"utf-8"),i=Hn(s),o=Ti(s),a=pI();o.sessionId=a,o.kind="main";let l=fI(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=i==="jsonl"?".jsonl":".json",u=`session-${c}-${a.slice(0,8)}${d}`,m=mI(l,u);return uI(l,{recursive:!0}),dI(m,Ip(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 Np,readFile as hI,rm as gI,stat as Vr}from"node:fs/promises";import{basename as _I,join as tt}from"node:path";function yI(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 ll(){return{shutdownTotals:null,assistantOutputSum:0}}function Cp(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=yI(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function Lp(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 EI(t){let e={};for(let r of t.split(`
|
|
1597
1597
|
`)){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 fr(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function TI(t){let e=0,r=ll(),n;for await(let s of ce(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=U(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;Cp(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function wI(t){let e=vI(t),r=new Map;for(let n of t){if(n.role!=="tool_use"||n.toolCallId===void 0)continue;if(n.toolName==="bash"){let l=e.get(n.toolCallId),d=[l?.content,l?.toolDetailedContent].filter(m=>typeof m=="string").join(`
|
|
1598
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function vI(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 bi,Op=k(()=>{"use strict";be();bi=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||tt(H,".copilot");this.sessionStateDir=tt(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Np(this.sessionStateDir)}catch{return e}for(let n of r){let s=tt(this.sessionStateDir,n);if((await Vr(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=tt(r,"events.jsonl"),i=await Vr(s).catch(()=>null),o=i?s:tt(r,"workspace.yaml"),a=await ue(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,m,p,_,h,g,f=n?.id||_I(r)||e,E=ll();if(i)for await(let y of ce(s)){let T=fr(y.timestamp)||a.modifiedAt;if(Cp(E,y),y.type==="session.start"&&y.data){y.data.sessionId&&(f=y.data.sessionId),y.data.copilotVersion&&(m=y.data.copilotVersion),y.data.startTime&&(g=fr(y.data.startTime)),y.data.selectedModel&&(u=y.data.selectedModel),y.data.context&&(y.data.context.cwd&&(d=y.data.context.cwd),y.data.context.branch&&(p=y.data.context.branch));continue}if(y.type==="session.model_change"&&y.data?.newModel){u=y.data.newModel;continue}if(y.type==="user.message"&&y.data){let b=y.data.content||"";b&&c.push(b);let v=b.trim();v&&(_||(_=U(v,80)),h=U(v,80)),l.push({role:"user",timestamp:T,content:Z(v||b)});continue}if(y.type==="assistant.message"&&y.data){let b=(y.data.content||"").trim();if(b&&l.push({role:"assistant",timestamp:T,content:Z(b),model:u}),y.data.toolRequests)for(let v of y.data.toolRequests)l.push({role:"tool_use",timestamp:T,content:v.name||"unknown tool",toolName:v.name,toolInput:v.arguments?JSON.stringify(v.arguments,null,2):void 0,toolInputData:
|
|
1598
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function vI(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 bi,Op=k(()=>{"use strict";be();bi=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||tt(H,".copilot");this.sessionStateDir=tt(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Np(this.sessionStateDir)}catch{return e}for(let n of r){let s=tt(this.sessionStateDir,n);if((await Vr(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=tt(r,"events.jsonl"),i=await Vr(s).catch(()=>null),o=i?s:tt(r,"workspace.yaml"),a=await ue(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,m,p,_,h,g,f=n?.id||_I(r)||e,E=ll();if(i)for await(let y of ce(s)){let T=fr(y.timestamp)||a.modifiedAt;if(Cp(E,y),y.type==="session.start"&&y.data){y.data.sessionId&&(f=y.data.sessionId),y.data.copilotVersion&&(m=y.data.copilotVersion),y.data.startTime&&(g=fr(y.data.startTime)),y.data.selectedModel&&(u=y.data.selectedModel),y.data.context&&(y.data.context.cwd&&(d=y.data.context.cwd),y.data.context.branch&&(p=y.data.context.branch));continue}if(y.type==="session.model_change"&&y.data?.newModel){u=y.data.newModel;continue}if(y.type==="user.message"&&y.data){let b=y.data.content||"";b&&c.push(b);let v=b.trim();v&&(_||(_=U(v,80)),h=U(v,80)),l.push({role:"user",timestamp:T,content:Z(v||b)});continue}if(y.type==="assistant.message"&&y.data){let b=(y.data.content||"").trim();if(b&&l.push({role:"assistant",timestamp:T,content:Z(b),model:u}),y.data.toolRequests)for(let v of y.data.toolRequests)l.push({role:"tool_use",timestamp:T,content:v.name||"unknown tool",toolName:v.name,toolInput:v.arguments?JSON.stringify(v.arguments,null,2):void 0,toolInputData:Ve(v.arguments),toolCallId:v.toolCallId});continue}if(y.type==="tool.execution_complete"&&y.data){let b=y.data.result?.content||"",v=y.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:T,content:Z(b),toolDetailedContent:v?Z(v):void 0,toolCallId:y.data.toolCallId});continue}if(y.type==="assistant.reasoning"&&y.data?.content){l.push({role:"thinking",timestamp:T,content:Z(y.data.content)});continue}if(y.type==="session.error"||y.type==="session.warning"||y.type==="session.info"||y.type==="system.message"){let b=y.data?.message||"";b.trim()&&l.push({role:"system",timestamp:T,content:Z(b)});continue}}if(!_){let y=(n?.summary||"").trim();y&&(_=U(y,80))}return wI(l),{provider:"copilot",sessionId:f,cwd:d,createdAt:g??fr(n?.created_at)??a.createdAt,modifiedAt:fr(n?.updated_at)??a.modifiedAt,model:u,cliVersion:m,startCommand:"copilot",gitBranch:p,firstUserMessage:_,lastUserMessage:h,messageCount:l.filter(y=>y.role==="user"||y.role==="assistant").length,filePath:o,...Lp(E),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=tt(e,"events.jsonl"),i=await Vr(s).catch(()=>null),o=i?s:tt(e,"workspace.yaml"),a=await ue(i?s:e),l=i?await je(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,m,p,_,h;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&&(p=fr(f.data.startTime)),f.data.selectedModel&&(u=f.data.selectedModel),f.data.context?.cwd&&(d=f.data.context.cwd)),f.type==="session.model_change"&&f.data?.newModel&&(u||(u=f.data.newModel)),f.type==="user.message"&&f.data){let E=(f.data.content||"").trim();E&&(_||(_=U(E,80)),h=U(E,80))}if(!_){let f=(n?.summary||"").trim();f&&(_=U(f,80))}let g=i?await TI(s):{messageCount:0,tokens:ll()};return{provider:"copilot",sessionId:c,cwd:d,createdAt:p??fr(n?.created_at)??a.createdAt,modifiedAt:fr(n?.updated_at)??a.modifiedAt,model:u,cliVersion:m,startCommand:"copilot",firstUserMessage:_,lastUserMessage:g.lastUserMessage??h,messageCount:g.messageCount,filePath:o,...Lp(g.tokens)}}async readWorkspaceYaml(e){let r=tt(e,"workspace.yaml");try{let n=await hI(r,"utf-8");return EI(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await gI(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await Np(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=tt(this.sessionStateDir,e);if((await Vr(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=tt(this.sessionStateDir,s);(await Vr(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=tt(this.sessionStateDir,s);if(!(await Vr(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 dl(t){return new cl(t)}var cl,ul=k(()=>{"use strict";Op();Be();St();J();$e();cl=class extends ee{copilotDir;constructor(e){super({provider:new bi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",G,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>mt(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return ft({...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 Se({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function fl(){return new ml}var ml,pl=k(()=>{"use strict";gi();Be();St();$e();ml=class extends ee{constructor(){super({provider:new Gr,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",G],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>mt(e,{...r,acpTool:"opencode"})})}openSession(e){return ft({...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??G),r}}});import{appendFile as SI,mkdir as bI,readFile as Dp,readdir as Mp,rm as II,stat as $p}from"node:fs/promises";import{basename as xI,dirname as kI,isAbsolute as Fp,join as pr,relative as AI,resolve as hl}from"node:path";function gl(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function CI(t){return typeof t=="number"?new Date(t):gl(t)??new Date(0)}function Pp(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(`
|
|
1599
1599
|
`).trim():""}function Up(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function OI(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:Up(t)??""}function DI(t){let e=MI(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 MI(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 RI,NI,LI,Ii,jp=k(()=>{"use strict";be();RI="1.4",NI="1.5",LI=new Set([RI,NI]),Ii=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=hl(e?.kimiHome??process.env.KIMI_CODE_HOME??pr(H,".kimi-code")),this.sessionsDir=pr(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 II(r.sessionDir,{recursive:!0,force:!0}),await bI(kI(this.indexPath()),{recursive:!0,mode:448}),await SI(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
1600
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return pr(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 Mp(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=pr(this.sessionsDir,s.name),o;try{o=await Mp(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=pr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Dp(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:hl(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:pr(r,"state.json"),wirePath:pr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!Fp(e)||xI(e)!==r)return!1;let n=AI(this.sessionsDir,hl(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Fp(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 Dp(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 $p(e.wirePath)}catch{return null}let s=await $p(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=gl(r.createdAt)??s.birthtime,a=gl(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?U(r.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,m=0,p=!1,_=0,h,g;for await(let f of ce(e)){let E=CI(f.time??f.created_at);if(i&&(i=!1,f.type==="metadata"&&!LI.has(f.protocol_version))){let T=`Kimi transcript wire protocol version ${JSON.stringify(f.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:E,content:T}],userPrompts:[],messageCount:1,firstUserMessage:T,lastUserMessage:T}}if((f.type==="config.update"||f.type==="profile.bind")&&f.modelAlias&&(o=f.modelAlias),f.type==="usage.record"){f.model&&(o=f.model),p||=f.usage!==void 0;let T=f.usage?.inputOther??0,b=f.usage?.inputCacheRead??0,v=f.usage?.inputCacheCreation??0,S=f.usage?.output??0;c+=T,d+=b,u+=v,m+=S,f.usageScope==="turn"&&(h=T+b+v,g={inputTokens:T,cachedInputTokens:b,cacheWriteInputTokens:v,outputTokens:S,totalTokens:h+S});continue}if(f.type==="turn.prompt"&&f.origin?.kind==="user"){let T=Pp(f.input);T&&((!f.promptId||!s.has(f.promptId))&&(n.push(T),f.promptId&&s.add(f.promptId)),a??=U(T,80),l=U(T,80),r.push({role:"user",timestamp:E,content:T}),_++);continue}if(f.type==="turn.steer"){let T=Pp(f.input);T&&(r.push({role:"system",timestamp:E,content:T}),_++);continue}if(f.type!=="context.append_loop_event"||!f.event)continue;let y=f.event;y.type==="content.part"&&y.part?.type==="text"&&y.part.text?(r.push({role:"assistant",timestamp:E,content:y.part.text,model:o}),_++):y.type==="content.part"&&y.part?.type==="think"&&y.part.think?r.push({role:"thinking",timestamp:E,content:y.part.think,model:o}):y.type==="tool.call"?r.push({role:"tool_use",timestamp:E,content:y.name??"tool",toolName:y.name,toolInput:Up(y.args),toolInputData:
|
|
1600
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return pr(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 Mp(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=pr(this.sessionsDir,s.name),o;try{o=await Mp(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=pr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Dp(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:hl(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:pr(r,"state.json"),wirePath:pr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!Fp(e)||xI(e)!==r)return!1;let n=AI(this.sessionsDir,hl(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Fp(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 Dp(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 $p(e.wirePath)}catch{return null}let s=await $p(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=gl(r.createdAt)??s.birthtime,a=gl(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?U(r.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,m=0,p=!1,_=0,h,g;for await(let f of ce(e)){let E=CI(f.time??f.created_at);if(i&&(i=!1,f.type==="metadata"&&!LI.has(f.protocol_version))){let T=`Kimi transcript wire protocol version ${JSON.stringify(f.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:E,content:T}],userPrompts:[],messageCount:1,firstUserMessage:T,lastUserMessage:T}}if((f.type==="config.update"||f.type==="profile.bind")&&f.modelAlias&&(o=f.modelAlias),f.type==="usage.record"){f.model&&(o=f.model),p||=f.usage!==void 0;let T=f.usage?.inputOther??0,b=f.usage?.inputCacheRead??0,v=f.usage?.inputCacheCreation??0,S=f.usage?.output??0;c+=T,d+=b,u+=v,m+=S,f.usageScope==="turn"&&(h=T+b+v,g={inputTokens:T,cachedInputTokens:b,cacheWriteInputTokens:v,outputTokens:S,totalTokens:h+S});continue}if(f.type==="turn.prompt"&&f.origin?.kind==="user"){let T=Pp(f.input);T&&((!f.promptId||!s.has(f.promptId))&&(n.push(T),f.promptId&&s.add(f.promptId)),a??=U(T,80),l=U(T,80),r.push({role:"user",timestamp:E,content:T}),_++);continue}if(f.type==="turn.steer"){let T=Pp(f.input);T&&(r.push({role:"system",timestamp:E,content:T}),_++);continue}if(f.type!=="context.append_loop_event"||!f.event)continue;let y=f.event;y.type==="content.part"&&y.part?.type==="text"&&y.part.text?(r.push({role:"assistant",timestamp:E,content:y.part.text,model:o}),_++):y.type==="content.part"&&y.part?.type==="think"&&y.part.think?r.push({role:"thinking",timestamp:E,content:y.part.think,model:o}):y.type==="tool.call"?r.push({role:"tool_use",timestamp:E,content:y.name??"tool",toolName:y.name,toolInput:Up(y.args),toolInputData:Ve(y.args),toolCallId:y.toolCallId,model:o}):y.type==="tool.result"&&r.push({role:"tool_result",timestamp:E,content:OI(y.result),toolCallId:y.toolCallId,model:o})}return DI(r),{messages:r,userPrompts:n,messageCount:_,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?d:void 0,totalCacheWriteInputTokens:p?u:void 0,totalOutputTokens:p?m:void 0,lastInputTokens:h,lastTokenUsage:g}}}});function yl(t){return new _l(t)}var _l,El=k(()=>{"use strict";jp();Be();St();$e();_l=class extends ee{kimiHome;constructor(e){super({provider:new Ii(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",G,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>mt(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return ft({...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??G,"--output-format","stream-json"),r}}});import{spawn as $I}from"node:child_process";import{mkdirSync as FI}from"node:fs";function wl(t){return new Tl(t)}async function PI(t,e){let r=Date.now(),n=Bp({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});Ie("lmplayer",n,e.permissionMode??"yolo");let s=await Hp(e.binary,n,{cwd:e.cwd,env:we(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(Wp(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function Bp(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(...Xt("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function Wp(t){if(t.error)return t.error;let e=xn(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function Hp(t,e,r){return new Promise((n,s)=>{let i;try{i=$I(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(h){s(h);return}let o="",a="",l="",c,d,u,m=[],p=!1,_=h=>{let g=h.trim();if(!g)return;let f;try{f=JSON.parse(g)}catch{m.push(h),r.onText?.(h);return}if(!Kr(f))return;let E=xi(f,!1);c===void 0&&E!==void 0&&(c=E),d=xi(f,!0)??d;let y=UI(f);y!==void 0&&(u=y);let T=Xp(f);T&&(m.push(T),r.onText?.(T))};i.stdout?.on("data",h=>{let g=h.toString("utf8");o+=g,l+=g;let f=l.indexOf(`
|
|
1601
1601
|
`);for(;f>=0;){let E=l.slice(0,f);l=l.slice(f+1),_(E),f=l.indexOf(`
|
|
1602
1602
|
`)}}),i.stderr?.on("data",h=>{a+=h.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",h=>{p||(p=!0,l.length>0&&_(l),n({code:h,stdout:o,stderr:a,sessionId:c??d,text:m.join(""),error:u}))}),i.on("error",h=>{p||(p=!0,s(h))})})}function UI(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Kr(e)){let r=e.data;if(Kr(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 Xp(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(Kr(r)){let n=Xp(r);if(n)return n}}}function xi(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(Kr(r)){let n=xi(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(Kr(s)){let i=xi(s,e);if(i!==void 0)return i}}}function Kr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Tl,vl=k(()=>{"use strict";gi();Be();$e();vt();ut();Ia();Tl=class extends ee{constructor(e){super({provider:new Gr({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",G],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:PI})}seedArgsFor(e){return Bp({prompt:e?.prompt??G,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){FI(e,{recursive:!0});let n=this.seedArgsFor(r);Ie("lmplayer",n);try{let s=await Hp(this.binary,n,{cwd:e,env:Xr(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:Wp(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 "${G}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as ki,readFile as jI,rm as BI}from"node:fs/promises";import{basename as qp,join as Kt}from"node:path";function WI(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Gn(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function HI(t,e){if(!e)return;t.observed=!0;let r=Gn(e.promptTokenCount),n=Gn(e.cachedContentTokenCount),s=Gn(e.candidatesTokenCount),i=Gn(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:Gn(e.totalTokenCount)||r+s}}function XI(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 Gp(t){return t.type==="user"||t.message?.role==="user"}function Jp(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function Vp(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(`
|
|
1603
1603
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1604
|
-
`):"":""}function Kp(t){return t.model||t.message?.model}function qI(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:zp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Jn(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 GI(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Jn(e.output??e.error??t)}return Jn(t)}function zp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function Yp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Jn(t.args,!0),toolInputData:Je(t.args),toolCallId:t.id,model:r}}var Ai,Qp=k(()=>{"use strict";be();Ai=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Kt(H,".qwen")}async discoverSessions(){let e=Kt(this.baseDir,"projects"),r;try{r=await ki(e)}catch{return[]}let n=[];for(let s of r){let i=Kt(e,s,"chats"),o;try{o=await ki(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Kt(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await ue(e),i="(unknown)",o,a,l,c,d=0;for await(let u of ce(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Gp(u)){let m=Vp(u).trim();m&&(l||(l=U(m,80)),c=U(m,80),d++)}if(Jp(u)){let m=Kp(u);m&&(o=m),d+=qI(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=qp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await ue(e),s="(unknown)",i,o,a,l,c,d,u=[],m=WI();for await(let p of ce(e)){if(HI(m,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let _=p.message,h=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let g=zp(p).filter(f=>f.functionResponse!==void 0);g.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:h,content:Jn(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let f of g){let E=f.functionResponse,y=GI(E.response),T=Jn(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:h,content:T??y??p.toolCallResult?.status??"tool result",toolName:E.name,toolCallId:p.toolCallResult?.callId??E.id,...y!==void 0?{toolDetailedContent:y}:{}})}}else if(Gp(p)){let g=Vp(p);g.trim()&&(c||(c=U(g.trim(),80)),d=U(g.trim(),80)),u.push({role:"user",timestamp:h,content:g})}else if(Jp(p)){let g=Kp(p);if(g&&(i=g),Array.isArray(_.content))for(let f of _.content)f.type==="text"&&f.text?u.push({role:"assistant",timestamp:h,content:f.text,model:g}):f.type==="thinking"&&f.thinking?u.push({role:"thinking",timestamp:h,content:f.thinking}):f.functionCall&&u.push(Yp(f.functionCall,h,g));else if(typeof _.content=="string")u.push({role:"assistant",timestamp:h,content:_.content,model:g});else if(Array.isArray(_.parts))for(let f of _.parts)if(f.thought||f.type==="thinking"){let E=f.thinking||f.text;E&&u.push({role:"thinking",timestamp:h,content:E})}else f.functionCall?u.push(Yp(f.functionCall,h,g)):f.text&&u.push({role:"assistant",timestamp:h,content:f.text,model:g})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...XI(m),messages:u}}async resolveSessionPath(e){let r=Kt(this.baseDir,"projects");try{let n=await ki(r),s=[];for(let i of n){let o=Kt(r,i,"chats",`${e}.jsonl`);try{return await jI(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Kt(r,i,"chats"),a;try{a=await ki(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;qp(l,".jsonl").startsWith(e)&&s.push(Kt(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 BI(r),!0}catch{return!1}}}});function bl(){return new Sl}var Sl,Il=k(()=>{"use strict";Qp();Be();St();$e();Sl=class extends ee{constructor(){super({provider:new Ai,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",G,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:_i})}openSession(e){return yi({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Zp,readFile as eh,rm as th,stat as rh}from"node:fs/promises";import{basename as xl,join as pt}from"node:path";import{fileURLToPath as JI}from"node:url";async function VI(t){let e=await Promise.all(t.map(r=>ue(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 KI(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function nh(t){return t.type==="USER_INPUT"}function sh(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function YI(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function ih(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function oh(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 zI(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function QI(t){for await(let e of ce(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=ZI(s);if(i)return i}let n=ex(e.content);if(n)return n}return null}function ZI(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 ex(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function tx(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 rx(t,e){let r=new Set;for(let n of e){let s=nx(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 nx(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:ax(r.event.content);if(n!==void 0)return ah(t.filter(i=>!e.has(i)&&lx(i)===n),r.event.step_index);let s=ox(r.event);if(s!==void 0)return ah(t.filter(i=>!e.has(i)&&sx(i.name,r.event.type)&&ch(ix(i))===s),r.event.step_index)}function ah(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 sx(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 ix(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function ox(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]),ch(e)}function ch(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return JI(e)}catch{return}}function ax(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function lx(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 lh(t){if(t.endsWith(".db"))return xl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ri,dh=k(()=>{"use strict";be();Ri=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||pt(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:pt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=pt(this.baseDir,"conversations"),r;try{r=await Zp(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=xl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return pt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return pt(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 rh(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await VI([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of ce(n)){let m=oh(u.content);if(m&&(a=m),nh(u)){let p=ih(u.content).trim();p&&(l||(l=U(p,80)),c=U(p,80)),d++}else sh(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=lh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,d=[],u=[];if(i)for await(let m of ce(i)){let p=KI(m.created_at,s.modifiedAt),_=oh(m.content);if(_&&(a=_),nh(m)){let h=ih(m.content),g=h.trim();g&&(l||(l=U(g,80)),c=U(g,80)),o.push({role:"user",timestamp:p,content:h});continue}if(Array.isArray(m.tool_calls))for(let h of m.tool_calls){let g=h.name||"tool",f=zI(h.args),E=Je(h.args),y={role:"tool_use",timestamp:p,content:f,toolName:g,toolInput:f,toolInputData:E};o.push(y),d.push({name:g,stepIndex:m.step_index,input:E,message:y})}if(sh(m)&&m.content)o.push({role:"assistant",timestamp:p,content:m.content,model:a});else if(YI(m)&&m.content){let h=tx(m,n),g=h===void 0?null:await this.readTaskLog(n,h),f={role:"tool_result",timestamp:g?.modifiedAt??p,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:h,...g===null?{}:{toolDetailedContent:g.content}};o.push(f),u.push({event:m,message:f})}m.thinking&&o.push({role:"thinking",timestamp:p,content:m.thinking})}return rx(d,u),{...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 rh(r),r}catch{}let n=pt(this.baseDir,"conversations");try{let s=[];for(let i of await Zp(n)){if(!i.endsWith(".db"))continue;xl(i,".db").startsWith(e)&&s.push(pt(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=lh(r);return n?(await th(this.conversationPath(n),{force:!0}),await th(pt(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 QI(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=pt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await eh(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=pt(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([eh(n,"utf8"),ue(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as cx}from"node:child_process";import{StringDecoder as uh}from"node:string_decoder";function Ni(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 dx(t.label,r.binary,s,{cwd:r.cwd,env:we(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 dx(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=cx(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new uh("utf8"),d=new uh("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=d.write(m)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",u),i(m)}),o.on("close",(m,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),m===0){s({stdout:a,stderr:l});return}let _=p?`signal ${p}`:`exit code ${m}`,h=l.trim()||a.trim();i(new Error(`${t} failed (${_})${h?`: ${h}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var kl=k(()=>{"use strict";ut()});function Rl(t){return new Al(t)}function mx(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Al,ux,Nl=k(()=>{"use strict";dh();Be();$e();vt();kl();Al=class extends ee{constructor(e){super({provider:new Ri(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",G,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:ux})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},ux=Ni({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",mx(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Ie("agy",t,e.permissionMode??"yolo")})});import fx from"node:zlib";function vx(t,e){return t[e]===hx&&t[e+1]===gx&&t[e+2]===_x&&t[e+3]===yx}function mh(t,e){return(t[e]&240)===80&&t[e+1]===Ex&&t[e+2]===Tx&&t[e+3]===wx}function Sx(t,e){if(mh(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!vx(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,m=c>>3;if(r+=3,u===3||(r+=u===1?1:m,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function bx(t){let e=[],r=0;for(;r+4<=t.length;){let n=Sx(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Li(t){let e=[];for(let r of bx(t))mh(r,0)||e.push(px(r).toString("utf8"));return e.join("")}var px,hx,gx,_x,yx,Ex,Tx,wx,Ll=k(()=>{"use strict";px=fx.zstdDecompressSync,hx=40,gx=181,_x=47,yx=253,Ex=42,Tx=77,wx=24});import{readdir as Cl,rm as Ix,stat as xx}from"node:fs/promises";import{join as Yt}from"node:path";function kx(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Ol(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 Ax(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 fh(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:Ol(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of Ax(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Ol(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:Ol(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function Rx(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 ph(t,e,r){let n=t.find(p=>p.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let p of t)if(p.type==="request/header"){let _=p.data?.header;_?.config?.model&&(a=_.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,m=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...Nx(t)}}function Nx(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=Ci(c.inputTokens),u=Ci(c.cacheReadTokens),m=Ci(c.outputTokens),p=Ci(c.reasoningTokens);r+=d,n+=u,s+=m,i+=p,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:m,reasoningOutputTokens:p,totalTokens:d+u+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 Ci(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var Oi,hh=k(()=>{"use strict";be();Ll();Oi=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||Yt(H,".dsh");this.sessionsDir=Yt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Cl(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Cl(Yt(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=fh(n),i=ph(n,r.filePath,s);return i?{...i,turnStatus:Rx(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 Ix(Yt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return Yt(this.sessionsDir,kx(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Cl(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=Yt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await xx(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=Yt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Li(i),a=[];for(let l of o.split(`
|
|
1604
|
+
`):"":""}function Kp(t){return t.model||t.message?.model}function qI(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:zp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Jn(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 GI(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Jn(e.output??e.error??t)}return Jn(t)}function zp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function Yp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Jn(t.args,!0),toolInputData:Ve(t.args),toolCallId:t.id,model:r}}var Ai,Qp=k(()=>{"use strict";be();Ai=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Kt(H,".qwen")}async discoverSessions(){let e=Kt(this.baseDir,"projects"),r;try{r=await ki(e)}catch{return[]}let n=[];for(let s of r){let i=Kt(e,s,"chats"),o;try{o=await ki(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Kt(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await ue(e),i="(unknown)",o,a,l,c,d=0;for await(let u of ce(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Gp(u)){let m=Vp(u).trim();m&&(l||(l=U(m,80)),c=U(m,80),d++)}if(Jp(u)){let m=Kp(u);m&&(o=m),d+=qI(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=qp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await ue(e),s="(unknown)",i,o,a,l,c,d,u=[],m=WI();for await(let p of ce(e)){if(HI(m,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let _=p.message,h=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let g=zp(p).filter(f=>f.functionResponse!==void 0);g.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:h,content:Jn(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let f of g){let E=f.functionResponse,y=GI(E.response),T=Jn(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:h,content:T??y??p.toolCallResult?.status??"tool result",toolName:E.name,toolCallId:p.toolCallResult?.callId??E.id,...y!==void 0?{toolDetailedContent:y}:{}})}}else if(Gp(p)){let g=Vp(p);g.trim()&&(c||(c=U(g.trim(),80)),d=U(g.trim(),80)),u.push({role:"user",timestamp:h,content:g})}else if(Jp(p)){let g=Kp(p);if(g&&(i=g),Array.isArray(_.content))for(let f of _.content)f.type==="text"&&f.text?u.push({role:"assistant",timestamp:h,content:f.text,model:g}):f.type==="thinking"&&f.thinking?u.push({role:"thinking",timestamp:h,content:f.thinking}):f.functionCall&&u.push(Yp(f.functionCall,h,g));else if(typeof _.content=="string")u.push({role:"assistant",timestamp:h,content:_.content,model:g});else if(Array.isArray(_.parts))for(let f of _.parts)if(f.thought||f.type==="thinking"){let E=f.thinking||f.text;E&&u.push({role:"thinking",timestamp:h,content:E})}else f.functionCall?u.push(Yp(f.functionCall,h,g)):f.text&&u.push({role:"assistant",timestamp:h,content:f.text,model:g})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...XI(m),messages:u}}async resolveSessionPath(e){let r=Kt(this.baseDir,"projects");try{let n=await ki(r),s=[];for(let i of n){let o=Kt(r,i,"chats",`${e}.jsonl`);try{return await jI(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Kt(r,i,"chats"),a;try{a=await ki(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;qp(l,".jsonl").startsWith(e)&&s.push(Kt(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 BI(r),!0}catch{return!1}}}});function bl(){return new Sl}var Sl,Il=k(()=>{"use strict";Qp();Be();St();$e();Sl=class extends ee{constructor(){super({provider:new Ai,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",G,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:_i})}openSession(e){return yi({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Zp,readFile as eh,rm as th,stat as rh}from"node:fs/promises";import{basename as xl,join as pt}from"node:path";import{fileURLToPath as JI}from"node:url";async function VI(t){let e=await Promise.all(t.map(r=>ue(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 KI(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function nh(t){return t.type==="USER_INPUT"}function sh(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function YI(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function ih(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function oh(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 zI(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function QI(t){for await(let e of ce(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=ZI(s);if(i)return i}let n=ex(e.content);if(n)return n}return null}function ZI(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 ex(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function tx(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 rx(t,e){let r=new Set;for(let n of e){let s=nx(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 nx(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:ax(r.event.content);if(n!==void 0)return ah(t.filter(i=>!e.has(i)&&lx(i)===n),r.event.step_index);let s=ox(r.event);if(s!==void 0)return ah(t.filter(i=>!e.has(i)&&sx(i.name,r.event.type)&&ch(ix(i))===s),r.event.step_index)}function ah(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 sx(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 ix(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function ox(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]),ch(e)}function ch(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return JI(e)}catch{return}}function ax(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function lx(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 lh(t){if(t.endsWith(".db"))return xl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ri,dh=k(()=>{"use strict";be();Ri=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||pt(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:pt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=pt(this.baseDir,"conversations"),r;try{r=await Zp(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=xl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return pt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return pt(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 rh(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await VI([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of ce(n)){let m=oh(u.content);if(m&&(a=m),nh(u)){let p=ih(u.content).trim();p&&(l||(l=U(p,80)),c=U(p,80)),d++}else sh(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=lh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,d=[],u=[];if(i)for await(let m of ce(i)){let p=KI(m.created_at,s.modifiedAt),_=oh(m.content);if(_&&(a=_),nh(m)){let h=ih(m.content),g=h.trim();g&&(l||(l=U(g,80)),c=U(g,80)),o.push({role:"user",timestamp:p,content:h});continue}if(Array.isArray(m.tool_calls))for(let h of m.tool_calls){let g=h.name||"tool",f=zI(h.args),E=Ve(h.args),y={role:"tool_use",timestamp:p,content:f,toolName:g,toolInput:f,toolInputData:E};o.push(y),d.push({name:g,stepIndex:m.step_index,input:E,message:y})}if(sh(m)&&m.content)o.push({role:"assistant",timestamp:p,content:m.content,model:a});else if(YI(m)&&m.content){let h=tx(m,n),g=h===void 0?null:await this.readTaskLog(n,h),f={role:"tool_result",timestamp:g?.modifiedAt??p,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:h,...g===null?{}:{toolDetailedContent:g.content}};o.push(f),u.push({event:m,message:f})}m.thinking&&o.push({role:"thinking",timestamp:p,content:m.thinking})}return rx(d,u),{...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 rh(r),r}catch{}let n=pt(this.baseDir,"conversations");try{let s=[];for(let i of await Zp(n)){if(!i.endsWith(".db"))continue;xl(i,".db").startsWith(e)&&s.push(pt(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=lh(r);return n?(await th(this.conversationPath(n),{force:!0}),await th(pt(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 QI(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=pt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await eh(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=pt(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([eh(n,"utf8"),ue(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as cx}from"node:child_process";import{StringDecoder as uh}from"node:string_decoder";function Ni(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 dx(t.label,r.binary,s,{cwd:r.cwd,env:we(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 dx(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=cx(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new uh("utf8"),d=new uh("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=d.write(m)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",u),i(m)}),o.on("close",(m,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),m===0){s({stdout:a,stderr:l});return}let _=p?`signal ${p}`:`exit code ${m}`,h=l.trim()||a.trim();i(new Error(`${t} failed (${_})${h?`: ${h}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var kl=k(()=>{"use strict";ut()});function Rl(t){return new Al(t)}function mx(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Al,ux,Nl=k(()=>{"use strict";dh();Be();$e();vt();kl();Al=class extends ee{constructor(e){super({provider:new Ri(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",G,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:ux})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},ux=Ni({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",mx(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Ie("agy",t,e.permissionMode??"yolo")})});import fx from"node:zlib";function vx(t,e){return t[e]===hx&&t[e+1]===gx&&t[e+2]===_x&&t[e+3]===yx}function mh(t,e){return(t[e]&240)===80&&t[e+1]===Ex&&t[e+2]===Tx&&t[e+3]===wx}function Sx(t,e){if(mh(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!vx(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,m=c>>3;if(r+=3,u===3||(r+=u===1?1:m,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function bx(t){let e=[],r=0;for(;r+4<=t.length;){let n=Sx(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Li(t){let e=[];for(let r of bx(t))mh(r,0)||e.push(px(r).toString("utf8"));return e.join("")}var px,hx,gx,_x,yx,Ex,Tx,wx,Ll=k(()=>{"use strict";px=fx.zstdDecompressSync,hx=40,gx=181,_x=47,yx=253,Ex=42,Tx=77,wx=24});import{readdir as Cl,rm as Ix,stat as xx}from"node:fs/promises";import{join as Yt}from"node:path";function kx(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Ol(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 Ax(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 fh(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:Ol(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of Ax(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Ol(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:Ol(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function Rx(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 ph(t,e,r){let n=t.find(p=>p.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let p of t)if(p.type==="request/header"){let _=p.data?.header;_?.config?.model&&(a=_.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,m=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...Nx(t)}}function Nx(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=Ci(c.inputTokens),u=Ci(c.cacheReadTokens),m=Ci(c.outputTokens),p=Ci(c.reasoningTokens);r+=d,n+=u,s+=m,i+=p,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:m,reasoningOutputTokens:p,totalTokens:d+u+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 Ci(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var Oi,hh=k(()=>{"use strict";be();Ll();Oi=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||Yt(H,".dsh");this.sessionsDir=Yt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Cl(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Cl(Yt(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=fh(n),i=ph(n,r.filePath,s);return i?{...i,turnStatus:Rx(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 Ix(Yt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return Yt(this.sessionsDir,kx(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Cl(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=Yt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await xx(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=Yt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Li(i),a=[];for(let l of o.split(`
|
|
1605
1605
|
`))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=Yt(this.sessionsDir,e,r,"session.jsonl.zstd");return ph(n,s,fh(n))}}});import{spawn as Lx}from"node:child_process";async function Di(t,e=r=>Dl.spawn(r)){if(zt){let r=await zt.catch(()=>{});if(r?.alive)return r;zt=void 0}return zt=e(t),zt}async function Vn(){if(!zt)return;(await zt.catch(()=>{}))?.shutdown(),zt=void 0}var Cx,gh,Yr,Dl,zt,_h=k(()=>{"use strict";Cx=/dsh web:\s*(https?:\/\/\S+)/,gh=2e4,Yr=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)}},Dl=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 Yr(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 Yr(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 Yr(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new Yr(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=Lx("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 ${gh}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},gh);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let d=Cx.exec(o);d&&(i=!0,clearTimeout(l),r(new t(d[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,d)=>{if(i)return;i=!0,clearTimeout(l);let u=d?`signal ${d}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${u}): ${a.slice(0,500)}`))})})}}});import{randomUUID as Ox}from"node:crypto";import{existsSync as yh}from"node:fs";import{readFile as Dx,mkdir as Mx}from"node:fs/promises";function Pl(t){return new Fl(t)}function $l(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function Fx(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 Mi(t){return t instanceof Error?t.message:String(t)}async function Px(t){let e=await Eh(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 Eh(t){let e;try{e=await Dx(t)}catch{return[]}let r=Li(e),n=[];for(let s of r.split(`
|
|
1606
1606
|
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function Ux(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 $x,Ml,Fl,Ul=k(()=>{"use strict";Be();hh();Ll();_h();$e();vt();$x=500,Ml=8*60*60*1e3;Fl=class extends ee{dshProvider;constructor(e){let r=new Oi(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 Mx(e,{recursive:!0});let n=`session-${Ox()}`,s=$l(process.env);Ie("dsh",[],"yolo");try{let i;try{i=await Di(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Mi(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Mi(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: ${Mi(a)}`}}let o=r?.prompt??G;try{await this.promptAndWait(i,e,n,o,Ml)}catch(a){return{success:!1,error:`seed turn failed: ${Mi(a)}`}}return{success:!0,sessionId:n}}finally{await Vn()}}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=$l(r.env??process.env);Ie("dsh",[],r.permissionMode??"yolo");let i;try{let o=await Di(s);r.model&&(await o.rpc("session.selectModel",{sessionId:r.sessionId,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,r.cwd,r.sessionId,e,r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Ml)}finally{await Vn()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:r.sessionId,durationMs:Date.now()-n}}async openSession(e){let r=$l(e.env??process.env);Ie("dsh",[],e.permissionMode??"yolo");let n=await Di(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!yh(s))throw await Vn(),new Error(`dsh bundle: session file does not exist for session "${e.sessionId}" (${s}) \u2014 the session must exist before a bundle can resume it`);e.model&&await n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,d=!1,u=!1,m=async()=>{u||(u=!0,await Vn())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(p,_={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(d)throw new Error("dsh bundle session has a turn still in flight");if(_.signal?.aborted)throw new Error("Aborted");if(!yh(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);d=!0;let h=Date.now();try{let g=o.promptAndWait(n,e.cwd,i,p,Ml,_.signal);g.catch(()=>{});let f=await Promise.race([g,new Promise((E,y)=>{_.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await m()})().finally(()=>y(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:f,sessionId:i,durationMs:Date.now()-h}}finally{d=!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 Px(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=Date.now()+i;for(;;){if(o?.aborted)throw new Error("Aborted");let d=await Eh(a),u=d.find(m=>m.type==="turn/end"&&(m.seq??-1)>l);if(u){let m=u.data?.reason,p=[...d].reverse().find(h=>h.type==="assistant/message"),_=p?Ux(p):"";if(m?.kind!=="completed"&&!_)throw new Error(Fx(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,$x))}}}});import{existsSync as jx}from"node:fs";import{join as bh,resolve as Bx}from"node:path";import{createRequire as Wx}from"node:module";function Hx(){return jl===null&&(jl=Wx(import.meta.url)("node:sqlite").DatabaseSync),jl}function Bl(t={}){return Bx(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||bh(H,".hermes"))}function Xx(t={}){return bh(Bl(t),"state.db")}function Kn(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function Fe(t){return typeof t=="string"&&t.length>0?t:void 0}function qx(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function vh(t){return Fe(t.cwd)??Fe(qx(t.model_config).cwd)??"(unknown)"}function Gx(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function Jx(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 Sh(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 jl,Th,wh,$i,Ih=k(()=>{"use strict";be();J();jl=null;Th="acp";wh=`id, source, model, model_config, started_at,
|
|
1607
1607
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
@@ -1610,7 +1610,7 @@ ${r}`:r}function Bb(t,e){return jn(t)?.filterExpectedStderr?.(e)??e}function lp(
|
|
|
1610
1610
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1611
1611
|
LIMIT ?`).all(Th,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:Fe(s.title),cwd:vh(s),createdAt:Kn(s.started_at),modifiedAt:Kn(s.last_activity_at??s.started_at),model:Fe(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...Sh(s)})}return n}catch(r){return L({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,
|
|
1612
1612
|
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 = ?
|
|
1613
|
-
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?U(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Kn(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=U(u,80)),l=U(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:Fe(c.tool_call_id),toolName:Fe(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Fe(n.model),stopReason:Fe(c.finish_reason)});for(let m of Gx(c.tool_calls)){let p=Jx(m.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Fe(m.function?.name)??"tool_call",toolName:Fe(m.function?.name),toolCallId:Fe(m.call_id)??Fe(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Je(p)})}}return{provider:this.name,sessionId:n.id,slug:Fe(n.title),cwd:vh(n),createdAt:Kn(n.started_at),modifiedAt:Kn(n.last_activity_at??n.started_at),model:Fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Sh(n),messages:i,userPrompts:o}}catch(n){return L({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 Vx}from"node:fs/promises";function Yx(t){return Kx.test(t)}function xh(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 zx}function Hl(t){return new Wl(t)}var Kx,zx,Wl,Xl=k(()=>{"use strict";Be();Ih();St();$e();J();Kx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;zx="dont_ask";Wl=class extends ee{hermesProvider;hermesHome;constructor(e){let r=new $i(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)=>mt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:xh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Bl(e)}async openSession(e){return ft({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:xh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Vx(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({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??G,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return Yx(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({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 kh,rm as Qx,stat as Zx}from"node:fs/promises";import{join as ql}from"node:path";function Gl(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 Ah(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Fi,Rh=k(()=>{"use strict";be();Fi=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||ql(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 kh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=ql(this.baseDir,n);try{if(!(await Zx(s)).isDirectory())continue;for(let i of await kh(s))i.endsWith(".jsonl")&&r.push(ql(s,i))}catch{}}return r}async readHeader(e){for await(let r of ce(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 ue(e),s,i,o,a=0,l=0,c=0,d=0,u=0,m=0,p=0,_;for await(let h of ce(e)){if(h.type==="model_change"&&h.provider&&h.modelId){s=`${h.provider}/${h.modelId}`;continue}if(h.type!=="message"||!h.message)continue;let g=h.message;if(g.provider&&g.model&&(s=`${g.provider}/${g.model}`),g.role==="user"){let f=Gl(g).trim();f&&(i||(i=U(f,80)),o=U(f,80)),a++}else if(g.role==="assistant"){a++;let f=g.usage;f&&(l+=f.input??0,c+=f.cacheRead??0,d+=f.cacheWrite??0,u+=f.output??0,m+=f.reasoning??0,p=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:d,totalOutputTokens:u,totalReasoningOutputTokens:m,lastInputTokens:p,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 ce(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:Gl(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:Ah(c.arguments),toolName:c.name??"tool",toolInput:Ah(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Gl(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 Qx(r,{force:!0}),!0):!1}}});function Vl(t){return new Jl(t)}var Jl,ek,Kl=k(()=>{"use strict";Rh();Be();$e();vt();kl();Jl=class extends ee{constructor(e){super({provider:new Fi(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",G],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:ek})}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}`}}},ek=Ni({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Ie("pi",t,e.permissionMode??"yolo")})});import{createHash as tk}from"node:crypto";import{existsSync as rk,mkdirSync as zl,readFileSync as nk,renameSync as sk,rmdirSync as Fh,statSync as ik,writeFileSync as ok}from"node:fs";import{dirname as tc,join as Nh,resolve as Yl}from"node:path";function ak(t){return tk("sha256").update(t).digest("hex").slice(0,8)}function lk(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function ck(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 Ph(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Pi(t){return Math.max(1,Math.ceil(t.length/4))}function Qr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Yl(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Nh(tc(Yl(r)),".lmctl-claude-mock","sessions.json"):Nh(Yl(t),".lmctl-claude-mock","sessions.json")}function Lh(){return{schemaVersion:1,sessions:{}}}function Yn(t){if(!rk(t))return Lh();try{let e=JSON.parse(nk(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=Ql(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Lh()}}function Uh(t,e){zl(tc(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;ok(r,`${JSON.stringify(e,null,2)}
|
|
1613
|
+
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?U(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Kn(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=U(u,80)),l=U(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:Fe(c.tool_call_id),toolName:Fe(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Fe(n.model),stopReason:Fe(c.finish_reason)});for(let m of Gx(c.tool_calls)){let p=Jx(m.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Fe(m.function?.name)??"tool_call",toolName:Fe(m.function?.name),toolCallId:Fe(m.call_id)??Fe(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Ve(p)})}}return{provider:this.name,sessionId:n.id,slug:Fe(n.title),cwd:vh(n),createdAt:Kn(n.started_at),modifiedAt:Kn(n.last_activity_at??n.started_at),model:Fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Sh(n),messages:i,userPrompts:o}}catch(n){return L({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 Vx}from"node:fs/promises";function Yx(t){return Kx.test(t)}function xh(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 zx}function Hl(t){return new Wl(t)}var Kx,zx,Wl,Xl=k(()=>{"use strict";Be();Ih();St();$e();J();Kx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;zx="dont_ask";Wl=class extends ee{hermesProvider;hermesHome;constructor(e){let r=new $i(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)=>mt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:xh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Bl(e)}async openSession(e){return ft({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:xh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Vx(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({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??G,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return Yx(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({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 kh,rm as Qx,stat as Zx}from"node:fs/promises";import{join as ql}from"node:path";function Gl(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 Ah(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Fi,Rh=k(()=>{"use strict";be();Fi=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||ql(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 kh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=ql(this.baseDir,n);try{if(!(await Zx(s)).isDirectory())continue;for(let i of await kh(s))i.endsWith(".jsonl")&&r.push(ql(s,i))}catch{}}return r}async readHeader(e){for await(let r of ce(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 ue(e),s,i,o,a=0,l=0,c=0,d=0,u=0,m=0,p=0,_;for await(let h of ce(e)){if(h.type==="model_change"&&h.provider&&h.modelId){s=`${h.provider}/${h.modelId}`;continue}if(h.type!=="message"||!h.message)continue;let g=h.message;if(g.provider&&g.model&&(s=`${g.provider}/${g.model}`),g.role==="user"){let f=Gl(g).trim();f&&(i||(i=U(f,80)),o=U(f,80)),a++}else if(g.role==="assistant"){a++;let f=g.usage;f&&(l+=f.input??0,c+=f.cacheRead??0,d+=f.cacheWrite??0,u+=f.output??0,m+=f.reasoning??0,p=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:d,totalOutputTokens:u,totalReasoningOutputTokens:m,lastInputTokens:p,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 ce(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:Gl(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:Ah(c.arguments),toolName:c.name??"tool",toolInput:Ah(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Gl(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 Qx(r,{force:!0}),!0):!1}}});function Vl(t){return new Jl(t)}var Jl,ek,Kl=k(()=>{"use strict";Rh();Be();$e();vt();kl();Jl=class extends ee{constructor(e){super({provider:new Fi(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",G],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:ek})}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}`}}},ek=Ni({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Ie("pi",t,e.permissionMode??"yolo")})});import{createHash as tk}from"node:crypto";import{existsSync as rk,mkdirSync as zl,readFileSync as nk,renameSync as sk,rmdirSync as Fh,statSync as ik,writeFileSync as ok}from"node:fs";import{dirname as tc,join as Nh,resolve as Yl}from"node:path";function ak(t){return tk("sha256").update(t).digest("hex").slice(0,8)}function lk(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function ck(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 Ph(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Pi(t){return Math.max(1,Math.ceil(t.length/4))}function Qr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Yl(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Nh(tc(Yl(r)),".lmctl-claude-mock","sessions.json"):Nh(Yl(t),".lmctl-claude-mock","sessions.json")}function Lh(){return{schemaVersion:1,sessions:{}}}function Yn(t){if(!rk(t))return Lh();try{let e=JSON.parse(nk(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=Ql(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Lh()}}function Uh(t,e){zl(tc(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;ok(r,`${JSON.stringify(e,null,2)}
|
|
1614
1614
|
`,"utf8"),sk(r,t)}function mk(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function fk(t){let e=`${t}.lock`;zl(tc(t),{recursive:!0});let r=Date.now()+Ch;for(;;)try{return zl(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-ik(e).mtimeMs>dk){try{Fh(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${Ch}ms: ${e}`);mk(uk)}}function pk(t){try{Fh(t)}catch{}}function jh(t,e){let r=fk(t);try{return e()}finally{pk(r)}}function hk(t){return{...t,timestamp:t.timestamp.toISOString()}}function gk(t){return{...t,timestamp:new Date(t.timestamp)}}function _k(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(hk)}}function Bh(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(gk)}}function Ui(t,e=process.cwd()){let r=zr.get(t);if(r!==void 0)return r;let s=Yn(Qr(e)).sessions[t];if(s===void 0)return;let i=Bh(s);return zr.set(i.sessionId,i),i}function Oh(t){zr.set(t.sessionId,t);let e=Qr(t.cwd);jh(e,()=>{let r=Yn(e);r.sessions[t.sessionId]=_k({...t,filePath:e}),Uh(e,r)})}function yk(t,e=process.cwd()){let r=Qr(e);return jh(r,()=>{let n=Yn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Uh(r,n)),s})}function Ek(){let t=Yn(Qr()),e=Object.values(t.sessions).map(Bh);for(let r of e)zr.set(r.sessionId,r);return e}function Ql(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Dh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Ql(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=Ql(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Mh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function Tk(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Dh(r[t]??r[Ph(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Dh(n[s]);if(i!==void 0)return i}}}function $h(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 rc(){return new ec}var zr,dk,uk,Ch,Zl,ec,nc=k(()=>{"use strict";zr=new Map;dk=5e3,uk=15,Ch=1e4;Zl=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of Ek())e.set(r.sessionId,r);for(let r of zr.values())e.set(r.sessionId,r);return[...e.values()].map($h)}async loadSession(e){let r=Ui(e);return r===void 0?null:{...$h(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Ui(e)?.filePath??null}async deleteSession(e){let r=zr.delete(e),n=yk(e);return r||n}},ec=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Zl;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=lk(ck(e,r)),s=`mock-${n}-${ak(`${e}:${n}`)}`,i=new Date,o=Qr(e),a=Ui(s,e),l=r?.prompt??"ClaudeMock seed",c=Pi(l),d={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=Pi("ACK: ClaudeMock seeded"),Oh(d),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Ui(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Yn(Qr(r.cwd)),a=Tk(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Mh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Ph(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+=Pi(e),s.totalOutputTokens+=Pi(c),Oh(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Mh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function Qt(t){let e=[Ya({claudeDir:t?.claudeDir}),el({codexDir:t?.codexDir,codeDir:t?.codeDir}),ol({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),dl({copilotDir:t?.copilotDir}),fl(),yl({kimiHome:t?.kimiHome}),wl({lmplayerDbPath:t?.lmplayerDbPath}),bl(),Rl({agyDir:t?.agyDir}),Pl({dshHome:t?.dshHome}),Hl({hermesHome:t?.hermesHome}),Vl({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(rc()),e}var sc=k(()=>{"use strict";za();tl();al();ul();pl();El();vl();Il();Nl();Ul();Xl();Kl();nc();za();tl();al();ul();pl();El();vl();Il();Nl();Ul();Xl();Kl();nc()});var hr,Zr,Wh=k(()=>{"use strict";hr=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Zr=["agy","pi","lmplayer"]});var lc={};se(lc,{BUNDLE_CAPABLE_PROVIDERS:()=>hr,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Zr,ProviderRegistry:()=>bn,TransportConnectionError:()=>te,TransportError:()=>Ht,TransportJsonError:()=>ti,TransportProcessError:()=>kn,TransportRpcError:()=>An,_resetDefaultRegistryForTests:()=>wk,bundleSupportedProviders:()=>tn,chat:()=>gr,countTokens:()=>Sk,createAdapterRegistry:()=>Wt,createAllAdapters:()=>Qt,listSessions:()=>ac,openBundleSession:()=>zn,seed:()=>oc});function en(){return ji===null&&(ji=Wt(Qt())),ji}function wk(){ji=null}function ic(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function gr(t){let e=t.registry??en(),r=ic(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 tn(t){return(t??en()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function zn(t){let e=t.registry??en(),r=ic(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${tn(e).join(", ")})`);return r.openSession(t)}async function oc(t){let e=t.registry??en(),r=ic(e,t.provider),n=await Hh(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await Hh(e,t.provider,t.cwd),a=vk(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function Hh(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 vk(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 ac(t={}){return(t.registry??en()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function Sk(t){let r=await(t.registry??en()).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 ji,bt=k(()=>{"use strict";va();sc();va();sc();Wh();dr();ji=null});function Bi(t){return Ik.has(t)}function dc(){return cc===null&&(cc=Wt(Qt())),cc}function uc(t,e,r={}){if(!Bi(t))return null;try{let n=dc().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?ai({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?bk[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,...Xh[t]??[]]}catch{return null}}function Gh(t,e,r={}){let n=uc(t,e,r);return n===null?null:n.join(" ")}function xe(t,e){return dc().getSession(t,e)}async function rn(t){return(await dc().resolveSessions(t)).map(r=>r.provider.name)}var Xh,bk,Ik,qh,cc,Zt=k(()=>{"use strict";bt();Ca();Xh={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:[]},bk={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]},Ik=new Set(Object.keys(Xh)),qh=/^[\w.:-]+$/;cc=null});function xk(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Jh;let r=Number(e);return!Number.isFinite(r)||r<=0?Jh:r}async function kk(t,e,r){try{let n=fe(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 rn(s);if(c.length!==1)return null;i=c[0]}let o=await xe(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 Vh(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??xk(),o=await kk(t,r,n),a=o!==null&&o>=i;return a&&L({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}var Jh,Kh=k(()=>{"use strict";J();Zt();Ue();Jh=36e5});function Ak(t){return t===null?null:Ne(t)?"live":"dead"}function mc(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:Ak(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function Rk(t){return(0,Yh.formatDuration)(t)}function fc(t){let e=[];return t.idle_ms!==null&&e.push(`active ${Rk(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var Yh,zh=k(()=>{"use strict";lr();Yh=_t(dt(),1)});import{randomUUID as Nk}from"node:crypto";import{hostname as Qh,networkInterfaces as Lk}from"node:os";function Zh(t){let e=(t.now??new Date).toISOString();return{lock_id:Nk(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??Qh(),holder_ips:t.ips??$k(),started_at:e,last_heartbeat:e}}function eg(t=process.env){return tg(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,Ck)}function Dk(t=process.env){return tg(t.LMCTL_TERMINAL_LOCK_STALE_MS,Ok)}function pc(t,e={}){let r=e.now??new Date,n=e.localHost??Qh(),s=e.staleMs??Dk();if(t.holder_host===n)return(e.isProcessAlive??Mk)(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 _r(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function tg(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 Mk(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 $k(){let t=new Set;for(let e of Object.values(Lk()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var Ck,Ok,Qn=k(()=>{"use strict";Ck=15e3,Ok=12e4});function Fk(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
1615
1615
|
manually, outside a member session that lmctl started. Running lmctl this way is
|
|
1616
1616
|
not officially supported.
|
|
@@ -1618,9 +1618,9 @@ To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}
|
|
|
1618
1618
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
1619
1619
|
Consulted ${hn(he())}
|
|
1620
1620
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function rg(t){return`unknown option --from
|
|
1621
|
-
${Fk(t)}`}function nn(t,e){let r=hc(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function hc(t,e){let r=t[ba];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=
|
|
1621
|
+
${Fk(t)}`}function nn(t,e){let r=hc(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function hc(t,e){let r=t[ba];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=Xe(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]}}var sn=k(()=>{"use strict";ut();nt();Tt()});function xt(t){let e=Ps(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var Zn=k(()=>{"use strict";Ue()});function es(t,e,r){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=Ze({path:he()})),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&&Ne(a.holder_pid)),pollMs:Pk,settleMs:Uk,maxHoldMs:Pr(r),onHold:()=>L({event:"delivery_hold_open_started",receiver:n}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&L({event:"delivery_hold_open_released",receiver:n,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function ng(t){let e=jk(t.newMessage,{newMessageFrom:t.newMessageFrom??Bk(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=z(),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=es(t.io,t.receiver,t.env),await t.onPromptBuilt?.(e);let l=await gr(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&&Ee(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 jk(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
1622
1622
|
`)}function Bk(t){return`${t.teamfile}:${t.alias}`}var Ej,Pk,Uk,Wi=k(()=>{"use strict";bt();J();Ut();nt();lr();Qe();Ej=60*60*1e3,Pk=2e3,Uk=5e3});async function Er(t){let e=t.onEvent??(()=>{}),r=Wk(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,d=null,u=t.prompt;try{let m=await C(r,N=>fe(t.teamfile,t.alias,N));if(t.expectedSession!==void 0&&(m.provider!==t.expectedSession.provider||m.sessionid!==t.expectedSession.sessionid))throw new ie(`session changed for ${m.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${m.provider}:${m.sessionid}`);let p=m.teamfile,_=await C(r,N=>Zk(N,t.env??process.env)),h=_.sender,g=await eA(r,{explicitRoot:t.rootFlag,sender:h,receiverTeamfile:p,operatorOrigin:_.origin==="operator"}),f=h===null?null:await tA(r,{rootTeamfile:g,sender:h,receiverTeamfile:p,receiverAlias:m.alias});f!==null&&!f.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${f.reason}
|
|
1623
|
-
`});let E=t.env??process.env,y=await C(r,N=>N.getRootTeam(g)?.name??null);y!==null&&(E.LMBEE_TEAM_NAME=y),i=await Gk(r,{receiverTeamfile:p,receiverAlias:m.alias,sender:h,rootTeamfile:g,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:Bt(E.LMCTL_INVOCATION_ID)}),o=Yk(r,i),i!==null&&(E.LMCTL_INVOCATION_ID=String(i));try{Dr(r,Ae(p),p)}catch{}n={root_teamfile:g,sender_teamfile:h?.teamfile??null,sender_alias:h?.alias??null,receiver_teamfile:p,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:_.origin,message_type:t.messageType??null,policy:f};let T=await cg(r,p,m.alias);if(T!==null){let N=_r(T);return yr(i,n,t.prompt,N,"unavailable"),d=gc(N,null),{status:"busy",message:N,teamChatLogId:null}}let b=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,K=>{let le=K.getAgentInflight(p,m.alias);return le===null||le.sender_teamfile!==N.row.sender_teamfile||le.sender_alias!==N.row.sender_alias||le.started_at!==N.row.started_at||le.holder_pid!==process.pid?!1:K.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let K=`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 yr(i,n,t.prompt,K,"unavailable"),d=ts(K,null),{status:"error",errorKind:"provider",message:K,teamChatLogId:null,messageId:null}}}else{let N=await Hk(r,p,m.alias);if(N.busy){let B=await Xk(r,p,m.alias);return B+=await qk(r,p,m.alias),yr(i,n,t.prompt,B,"unavailable"),d=gc(B,null),{status:"busy",message:B,teamChatLogId:null}}b=N.idleReclaim}if(h!==null&&h.teamfile!==p){let N=await C(r,B=>rm(B,{root:g,sender:h,receiverTeamfile:p,receiverAlias:m.alias,now:new Date}));if(N.stop){let B=sm(N.chain);return yr(i,n,t.prompt,B,"cycle"),d=ts(B,null),{status:"error",errorKind:"cycle",message:B,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await sA(r,{receiver_teamfile:p,receiver_alias:m.alias,sender_teamfile:h?.teamfile??p,sender_alias:h?.alias??"operator",...b?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let B=dg(p,m.alias,N.current);return B+=` ${fc(mc({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,yr(i,n,t.prompt,B,"unavailable"),d=gc(B,null),{status:"busy",message:B,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=Fr(B=>C(r,K=>K.heartbeatAgentInflight(s.row,s.leaseId,B)),{intervalMs:ag,onError:B=>{z()&&Ee(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:B instanceof Error?B.message:String(B)}))}})}let v=await ng({sender:h??{teamfile:p,alias:"operator"},receiver:{teamfile:p,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:h===null?"operator":`${h.teamfile}:${h.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:N=>e({kind:"delta",chunk:N}),onProgress:N=>e({kind:"progress",alias:m.alias,event:N}),onPromptBuilt:async N=>{u=N,l===null&&(l=await oA(r,{...n,message:N}),l!==null&&(t.onAccepted?.(wt(l)),i!==null&&await Kk(r,i,l))),i!==null&&await Vk(r,i,N)}});u=v.prompt;let S=v.status==="stalled",w=v.status==="empty",x=null,I=S?`provider stalled${v.stalledAfterMs!==void 0?` after ${v.stalledAfterMs}ms`:""}`:w?"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":v.status==="error"?v.error??v.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=S||w||v.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await og(r,l,{...n,message:u,response:v.receipt,status:R,error_detail:I}),c=!0,x=l):x=await lA(r,{...n,message:u,response:v.receipt,status:R,error_detail:I});let F=v.status!=="error"?v.warnings:void 0;if(S||w){let N=I;yr(i,n,u,N,"error"),d=ts(N,x,v.receipt,F)}else d=zk(v.receipt,x,F);return{status:S?"stalled":w?"empty":"ok",replyText:v.receipt,wroteDelta:v.wroteDelta,teamChatLogId:x,messageId:x===null?null:wt(x),durationMs:v.durationMs}}catch(m){let p=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await og(r,l,{...n,message:u,response:null,status:"error",error_detail:p}),c=!0),yr(i,n,u,p,"error"),d=ts(p,l),{status:"error",errorKind:m instanceof ie?"target":"provider",message:p,teamChatLogId:l,messageId:l===null?null:wt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await aA(r,n,wt(l)),s!==null&&await iA(r,s.row,s.leaseId),i!==null&&await Jk(r,i,d??ts("chat turn exited without a terminal outcome",null))}}function Wk(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function Hk(t,e,r){let n=await C(t,i=>(Br(i,e,r),lt(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>Vh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function Xk(t,e,r){let n=await cg(t,e,r);if(n!==null)return _r(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?dg(e,r,s):`${r} is busy; wait and retry`}async function qk(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${fc(mc({holderPid:n.holder_pid,since:n.started_at}))}`}async function Gk(t,e){try{return(await C(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:Qk(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 z()&&Ee(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function Jk(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Vk(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Kk(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function Yk(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&Ee(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},ag);return r.unref?.(),r}function lg(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function zk(t,e,r){return{status:"done",result_summary:rs(t),error:null,team_chat_log_id:e,...lg(r)}}function gc(t,e){return{status:"busy",result_summary:rs(t),error:t,team_chat_log_id:e}}function ts(t,e,r,n){return{status:"error",result_summary:rs(r===void 0?t:r),error:t,team_chat_log_id:e,...lg(n)}}function rs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function Qk(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function Zk(t,e){let r=nn(e,t);if(r.ok)return{sender:xt(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(It("chat"))}async function eA(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>ge(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>nm(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function tA(t,e){return await C(t,r=>Qu({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:rA(r,e.sender.teamfile,e.receiverTeamfile)}))}function rA(t,e,r){return{teams:[e,r].map(s=>nA(s,t))}}function nA(t,e){let r=He(t,e),n=Ot(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function sA(t,e){return await C(t,r=>{let n=z(),s=$t(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:at(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Ee(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:ig(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Ee(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:ig(s.current)})),{acquired:!1,current:s.current})})}async function cg(t,e,r){return await C(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(pc(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:pc(s).live?s:null})}function ig(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 iA(t,e,r){try{await C(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)}
|
|
1623
|
+
`});let E=t.env??process.env,y=await C(r,N=>N.getRootTeam(g)?.name??null);y!==null&&(E.LMBEE_TEAM_NAME=y),i=await Gk(r,{receiverTeamfile:p,receiverAlias:m.alias,sender:h,rootTeamfile:g,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:Bt(E.LMCTL_INVOCATION_ID)}),o=Yk(r,i),i!==null&&(E.LMCTL_INVOCATION_ID=String(i));try{Dr(r,Ae(p),p)}catch{}n={root_teamfile:g,sender_teamfile:h?.teamfile??null,sender_alias:h?.alias??null,receiver_teamfile:p,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:_.origin,message_type:t.messageType??null,policy:f};let T=await cg(r,p,m.alias);if(T!==null){let N=_r(T);return yr(i,n,t.prompt,N,"unavailable"),d=gc(N,null),{status:"busy",message:N,teamChatLogId:null}}let b=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,K=>{let le=K.getAgentInflight(p,m.alias);return le===null||le.sender_teamfile!==N.row.sender_teamfile||le.sender_alias!==N.row.sender_alias||le.started_at!==N.row.started_at||le.holder_pid!==process.pid?!1:K.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let K=`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 yr(i,n,t.prompt,K,"unavailable"),d=ts(K,null),{status:"error",errorKind:"provider",message:K,teamChatLogId:null,messageId:null}}}else{let N=await Hk(r,p,m.alias);if(N.busy){let B=await Xk(r,p,m.alias);return B+=await qk(r,p,m.alias),yr(i,n,t.prompt,B,"unavailable"),d=gc(B,null),{status:"busy",message:B,teamChatLogId:null}}b=N.idleReclaim}if(h!==null&&h.teamfile!==p){let N=await C(r,B=>rm(B,{root:g,sender:h,receiverTeamfile:p,receiverAlias:m.alias,now:new Date}));if(N.stop){let B=sm(N.chain);return yr(i,n,t.prompt,B,"cycle"),d=ts(B,null),{status:"error",errorKind:"cycle",message:B,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await sA(r,{receiver_teamfile:p,receiver_alias:m.alias,sender_teamfile:h?.teamfile??p,sender_alias:h?.alias??"operator",...b?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let B=dg(p,m.alias,N.current);return B+=` ${fc(mc({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,yr(i,n,t.prompt,B,"unavailable"),d=gc(B,null),{status:"busy",message:B,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=Fr(B=>C(r,K=>K.heartbeatAgentInflight(s.row,s.leaseId,B)),{intervalMs:ag,onError:B=>{z()&&Ee(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:B instanceof Error?B.message:String(B)}))}})}let v=await ng({sender:h??{teamfile:p,alias:"operator"},receiver:{teamfile:p,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:h===null?"operator":`${h.teamfile}:${h.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:N=>e({kind:"delta",chunk:N}),onProgress:N=>e({kind:"progress",alias:m.alias,event:N}),onPromptBuilt:async N=>{u=N,l===null&&(l=await oA(r,{...n,message:N}),l!==null&&(t.onAccepted?.(wt(l)),i!==null&&await Kk(r,i,l))),i!==null&&await Vk(r,i,N)}});u=v.prompt;let S=v.status==="stalled",w=v.status==="empty",x=null,I=S?`provider stalled${v.stalledAfterMs!==void 0?` after ${v.stalledAfterMs}ms`:""}`:w?"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":v.status==="error"?v.error??v.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=S||w||v.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await og(r,l,{...n,message:u,response:v.receipt,status:R,error_detail:I}),c=!0,x=l):x=await lA(r,{...n,message:u,response:v.receipt,status:R,error_detail:I});let F=v.status!=="error"?v.warnings:void 0;if(S||w){let N=I;yr(i,n,u,N,"error"),d=ts(N,x,v.receipt,F)}else d=zk(v.receipt,x,F);return{status:S?"stalled":w?"empty":"ok",replyText:v.receipt,wroteDelta:v.wroteDelta,teamChatLogId:x,messageId:x===null?null:wt(x),durationMs:v.durationMs}}catch(m){let p=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await og(r,l,{...n,message:u,response:null,status:"error",error_detail:p}),c=!0),yr(i,n,u,p,"error"),d=ts(p,l),{status:"error",errorKind:m instanceof ie?"target":"provider",message:p,teamChatLogId:l,messageId:l===null?null:wt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await aA(r,n,wt(l)),s!==null&&await iA(r,s.row,s.leaseId),i!==null&&await Jk(r,i,d??ts("chat turn exited without a terminal outcome",null))}}function Wk(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function Hk(t,e,r){let n=await C(t,i=>(Br(i,e,r),lt(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>Vh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function Xk(t,e,r){let n=await cg(t,e,r);if(n!==null)return _r(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?dg(e,r,s):`${r} is busy; wait and retry`}async function qk(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${fc(mc({holderPid:n.holder_pid,since:n.started_at}))}`}async function Gk(t,e){try{return(await C(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:Qk(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 z()&&Ee(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function Jk(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Vk(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Kk(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function Yk(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&Ee(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},ag);return r.unref?.(),r}function lg(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function zk(t,e,r){return{status:"done",result_summary:rs(t),error:null,team_chat_log_id:e,...lg(r)}}function gc(t,e){return{status:"busy",result_summary:rs(t),error:t,team_chat_log_id:e}}function ts(t,e,r,n){return{status:"error",result_summary:rs(r===void 0?t:r),error:t,team_chat_log_id:e,...lg(n)}}function rs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function Qk(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function Zk(t,e){let r=nn(e,t);if(r.ok)return{sender:xt(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(It("chat"))}async function eA(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>ge(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>nm(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function tA(t,e){return await C(t,r=>Qu({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:rA(r,e.sender.teamfile,e.receiverTeamfile)}))}function rA(t,e,r){return{teams:[e,r].map(s=>nA(s,t))}}function nA(t,e){let r=Xe(t,e),n=Ot(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function sA(t,e){return await C(t,r=>{let n=z(),s=$t(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:at(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Ee(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:ig(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Ee(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:ig(s.current)})),{acquired:!1,current:s.current})})}async function cg(t,e,r){return await C(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(pc(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:pc(s).live?s:null})}function ig(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 iA(t,e,r){try{await C(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)}
|
|
1624
1624
|
`)}}function dg(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 oA(t,e){let r=ns(e.message);try{return await C(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)}
|
|
1625
1625
|
`),null}}async function og(t,e,r){let n=ns(r.message),s=r.response===null?null:ns(r.response);try{await C(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)}
|
|
1626
1626
|
`)}}async function aA(t,e,r){if(e!==null)try{await C(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)}
|
|
@@ -1935,7 +1935,7 @@ try {
|
|
|
1935
1935
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
1936
1936
|
`);return f.success?(console.log(f.output.map(E=>" [out] "+E).join(`
|
|
1937
1937
|
`)),console.log(` -> Passed!
|
|
1938
|
-
`)):(console.error(" -> Failed:",f.diagnostics),e=!1),e}async function RA(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await AA()||(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:ye.resolve(t[0]),o=s?t[1]:$.readFileSync(i,"utf-8"),a=new nr,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(bg(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 M,
|
|
1938
|
+
`)):(console.error(" -> Failed:",f.diagnostics),e=!1),e}async function RA(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await AA()||(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:ye.resolve(t[0]),o=s?t[1]:$.readFileSync(i,"utf-8"),a=new nr,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(bg(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 M,He,Tc,Gi,Xi,Eg,is,os,wA,yc,Tr,vc,on,er,tr,an,rt,Vi,Sc,Ki,bA,IA,xA,nr,wg,bc=k(()=>{"use strict";M=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}},He=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};Tc=10*1024*1024;Gi=new Set,Xi=1e3;process.on("exit",()=>{for(let t of Gi)try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,"SIGKILL"):t.kill("SIGKILL")}catch{}Gi.clear()});Eg={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"},is=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 M("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 M("Unexpected character '|'. Did you mean '||'?",r,n,"LEXER",this.file);break;default:throw new M(`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===`
|
|
1939
1939
|
`?(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===`
|
|
1940
1940
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
1941
1941
|
`;)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 M("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()===`
|
|
@@ -2046,16 +2046,17 @@ fn clamp(val, low, high) {
|
|
|
2046
2046
|
`)+(v.output.length>0?`
|
|
2047
2047
|
`:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x})();{let v=b.run(y,{file:E}),S=v.output.join(`
|
|
2048
2048
|
`)+(v.output.length>0?`
|
|
2049
|
-
`:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:g=>this.isAsync?EA(g):xg(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,g));let f=Date.now()+g;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new rt,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 rt(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 M(`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 M("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 er)break;if(s instanceof tr)continue;throw s}}return}case"ForStmt":{let n=new rt(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 M("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 er)break;if(!(i instanceof tr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new on(n)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("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 M("'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 M(`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),rr(n,s,i),i;throw new M("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)rr(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 M("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]:ht(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 M(`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 M("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 M(`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 an)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>Xi)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",o);let l=new rt(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 on)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 M(`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 M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`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 an(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new rt,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 rt(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 M(`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 M("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 er)break;if(i instanceof tr)continue;throw i}}return}case"ForStmt":{let s=new rt(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 M("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 er)break;if(!(o instanceof tr))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 on(s)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`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 M("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),rr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("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 M(`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 M("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 M(`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),rr(s,i,o),o;throw new M("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)rr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("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]:ht(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 M(`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 M("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 M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xi)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",a);let u=new rt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof on)return m.value;throw m}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof Ve||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},bA=[{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;"}],IA=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],xA=[{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);"}];nr=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 bA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of IA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of xA)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=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
2049
|
+
`:""),w=v.exitCode!==void 0?v.exitCode:v.success?0:1,x={success:v.success&&w===0,stdout:S,output:[...v.output],value:v.value,exit_code:w,code:w,errors:v.errors??[]};return x.toString=()=>S,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:g=>this.isAsync?EA(g):xg(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(E=>setTimeout(E,g));let f=Date.now()+g;for(;Date.now()<f;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new rt,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 rt(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 M(`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 M("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 er)break;if(s instanceof tr)continue;throw s}}return}case"ForStmt":{let n=new rt(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 M("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 er)break;if(!(i instanceof tr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new on(n)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("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 M("'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 M(`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),rr(n,s,i),i;throw new M("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)rr(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 M("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]:ht(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 M(`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 M("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 M(`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 an)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>Xi)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",o);let l=new rt(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 on)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 He||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`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 M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`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 an(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new rt,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 rt(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 M(`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 M("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 er)break;if(i instanceof tr)continue;throw i}}return}case"ForStmt":{let s=new rt(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 M("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 er)break;if(!(o instanceof tr))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 on(s)}case"BreakStmt":throw new er;case"ContinueStmt":throw new tr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`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 M("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),rr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("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 M(`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 M("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 M(`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),rr(s,i,o),o;throw new M("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)rr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("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]:ht(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 M(`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 M("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 M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Xi)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Xi})`,s,i,"RUNTIME",a);let u=new rt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)u.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,u,o)}catch(m){if(m instanceof on)return m.value;throw m}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof He||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},bA=[{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;"}],IA=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:"getstr(obj: any, path: string|array): string",description:'Typed form of get(): reads a string field, "" when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null", not "" -- getstr never does that).',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array): array",description:"Typed form of get(): reads an array field, [] when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],xA=[{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);"}];nr=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 bA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of IA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of xA)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=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
2050
2050
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
2051
2051
|
`)&&(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(`
|
|
2052
2052
|
`)+`
|
|
2053
|
-
`;return $.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($.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 $.readdirSync(ye.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>($.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=$.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>($.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=$.readFileSync(e,"utf-8");return gg(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=",")=>($.writeFileSync(e,yg(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",gg,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",yg,{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=ye.resolve(yA(),`lmscript-${_A()}`),r=$.openSync(e,"wx",384);return $.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>$.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new
|
|
2053
|
+
`;return $.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($.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 $.readdirSync(ye.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>($.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=$.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>($.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=$.readFileSync(e,"utf-8");return gg(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=",")=>($.writeFileSync(e,yg(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",gg,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",yg,{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=ye.resolve(yA(),`lmscript-${_A()}`),r=$.openSync(e,"wx",384);return $.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>$.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new He(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,r=!0)=>($.mkdirSync(e,{recursive:!!r}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,r=!1)=>$.existsSync(e)?(r?$.rmSync(e,{recursive:!0,force:!0}):$.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)=>($.copyFileSync(e,r),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,r)=>($.renameSync(e,r),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,r)=>ye.basename(e,r),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>ye.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>ye.join(...e),void 0,"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>ye.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?Rg(e,r):Ag(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=ye.resolve(String(e));if(!$.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=$.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(`
|
|
2054
2054
|
`)+(a.output.length>0?`
|
|
2055
2055
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
2056
2056
|
`)+(a.output.length>0?`
|
|
2057
2057
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
2058
|
-
`):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=>xg(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?cs(e):ls(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)=>TA(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=ss(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=ss(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=ss(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=ss(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=ss(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(ht(i,a)==null||typeof ht(i,a)!="object")&&rr(i,a,{}),i=ht(i,a)}return s.length>0&&rr(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=>ht(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&ht(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&&ht(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=as(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof an,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>kg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let m=Number(u);o+=m<r.length?a(r[m]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>as(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)=>Tg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Tg(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 an?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!u)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:kA(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}=SA(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new vc(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof M?{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 Ki(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof 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:d}}let u=c instanceof M?c.line:1,m=c instanceof M?c.column:1,p=c instanceof M&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:m,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new Ki(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof Ve||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof M?l.line:1,u=l instanceof M?l.column:1,m=l instanceof M&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,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())}};wg=ye.basename(Sg(import.meta.url));(wg==="lmscript.ts"||wg==="lmscript.js")&&process.argv[1]&&$.existsSync(process.argv[1])&&$.realpathSync(Sg(import.meta.url))===$.realpathSync(ye.resolve(process.argv[1]))&&RA()});import{mkdirSync as Fg,readFileSync as NA,renameSync as LA,writeFileSync as CA,existsSync as Pg}from"node:fs";import{homedir as OA}from"node:os";import{dirname as Ug,join as Yi,resolve as zi}from"node:path";import{fileURLToPath as DA}from"node:url";function UA(){return Yi(OA(),".lmctl","cache","lmprice")}function ln(t,e){return Yi(t,e)}function wr(t){try{return JSON.parse(NA(t,"utf-8"))}catch{return null}}function Bg(t,e){let r=`${t}.tmp-${process.pid}`;CA(r,e),LA(r,t)}function Ic(t){return t===null||typeof t=="number"}function Qi(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 Ic(s.input_per_1m_tokens)&&Ic(s.output_per_1m_tokens)&&Ic(s.input_cache_read_per_1m_tokens)})}function Zi(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"&&BA.has(i.evidence)});return r&&n}function WA(t){let e=wr(ln(t,jg)),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=wr(ln(t,jA));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 HA(t){let e=WA(t),r=wr(ln(t,xc)),n=wr(ln(t,kc));return{catalog:Qi(r)?r:null,aliases:Zi(n)?n:null,meta:e}}function XA(t,e){try{Fg(t,{recursive:!0}),Bg(ln(t,jg),JSON.stringify(e))}catch{}}function Lg(t,e,r){try{Fg(t,{recursive:!0}),Bg(ln(t,e),JSON.stringify(r))}catch{}}function qA(t,e){let r=GA(t),n=r?[zi(r,"data",e)]:[zi(t,"..","..","data",e)];for(let s of n)if(Pg(s))return s;return null}function GA(t){let e=zi(t);for(;;){if(Pg(zi(e,"package.json")))return e;let r=Ug(e);if(r===e)return null;e=r}}function Cg(t,e,r){let n=r!==void 0?r:qA(t,e);return n===null?null:wr(n)}function JA(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Ng;let e=Number(t);return!Number.isFinite(e)||e<0?Ng:e*1e3}function VA(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function Og(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(FA)});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(PA)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function eo(t={}){return Object.keys(t).length===0?(Dg??=Mg(t),Dg):Mg(t)}async function Mg(t){let e=Ug(DA(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:VA();if(r!==null&&r!==""){let _=wr(Yi(r,xc)),h=wr(Yi(r,kc));if(Qi(_)&&Zi(h)){let g={catalog:_,aliases:h,source:"pinned",generatedAt:_.generated_at??null};return Ac=g.generatedAt,g}return $g(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??UA(),i=t.now??Date.now(),o=t.ttlMs??JA(),a=HA(s),l=(_,h)=>_!==null&&h.last_checked!==null&&i-Date.parse(h.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},p=!1;if(!l(c,a.meta.model_list)){let _=await Og(n,MA,c,a.meta.model_list.etag);_.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),p=!0,Qi(_.payload)&&(c=_.payload,_.etag!==null&&(m.model_list.etag=_.etag),Lg(s,xc,c),u=!0))}if(!l(d,a.meta.aliases)){let _=await Og(n,$A,d,a.meta.aliases.etag);_.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),p=!0,Zi(_.payload)&&(d=_.payload,_.etag!==null&&(m.aliases.etag=_.etag),Lg(s,kc,d),u=!0))}if((p||u)&&XA(s,m),c!==null||d!==null){let _={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return Ac=_.generatedAt,_}return $g(t,e)}function $g(t,e){let r=Cg(e,"price-data.json",t.bundledPath),n=Cg(e,"price-aliases.json",t.bundledAliasesPath),s=Qi(r)?r:null,i=Zi(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Ac=o.generatedAt,o}function Wg(t,e){if(e===null)return null;let{input_per_1m_tokens:r,output_per_1m_tokens:n,input_cache_read_per_1m_tokens:s}=e;if(r===null||n===null)return null;let i=s??r,o=t.input/1e6*r+t.output/1e6*n+t.cachedInput/1e6*i;return Number(o.toPrecision(10))}var MA,$A,FA,PA,Ng,xc,kc,jg,jA,BA,Ac,Dg,Rc=k(()=>{"use strict";MA="https://lmctl.com/dataset/model_list.json",$A="https://lmctl.com/dataset/aliases.json",FA=1e3,PA=1e4,Ng=6*60*60*1e3;xc="model_list.json",kc="aliases.json",jg="meta.json",jA="model_list.meta.json";BA=new Set(["established","asserted","unresolved"]);Ac=null,Dg=null});function Sr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function vr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Sr(r)}function Xg(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Sr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function KA(t,e){let r=new Set,n=l=>{r.add(Sr(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 cn(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=>KA(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=Xg(n);return s.some(o=>i.has(o))}}}function zA(t){let e=t.trim(),r=YA.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function tR(t,e,r){let n=e.trim().toLowerCase(),s=Sr(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 rR(t,e,r){let n=[];for(let[s,i]of Object.entries(ds))s!==r&&tR(i,t,e)&&n.push(s);return n}function to(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function nR(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 sR(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}${Sr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!nR(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 iR(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 zg(t,e){return t.map(iR).sort((r,n)=>{let s=to(r.source)-to(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 Nc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function oR(t,e,r){let n=sR(t),s=zg(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 Lc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=oR(t,e,r),s=n.offers.find(Nc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function aR(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function lR(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=vr(i),a=r.records.filter(l=>vr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:Lc(a,o,Cc)}function Qg(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let h=[e.trim().toLowerCase()];h.push(`${t.toLowerCase()}/${h[0]}`);let g=n.aliases.find(f=>h.includes(f.alias.toLowerCase()));if(g){if(g.evidence==="unresolved"||g.standard_slug===null)return{state:{kind:"unresolved",alias:g.alias},viaAlias:!0,pinRoute:null};let f=aR(n,g.standard_slug);return{state:lR(g,f,r),viaAlias:!0,pinRoute:f?.catalog_record_id?.toLowerCase()??null}}}let s=ds[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=h=>({state:h,viaAlias:!1,pinRoute:null}),l=Sr(i),c=r.records.filter(h=>h.source_model_id.toLowerCase()===i&&s.matchRow(h,[l]));if(c.length>0){let h=vr(c[0]),g=r.records.filter(f=>s.matchRow(f,[h])&&vr(f)===h);return a(Lc(g.length>0?g:c,h,Hg[t]??Cc))}let d=r.records.filter(h=>s.matchRow(h,o));if(d.length===0){let h=rR(e,r,t);return h.length>0?a({kind:"wrong-provider",declared:e,otherProviders:h}):a({kind:"unknown",declared:e})}let u=new Map;for(let h of d){let g=vr(h),f=u.get(g);f?f.push(h):u.set(g,[h])}let m=Hg[t]??Cc,p=null,_=null;for(let h of u.values()){let g=zg(h,m);(_===null||cR(g[0],_[0],m)<0)&&(p=h,_=g)}return a(Lc(p,vr(p[0]),m))}function ro(t,e,r,n){return Qg(t,e,r,n).state}function Zg(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=Qg(t,e,r,n);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(d=>d.route.toLowerCase()===o);if(c!==void 0&&Nc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Nc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function e_(t,e){let r=ds[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(vr(s));return n.size}function cR(t,e,r){let n=to(t.source)-to(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 qg,Gg,Jg,Vg,Kg,Yg,YA,QA,ZA,eR,ds,Hg,Cc,Oc=k(()=>{"use strict";qg=cn({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),Gg=cn({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)(-|$)/}),Jg=cn({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Vg=cn({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Kg=cn({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Yg=cn({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),YA=/\s*\(([^()]+)\)\s*$/;QA={"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"},ZA=["gemini","google","vertex_ai-language-models","anthropic"],eR={normalize(t){let{model:e}=zA(t),r=QA[e.toLowerCase()];return r===void 0?[]:[Sr(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=Xg(t);return e.some(n=>r.has(n))}},ds={claude:qg,codex:Gg,gemini:Jg,agy:eR,kimi:Vg,qwen:Kg,hermes:Yg},Hg={claude:qg.firstPartyProviders,codex:Gg.firstPartyProviders,gemini:Jg.firstPartyProviders,agy:ZA,kimi:Vg.firstPartyProviders,qwen:Kg.firstPartyProviders,hermes:Yg.firstPartyProviders};Cc=[]});import{spawnSync as Uc}from"node:child_process";import{existsSync as s_,readFileSync as i_}from"node:fs";import{homedir as o_}from"node:os";import{dirname as hB,resolve as Fc}from"node:path";function dn(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 fR(){let t=Uc("agy",["models"],{encoding:"utf-8",timeout:mR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function pR(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 hR(t){if(!t&&Dc)return Dc;let e=s=>(t||(Dc=s),s),r;try{r=(t??fR)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=pR(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function _R(){let t=Uc("codex",["debug","models"],{encoding:"utf-8",timeout:gR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function yR(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 ER(t){if(!t&&Mc)return Mc;let e=s=>(t||(Mc=s),s),r;try{r=(t??_R)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("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=yR(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})}function wR(t){let e=Uc("opencode",["models",t],{encoding:"utf-8",timeout:TR});return{status:e.status,stdout:e.stdout??"",error:e.error}}function vR(t,e){if(!e&&$c.has(t))return $c.get(t);let r=i=>(e||$c.set(t,i),i),n;try{n=(e??wR)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?dn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:dn(`opencode models ${t}`,n.error)});if(n.status!==0)return r({available:!1,models:[],reason:`opencode models ${t} exited with status ${n.status??"unknown"}`});let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);return s.length===0?r({available:!1,models:[],reason:`opencode models ${t} returned no models`}):r({available:!0,models:s})}function jc(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.`),!n.model&&uR.has(s)&&r.push(`[${n.alias}] provider=${s} has no model= \u2014 ${s} will use its own ambient default, which cannot be linted or priced and may not be the intended one. Set model= explicitly.`),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"&&!n.model){r.push(`[${n.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);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){r.push(`[${n.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}let i=IR(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=vR(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=SR(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: ${us(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=hR(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: ${us(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||r_.includes(n.model))continue;t_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${us(t_)}. 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): ${us(r_)}. 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===n_&&r.push(`[${n.alias}] model="${n_}" 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=ER(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: ${us(i.models)}`);continue}n.model&&(a_.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 l_(t,e={}){let r=t.filter(o=>o.model!==void 0&&a_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await eo();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=ro(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=e_(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${d} 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")&&dR.test(l)){let d=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="${d}" instead.`)}}return{warnings:s,errors:i}}async function c_(t,e={}){return(await l_(t,e)).warnings}async function d_(t,e={}){return(await l_(t,e)).errors}function SR(t){let e=process.env.KIMI_CODE_HOME||Fc(o_(),".kimi-code"),r=t??Fc(e,"config.toml");if(!s_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=i_(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=bR(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 bR(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 IR(t){let e=t??Fc(o_(),".config","opencode","opencode.json");if(!s_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(i_(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:xR(r)}}function xR(t){if(!Pc(t))return[];let e=no(t.provider)??no(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Pc(s))continue;let i=no(s.models)??no(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function no(t){return Pc(t)?t:null}function Pc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function us(t){return t.length>0?t.join(", "):"(none)"}var a_,dR,uR,t_,r_,n_,mR,Dc,gR,Mc,TR,$c,u_=k(()=>{"use strict";Rc();Oc();a_=new Set(Object.keys(ds).filter(t=>t!=="codex"&&t!=="kimi")),dR=/\d\.(?=\d)/,uR=new Set(["claude","codex","gemini","qwen","kimi","agy"]),t_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],r_=["deepseek-flash","deepseek-pro"],n_="gpt-5.3-codex-spark",mR=15e3;Dc=null;gR=5e3;Mc=null;TR=5e3;$c=new Map});import{homedir as kR}from"node:os";import{basename as AR}from"node:path";function m_(t,e){let r=new Set;return{text:t.replace(NR,(s,i)=>{let o=i.trim(),a=RR[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function f_(t){return{workdir:t.workdir,teamfile:t.teamfile,date:LR(t.date)}}function LR(t){return t.toISOString().slice(0,10)}var RR,NR,p_=k(()=>{"use strict";RR={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=AR(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>kR(),date:t=>t.date},NR=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var Vc={};se(Vc,{GEMINI_PROVIDER_NOTICE:()=>w_,_setAgyModelsRunnerForTests:()=>PR,_setCatalogSnapshotForTests:()=>FR,_setCodexModelsRunnerForTests:()=>UR,_setLintOpenCodeConfigProbeForTests:()=>WR,_setLintSessiondirFsOpsForTests:()=>BR,_setTeamfileSeedForTests:()=>jR,buildRootTeamRegistrationRow:()=>k_,registerRootTeam:()=>A_,runLint:()=>xr,runSeed:()=>kr,seedTeamfile:()=>so,sha256Text:()=>x_,validateMemberSpec:()=>kt});import{createHash as CR}from"node:crypto";import{accessSync as OR,constants as h_,existsSync as DR,readFileSync as E_,realpathSync as Hc,statSync as MR,writeFileSync as g_}from"node:fs";import{dirname as Ir,resolve as T_}from"node:path";function FR(t){fs=t??void 0}function b_(t){return c_(t,fs!==void 0?{snapshot:fs}:{})}function I_(t){return d_(t,fs!==void 0?{snapshot:fs}:{})}function PR(t){Gc=t??void 0}function UR(t){Jc=t??void 0}function jR(t){v_=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(bt(),lc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function BR(t){br=t===null?Xc:{...Xc,...t}}function WR(t){S_=t??Fn}async function HR(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 S_({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 XR(t,e){let r=Ir(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=T_(o);if(n.has(a))continue;let l=qR(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 qR(t){try{if(br.existsSync(t)){if(!br.statSync(t).isDirectory())return"ENOTDIR";br.accessSync(t,h_.W_OK);return}let e=JR(t);if(e===void 0)return;if(!br.statSync(e).isDirectory())return"ENOTDIR";br.accessSync(e,h_.W_OK);return}catch(e){return VR(e)??"permission check failed"}}function GR(t){let e=T_(t);try{return Hc(e)}catch{return e}}function JR(t){let e=t;for(;;){try{if(br.existsSync(e))return e}catch{return}let r=Ir(e);if(r===e)return;e=r}}function VR(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 xr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write($R),0;let r=oe(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2058
|
+
`):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=>xg(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?cs(e):ls(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)=>TA(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=ss(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r)=>{let n=ss(e,r);return n==null?"":String(n)},2,'Reads a string field from a map/request form; "" when missing or null (never the string "null")'),this.registerFunction("getnum",(e,r,n=0)=>{let s=ss(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=ss(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r)=>{let n=ss(e,r);return Array.isArray(n)?n:[]},2,"Reads an array field from a map/request form; [] when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
|
|
2059
|
+
`):console.error(`error: ${String(r)}`),new He(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];(ht(i,a)==null||typeof ht(i,a)!="object")&&rr(i,a,{}),i=ht(i,a)}return s.length>0&&rr(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=>ht(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&ht(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&&ht(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=as(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/);for(let n=r.length-1;n>=0;n--){let s=r[n].trim();if(s.length>0)return s==="DONE"||s==="NOTHING_TO_DO"||s==="BLOCKED"||s==="OTHER"?s:null}return null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof an,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>kg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let m=Number(u);o+=m<r.length?a(r[m]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>as(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)=>Tg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Tg(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 an?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==m&&!u)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${p}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:kA(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}=SA(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new vc(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof M?{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 Ki(this.hostFunctions,u=>n.push(u),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let d=l.getRecordedErrors();return this.lastRecordedErrors=d,{success:!0,value:c,diagnostics:i,output:n,errors:d}}catch(c){let d=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=d,c instanceof He||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:d}}let u=c instanceof M?c.line:1,m=c instanceof M?c.column:1,p=c instanceof M&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:m,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new Ki(this.hostFunctions,d=>n.push(d),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof He||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof M?l.line:1,u=l instanceof M?l.column:1,m=l instanceof M&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,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())}};wg=ye.basename(Sg(import.meta.url));(wg==="lmscript.ts"||wg==="lmscript.js")&&process.argv[1]&&$.existsSync(process.argv[1])&&$.realpathSync(Sg(import.meta.url))===$.realpathSync(ye.resolve(process.argv[1]))&&RA()});import{mkdirSync as Fg,readFileSync as NA,renameSync as LA,writeFileSync as CA,existsSync as Pg}from"node:fs";import{homedir as OA}from"node:os";import{dirname as Ug,join as Yi,resolve as zi}from"node:path";import{fileURLToPath as DA}from"node:url";function UA(){return Yi(OA(),".lmctl","cache","lmprice")}function ln(t,e){return Yi(t,e)}function wr(t){try{return JSON.parse(NA(t,"utf-8"))}catch{return null}}function Bg(t,e){let r=`${t}.tmp-${process.pid}`;CA(r,e),LA(r,t)}function Ic(t){return t===null||typeof t=="number"}function Qi(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 Ic(s.input_per_1m_tokens)&&Ic(s.output_per_1m_tokens)&&Ic(s.input_cache_read_per_1m_tokens)})}function Zi(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"&&BA.has(i.evidence)});return r&&n}function WA(t){let e=wr(ln(t,jg)),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=wr(ln(t,jA));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 HA(t){let e=WA(t),r=wr(ln(t,xc)),n=wr(ln(t,kc));return{catalog:Qi(r)?r:null,aliases:Zi(n)?n:null,meta:e}}function XA(t,e){try{Fg(t,{recursive:!0}),Bg(ln(t,jg),JSON.stringify(e))}catch{}}function Lg(t,e,r){try{Fg(t,{recursive:!0}),Bg(ln(t,e),JSON.stringify(r))}catch{}}function qA(t,e){let r=GA(t),n=r?[zi(r,"data",e)]:[zi(t,"..","..","data",e)];for(let s of n)if(Pg(s))return s;return null}function GA(t){let e=zi(t);for(;;){if(Pg(zi(e,"package.json")))return e;let r=Ug(e);if(r===e)return null;e=r}}function Cg(t,e,r){let n=r!==void 0?r:qA(t,e);return n===null?null:wr(n)}function JA(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Ng;let e=Number(t);return!Number.isFinite(e)||e<0?Ng:e*1e3}function VA(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function Og(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(FA)});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(PA)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function eo(t={}){return Object.keys(t).length===0?(Dg??=Mg(t),Dg):Mg(t)}async function Mg(t){let e=Ug(DA(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:VA();if(r!==null&&r!==""){let _=wr(Yi(r,xc)),h=wr(Yi(r,kc));if(Qi(_)&&Zi(h)){let g={catalog:_,aliases:h,source:"pinned",generatedAt:_.generated_at??null};return Ac=g.generatedAt,g}return $g(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??UA(),i=t.now??Date.now(),o=t.ttlMs??JA(),a=HA(s),l=(_,h)=>_!==null&&h.last_checked!==null&&i-Date.parse(h.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},p=!1;if(!l(c,a.meta.model_list)){let _=await Og(n,MA,c,a.meta.model_list.etag);_.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),p=!0,Qi(_.payload)&&(c=_.payload,_.etag!==null&&(m.model_list.etag=_.etag),Lg(s,xc,c),u=!0))}if(!l(d,a.meta.aliases)){let _=await Og(n,$A,d,a.meta.aliases.etag);_.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),p=!0,Zi(_.payload)&&(d=_.payload,_.etag!==null&&(m.aliases.etag=_.etag),Lg(s,kc,d),u=!0))}if((p||u)&&XA(s,m),c!==null||d!==null){let _={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return Ac=_.generatedAt,_}return $g(t,e)}function $g(t,e){let r=Cg(e,"price-data.json",t.bundledPath),n=Cg(e,"price-aliases.json",t.bundledAliasesPath),s=Qi(r)?r:null,i=Zi(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Ac=o.generatedAt,o}function Wg(t,e){if(e===null)return null;let{input_per_1m_tokens:r,output_per_1m_tokens:n,input_cache_read_per_1m_tokens:s}=e;if(r===null||n===null)return null;let i=s??r,o=t.input/1e6*r+t.output/1e6*n+t.cachedInput/1e6*i;return Number(o.toPrecision(10))}var MA,$A,FA,PA,Ng,xc,kc,jg,jA,BA,Ac,Dg,Rc=k(()=>{"use strict";MA="https://lmctl.com/dataset/model_list.json",$A="https://lmctl.com/dataset/aliases.json",FA=1e3,PA=1e4,Ng=6*60*60*1e3;xc="model_list.json",kc="aliases.json",jg="meta.json",jA="model_list.meta.json";BA=new Set(["established","asserted","unresolved"]);Ac=null,Dg=null});function Sr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function vr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Sr(r)}function Xg(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Sr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function KA(t,e){let r=new Set,n=l=>{r.add(Sr(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 cn(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=>KA(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=Xg(n);return s.some(o=>i.has(o))}}}function zA(t){let e=t.trim(),r=YA.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function tR(t,e,r){let n=e.trim().toLowerCase(),s=Sr(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 rR(t,e,r){let n=[];for(let[s,i]of Object.entries(ds))s!==r&&tR(i,t,e)&&n.push(s);return n}function to(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function nR(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 sR(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}${Sr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!nR(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 iR(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 zg(t,e){return t.map(iR).sort((r,n)=>{let s=to(r.source)-to(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 Nc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function oR(t,e,r){let n=sR(t),s=zg(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 Lc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=oR(t,e,r),s=n.offers.find(Nc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function aR(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function lR(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=vr(i),a=r.records.filter(l=>vr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:Lc(a,o,Cc)}function Qg(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let h=[e.trim().toLowerCase()];h.push(`${t.toLowerCase()}/${h[0]}`);let g=n.aliases.find(f=>h.includes(f.alias.toLowerCase()));if(g){if(g.evidence==="unresolved"||g.standard_slug===null)return{state:{kind:"unresolved",alias:g.alias},viaAlias:!0,pinRoute:null};let f=aR(n,g.standard_slug);return{state:lR(g,f,r),viaAlias:!0,pinRoute:f?.catalog_record_id?.toLowerCase()??null}}}let s=ds[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=h=>({state:h,viaAlias:!1,pinRoute:null}),l=Sr(i),c=r.records.filter(h=>h.source_model_id.toLowerCase()===i&&s.matchRow(h,[l]));if(c.length>0){let h=vr(c[0]),g=r.records.filter(f=>s.matchRow(f,[h])&&vr(f)===h);return a(Lc(g.length>0?g:c,h,Hg[t]??Cc))}let d=r.records.filter(h=>s.matchRow(h,o));if(d.length===0){let h=rR(e,r,t);return h.length>0?a({kind:"wrong-provider",declared:e,otherProviders:h}):a({kind:"unknown",declared:e})}let u=new Map;for(let h of d){let g=vr(h),f=u.get(g);f?f.push(h):u.set(g,[h])}let m=Hg[t]??Cc,p=null,_=null;for(let h of u.values()){let g=zg(h,m);(_===null||cR(g[0],_[0],m)<0)&&(p=h,_=g)}return a(Lc(p,vr(p[0]),m))}function ro(t,e,r,n){return Qg(t,e,r,n).state}function Zg(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=Qg(t,e,r,n);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(d=>d.route.toLowerCase()===o);if(c!==void 0&&Nc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Nc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function e_(t,e){let r=ds[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(vr(s));return n.size}function cR(t,e,r){let n=to(t.source)-to(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 qg,Gg,Jg,Vg,Kg,Yg,YA,QA,ZA,eR,ds,Hg,Cc,Oc=k(()=>{"use strict";qg=cn({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),Gg=cn({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)(-|$)/}),Jg=cn({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),Vg=cn({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),Kg=cn({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),Yg=cn({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),YA=/\s*\(([^()]+)\)\s*$/;QA={"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"},ZA=["gemini","google","vertex_ai-language-models","anthropic"],eR={normalize(t){let{model:e}=zA(t),r=QA[e.toLowerCase()];return r===void 0?[]:[Sr(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=Xg(t);return e.some(n=>r.has(n))}},ds={claude:qg,codex:Gg,gemini:Jg,agy:eR,kimi:Vg,qwen:Kg,hermes:Yg},Hg={claude:qg.firstPartyProviders,codex:Gg.firstPartyProviders,gemini:Jg.firstPartyProviders,agy:ZA,kimi:Vg.firstPartyProviders,qwen:Kg.firstPartyProviders,hermes:Yg.firstPartyProviders};Cc=[]});import{spawnSync as Uc}from"node:child_process";import{existsSync as s_,readFileSync as i_}from"node:fs";import{homedir as o_}from"node:os";import{dirname as hB,resolve as Fc}from"node:path";function dn(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 fR(){let t=Uc("agy",["models"],{encoding:"utf-8",timeout:mR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function pR(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 hR(t){if(!t&&Dc)return Dc;let e=s=>(t||(Dc=s),s),r;try{r=(t??fR)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=pR(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function _R(){let t=Uc("codex",["debug","models"],{encoding:"utf-8",timeout:gR});return{status:t.status,stdout:t.stdout??"",error:t.error}}function yR(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 ER(t){if(!t&&Mc)return Mc;let e=s=>(t||(Mc=s),s),r;try{r=(t??_R)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?dn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:dn("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=yR(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})}function wR(t){let e=Uc("opencode",["models",t],{encoding:"utf-8",timeout:TR});return{status:e.status,stdout:e.stdout??"",error:e.error}}function vR(t,e){if(!e&&$c.has(t))return $c.get(t);let r=i=>(e||$c.set(t,i),i),n;try{n=(e??wR)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?dn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:dn(`opencode models ${t}`,n.error)});if(n.status!==0)return r({available:!1,models:[],reason:`opencode models ${t} exited with status ${n.status??"unknown"}`});let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);return s.length===0?r({available:!1,models:[],reason:`opencode models ${t} returned no models`}):r({available:!0,models:s})}function jc(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.`),!n.model&&uR.has(s)&&r.push(`[${n.alias}] provider=${s} has no model= \u2014 ${s} will use its own ambient default, which cannot be linted or priced and may not be the intended one. Set model= explicitly.`),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"&&!n.model){r.push(`[${n.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);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){r.push(`[${n.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}let i=IR(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=vR(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=SR(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: ${us(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=hR(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: ${us(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||r_.includes(n.model))continue;t_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${us(t_)}. 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): ${us(r_)}. 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===n_&&r.push(`[${n.alias}] model="${n_}" 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=ER(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: ${us(i.models)}`);continue}n.model&&(a_.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 l_(t,e={}){let r=t.filter(o=>o.model!==void 0&&a_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await eo();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=ro(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=e_(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${d} 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")&&dR.test(l)){let d=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="${d}" instead.`)}}return{warnings:s,errors:i}}async function c_(t,e={}){return(await l_(t,e)).warnings}async function d_(t,e={}){return(await l_(t,e)).errors}function SR(t){let e=process.env.KIMI_CODE_HOME||Fc(o_(),".kimi-code"),r=t??Fc(e,"config.toml");if(!s_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=i_(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=bR(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 bR(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 IR(t){let e=t??Fc(o_(),".config","opencode","opencode.json");if(!s_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(i_(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:xR(r)}}function xR(t){if(!Pc(t))return[];let e=no(t.provider)??no(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Pc(s))continue;let i=no(s.models)??no(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function no(t){return Pc(t)?t:null}function Pc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function us(t){return t.length>0?t.join(", "):"(none)"}var a_,dR,uR,t_,r_,n_,mR,Dc,gR,Mc,TR,$c,u_=k(()=>{"use strict";Rc();Oc();a_=new Set(Object.keys(ds).filter(t=>t!=="codex"&&t!=="kimi")),dR=/\d\.(?=\d)/,uR=new Set(["claude","codex","gemini","qwen","kimi","agy"]),t_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],r_=["deepseek-flash","deepseek-pro"],n_="gpt-5.3-codex-spark",mR=15e3;Dc=null;gR=5e3;Mc=null;TR=5e3;$c=new Map});import{homedir as kR}from"node:os";import{basename as AR}from"node:path";function m_(t,e){let r=new Set;return{text:t.replace(NR,(s,i)=>{let o=i.trim(),a=RR[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function f_(t){return{workdir:t.workdir,teamfile:t.teamfile,date:LR(t.date)}}function LR(t){return t.toISOString().slice(0,10)}var RR,NR,p_=k(()=>{"use strict";RR={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=AR(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>kR(),date:t=>t.date},NR=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var Vc={};se(Vc,{GEMINI_PROVIDER_NOTICE:()=>w_,_setAgyModelsRunnerForTests:()=>PR,_setCatalogSnapshotForTests:()=>FR,_setCodexModelsRunnerForTests:()=>UR,_setLintOpenCodeConfigProbeForTests:()=>WR,_setLintSessiondirFsOpsForTests:()=>BR,_setTeamfileSeedForTests:()=>jR,buildRootTeamRegistrationRow:()=>k_,registerRootTeam:()=>A_,runLint:()=>xr,runSeed:()=>kr,seedTeamfile:()=>so,sha256Text:()=>x_,validateMemberSpec:()=>kt});import{createHash as CR}from"node:crypto";import{accessSync as OR,constants as h_,existsSync as DR,readFileSync as E_,realpathSync as Hc,statSync as MR,writeFileSync as g_}from"node:fs";import{dirname as Ir,resolve as T_}from"node:path";function FR(t){fs=t??void 0}function b_(t){return c_(t,fs!==void 0?{snapshot:fs}:{})}function I_(t){return d_(t,fs!==void 0?{snapshot:fs}:{})}function PR(t){Gc=t??void 0}function UR(t){Jc=t??void 0}function jR(t){v_=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(bt(),lc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function BR(t){br=t===null?Xc:{...Xc,...t}}function WR(t){S_=t??Fn}async function HR(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 S_({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 XR(t,e){let r=Ir(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=T_(o);if(n.has(a))continue;let l=qR(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 qR(t){try{if(br.existsSync(t)){if(!br.statSync(t).isDirectory())return"ENOTDIR";br.accessSync(t,h_.W_OK);return}let e=JR(t);if(e===void 0)return;if(!br.statSync(e).isDirectory())return"ENOTDIR";br.accessSync(e,h_.W_OK);return}catch(e){return VR(e)??"permission check failed"}}function GR(t){let e=T_(t);try{return Hc(e)}catch{return e}}function JR(t){let e=t;for(;;){try{if(br.existsSync(e))return e}catch{return}let r=Ir(e);if(r===e)return;e=r}}function VR(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 xr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write($R),0;let r=oe(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2059
2060
|
`),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
|
|
2060
2061
|
`),2;let n=r.positionals[0],s;try{s=await C(e,d=>ge(n,d))}catch(d){return un(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=Ae(s)}catch(d){return un(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let o=sa(i,Ir(s));e.stderr.write(`notice: checking teamfile and models ...
|
|
2061
2062
|
`);let a=jc(i.members,{agyModelsRunner:Gc,codexModelsRunner:Jc});a.push(...await b_(i.members)),o.push(...await I_(i.members));let l=E_(s,"utf8"),c=m_(l,f_({workdir:Ir(s),teamfile:s,date:new Date})).unknownNames;c.length>0&&a.push(`unknown template placeholder${c.length===1?"":"s"}: ${c.map(d=>`{{${d}}}`).join(", ")}`),a.push(...Fa(i.members,Ir(s))),a.push(...XR(i.members,s)),a.push(...await HR(i.members,Ir(s),e.env));for(let d of o)e.stderr.write(`error: ${d.field}: ${d.message}
|
|
@@ -2162,11 +2163,11 @@ possibly work, seed reports it as an error and seeds nothing.
|
|
|
2162
2163
|
`)}}function gN(t={}){let e=new nr;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+`
|
|
2163
2164
|
`),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+`
|
|
2164
2165
|
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=as(s,i);return n.stdout.write(o+`
|
|
2165
|
-
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return cs(s,i,o)}return ls(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 _N(t,e,r,n=process.env){t.registerFunction("lm_exit",(h=0)=>{let g=Math.floor(Number(h)),f=Number.isFinite(g)&&g>=0&&g<=255?g:1;throw new
|
|
2166
|
+
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return cs(s,i,o)}return ls(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 _N(t,e,r,n=process.env){t.registerFunction("lm_exit",(h=0)=>{let g=Math.floor(Number(h)),f=Number.isFinite(g)&&g>=0&&g<=255?g:1;throw new He(f)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...h)=>{let g=h.map(f=>typeof f=="object"?JSON.stringify(f):String(f)).join(" ");return e.stderr.write(g+(g.endsWith(`
|
|
2166
2167
|
`)?"":`
|
|
2167
2168
|
`)),g},void 0,"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...h)=>{let g=h.map(f=>typeof f=="object"?JSON.stringify(f):String(f)).join(" ");return e.stderr.write(`error: ${g}
|
|
2168
2169
|
`),r.recordError(g),g},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(h,g=!1)=>{try{let f=cN(String(h),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2169
|
-
`);return!!g?[f.trim()].filter(y=>y.length>0):f.split(/\n\s*\n/u).map(y=>y.trim()).filter(Boolean)}catch(f){throw A(e,`batch: ${f instanceof Error?f.message:String(f)}`),new
|
|
2170
|
+
`);return!!g?[f.trim()].filter(y=>y.length>0):f.split(/\n\s*\n/u).map(y=>y.trim()).filter(Boolean)}catch(f){throw A(e,`batch: ${f instanceof Error?f.message:String(f)}`),new He(1)}};t.registerFunction("lm_read_prompts",(h,g=!1)=>s(h,g),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",h=>s(h,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",h=>{try{return Ae(String(h)).members.map(f=>({alias:f.alias,provider:f.provider,model:f.model,sessionid:f.session,sessiondir:f.sessiondir}))}catch(g){throw new Error(`Failed to read teamfile '${h}': ${g?.message||String(g)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(h,g)=>{try{let f=fe(String(h),String(g),e.dal);return{alias:f.alias,provider:f.provider,model:f.model,sessionid:f.sessionid,sessiondir:f.sessiondir,isLead:f.isLead,teamfile:f.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(h,g,f,E={})=>{if(typeof h!="string"){if(!h||Array.isArray(h)||typeof h!="object"||typeof h.provider!="string"||!h.provider.trim())throw new Error("lm_batch_open: member map requires provider");let N=g??{};if(typeof N!="object"||Array.isArray(N)||f!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let B={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...h},sourceMember:h,options:{...N},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(B),B}if(typeof g!="string"||typeof f!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let y;try{y=fe(String(h),String(g),e.dal)}catch(N){return A(e,`batch: ${N?.message||String(N)}`),null}let T=Number(E?.promptCount??1),v=!!!E?.legacy&&T>1&&await uN(y),S={...e.env??n},w=await fN(e,{member:y,batchfile:String(f),promptCount:T,parentInvocationId:Bt(S.LMCTL_INVOCATION_ID)});w!==null&&(S.LMCTL_INVOCATION_ID=String(w));let x,I,R,F=!1;e.stderr.write(`batch ${Me()}: starting ${T} prompt${T===1?"":"s"} -> ${y.alias} (teamfile=${h} input=${f})
|
|
2170
2171
|
`);try{if(v){let K=await C(e,Y=>(Br(Y,y.teamfile,y.alias),lt(Y,y.teamfile,y.alias)));if(K.busy){let Y=K.reason==="in-flight"?`${y.alias} is servicing ${K.inFlight.sender_alias} (${K.inFlight.sender_teamfile}) since ${K.inFlight.started_at} \u2014 wait and retry`:K.source==="terminal-lock"?_r(K.terminalLock):`${y.alias} is busy (interactive terminal); wait and retry`;return w!==null&&await C(e,ke=>{ke.finishTrackedInvocation(w,{status:"busy",exit_code:1,error:Y,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${Y}`),null}let le=await C(e,Y=>mN(S,Y)),de=await C(e,Y=>$t(Y,{receiver_teamfile:y.teamfile,receiver_alias:y.alias,sender_teamfile:le?.teamfile??y.teamfile,sender_alias:le?.alias??"operator",ttlMs:at(S)}));if(!de.acquired){let Y=`${y.alias} is servicing ${de.current.sender_alias} (${de.current.sender_teamfile}) since ${de.current.started_at} \u2014 wait and retry`;return w!==null&&await C(e,ke=>{ke.finishTrackedInvocation(w,{status:"busy",exit_code:1,error:Y,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${Y}`),null}x={row:de.lease,leaseId:de.leaseId};let Pe=Fr(Y=>C(e,ke=>ke.heartbeatAgentInflight(x.row,x.leaseId,Y)));R={stop:()=>clearInterval(Pe)};let ir=et(e,Y=>`batch ${Me()}: opening provider session (${Y}s elapsed)
|
|
2171
2172
|
`);try{let Y={...S};try{let ke=await C(e,P=>P.getRootTeam(y.teamfile)?.name??null);ke!==null&&(Y.LMBEE_TEAM_NAME=ke)}catch{}I=await zn({provider:y.provider,sessionId:y.sessionid,cwd:y.sessiondir,env:Y,...y.model!==void 0?{model:y.model}:{},...y.effort!==void 0?{effort:y.effort}:{},alias:y.alias,isLead:y.isLead,permissionMode:"yolo",holdOpen:es(e,{teamfile:y.teamfile,alias:y.alias},Y)}),F=!0}catch{R&&R.stop(),R=void 0,await Qc(e,x),x=void 0,F=!1}finally{ir.stop()}}let B={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(h),alias:String(g),batchfile:String(f),member:y,promptCount:T,useBundle:F,rootId:w,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:x,bundleSession:I,heartbeatTimer:R,closed:!1,env:S};return r.registerBatch(B),B}catch(N){if(R){try{R.stop()}catch{}R=void 0}if(x){try{await Qc(e,x)}catch{}x=void 0}if(I){try{await I.close()}catch{}I=void 0}if(w!==null)try{await C(e,B=>{B.finishTrackedInvocation(w,{status:"error",exit_code:1,error:N?.message||String(N),result_summary:"0 prompts completed"})})}catch{}throw N}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),t.registerFunction("lm_batch_turn",async(h,g,f,E)=>{let y=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;if(!y)throw new Error("Invalid or unmanaged batch handle");if(y.kind==="agent"){if(r.getBatch(y.id)!==y)throw new Error("Invalid or unmanaged batch handle");if(y.closed||y.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(y.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};y.inFlight=!0;try{let S=y.member.sessionid,w=await d(y.member,String(g),y.options);return y.member.sessionid&&y.sourceMember.provider===y.member.provider&&y.sourceMember.sessionid===S&&(y.sourceMember.sessionid=y.member.sessionid),w.status!=="ok"&&(y.failed=!0),{status:w.status,reply:w.reply.replace(/\n+$/u,""),error:w.error}}finally{y.inFlight=!1}}let T=Number(f),b=Number(E);e.stderr.write(`batch ${Me()}: prompt ${T}/${b} -> ${y.member.alias}
|
|
2172
2173
|
`);let v=et(e,S=>`batch ${Me()}: prompt ${T}/${b} still running (${S}s elapsed)
|
|
@@ -2188,7 +2189,7 @@ possibly work, seed reports it as an error and seeds nothing.
|
|
|
2188
2189
|
`)}};try{let d=ps(r,e,i,n);l=d;let u=await d.runAsync(t,{file:s,stderr:m=>{r.stderr.write(m.endsWith(`
|
|
2189
2190
|
`)?m:`${m}
|
|
2190
2191
|
`)}});if(c(),u.exitCode!==void 0)return u.exitCode;if(!u.success){for(let m of u.diagnostics){let p=m.file?`${m.file}:${m.line}:${m.column}`:`${m.line}:${m.column}`;r.stderr.write(`error:${p}: ${m.message}
|
|
2191
|
-
`)}return 1}return i.hasErrors()||u.errors&&u.errors.length>0?1:0}catch(d){return c(),d instanceof
|
|
2192
|
+
`)}return 1}return i.hasErrors()||u.errors&&u.errors.length>0?1:0}catch(d){return c(),d instanceof He||d?.name==="LMScriptExit"?d.exitCode:(r.stderr.write(`error: ${d instanceof Error?d.message:String(d)}
|
|
2192
2193
|
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var Rt,hN,yN,P_=k(()=>{"use strict";bc();Hi();Ue();At();Et();lo();In();bt();Wi();_e();Ut();nt();Qe();Sn();Qn();sn();Zn();yn();bc();Rt=class{batchHandles=new Map;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}async forceCloseAll(e){for(let r of this.getOpenBatches())await $_(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}};hN=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"Values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"Error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));yN={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:hN,register(t,e){_N(t,e.io,e.registry,e.env)}}});var W_={};se(W_,{formatCategoryOverview:()=>ed,formatFunctionDoc:()=>j_,formatModuleOverview:()=>B_,runScript:()=>wN});import{readFileSync as U_}from"node:fs";import{resolve as TN}from"node:path";function j_(t){let e="";if(e+=`Function: ${t.signature||t.name}
|
|
2193
2194
|
`,t.module&&(e+=`Module: ${t.module}
|
|
2194
2195
|
`),e+=`Category: ${t.category}
|
|
@@ -2494,7 +2495,7 @@ Start the stdio MCP bridge. The bridge resolves api.url and api.token from
|
|
|
2494
2495
|
local config, then uses stdin/stdout for JSON-RPC frames.
|
|
2495
2496
|
`});function My(t,e){if(t===void 0)return{date:void 0};let r=/^(\d+)([smhd])$/.exec(t);if(r!==null){let s=Number(r[1]),i=r[2],o=i==="s"?s:i==="m"?s*60:i==="h"?s*3600:s*86400;return{date:new Date(Date.now()-o*1e3)}}let n=Date.parse(t);return Number.isFinite(n)?{date:new Date(n)}:{error:`invalid ${e} "${t}" (expected ISO8601 or duration like 24h)`}}var $y=k(()=>{"use strict"});var Gy={};se(Gy,{applyMaxBytes:()=>bo,parseTailSince:()=>Xy,renderMessage:()=>Hy,runTail:()=>HL});async function HL(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${WL}
|
|
2496
2497
|
`),0;let r=oe(t,["--lines","--max-bytes","--watch-interval","--provider","--session","--run","--since"],["--watch","--help","--json"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=W(r,"--since"),i=Xy(s);if("error"in i)return A(e,i.error);let o=i.date,a=W(r,"--lines"),l=W(r,"--max-bytes");if(a!==void 0&&l!==void 0)return A(e,"--lines and --max-bytes are mutually exclusive (choose one)");let c;if(a!==void 0){let f=Number.parseInt(a,10);if(!Number.isFinite(f)||f<1||String(f)!==a)return A(e,`invalid --lines "${a}" (expected a positive integer)`);c={kind:"lines",lines:f}}else{let f=l===void 0?jL:Number.parseInt(l,10);if(!Number.isFinite(f)||f<0||l!==void 0&&String(f)!==l)return A(e,`invalid --max-bytes "${l}" (expected a non-negative integer)`);n&&l!==void 0&&e.stderr.write(`warning: --max-bytes has no effect under --json (byte-truncation has no JSON analog); ignoring
|
|
2497
|
-
`),c={kind:"bytes",maxBytes:f}}let d=X(r,"--watch"),u=W(r,"--watch-interval"),m=u===void 0?BL:Number.parseInt(u.replace(/s$/,""),10);if(!Number.isFinite(m)||m<1)return A(e,`invalid --watch-interval "${u}" (expected <N>s, N\u22651)`);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected [target] [alias]`);let p=W(r,"--run");if(p!==void 0){if(r.positionals.length>0)return A(e,"--run is mutually exclusive with positional [target] [alias]");if(W(r,"--session")!==void 0)return A(e,"--run is mutually exclusive with --session");if(W(r,"--provider")!==void 0)return A(e,"--run is mutually exclusive with --provider");let f=Number.parseInt(p,10);if(!Number.isFinite(f)||f<=0||String(f)!==p)return A(e,`invalid --run "${p}" (expected a positive integer run id)`);try{return await C(e,async E=>XL(e,E,f,c,d,m,o,n))}catch(E){return
|
|
2498
|
+
`),c={kind:"bytes",maxBytes:f}}let d=X(r,"--watch"),u=W(r,"--watch-interval"),m=u===void 0?BL:Number.parseInt(u.replace(/s$/,""),10);if(!Number.isFinite(m)||m<1)return A(e,`invalid --watch-interval "${u}" (expected <N>s, N\u22651)`);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected [target] [alias]`);let p=W(r,"--run");if(p!==void 0){if(r.positionals.length>0)return A(e,"--run is mutually exclusive with positional [target] [alias]");if(W(r,"--session")!==void 0)return A(e,"--run is mutually exclusive with --session");if(W(r,"--provider")!==void 0)return A(e,"--run is mutually exclusive with --provider");let f=Number.parseInt(p,10);if(!Number.isFinite(f)||f<=0||String(f)!==p)return A(e,`invalid --run "${p}" (expected a positive integer run id)`);try{return await C(e,async E=>XL(e,E,f,c,d,m,o,n))}catch(E){return Je(e,E)}}let _=it(UL,{target:r.positionals[0],alias:r.positionals[1],flags:{session:W(r,"--session"),provider:W(r,"--provider")}});if(_.mode==="error")return A(e,_.message);if(_.mode==="managed")return A(e,"tail managed mode requires --run <id>");let h;if(_.mode==="ai-team")if(_.alias===void 0){let f;try{f=await C(e,T=>ge(_.teamfile,T))}catch(T){return A(e,`tail: ${T instanceof Error?T.message:String(T)}`)}let E;try{E=Ae(f)}catch(T){return A(e,`tail: ${T instanceof Error?T.message:String(T)}`)}let y=Ot(E);if(y===void 0)return A(e,`tail: ${_.teamfile} has no Lead member; pass <tf>:<alias>`);try{let T=await C(e,b=>fe(_.teamfile,y.alias,b));h={provider:T.provider,sessionId:T.sessionid,cwd:T.sessiondir}}catch(T){return T instanceof ie?A(e,T.message):Je(e,T)}}else try{let f=await C(e,E=>fe(_.teamfile,_.alias,E));h={provider:f.provider,sessionId:f.sessionid,cwd:f.sessiondir}}catch(f){return f instanceof ie?A(e,f.message):Je(e,f)}else{let f=_.sessionid,E=_.provider;if(E===void 0){let y=await rn(f);if(y.length===0)return A(e,`tail: session "${f}" not found in any provider store`);if(y.length>1)return A(e,`tail: session "${f}" matches multiple providers (${y.join(", ")}); pass --provider`);E=y[0]}h={provider:E,sessionId:f}}let g=await Fy(e,h.provider,h.sessionId,c,-1,o,n);return g===So?1:d?await new Promise(f=>{let E=async()=>{try{let b=await Fy(e,h.provider,h.sessionId,c,g,o,n);b!==So&&(g=b)}catch(b){e.stderr.write(`tail: ${b instanceof Error?b.message:String(b)}
|
|
2498
2499
|
`)}},y=setInterval(()=>{E()},m*1e3),T=()=>{clearInterval(y),f(0)};process.once("SIGINT",T),process.once("SIGTERM",T)}):0}async function Fy(t,e,r,n,s,i,o){let a;try{a=await xe(r,e)}catch(m){return t.stderr.write(`tail: failed to load session: ${m instanceof Error?m.message:String(m)}
|
|
2499
2500
|
`),So}if(a===null)return t.stderr.write(`tail: session not found: ${r} (provider=${e})
|
|
2500
2501
|
`),So;let l=a.messages??[],c=s<0&&n.kind==="lines"?Math.max(0,l.length-n.lines):s+1;if(s<0&&i!==void 0){let m=i.getTime(),p=l.length;for(let _=0;_<l.length;_+=1){let h=l[_].timestamp,g=h===void 0?NaN:(h instanceof Date?h:new Date(h)).getTime();if(!Number.isNaN(g)&&g>=m){p=_;break}}c=Math.max(c,p)}let d=s<0&&c>0;if(c>=l.length)return o===!0&&s<0&&re(t,{schema_version:vo,provider:e,sessionId:r,messages:[],truncated:d}),l.length-1;if(o===!0){let m=l.slice(c).map(_=>({role:_.role,content:_.content,model:_.model??null,timestamp:(_.timestamp instanceof Date?_.timestamp:new Date(_.timestamp)).toISOString()}));return re(t,{schema_version:vo,provider:e,sessionId:r,messages:m,truncated:d}),l.length-1}let u="";for(let m=c;m<l.length;m+=1)u+=`${Hy(l[m])}
|
|
@@ -2534,7 +2535,7 @@ ignored under --json (a stderr note is printed if you passed it
|
|
|
2534
2535
|
explicitly); --lines still applies. --watch --json emits one JSON
|
|
2535
2536
|
object per poll tick with something new (NDJSON) -- a tick with
|
|
2536
2537
|
nothing new prints no line at all, same as text mode.`;So=-2;Uy=`\u2026 [truncated older output \u2014 raise with --max-bytes]
|
|
2537
|
-
`});var Ky={};se(Ky,{runExport:()=>qL});async function qL(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(Vy),0;let r=oe(t,[],["--prompt-only"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==2)return A(e,Vy.trimEnd());let n;try{n=fe(r.positionals[0],r.positionals[1],e.dal)}catch(a){return a instanceof ie?A(e,a.message):
|
|
2538
|
+
`});var Ky={};se(Ky,{runExport:()=>qL});async function qL(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(Vy),0;let r=oe(t,[],["--prompt-only"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==2)return A(e,Vy.trimEnd());let n;try{n=fe(r.positionals[0],r.positionals[1],e.dal)}catch(a){return a instanceof ie?A(e,a.message):Je(e,a)}let s;try{s=await xe(n.sessionid,n.provider)}catch(a){return A(e,`export: failed to load session: ${a instanceof Error?a.message:String(a)}`)}if(s===null)return A(e,`export: session not found: ${n.sessionid} (provider=${n.provider})`);let i=X(r,"--prompt-only"),o=[];if(i){let a=s.userPrompts??s.messages.filter(l=>l.role==="user").map(l=>l.content);for(let l of a){if(l.trimStart().replace(/^["']/u,"").startsWith("lmctl seed initial connection only. Create or pin this provider session, then stop."))continue;let c=l.split(/\r\n|[\r\n\u2028\u2029]/u).map(d=>d.trim()).filter(Boolean).join(" ");c!==""&&o.push(c)}}else for(let a of s.messages)a.role!=="user"&&a.role!=="assistant"||a.content.trim()!==""&&o.push(`${a.role}:
|
|
2538
2539
|
${a.content}`);return o.length>0&&e.stdout.write(`${o.join(`
|
|
2539
2540
|
|
|
2540
2541
|
`)}
|
|
@@ -2581,7 +2582,7 @@ unavailable) and
|
|
|
2581
2582
|
strict short timeout and NEVER blocks or fails this command: any network
|
|
2582
2583
|
error degrades silently to the local cache, then the bundled built-in
|
|
2583
2584
|
copy, in that order.`});var eE={};se(eE,{runLs:()=>eC});import{resolve as yd}from"node:path";function ZL(t){let e=new Map;for(let r of t){let n=`${r.provider}:${r.sessionId}`,s=e.get(n);(s===void 0||r.modifiedAt.getTime()>s.modifiedAt.getTime())&&e.set(n,r)}return[...e.values()]}async function eC(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${zL}
|
|
2584
|
-
`),0;let r=oe(t,["--provider","--sessiondir","--format","--limit"],["--recursive","--all","--json","--runs","--help"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>0)return A(e,"ls does not accept positional targets (use --provider/--sessiondir/--all to filter)");let n=W(r,"--format"),s=X(r,"--json");if(X(r,"--runs")){for(let g of["--provider","--sessiondir"])if(W(r,g)!==void 0)return A(e,`--runs is mutually exclusive with ${g}`);for(let g of["--recursive","--all"])if(X(r,g))return A(e,`--runs is mutually exclusive with ${g}`);if(n==="teamfile")return A(e,"--runs is mutually exclusive with --format teamfile (runs are not teamfile members)");let p=W(r,"--limit"),_=QL;if(p!==void 0){let g=Number.parseInt(p,10);if(!Number.isFinite(g)||g<1||String(g)!==p)return A(e,`invalid --limit "${p}" (expected a positive integer)`);if(g>Zy)return A(e,`--limit ${g} exceeds maximum (${Zy})`);_=g}let h=n==="json"||s===!0?"json":"table";try{return await C(e,async g=>tC(e,g,_,h))}catch(g){return
|
|
2585
|
+
`),0;let r=oe(t,["--provider","--sessiondir","--format","--limit"],["--recursive","--all","--json","--runs","--help"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>0)return A(e,"ls does not accept positional targets (use --provider/--sessiondir/--all to filter)");let n=W(r,"--format"),s=X(r,"--json");if(X(r,"--runs")){for(let g of["--provider","--sessiondir"])if(W(r,g)!==void 0)return A(e,`--runs is mutually exclusive with ${g}`);for(let g of["--recursive","--all"])if(X(r,g))return A(e,`--runs is mutually exclusive with ${g}`);if(n==="teamfile")return A(e,"--runs is mutually exclusive with --format teamfile (runs are not teamfile members)");let p=W(r,"--limit"),_=QL;if(p!==void 0){let g=Number.parseInt(p,10);if(!Number.isFinite(g)||g<1||String(g)!==p)return A(e,`invalid --limit "${p}" (expected a positive integer)`);if(g>Zy)return A(e,`--limit ${g} exceeds maximum (${Zy})`);_=g}let h=n==="json"||s===!0?"json":"table";try{return await C(e,async g=>tC(e,g,_,h))}catch(g){return Je(e,g)}}let o=rC(n,s);if("error"in o)return A(e,o.error);let a=o.format,l=W(r,"--provider"),c=W(r,"--sessiondir"),d=X(r,"--recursive"),u=X(r,"--all"),m;try{m=await ac(l?{provider:l}:{})}catch(p){return A(e,`ls: discovery failed: ${p instanceof Error?p.message:String(p)}`)}if(!u){let p=c!==void 0?yd(c):yd(process.cwd());m=m.filter(_=>{let h=yd(_.cwd);return d?h===p||h.startsWith(`${p}/`):h===p})}if(m=ZL(m),a==="json")return re(e,m.map(p=>({provider:p.provider,sessionId:p.sessionId,cwd:p.cwd,messageCount:p.messageCount,modifiedAt:p.modifiedAt.toISOString(),...p.model!==void 0?{model:p.model}:{}}))),0;if(m.length===0){if(a==="table"){let p=u?"(all)":c??process.cwd(),_=d?"under":"in";e.stdout.write(`No native sessions found ${_} ${p}.
|
|
2585
2586
|
`)}return 0}if(a==="teamfile"){for(let p of m)e.stdout.write(`_MEMBER_ alias=- provider=${p.provider} sessionid=${p.sessionId} sessiondir=${p.cwd}
|
|
2586
2587
|
`);return 0}return(0,Le.printTable)(m.map(p=>[(0,Le.escapeCell)(p.sessionId),(0,Le.escapeCell)(p.provider),(0,Le.escapeCell)(p.cwd.length>36?`\u2026${p.cwd.slice(-35)}`:p.cwd),(0,Le.formatRelativeTime)(p.modifiedAt)]),{headers:["SESSION","PROVIDER","SESSIONDIR","MODIFIED"],stream:e.stdout}),0}async function tC(t,e,r,n){let s=G_(e,{limit:r});return n==="json"?(re(t,s.map(i=>({id:i.id,job_id:i.job_id,workflow_id:i.workflow_id,team_id:i.team_id,current_state:i.current_state,terminal_state:i.terminal_state,started_at:i.started_at,ended_at:i.ended_at,paused_at:i.paused_at}))),0):s.length===0?(t.stdout.write(`No runs found.
|
|
2587
2588
|
`),0):((0,Le.printTable)(s.map(i=>[(0,Le.escapeCell)(i.id),(0,Le.escapeCell)(i.workflow_id),(0,Le.escapeCell)(i.team_id),(0,Le.escapeCell)(i.current_state??""),(0,Le.escapeCell)(i.terminal_state??""),(0,Le.escapeCell)(i.started_at)]),{headers:["RUN_ID","WORKFLOW","TEAM","STATE","TERMINAL","STARTED"],stream:t.stdout}),0)}function rC(t,e){return t===void 0?{format:e?"json":"teamfile"}:t==="table"||t==="teamfile"||t==="json"?{format:t}:{error:`invalid --format "${t}" (expected: table | teamfile | json)`}}var Le,zL,QL,Zy,tE=k(()=>{"use strict";Le=_t(dt(),1);bt();_e();rd();zL=`usage: lmctl ls [--provider <name>] [--sessiondir <path>]
|
|
@@ -2615,7 +2616,7 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2615
2616
|
|
|
2616
2617
|
--force Overwrite ~/.lmctl/init.toml if it already exists
|
|
2617
2618
|
-h, --help display help for command
|
|
2618
|
-
`});import{execFileSync as iC}from"node:child_process";import{resolve as sE}from"node:path";function oC(t){return t.filter(e=>e.state!=="retired")}function iE(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?A(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=iC("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return A(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=sE(s),o=e.listProjects().find(a=>sE(a.local_path)===i);return o===void 0?A(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function oE(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?A(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?A(t,`project ${r.name} has no assigned team; use --team <name>`):s}function aE(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?A(t,`member not found: ${n}`):i}let s=oC(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?A(t,`team ${r.name} has no active agent member`):s}var lE=k(()=>{"use strict";_e()});var uE={};se(uE,{SIZE_WARN_EST_TOKENS:()=>Ts,estimateTokens:()=>dE,runTerminal:()=>Ed});import{spawn as aC}from"node:child_process";import{statSync as lC}from"node:fs";async function Ed(t,e){if(t.includes("--help")||t.includes("-h"))return gC(e);let r=oe(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return A(e,r.error);let n=W(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return A(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return A(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"?X(r,o):W(r,o)!==void 0)return A(e,`--run is mutually exclusive with ${o}`);try{return await C(e,async o=>{let a=W(r,"--alias"),l=X_(o,s,a);return"err"in l?A(e,l.err):Td(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
|
|
2619
|
+
`});import{execFileSync as iC}from"node:child_process";import{resolve as sE}from"node:path";function oC(t){return t.filter(e=>e.state!=="retired")}function iE(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?A(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=iC("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return A(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=sE(s),o=e.listProjects().find(a=>sE(a.local_path)===i);return o===void 0?A(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function oE(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?A(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?A(t,`project ${r.name} has no assigned team; use --team <name>`):s}function aE(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?A(t,`member not found: ${n}`):i}let s=oC(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?A(t,`team ${r.name} has no active agent member`):s}var lE=k(()=>{"use strict";_e()});var uE={};se(uE,{SIZE_WARN_EST_TOKENS:()=>Ts,estimateTokens:()=>dE,runTerminal:()=>Ed});import{spawn as aC}from"node:child_process";import{statSync as lC}from"node:fs";async function Ed(t,e){if(t.includes("--help")||t.includes("-h"))return gC(e);let r=oe(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return A(e,r.error);let n=W(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return A(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return A(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"?X(r,o):W(r,o)!==void 0)return A(e,`--run is mutually exclusive with ${o}`);try{return await C(e,async o=>{let a=W(r,"--alias"),l=X_(o,s,a);return"err"in l?A(e,l.err):Td(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 Je(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?X(r,l):W(r,l)!==void 0)return A(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=it(cC,{target:i,alias:o,flags:{}});return a.mode==="error"?A(e,a.message):a.mode!=="ai-team"?A(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?A(e,"terminal: alias required for the teamfile target"):await C(e,l=>dC(e,a.teamfile,a.alias,l,X(r,"--json")))}try{return await C(e,async s=>{let i=fC(e,s,r);if(typeof i=="number")return i;let o=W(r,"--alias");return X(r,"--size")?hC(e,s,i,o,X(r,"--json")):pC(e,s,i,o)})}catch(s){return Je(e,s)}}async function dC(t,e,r,n,s){let i;try{i=fe(e,r,n)}catch(m){return m instanceof ie?A(t,m.message):Je(t,m)}let o=$t(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:at()});if(!o.acquired){let m=o.current.holder_pid,p=m===null?null:Ne(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}, ${p})`);return s?(re(t,{status:"error",errorKind:"busy",message:_,holder_pid:m,holder_liveness:p}),1):A(t,_)}let a=Zh({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,d=null,u=[];try{n.setTerminalLock(a),c=uC(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 p=new Date().toISOString(),_=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,p);_&&n.heartbeatAgentInflight(o.lease,o.leaseId,p),!_&&l!==null&&(clearInterval(l),l=null)}catch{}},eg()),l.unref?.();try{Dr(t,Ae(i.teamfile),i.teamfile)}catch{}return d=await Td(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},p=>{u.push(`${p.provider} terminal ignored model=${p.model}: ${p.reason}`)}),d}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),mC(n,c,d,u)}}function uC(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:Bt(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 mC(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 Td(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!Bi(n))return A(t,`no resume incantation for provider "${n}"`);if(!qh.test(s))return A(t,"refusing to resume: malformed sessionid");let a=uc(n,s,{isLead:e.isLead,model:o,onModelIgnored:d=>{let u=`warning: ${d.provider} terminal ignored model=${d.model}: ${d.reason}`;t.stderr.write(`${u}
|
|
2619
2620
|
`),Se({event:"model_ignored",provider:d.provider,model:d.model,reason:d.reason}),r?.(d)}});if(a===null||a.length===0)return A(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(d=>{let u=aC(l,c,{stdio:"inherit",cwd:i,env:we(process.env,i,s,"terminal")});u.on("error",m=>{d(A(t,`failed to launch ${l}: ${m.message}`))}),u.on("exit",m=>d(m??0))})}function fC(t,e,r){let n=W(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?A(t,`team not found: ${n}`):o}let s=iE(t,e,W(r,"--project"));return typeof s=="number"?s:oE(t,e,s,void 0)}async function pC(t,e,r,n){let s=aE(t,e,r,n);if(typeof s=="number")return s;let i=s.sessionid;return i===null||i.trim().length===0?A(t,`member ${s.alias} has no session yet \u2014 seed it first: lmctl seed <teamfile> (check with lmctl status <teamfile>)`):Td(t,{provider:ya(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function dE(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=lC(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 hC(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 A(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=ya(a),d=a.model??null,u=null;Bi(c)&&(u=await xe(l,c));let m=dE(u),p=m.est>Ts;o.push({alias:a.alias,provider:c,sessionid:l,messages:m.messages,bytes:m.bytes,est_tokens:m.est,estimate:!0,over_guide:p,model:d,resume_incantation:p?Gh(c,l,d!==null?{model:d}:{}):null})}if(s)return re(t,{estimate:!0,legend:cE,guide_tokens:Ts,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
2620
2621
|
`),t.stdout.write(`${cE}
|
|
2621
2622
|
`);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)
|
|
@@ -2697,8 +2698,8 @@ Example:
|
|
|
2697
2698
|
lmctl hello claude -p "hi"
|
|
2698
2699
|
`});import{execFileSync as vd}from"node:child_process";import{dirname as yE,resolve as RC}from"node:path";function EE(t){return(0,Sd.formatCount)(t)}async function bd(t,e){return C(t,r=>{let n=r.query(`SELECT config_warnings FROM tracked_invocation
|
|
2699
2700
|
WHERE target_teamfile = ? AND target_alias = ? AND config_warnings IS NOT NULL
|
|
2700
|
-
ORDER BY started_at DESC LIMIT 1`,e.teamfile,e.alias);if(n.length!==0)try{let s=JSON.parse(n[0].config_warnings);if(!Array.isArray(s))return;let i=s.filter(o=>typeof o=="string"&&o.length>0);return i.length>0?i:void 0}catch{return}})}function Id(t,e,r,n){let s=ge(t,e);if(r.has(s))return[];r.add(s);let i=
|
|
2701
|
-
`)}catch{}}async function YC(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(VC),0;let r=t.find(a=>a==="--project"||a.startsWith("--project=")||a==="--web");if(r!==void 0)return A(e,`unknown option ${r}; lmctl status is team/SELF scoped now`);let n=oe(t,["--since"],["--json","--details"]);if(n.error!==void 0)return A(e,n.error);let s=X(n,"--json"),i=X(n,"--details");if(n.positionals.length>0){let a=await QC(e,n.positionals,{json:s,details:i,since:W(n,"--since")});return a===0&&Cd({verb:"status",args:t}),a}if(i)return A(e,"--details only applies with a teamfile argument (lmctl status <teamfile> --details)");let o=EO(W(n,"--since"));if("error"in o)return A(e,o.error);try{let a=e.env??process.env;if(s){let l=await C(e,c=>AE(c,a));re(e,{schema_version:Pd,...l})}else{let l=await C(e,async c=>uO(await AE(c,a),{sinceIso:o.iso}));e.stdout.write(l)}return Cd({verb:"status",args:t}),0}catch(a){return A(e,a instanceof Error?a.message:String(a))}}async function QC(t,e,r){if(e.length>2)return A(t,`too many positionals (${e.length}); expected <teamfile> [alias]`);if(r.since!==void 0)return A(t,"--since only applies to the activity view (lmctl status with no teamfile argument)");let n=it(zC,{target:e[0],alias:e[1],flags:{}});if(n.mode==="error")return A(t,n.message);if(n.mode!=="ai-team")return A(t,"lmctl status: expected <teamfile> [alias]");try{return n.alias===void 0?await TO(t,n.teamfile,r.json,r.details):await xO(t,n.teamfile,n.alias,r.json)}catch(s){return s instanceof ie?A(t,s.message):A(t,`status: ${s instanceof Error?s.message:String(s)}`)}}async function AE(t,e){let r=hc(e,t);if(!r.ok){if(r.reason==="not-found")throw new Error(It("status"));return await eO(t)}return await ZC(t,r.identity)}async function ZC(t,e){let r=xt(e),n=t.getRootTeam(r.teamfile);if(n===null)throw new Error(It("status"));let s=
|
|
2701
|
+
ORDER BY started_at DESC LIMIT 1`,e.teamfile,e.alias);if(n.length!==0)try{let s=JSON.parse(n[0].config_warnings);if(!Array.isArray(s))return;let i=s.filter(o=>typeof o=="string"&&o.length>0);return i.length>0?i:void 0}catch{return}})}function Id(t,e,r,n){let s=ge(t,e);if(r.has(s))return[];r.add(s);let i=Xe(s,e);if(i.parseErrors.length>0)throw new Error(`${s}: ${i.parseErrors.join("; ")}`);let o=[];for(let a of i.members){if(a.teamfile!==void 0){o.push(...Id(RC(yE(s),a.teamfile),e,r,[...n,a.alias]));continue}o.push({teamfile:s,alias:a.alias,reportPath:[...n,a.alias].join("/"),provider:a.provider,sessionid:a.session!==void 0&&a.session.length>0?a.session:null,model:a.model??null})}return o}async function xd(t,e){try{let r=await C(t,n=>e.map(s=>{let i=lt(n,s.teamfile,s.alias);return[xo(s.teamfile,s.alias),NC(i)]}));return new Map(r)}catch{return new Map}}function xo(t,e){return`${t}\0${e.toLowerCase()}`}function NC(t){return t.busy?t.reason==="terminal-held"?t.source==="terminal-invocation"?{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:null,terminalInvocation:{id:t.terminalInvocation.id,startedAt:t.terminalInvocation.started_at,lastHeartbeat:t.terminalInvocation.last_heartbeat_at,holderPid:t.terminalInvocation.holder_pid,holderHost:t.terminalInvocation.holder_host},reclaimable:null}:{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:{startedAt:t.terminalLock.started_at,lastHeartbeat:t.terminalLock.last_heartbeat,holderPid:t.terminalLock.holder_pid,holderHost:t.terminalLock.holder_host},terminalInvocation:null,reclaimable:null}:{state:"busy",reason:"in-flight",inFlight:{senderTeamfile:t.inFlight.sender_teamfile,senderAlias:t.inFlight.sender_alias,startedAt:t.inFlight.started_at,activeCount:t.inFlight.active_count,holderPid:t.inFlight.holder_pid},terminalLock:null,terminalInvocation:null,reclaimable:null}:ko(t.reclaimable===void 0?null:{source:t.reclaimable.source,holderPid:t.reclaimable.holder_pid,holderHost:t.reclaimable.holder_host,reason:t.reclaimable.reason})}function ko(t=null){return{state:"idle",reason:null,inFlight:null,terminalLock:null,terminalInvocation:null,reclaimable:t}}function Ao(t){if(t.state!=="idle")return`busy (${t.reason})`;if(t.reclaimable!==null){let{holderPid:e,holderHost:r,reason:n}=t.reclaimable;return`idle (reclaimable lock: ${e!==null?`pid ${e}${r!==null?` on ${r}`:""}`:"holder"} ${n==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale"})`}return"idle"}function kd(t){return t.resets_at!==null?t.resets_at:t.timezone!==null?`${t.reset_time} (${t.timezone})`:t.reset_time}function Ke(t){return t==null?"unknown":(0,Sd.formatCount)(t)}function TE(t){return t==="n/a"?t:Ke(t)}function wE(t,e,r=String){return t!==void 0?r(t):e?"n/a":"unknown"}function Ad(t){let e=yE(t),r;try{vd("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-repo",teamDir:e}}try{r=vd("git",["-C",e,"log","-2","--format=%ct"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-commits",teamDir:e}}let n=r.split(/\r?\n/).map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(n.length===0)return{kind:"unavailable",reason:"no-commits",teamDir:e};let s=n.slice(0,2).map((i,o)=>({ref:o===0?"HEAD":`HEAD~${o}`,timestamp:new Date(i*1e3)}));return{kind:"repo",teamDir:e,since:s[0].timestamp,commits:s,working:LC(e)}}function LC(t){let e;try{e=vd("git",["-C",t,"status","--porcelain"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{uncommittedTracked:null,untracked:null}}let r=0,n=0;for(let s of e.split(/\r?\n/))s.trim().length!==0&&(s.startsWith("??")?n+=1:r+=1);return{uncommittedTracked:r,untracked:n}}function Rd(t,e){let r=e.getTime();return t.messages.filter(n=>(n.role==="user"||n.role==="assistant")&&Number.isFinite(n.timestamp.getTime())&&n.timestamp.getTime()>r).length}function Nd(t){if(t===null)return null;let e=[t.totalInputTokens,t.totalCachedInputTokens,t.totalCacheWriteInputTokens,t.totalOutputTokens,t.totalReasoningOutputTokens].filter(r=>typeof r=="number"&&Number.isFinite(r));return e.length===0?null:e.reduce((r,n)=>r+n,0)}var Sd,vE=k(()=>{"use strict";Sd=_t(dt(),1);Qe();_e();Tt()});function Ld(t){for(let e=t.length-1;e>=0;e-=1){let r=t[e],n=CC.exec(r.content);if(n===null){if(r.role==="assistant"&&r.content.trim().length>0)return null;continue}let s=Number.parseInt(n[1],10),i=n[2]===void 0?0:Number.parseInt(n[2],10),o=n[3].toLowerCase(),a=n[4]?.trim()??null,l=`${n[1]}${n[2]!==void 0?`:${n[2]}`:""}${o}`;return{state:"LIMITED",resets_at:a===null?null:OC(r.timestamp,s,i,o,a),reset_time:l,timezone:a,detected_at:r.timestamp.toISOString()}}return null}function OC(t,e,r,n,s){if(!Number.isFinite(t.getTime())||e<1||e>12||r<0||r>59)return null;let i=DC(e,n);try{let o=MC(t,s),a=SE(o.year,o.month,o.day,i,r,s);if(a.getTime()<=t.getTime()){let l=UC(o,1);a=SE(l.year,l.month,l.day,i,r,s)}return a.toISOString()}catch{return null}}function DC(t,e){return e==="am"?t===12?0:t:t===12?12:t+12}function MC(t,e){let r=bE(e,!1).formatToParts(t);return{year:Nt(r,"year"),month:Nt(r,"month"),day:Nt(r,"day")}}function SE(t,e,r,n,s,i){let o=Date.UTC(t,e-1,r,n,s,0,0);for(let a=0;a<3;a+=1){let l=$C(new Date(o),i);o=Date.UTC(t,e-1,r,n,s,0,0)-l}return new Date(o)}function $C(t,e){let r=bE(e,!0).formatToParts(t);return Date.UTC(Nt(r,"year"),Nt(r,"month")-1,Nt(r,"day"),Nt(r,"hour"),Nt(r,"minute"),Nt(r,"second"),0)-t.getTime()}function bE(t,e){let r=e?PC:FC,n=r.get(t);if(n!==void 0)return n;let s=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",...e?{hour:"2-digit",minute:"2-digit",second:"2-digit"}:{}});return r.set(t,s),s}function Nt(t,e){let r=t.find(n=>n.type===e)?.value;if(r===void 0)throw new Error(`missing ${e}`);return Number.parseInt(r,10)}function UC(t,e){let r=new Date(Date.UTC(t.year,t.month-1,t.day+e));return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}}var CC,FC,PC,IE=k(()=>{"use strict";CC=/you['\u2019]ve hit your session limit\s*(?:\u00b7|-|:)?\s*resets\s+([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;FC=new Map,PC=new Map});var PE={};se(PE,{appendIntent:()=>Cd,formatAge:()=>ws,formatDuration:()=>Lo,resolveIntentLogPath:()=>LE,runStatus:()=>YC,shortIdentity:()=>gt});import{appendFileSync as jC,existsSync as BC,mkdirSync as WC}from"node:fs";import{homedir as HC}from"node:os";import{basename as XC,dirname as NE,isAbsolute as qC,join as GC,resolve as JC}from"node:path";function LE(){return process.env.LMCTL_INTENT_LOG??GC(HC(),".lmctl","recent-intents.log")}function Cd(t){try{let e=LE();WC(NE(e),{recursive:!0});let r=JSON.stringify({ts:t.ts??new Date().toISOString(),cwd:t.cwd??process.cwd(),verb:t.verb,args:[...t.args]});jC(e,`${r}
|
|
2702
|
+
`)}catch{}}async function YC(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(VC),0;let r=t.find(a=>a==="--project"||a.startsWith("--project=")||a==="--web");if(r!==void 0)return A(e,`unknown option ${r}; lmctl status is team/SELF scoped now`);let n=oe(t,["--since"],["--json","--details"]);if(n.error!==void 0)return A(e,n.error);let s=X(n,"--json"),i=X(n,"--details");if(n.positionals.length>0){let a=await QC(e,n.positionals,{json:s,details:i,since:W(n,"--since")});return a===0&&Cd({verb:"status",args:t}),a}if(i)return A(e,"--details only applies with a teamfile argument (lmctl status <teamfile> --details)");let o=EO(W(n,"--since"));if("error"in o)return A(e,o.error);try{let a=e.env??process.env;if(s){let l=await C(e,c=>AE(c,a));re(e,{schema_version:Pd,...l})}else{let l=await C(e,async c=>uO(await AE(c,a),{sinceIso:o.iso}));e.stdout.write(l)}return Cd({verb:"status",args:t}),0}catch(a){return A(e,a instanceof Error?a.message:String(a))}}async function QC(t,e,r){if(e.length>2)return A(t,`too many positionals (${e.length}); expected <teamfile> [alias]`);if(r.since!==void 0)return A(t,"--since only applies to the activity view (lmctl status with no teamfile argument)");let n=it(zC,{target:e[0],alias:e[1],flags:{}});if(n.mode==="error")return A(t,n.message);if(n.mode!=="ai-team")return A(t,"lmctl status: expected <teamfile> [alias]");try{return n.alias===void 0?await TO(t,n.teamfile,r.json,r.details):await xO(t,n.teamfile,n.alias,r.json)}catch(s){return s instanceof ie?A(t,s.message):A(t,`status: ${s instanceof Error?s.message:String(s)}`)}}async function AE(t,e){let r=hc(e,t);if(!r.ok){if(r.reason==="not-found")throw new Error(It("status"));return await eO(t)}return await ZC(t,r.identity)}async function ZC(t,e){let r=xt(e),n=t.getRootTeam(r.teamfile);if(n===null)throw new Error(It("status"));let s=Xe(n.teamfile_path,t),i=Dd(No(t,{from:r.value})),o=Dd(No(t,{target_teamfile:r.teamfile,target_alias:r.alias})),a=sO([...Od(t,{from:r.value}),...Od(t,{target_teamfile:r.teamfile,target_alias:r.alias})]);return{scope:"self",identity:r.value,...CE(),team:{name:s.name,teamfile:n.teamfile_path},members:s.members.map(l=>rO(t,n.teamfile_path,l)),activity:{from_me:i.map(l=>Md(l)),to_me:o.map(l=>Md(l))},transcript_harvest:await OE(a)}}function CE(){let t=null;try{t=af(Hr())}catch{}return{db_path:he(),site_name:t}}async function eO(t){let e=t.listRootTeams();return{scope:"db",identity:null,...CE(),teams:e.map(r=>tO(t,r)),activity:Dd(No(t)).map(r=>Md(r)),transcript_harvest:await OE(Od(t))}}function tO(t,e){if(!BC(e.teamfile_path))return{name:e.name,teamfile:e.teamfile_path,member_count:0,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at,missing_on_disk:!0};let r=0;try{r=Xe(e.teamfile_path,t).members.length}catch{r=0}return{name:e.name,teamfile:e.teamfile_path,member_count:r,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at}}function rO(t,e,r){let n=r.teamfile===void 0?null:ge(qC(r.teamfile)?r.teamfile:JC(NE(e),r.teamfile),t),s=lt(t,e,r.alias),i=s.busy&&s.reason==="in-flight"?nO(t,e,r.alias,s.inFlight):null;return{alias:r.alias,provider:r.provider,model:r.model??null,teamfile:e,referenced_teamfile:n,sessionid:r.session??null,sessiondir:r.sessiondir??null,state:s.busy?"busy":"idle",reason:s.busy?s.reason:null,handling:i,reclaimable:!s.busy&&s.reclaimable!==void 0?s.reclaimable:null}}function nO(t,e,r,n){let s=n.sender_alias==="operator"?"operator":`${n.sender_teamfile}:${n.sender_alias}`,o=t.db.prepare(`
|
|
2702
2703
|
SELECT * FROM tracked_invocation
|
|
2703
2704
|
WHERE kind = 'chat'
|
|
2704
2705
|
AND status = 'running'
|
|
@@ -2716,7 +2717,7 @@ Example:
|
|
|
2716
2717
|
|
|
2717
2718
|
`),assistantTimestamp:cO(s[s.length-1]?.timestamp)}}function cO(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function dO(t){if(!(t===null||t.trim()===""))try{let e=JSON.parse(t);if(!Array.isArray(e))return;let r=e.filter(n=>typeof n=="string"&&n.length>0);return r.length>0?r:void 0}catch{return}}function Md(t){let e=dO(t.config_warnings);return{id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:Ft(t),from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:RE(t.result_summary),error:RE(t.error),...e!==void 0?{config_warnings:e}:{}}}function uO(t,e){return t.scope==="self"?fO(t,e):pO(t,e)}function mO(t){if(t===null)return"idle";let e=t.holder_pid!==null?`pid ${t.holder_pid}${t.holder_host!==null?` on ${t.holder_host}`:""}`:"holder",r=t.reason==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale";return`idle (reclaimable lock: ${e} ${r})`}function fO(t,e){let r=[];r.push(`identity: ${t.identity}`),r.push(`team: ${t.team.name}`),r.push(`teamfile: ${t.team.teamfile}`),r.push(""),r.push("members:"),t.members.length===0&&r.push(" none");for(let n of t.members){let s=n.model===null?"":` model=${n.model}`,i=n.sessionid===null?"":` session=${n.sessionid}`,o=n.state==="idle"?mO(n.reclaimable):`busy (${n.reason})`,a=n.handling===null?"":` handling="${n.handling.request_preview}"`;r.push(` ${n.alias}: ${o} provider=${n.provider}${s}${i}${a}`)}return r.push(""),r.push("transcript harvest:"),ME(r,t.transcript_harvest,"self"),r.push(""),r.push("activity from me:"),$d(r,Fd(t.activity.from_me,e.sinceIso),"from-me"),r.push(""),r.push("activity to me:"),$d(r,Fd(t.activity.to_me,e.sinceIso),"to-me"),r.push(""),r.push(DE(t)),r.join(`
|
|
2718
2719
|
`)}function pO(t,e){let r=[];r.push("scope: db"),r.push("identity: none"),r.push(""),r.push("teams:"),t.teams.length===0&&r.push(" none");for(let n of t.teams){let s=n.name===null?"(unnamed)":n.name;r.push(` ${s}: ${n.teamfile} (${n.member_count} members)`)}return r.push(""),r.push("transcript harvest:"),ME(r,t.transcript_harvest,"db"),r.push(""),r.push("recent activity:"),$d(r,Fd(t.activity,e.sinceIso),"db"),r.push(""),r.push(DE(t)),r.join(`
|
|
2719
|
-
`)}function DE(t){return hn(t.db_path)}function $d(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Ro))hO(t,n,r);$E(t,e.length,Ro,"older")}function ME(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Ro)){let s=r==="db"?` from ${gt(n.from_identity)} -> ${gt(n.target)}`:` -> ${gt(n.target)}`;if(n.state==="completed"){let i=n.result_preview===null?"":` "${n.result_preview}"`;t.push(` #${n.tracked_invocation_id} completed in transcript; lmctl DB not finalized${s} since ${n.started_at}${i}`)}else t.push(` #${n.tracked_invocation_id} unreconciled${s} since ${n.started_at} (${n.reason??"unknown"})`);n.tail_hint.length>0&&t.push(` inspect: ${n.tail_hint}`)}$E(t,e.length,Ro,"more transcript harvest rows")}function Fd(t,e){let r=Date.parse(e);return Number.isFinite(r)?t.filter(n=>{let s=Date.parse(n.ended_at??n.started_at);return Number.isFinite(s)&&s>=r}):t}function hO(t,e,r){let n=_O(e,r),s=e.status==="running"?`since ${e.started_at}`:`ended ${e.ended_at??e.started_at}`,i=e.error??e.result,o=i===null?"":` "${FE(i)}"`;if(t.push(` #${e.id} ${gO(e)} ${e.kind}${n} ${s}${o}`),e.config_warnings!==void 0)for(let a of e.config_warnings)t.push(` config not applied: ${a}`)}function gO(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function _O(t,e){if(e==="from-me")return t.target===null?"":` -> ${gt(t.target)}`;if(e==="to-me")return` from ${gt(t.from_identity)}`;let r=t.target===null?"":` -> ${gt(t.target)}`;return` from ${gt(t.from_identity)}${r}`}function $E(t,e,r,n){let s=e-r;s>0&&t.push(` (+${s} ${n} -- use --json)`)}function RE(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function FE(t){let e=t.replace(/\s+/g," ").trim();return e.length<=xE?e:`${e.slice(0,xE-3)}...`}function yO(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=kE?e:`${e.slice(0,kE-3)}...`}function Lo(t){return(0,Ce.formatDuration)(t)}function ws(t){return(0,Ce.formatRelativeTime)(t)}function gt(t){if(t==="operator")return t;try{let e=xt(t);return`${XC(e.teamfile)}:${e.alias}`}catch{return t}}function EO(t){if(t===void 0)return{iso:new Date(Date.now()-KC).toISOString()};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2],i=s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400;return{iso:new Date(Date.now()-i*1e3).toISOString()}}let r=Date.parse(t);return Number.isFinite(r)?{iso:new Date(r).toISOString()}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}async function TO(t,e,r,n){let s=await C(t,d=>{let u=ge(e,d),m=
|
|
2720
|
+
`)}function DE(t){return hn(t.db_path)}function $d(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Ro))hO(t,n,r);$E(t,e.length,Ro,"older")}function ME(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Ro)){let s=r==="db"?` from ${gt(n.from_identity)} -> ${gt(n.target)}`:` -> ${gt(n.target)}`;if(n.state==="completed"){let i=n.result_preview===null?"":` "${n.result_preview}"`;t.push(` #${n.tracked_invocation_id} completed in transcript; lmctl DB not finalized${s} since ${n.started_at}${i}`)}else t.push(` #${n.tracked_invocation_id} unreconciled${s} since ${n.started_at} (${n.reason??"unknown"})`);n.tail_hint.length>0&&t.push(` inspect: ${n.tail_hint}`)}$E(t,e.length,Ro,"more transcript harvest rows")}function Fd(t,e){let r=Date.parse(e);return Number.isFinite(r)?t.filter(n=>{let s=Date.parse(n.ended_at??n.started_at);return Number.isFinite(s)&&s>=r}):t}function hO(t,e,r){let n=_O(e,r),s=e.status==="running"?`since ${e.started_at}`:`ended ${e.ended_at??e.started_at}`,i=e.error??e.result,o=i===null?"":` "${FE(i)}"`;if(t.push(` #${e.id} ${gO(e)} ${e.kind}${n} ${s}${o}`),e.config_warnings!==void 0)for(let a of e.config_warnings)t.push(` config not applied: ${a}`)}function gO(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function _O(t,e){if(e==="from-me")return t.target===null?"":` -> ${gt(t.target)}`;if(e==="to-me")return` from ${gt(t.from_identity)}`;let r=t.target===null?"":` -> ${gt(t.target)}`;return` from ${gt(t.from_identity)}${r}`}function $E(t,e,r,n){let s=e-r;s>0&&t.push(` (+${s} ${n} -- use --json)`)}function RE(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function FE(t){let e=t.replace(/\s+/g," ").trim();return e.length<=xE?e:`${e.slice(0,xE-3)}...`}function yO(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=kE?e:`${e.slice(0,kE-3)}...`}function Lo(t){return(0,Ce.formatDuration)(t)}function ws(t){return(0,Ce.formatRelativeTime)(t)}function gt(t){if(t==="operator")return t;try{let e=xt(t);return`${XC(e.teamfile)}:${e.alias}`}catch{return t}}function EO(t){if(t===void 0)return{iso:new Date(Date.now()-KC).toISOString()};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2],i=s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400;return{iso:new Date(Date.now()-i*1e3).toISOString()}}let r=Date.parse(t);return Number.isFinite(r)?{iso:new Date(r).toISOString()}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}async function TO(t,e,r,n){let s=await C(t,d=>{let u=ge(e,d),m=Xe(u,d);if(m.parseErrors.length>0)throw new Error(m.parseErrors.join("; "));return{teamfile:u,teamName:m.name,targets:Id(u,d,new Set,[])}}),i=Ad(s.teamfile),o=i.kind==="repo"?i:null,a=await xd(t,s.targets),l=[],c=0;for(let d of s.targets){let u={alias:d.alias,reportPath:d.reportPath,teamfile:d.teamfile,provider:d.provider,sessionid:d.sessionid,declaredModel:d.model,liveness:a.get(xo(d.teamfile,d.alias))??ko(),probed:!1,detailLoaded:!1},m=await bd(t,{teamfile:d.teamfile,alias:d.alias});if(m!==void 0&&(u.configWarnings=m),n&&d.sessionid!==null){u.probed=!0;let p=null;try{p=await xe(d.sessionid,d.provider)}catch(_){t.stderr.write(`warning: failed to load session "${d.sessionid}" for ${d.reportPath} (${d.provider}): ${_ instanceof Error?_.message:String(_)}
|
|
2720
2721
|
`)}u.detailLoaded=p!==null,u.messageCount=p?.messageCount??null,u.observedModel=p?.model??"(unknown)",u.lastContext=p?.lastInputTokens??null,u.totalInputTokens=p?.totalInputTokens??null,u.totalOutputTokens=p?.totalOutputTokens??null,p?.totalCachedInputTokens!==void 0&&(u.totalCachedInputTokens=p.totalCachedInputTokens),u.sessionLimit=p===null?null:Ld(p.messages),o!==null&&(u.activitySinceLastCommit={messageCount:p===null?null:Rd(p,o.since),tokens:null},u.cumulativeTokens=p===null?null:Nd(p)??"n/a"),p?.messageCount===void 0?c=void 0:c!==void 0&&(c+=p.messageCount)}l.push(u)}return r?(re(t,{schema_version:Pd,scope:"team",team:s.teamName,teamfile:s.teamfile,details:n,git:o===null?null:{teamDir:o.teamDir,commits:o.commits.map(d=>({ref:d.ref,timestamp:d.timestamp.toISOString()})),since:o.since.toISOString(),working:o.working},members:l.map(d=>{let u={alias:d.alias,reportPath:d.reportPath,teamfile:d.teamfile,provider:d.provider,sessionid:d.sessionid,seeded:d.sessionid!==null,model:d.declaredModel,liveness:d.liveness};return d.configWarnings!==void 0&&(u.config_warnings=d.configWarnings),d.probed&&(u.messageCount=d.messageCount??null,u.observed_model=d.observedModel,u.lastContext=d.lastContext??null,u.totalInputTokens=d.totalInputTokens??null,u.totalOutputTokens=d.totalOutputTokens??null,d.totalCachedInputTokens!==void 0&&(u.totalCachedInputTokens=d.totalCachedInputTokens),u.sessionLimit=d.sessionLimit??null,d.activitySinceLastCommit!==void 0&&(u.activitySinceLastCommit=d.activitySinceLastCommit),d.cumulativeTokens!==void 0&&(u.cumulativeTokens=d.cumulativeTokens==="n/a"?null:d.cumulativeTokens)),u}),...n?{total:{messageCount:c??null}}:{}}),0):(t.stdout.write(SO(s.teamName,s.teamfile,i,l,n,c)),0)}function wO(t){return t.sessionid??"(not seeded)"}function vO(t){return t.sessionid===null?"not seeded":Ao(t.liveness)}function SO(t,e,r,n,s,i){let o=[],a=r.kind==="repo"?r:null;if(o.push(`TEAM: ${t}`),o.push(`teamfile: ${e}`),r.kind==="repo"){o.push("Git progress:");for(let h of r.commits)o.push(` ${h.ref}: ${h.timestamp.toISOString()}`);o.push(` Uncommitted: ${Ke(r.working.uncommittedTracked)} changed (tracked), ${Ke(r.working.untracked)} untracked`)}else r.reason==="no-commits"?o.push(`Git progress: git repository in ${r.teamDir} has no commits (no commit-based progress to report)`):o.push(`Git progress: no git repository in ${r.teamDir} (no commit-based progress to report)`);if(!s){o.push("members:"),n.length===0&&o.push(" none");for(let h of n){let g=h.declaredModel===null?"":` model=${h.declaredModel}`;if(h.sessionid===null?o.push(` ${h.reportPath}: not seeded provider=${h.provider}${g} (run: lmctl seed "${h.teamfile}")`):o.push(` ${h.reportPath}: ${Ao(h.liveness)} provider=${h.provider}${g} session=${h.sessionid}`),h.configWarnings!==void 0)for(let f of h.configWarnings)o.push(` config not applied: ${f}`)}return o.push(""),o.push("session detail (observed model, messages, tokens, limits) not probed -- use --details"),`${o.join(`
|
|
2721
2722
|
`)}
|
|
2722
2723
|
`}let l=a!==null?["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT","MSGS SINCE COMMIT","TOKENS SINCE COMMIT","TOKENS (cumulative)"]:["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT"],c=l.map((h,g)=>g>=5?"right":"left"),d=!1,u=n.filter(h=>h.sessionLimit!=null),m=[];for(let h of n){let g=wE(h.lastContext??void 0,h.detailLoaded,EE);(g==="n/a"||h.cumulativeTokens==="n/a")&&(d=!0);let f=[(0,Ce.escapeCell)(wO(h)),(0,Ce.escapeCell)(h.reportPath),(0,Ce.escapeCell)(h.provider),(0,Ce.escapeCell)(h.observedModel??"(unknown)"),vO(h),Ke(h.messageCount),g];a!==null&&f.push(Ke(h.activitySinceLastCommit?.messageCount),Ke(h.activitySinceLastCommit?.tokens),TE(h.cumulativeTokens)),m.push(f)}let p=["TOTAL","","","","",Ke(i)];a!==null&&p.push("",Ke(bO(n)),Ke(null),Ke(IO(n))),m.push(p);let _=(0,Ce.formatTable)(m,{headers:l,align:c,margin:2}).split(`
|