@lmctl-ai/lmctl 0.2.18 → 0.2.19
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 +74 -72
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDescriptor;var oT=Object.getOwnPropertyNames;var aT=Object.getPrototypeOf,lT=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var cT=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),se=(t,e)=>{for(var r in e)Mo(t,r,{get:e[r],enumerable:!0})},dT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of oT(e))!lT.call(t,s)&&s!==r&&Mo(t,s,{get:()=>e[s],enumerable:!(n=iT(e,s))||n.enumerable});return t};var _t=(t,e,r)=>(r=t!=null?sT(aT(t)):{},dT(e||!t||!t.__esModule?Mo(r,"default",{value:t,enumerable:!0}):r,t));var ru={};se(ru,{defaultDbPath:()=>eu,describeStateLocation:()=>hn,isSlowWslMount:()=>tu,lmctlNextHome:()=>Zd,resolveDbPath:()=>he,warnIfSlowDbPath:()=>$o});import{platform as zd}from"node:os";import{homedir as uT}from"node:os";import{join as Qd}from"node:path";function Zd(){let t=process.env.LMCTL_HOME;return t!==void 0&&t.length>0?t:Qd(uT(),mT)}function eu(){return Qd(Zd(),fT)}function he(t){return t!==void 0&&t.length>0?t:process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?process.env.LMCTL_DB:eu()}function hn(t){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}function tu(t,e=zd()){return e!=="linux"?!1:t.startsWith("/mnt/c/")||t==="/mnt/c"}function $o(t,e=process.stderr,r=zd()){tu(t,r)&&e.write(`warning: DB on /mnt/c is slow; consider moving to ~/.lmctl/state.db (set LMCTL_DB or use --db)
|
|
2
|
-
`)}var mT,fT,nt=k(()=>{"use strict";mT=".lmctl",fT="state.db"});import{readFileSync as au,appendFileSync as yT,mkdirSync as ET,existsSync as
|
|
2
|
+
`)}var mT,fT,nt=k(()=>{"use strict";mT=".lmctl",fT="state.db"});import{readFileSync as au,appendFileSync as yT,mkdirSync as ET,existsSync as m0,readdirSync as f0,unlinkSync as p0}from"node:fs";import{join as Ss,dirname as TT}from"node:path";import{homedir as wT}from"node:os";function jo(){return Ss(wT(),".lmctl")}function lu(){Lr=!0,process.env.LMCTL_DEBUG="1"}function cu(){return{cliDebug:Lr,lmctlDebugEnv:process.env.LMCTL_DEBUG}}function du(t){Lr=t.cliDebug,t.lmctlDebugEnv===void 0?delete process.env.LMCTL_DEBUG:process.env.LMCTL_DEBUG=t.lmctlDebugEnv}function z(){if(Lr||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-ou>=vT&&(iu=IT(),ou=t),iu}function uu(){return Lr||process.env.LMCTL_DEBUG==="1"}function ST(){let t=new Date,e=t.getTimezoneOffset(),r=e<=0?"+":"-",n=String(Math.floor(Math.abs(e)/60)).padStart(2,"0"),s=String(Math.abs(e)%60).padStart(2,"0");return new Date(t.getTime()-e*6e4).toISOString().replace("Z",`${r}${n}:${s}`)}function Se(t,e){if(e?.verbose){if(!Lr)return}else if(!e?.always&&!z())return;try{bT();let r={ts:new Date().toISOString(),pid:process.pid,vti:process.env.LMCTL_VTI??null,autocode_run_id:process.env.LMCTL_AUTOCODE_RUN_ID??void 0,...t};yT(vs,JSON.stringify(r)+`
|
|
3
3
|
`)}catch{}}function bT(){if(!vs){let e=ST().slice(0,13).replace("T","-");vs=Ss(jo(),`debug-${e}.log`)}ET(TT(vs),{recursive:!0})}function Ee(...t){Se({event:"legacy",msg:t.join(" ")})}function Te(...t){Se({event:"legacy",msg:t.join(" ")},{verbose:!0})}function L(t){Se(t,{always:!0})}function IT(){return xT()||kT()}function xT(){try{let t=au(Ss(jo(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
4
4
|
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function kT(){try{let t=au(Ss(jo(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Lr,iu,ou,vT,vs,J=k(()=>{"use strict";Lr=!1,iu=!1,ou=0,vT=5e3;vs=null});var _u={};se(_u,{INFRA_CLI_CONTRACT_EXPECTED:()=>GT,INFRA_FLAT_COMMANDS:()=>gu,INFRA_NAMESPACE_COMMAND:()=>Wo,infraCliEnabled:()=>bs,isInfraCommand:()=>Is,runInfraCommand:()=>VT});function bs(t=process.env){return t.LMCTL_INFRA_CLI==="1"||t.LMCTL_INFRA_CLI==="true"}function Is(t){return gu.includes(t)||t===Wo}async function VT(t,e,r,n=KT){let s;try{s=await n()}catch{return r.stderr.write(JT),1}if(s.INFRA_CLI_CONTRACT!==1)return r.stderr.write(`lmctl: infra command library contract version ${s.INFRA_CLI_CONTRACT} does not match the version this lmctl build expects (1).
|
|
5
5
|
`),1;let i=t===Wo?e:[t,...e],o=s.createRuntime();return s.dispatch(i,o)}async function KT(){throw new Error("infra CLI adapter target (lmt) is retired; no successor module currently implements this contract")}var GT,gu,Wo,JT,Ho=k(()=>{"use strict";GT=1,gu=["lmchat","lmmail","lmnote","lmsheet","lmtext","lmsound","login","whoami","exec","tell","peers","site"],Wo="auto";JT=`lmctl: infra commands (site/auto/exec/tell/peers/login/whoami/lmchat/lmmail/lmnote/lmsheet/lmtext/lmsound) are not available in this build.
|
|
@@ -795,7 +795,7 @@ var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDe
|
|
|
795
795
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:r,mode:"best_effort"}})}
|
|
796
796
|
`))}function ww(){Qo=!1,Zo=null}function vw(){return Zo}function Sw(){return process.env.LMCTL_DB??fw(mw(),".lmctl","state.db")}var bu,Iu,gw,yt,Ct,Qo,Zo,Ns=k(()=>{"use strict";Ko();zo();bu=vu(pw(import.meta.url)),Iu=Su(bu,"schema.sql"),gw=Su(bu,"migrations"),yt=61,Ct=class extends Error{dbPath;dbVersion;buildVersion;constructor(e,r,n=yt){super(`${e}: state.db is v${r}; this build understands v${n} -- refusing to proceed rather than risk misreading newer data or corrupting it. Update: npm install -g @lmctl-ai/lmctl@latest -- or, only if you must run THIS exact build against this db right now, re-run with --allow-schema-skew (best-effort; newer data/features may be invisible).`),this.name="SchemaSkewError",this.dbPath=e,this.dbVersion=r,this.buildVersion=n}};Qo=!1;Zo=null;if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===hw(process.argv[1]).href){let t=gn({dbPath:process.argv[2]??Sw()});try{process.stdout.write(`migrated user_version=${xu(t)}
|
|
797
797
|
`)}finally{t.close()}}});function Au(t){if(t.length===0||!t.startsWith("---"))throw new st("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
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: ${Ls.join(", ")}`);r[c]=d}if(n===-1)throw new st("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Ls)if(r[o]===void 0)throw new st(`missing required frontmatter key "${o}" \u2014 required: ${Ls.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 Ls,bw,st,Ru=k(()=>{"use strict";Ls=["title","description","members"],bw=new Set(Ls),st=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as Iw,writeFileSync as
|
|
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: ${Ls.join(", ")}`);r[c]=d}if(n===-1)throw new st("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Ls)if(r[o]===void 0)throw new st(`missing required frontmatter key "${o}" \u2014 required: ${Ls.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 Ls,bw,st,Ru=k(()=>{"use strict";Ls=["title","description","members"],bw=new Set(Ls),st=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as Iw,writeFileSync as B0,renameSync as W0,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
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 Cs(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 Ds(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}
|
|
@@ -1097,7 +1097,7 @@ var sT=Object.create;var Mo=Object.defineProperty;var iT=Object.getOwnPropertyDe
|
|
|
1097
1097
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1098
1098
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(r,e.kind,e.origin,e.launch_source??e.kind,e.from_identity,e.target_teamfile,e.target_alias,e.root_teamfile,e.cwd,e.command,e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,e.request_payload,e.holder_pid,e.holder_host,e.started_at,e.last_heartbeat_at,i),ga(e)&&Tm(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function Xs(t,e){let r=cr(e.id),n=Sm(t,r);return n===null?!1:(Oe(t,{stream_id:r,event_type:Fv,observedLastSeq:n.last_seq,ts:e.ended_at??e.started_at,payload:{invocation_id:r,status:e.status,ended_at:e.ended_at,exit_code:e.exit_code,signal:e.signal,result_summary:e.result_summary,error:e.error,legacy:{table:"tracked_invocation",id:e.id}}},s=>{if(t.prepare(`UPDATE invocation_state
|
|
1099
1099
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1100
|
-
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,r,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${r}`);ga(e)&&vm(t,s,r)}),!0)}function Im(t,e,r,n){let s=cr(e.id),i=Sm(t,s);return i===null?!1:(Oe(t,{stream_id:s,event_type:Pv,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:r,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(r,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function xm(t,e,r){let n=cr(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),ga(e)&&wm(t,n,r)}function km(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,cr(e))}function Am(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,cr(e))}var $v,Fv,Pv,Rm=k(()=>{"use strict";ks();Hs();$v="INVOCATION_START",Fv="INVOCATION_FINISH",Pv="INVOCATION_NOTIFY_CLAIM"});var Uv,jv,
|
|
1100
|
+
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,r,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${r}`);ga(e)&&vm(t,s,r)}),!0)}function Im(t,e,r,n){let s=cr(e.id),i=Sm(t,s);return i===null?!1:(Oe(t,{stream_id:s,event_type:Pv,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:r,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(r,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function xm(t,e,r){let n=cr(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),ga(e)&&wm(t,n,r)}function km(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,cr(e))}function Am(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,cr(e))}var $v,Fv,Pv,Rm=k(()=>{"use strict";ks();Hs();$v="INVOCATION_START",Fv="INVOCATION_FINISH",Pv="INVOCATION_NOTIFY_CLAIM"});var Uv,jv,xD,Nm,Lm,Cm,Om=k(()=>{"use strict";Uv="other",jv=["not_enough_information","dont_know","other_work"],xD=new Set([Uv,...jv]),Nm="@abort",Lm="invalid_decision",Cm="workflow_escalation"});import{randomUUID as Dm}from"node:crypto";import{existsSync as Um,mkdirSync as Bv,renameSync as Wv,rmdirSync as Hv}from"node:fs";import{hostname as _a}from"node:os";function ya(t){return t.provider_resolved??t.provider}function D(){return new Date().toISOString()}function Xv(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!Um(t))return e;let r;try{r=new xs(t,{readonly:!0})}catch{return e}try{let n=[];try{n=r.prepare("SELECT teamfile_path, name, raw_text, raw_sha256, registered_at, last_seeded_at FROM root_team").all()}catch{}let s=[];try{s=r.prepare("SELECT key, value FROM lmctl_config").all()}catch{}return{rootTeams:n,config:s}}finally{r.close()}}function qv(t){if(t===":memory:"||!Um(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{Wv(n,`${e}${r}`)}catch{}}return e}function Mm(t,e){let r=e instanceof Error?e.message:String(e);try{let n=Xv(t),s=qv(t),i=new qs(gn({dbPath:t}));for(let o of n.rootTeams)i.upsertRootTeam(o);for(let{key:o,value:a}of n.config)i.setConfig(o,a);return process.stderr.write(`lmctl: couldn't migrate ${t} to schema v${yt} (${r}); started a fresh database instead. Preserved ${n.rootTeams.length} team registration(s) and ${n.config.length} config value(s).`+(s!==null?` Old database backed up at ${s}.
|
|
1101
1101
|
`:`
|
|
1102
1102
|
`)),i}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${t}: unusable (${r}), and recovery into a fresh database also failed (${s}). Check that the containing directory is writable, or move the file aside manually and retry.`)}}function $m(t,e){let r;try{return r=gn({dbPath:t,allowSchemaSkew:e}),{dal:new qs(r)}}catch(n){if(n instanceof Ct)throw n;let s;if(r!==void 0)try{s=r.pragma("user_version",{simple:!0})}catch{}try{r?.close()}catch{}return{cause:n,dbVersion:s}}}function Kv(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Yv(t){if(t===":memory:")return!0;try{return Bv(`${t}${jm}`),!0}catch{return!1}}function zv(t){if(t!==":memory:")try{Hv(`${t}${jm}`)}catch{}}function Ze(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<Gv;n+=1)if(r=$m(t.path,e),r.dal!==void 0)return r.dal;if(r.dbVersion!==void 0&&r.dbVersion>yt){let n=r.cause instanceof Error?r.cause.message:String(r.cause);throw new Error(`${t.path}: state.db schema is v${r.dbVersion}; this build (understands v${yt}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<Jv;n+=1){if(Yv(t.path))try{return Mm(t.path,r.cause)}finally{zv(t.path)}Kv(Vv);let s=$m(t.path,e);if(s.dal!==void 0)return s.dal}return Mm(t.path,r.cause)}function Fm(t,e,r){let n=Pm(e);if(n.length===0)return;let s=new Set,i=[],o=l=>{if(l===t)return n;let c=r(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Pm(c.definition)},a=l=>{let c=i.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...i.slice(c),l].join(" -> ")}`);if(!s.has(l)){i.push(l);try{for(let d of o(l))a(d)}finally{i.pop()}s.add(l)}};a(t)}function Pm(t){let e=Qv(t),r=e===null?null:Zv(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))Gs(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function Qv(t){try{let e=JSON.parse(t);return Gs(e)?e:null}catch{return null}}function Zv(t,e){let r=t[e];return Gs(r)?r:null}function Gs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function eS(t){try{let e=JSON.parse(t);return!Gs(e)||typeof e.lock_id!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}function tS(t,e){return t===null?!0:t.holder_host===_a()?!Ne(t.holder_pid):t.last_heartbeat<e}function rS(t){return{getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
1103
1103
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
@@ -1527,7 +1527,7 @@ ${c}`)}`}De.renderGrid=Xm;function qm(t,{headers:e,align:r,truncate:n,truncateTr
|
|
|
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
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 Ks,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 Ys,sf=k(()=>{"use strict";be();Ys=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 Ks(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 Ks(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
|
-
`):"";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 Ks(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 Ks(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
|
|
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 Ks(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 Ks(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 uM,mkdirSync as mM}from"node:fs";import{join as RS,dirname as pM}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,Qs,$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}`,Qs=`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:Qs,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,Zs,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}},Zs=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 ti(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??ei,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 ti(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,ei,YS,zS,QS,Ra,ri=k(()=>{"use strict";J();KS=2e3,ei=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(`
|
|
1533
1533
|
|
|
@@ -1619,7 +1619,7 @@ The session marker may be stale or the team may not be registered in this lmctl
|
|
|
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
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=$s(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
|
-
`)}function Bk(t){return`${t.teamfile}:${t.alias}`}var
|
|
1622
|
+
`)}function Bk(t){return`${t.teamfile}:${t.alias}`}var Tj,Pk,Uk,ji=k(()=>{"use strict";bt();J();Ut();nt();lr();Qe();Tj=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
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)}
|
|
@@ -2056,7 +2056,7 @@ fn clamp(val, low, high) {
|
|
|
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
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,n="")=>{let s=ss(e,r);return s==null?n:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,r,n=0)=>{let s=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,n=[])=>{let s=ss(e,r);return Array.isArray(s)?s:n},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
|
|
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 Ji(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 Ji(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 Vi,resolve as Ki}from"node:path";import{fileURLToPath as DA}from"node:url";function UA(){return Vi(OA(),".lmctl","cache","lmprice")}function ln(t,e){return Vi(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 Yi(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:Yi(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?[Ki(r,"data",e)]:[Ki(t,"..","..","data",e)];for(let s of n)if(Pg(s))return s;return null}function GA(t){let e=Ki(t);for(;;){if(Pg(Ki(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 Qi(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(Vi(r,xc)),h=wr(Vi(r,kc));if(Yi(_)&&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,Yi(_.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=Yi(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 Zi(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=Zi(r.source)-Zi(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 eo(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=Zi(t.source)-Zi(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 Qi();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=eo(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=to(t.provider)??to(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Pc(s))continue;let i=to(s.models)??to(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function to(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:()=>ro,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
|
+
`):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 Ji(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 Ji(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 Vi,resolve as Ki}from"node:path";import{fileURLToPath as DA}from"node:url";function UA(){return Vi(OA(),".lmctl","cache","lmprice")}function ln(t,e){return Vi(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 Yi(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:Yi(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?[Ki(r,"data",e)]:[Ki(t,"..","..","data",e)];for(let s of n)if(Pg(s))return s;return null}function GA(t){let e=Ki(t);for(;;){if(Pg(Ki(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 Qi(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(Vi(r,xc)),h=wr(Vi(r,kc));if(Yi(_)&&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,Yi(_.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=Yi(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 Zi(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=Zi(r.source)-Zi(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 eo(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=Zi(t.source)-Zi(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 gB,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 Qi();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=eo(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=to(t.provider)??to(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Pc(s))continue;let i=to(s.models)??to(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function to(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:()=>ro,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}
|
|
2060
2060
|
`),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
|
|
2061
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 ...
|
|
2062
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}
|
|
@@ -2472,25 +2472,27 @@ Examples:
|
|
|
2472
2472
|
lmctl plan ./backend --pattern 3 --provider claude --seed
|
|
2473
2473
|
`,vy=`missing required flags for non-interactive plan:
|
|
2474
2474
|
one of: --pattern <${mo}>, --member <Alias:provider[:model]>, or --from <file|dir|url>
|
|
2475
|
-
plus: --provider <name> (required with --pattern)`;fL=new Set([301,302,303,307,308]),yy=10});var To={};se(To,{extractSaveScriptFlags:()=>xy,performSaveScript:()=>ky,runWithSaveScript:()=>
|
|
2476
|
-
`),1;let a=`${
|
|
2477
|
-
`)
|
|
2478
|
-
`),1
|
|
2479
|
-
`),
|
|
2480
|
-
`),
|
|
2481
|
-
`),
|
|
2482
|
-
`)
|
|
2483
|
-
`
|
|
2475
|
+
plus: --provider <name> (required with --pattern)`;fL=new Set([301,302,303,307,308]),yy=10});var To={};se(To,{extractSaveScriptFlags:()=>xy,performSaveScript:()=>ky,runWithSaveScript:()=>bL});import{existsSync as hL,mkdirSync as gL,renameSync as _L,writeFileSync as yL}from"node:fs";import{dirname as EL,extname as TL,join as wL}from"node:path";function xy(t,e,r={}){let n=[],s,i,o=!1;for(let c=0;c<t.length;c+=1){let d=t[c];if(d==="--save-script"){let u=t[c+1];if(u===void 0)return{rest:n,error:"--save-script requires a file path"};s=u,c+=1;continue}if(d==="--script"){let u=t[c+1];if(u===void 0)return{rest:n,error:"--script requires a name"};i=u,c+=1;continue}if(d==="--force"&&!r.ownsForce){o=!0;continue}n.push(d)}if(r.ownsForce&&(o=t.includes("--force")),s===void 0)return i!==void 0?{rest:n,error:"--script requires --save-script"}:{rest:n};let a=i??e;if(!Iy.test(a))return{rest:n,error:`--script "${a}" must match ${Iy} (letters, digits, ., _, -)`};let l=r.extension??".lms";return{rest:n,request:{destPath:s,slug:a,extension:l,force:o}}}function SL(t){let e=t.slice(0,512).trimStart().toLowerCase();return e.startsWith("<!doctype html")||e.startsWith("<html")}async function ky(t,e,r=fetch){let{destPath:n,slug:s,extension:i,force:o}=e;if(hL(n)&&!o)return t.stderr.write(`error: --save-script: ${n} already exists (use --force to overwrite)
|
|
2476
|
+
`),1;let a=`${vL}/${s}${i}`,l;try{l=await sr(a,r,process.cwd())}catch(u){let m=u instanceof Error?u.message:String(u);return m==="HTTP 404"?t.stderr.write(`error: --save-script: no script is published at ${a} for this command
|
|
2477
|
+
`):t.stderr.write(`error: --save-script: could not fetch ${a}: ${m}
|
|
2478
|
+
`),1}if(TL(n).toLowerCase()!==i.toLowerCase()&&t.stderr.write(`warning: --save-script: ${n} does not end in "${i}", the extension lmctl.com actually serves for this command
|
|
2479
|
+
`),l.trim().length===0)return t.stderr.write(`error: --save-script: ${a} returned an empty response
|
|
2480
|
+
`),1;if(SL(l))return t.stderr.write(`error: --save-script: ${a} did not return a script (looks like an HTML page, not lmscript)
|
|
2481
|
+
`),1;let c=EL(n);gL(c,{recursive:!0});let d=wL(c,`.save-script-${process.pid}-${Date.now()}.tmp`);return yL(d,l,"utf8"),_L(d,n),t.stdout.write(`Saved ${a} to ${n}
|
|
2482
|
+
`),0}async function bL(t,e,r,n,s={}){let i=xy(r,e,s);if(i.error!==void 0)return t.stderr.write(`error: ${i.error}
|
|
2483
|
+
`),2;let o=await n(i.rest);return o!==0||i.request===void 0?o:ky(t,i.request)}var vL,Iy,wo=k(()=>{"use strict";gs();vL="https://lmctl.com/lmscript/commands",Iy=/^[A-Za-z0-9._-]+$/});var _s,QW,pd=k(()=>{"use strict";_s=[{name:"lmctl_chat",description:"Synchronous/blocking backup: send one prompt to a member of an AI-managed .lmctl team \u2014 addressed by teamfile path (team) and alias \u2014 and return the reply. This is the only MCP tool lmctl exposes. Prefer the CLI for normal delegation. For async or long-running work, use the provider or host runtime background/task surface around the blocking command.",inputSchema:{type:"object",properties:{team:{type:"string",description:"Path to .lmctl teamfile"},alias:{type:"string",description:"Target alias; omitted means Lead"},prompt:{type:"string",description:"Prompt text to send"}},required:["team","prompt"]},local:!0}],QW=_s.length});import{spawn as IL}from"node:child_process";async function Ry(t,e,r){let n=kL.get(t);if(n===void 0)return{status:"error",code:404,message:`unknown tool: ${t}`};let s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};for(let i of n.inputSchema.required??[])if(s[i]===void 0)return{status:"error",code:400,message:`missing required parameter: ${i}`};return AL(n.name,s)}function AL(t,e){return t==="lmctl_chat"?RL(e):{status:"error",code:404,message:`unknown local tool: ${t}`}}function RL(t){let e=typeof t.prompt=="string"?t.prompt:"";if(e.length===0)return Promise.resolve({status:"error",code:400,message:"missing required parameter: prompt"});let r=typeof t.team=="string"?t.team:"";if(r.length===0)return Promise.resolve({status:"error",code:400,message:"missing required parameter: team"});let n=typeof t.alias=="string"&&t.alias.length>0?t.alias:"Lead",s=["prompt",r,n,e];return z()&&Ee(JSON.stringify({event:"mcp_chat_spawn",team:r,alias:n})),NL(s,process.cwd())}function NL(t,e){return new Promise(r=>{let n=!1,s,i=d=>{n||(n=!0,s!==void 0&&clearTimeout(s),r(d))},o=IL("lmctl",t,{cwd:e,env:process.env,stdio:["ignore","pipe","pipe"]}),a=LL(process.env);s=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}i({status:"error",code:124,message:`lmctl prompt timed out after ${a}ms`})},a),s.unref?.();let l="",c="";o.stdout?.on("data",d=>{l+=d.toString("utf8")}),o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",d=>{i({status:"error",code:1,message:`failed to spawn lmctl prompt: ${d.message}`})}),o.on("exit",d=>{if(d===0){z()&&Ee(JSON.stringify({event:"mcp_chat_payload",bytes:Buffer.byteLength(l,"utf8"),lines:l.split(`
|
|
2484
|
+
`).length})),i({status:"ok",data:{text:l.trim()||"(empty response)"}});return}i({status:"error",code:d??1,message:c.trim()||`lmctl prompt exited with code ${d}`})})})}function LL(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return Ay;let r=Number(e);return!Number.isFinite(r)||r<=0?Ay:r}function hd(t,e=process.env){let n=t.getConfig("api.url")??(e.LMCTL_API_URL!==void 0&&e.LMCTL_API_URL.length>0?e.LMCTL_API_URL:xL),s=t.getConfig("api.token"),i=e.LMCTL_API_TOKEN!==void 0&&e.LMCTL_API_TOKEN.length>0?e.LMCTL_API_TOKEN:s;return{baseUrl:n,token:i}}var xL,Ay,kL,gd=k(()=>{"use strict";pd();J();xL="http://127.0.0.1:8787",Ay=30*60*1e3,kL=new Map(_s.map(t=>[t.name,t]))});async function ML(t,e){let r=t.id===void 0,n=t.id??null;if(t.method==="exit")return r||e.io.write(_d({jsonrpc:"2.0",id:n,result:null})),{kind:"exit"};if(t.method==="initialize")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{protocolVersion:CL,capabilities:{tools:{listChanged:!1}},serverInfo:{name:OL,version:DL}}}};if(t.method==="notifications/initialized")return{kind:"notification"};if(t.method==="shutdown")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:null}};if(t.method==="tools/list")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{tools:_s.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema}))}}};if(t.method==="tools/call"){let s=t.params!==null&&typeof t.params=="object"?t.params:{},i=typeof s.name=="string"?s.name:"",o=s.arguments,a=await Ry(i,o,e.dispatch),l=i==="lmctl_chat"&&a.status==="ok"&&a.data!==null&&typeof a.data=="object"&&typeof a.data.text=="string"?a.data.text:JSON.stringify(a);return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{isError:a.status==="error",content:[{type:"text",text:l}]}}}}return r?{kind:"notification"}:{kind:"response",message:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`method not found: ${t.method}`}}}}function _d(t){return`${JSON.stringify(t)}
|
|
2485
|
+
`}async function Ny(t,e){let r=!1,n="",s=!1,i=async o=>{let a=o.trim();if(a.length===0)return;let l;try{l=JSON.parse(a)}catch(d){t.io.write(_d({jsonrpc:"2.0",id:null,error:{code:-32700,message:`parse error: ${d instanceof Error?d.message:String(d)}`}}));return}l.method==="shutdown"&&(r=!0);let c=await ML(l,t);c.kind==="response"?t.io.write(_d(c.message)):c.kind==="exit"&&(s=!0)};return new Promise(o=>{let a=Promise.resolve(),l=!1,c=u=>{l||(l=!0,o(u))},d=()=>{let u=n.indexOf(`
|
|
2484
2486
|
`);for(;u!==-1;){let m=n.slice(0,u);n=n.slice(u+1),a=a.then(()=>i(m)).then(()=>{s&&c(0)}),u=n.indexOf(`
|
|
2485
2487
|
`)}};e.setEncoding("utf8"),e.on("data",u=>{n+=u,d()}),e.on("end",()=>{n.trim().length>0&&(a=a.then(()=>i(n))),a.finally(()=>c(0))}),e.on("error",u=>{t.io.log?.(`mcp: stdin error: ${u.message}
|
|
2486
|
-
`),a.finally(()=>c(1))})})}var
|
|
2487
|
-
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??
|
|
2488
|
+
`),a.finally(()=>c(1))})})}var CL,OL,DL,Ly=k(()=>{"use strict";pd();gd();CL="2025-06-18",OL="lmctl",DL="0.0.1"});var Oy={};se(Oy,{runMcp:()=>FL});async function FL(t,e={stdout:process.stdout,stderr:process.stderr},r=process.stdin){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write($L),0;if(t.length>0)return e.stderr.write(`usage: lmctl mcp
|
|
2489
|
+
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??PL(),i=1;try{let o=s===void 0?hd({getConfig:()=>null},process.env):hd(s,process.env);return i=await Ny({io:{write:l=>e.stdout.write(l),log:l=>e.stderr.write(l)},dispatch:{config:o,...s!==void 0?{dal:s}:{}}},r),i}finally{L({event:"mcp_bridge_exit",pid:process.pid,exit_code:i}),n&&s!==void 0&&s.close()}}function PL(){let t=he(),e=3;for(let r=1;r<=e;r+=1)try{return Ze({path:t})}catch(n){let s=n instanceof Error?n.message:String(n);if(L({event:"mcp_bridge_db_open_failed",pid:process.pid,attempt:r,db_path:t,error_message:s}),r<e&&Cy(s))UL(50*r);else if(!Cy(s))break}}function Cy(t){return/SQLITE_BUSY|database is locked|database is busy/i.test(t)}function UL(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}var $L,Dy=k(()=>{"use strict";Ut();gd();Ly();J();nt();$L=`usage: lmctl mcp
|
|
2488
2490
|
|
|
2489
2491
|
Start the stdio MCP bridge. The bridge resolves api.url and api.token from
|
|
2490
2492
|
local config, then uses stdin/stdout for JSON-RPC frames.
|
|
2491
|
-
`});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:()=>
|
|
2492
|
-
`),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?
|
|
2493
|
-
`),c={kind:"bytes",maxBytes:f}}let d=X(r,"--watch"),u=W(r,"--watch-interval"),m=u===void 0?
|
|
2493
|
+
`});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:()=>XL});async function XL(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${HL}
|
|
2494
|
+
`),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?BL: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
|
|
2495
|
+
`),c={kind:"bytes",maxBytes:f}}let d=X(r,"--watch"),u=W(r,"--watch-interval"),m=u===void 0?WL: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=>qL(e,E,f,c,d,m,o,n))}catch(E){return Je(e,E)}}let _=it(jL,{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)}
|
|
2494
2496
|
`)}},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)}
|
|
2495
2497
|
`),So}if(a===null)return t.stderr.write(`tail: session not found: ${r} (provider=${e})
|
|
2496
2498
|
`),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])}
|
|
@@ -2499,10 +2501,10 @@ local config, then uses stdin/stdout for JSON-RPC frames.
|
|
|
2499
2501
|
`).split(`
|
|
2500
2502
|
`),i=s[0]??"",o=s.slice(1);return o.length===0?`${r}: ${i}`:`${r}: ${i}
|
|
2501
2503
|
${o.map(a=>` ${a}`).join(`
|
|
2502
|
-
`)}`}function Py(t){return t.map(e=>({id:e.id,kind:e.kind,step_id:e.step_id,timestamp:new Date(e.timestamp_ms).toISOString(),payload:e.payload}))}async function
|
|
2504
|
+
`)}`}function Py(t){return t.map(e=>({id:e.id,kind:e.kind,step_id:e.step_id,timestamp:new Date(e.timestamp_ms).toISOString(),payload:e.payload}))}async function qL(t,e,r,n,s,i,o,a){if(e.getRun(r)===null)return A(t,`tail: run ${r}: not found`);let c=o===void 0?e.listSessionEvents(r):e.listSessionEvents(r).filter(m=>m.timestamp_ms>=o.getTime()),d=n.kind==="lines"?c.slice(Math.max(0,c.length-n.lines)):c;if(a===!0)re(t,{schema_version:vo,run_id:r,truncated:d.length<c.length,events:Py(d)});else{let m=d.map(p=>`${By(p)}
|
|
2503
2505
|
`).join("");t.stdout.write(n.kind==="bytes"?bo(m,n.maxBytes):m)}let u=c.length>0?c[c.length-1].id:0;return s?await new Promise(m=>{let _=setInterval(()=>{try{let g=e.listSessionEvents(r,u);if(g.length===0)return;for(let E of g)u=E.id;if(a===!0){re(t,{schema_version:vo,run_id:r,truncated:!1,events:Py(g)});return}let f=g.map(E=>`${By(E)}
|
|
2504
2506
|
`).join("");t.stdout.write(n.kind==="bytes"?bo(f,n.maxBytes):f)}catch(g){t.stderr.write(`tail: ${g instanceof Error?g.message:String(g)}
|
|
2505
|
-
`)}},i*1e3),h=()=>{clearInterval(_),m(0)};process.once("SIGINT",h),process.once("SIGTERM",h)}):0}function bo(t,e){if(e===0||Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.byteLength(Uy,"utf8");if(n>=e)return jy(t,e);let s=e-n,i=jy(t,s);return`${Uy}${i}`}function jy(t,e){if(e<=0)return"";let r=Buffer.from(t,"utf8"),n=Math.max(0,r.length-e);for(;n<r.length&&(r[n]&192)===128;)n+=1;return r.subarray(n).toString("utf8")}function By(t){let e=qy(new Date(t.timestamp_ms))??"",r="";try{let i=JSON.parse(t.payload);typeof i.alias=="string"&&(r=`alias=${i.alias}`),typeof i.provider=="string"&&(r+=`${r?" ":""}provider=${i.provider}`),typeof i.tool=="string"&&(r+=`${r?" ":""}tool=${i.tool}`),typeof i.status=="string"&&(r+=`${r?" ":""}status=${i.status}`),(typeof i.tokens_in=="number"||typeof i.tokens_out=="number")&&(r+=`${r?" ":""}tokens=${i.tokens_in??0}/${i.tokens_out??0}`)}catch{}let n=r!==""?r:t.payload.slice(0,200),s=t.step_id===null?"":` step=${t.step_id}`;return`${e} ${t.kind}${s}: ${n}`}function Xy(t){return My(t,"--since")}function qy(t){if(t===void 0)return;let e=(0,Wy.formatLocalTimestamp)(t);return e==="unknown"?void 0:e}var Wy,
|
|
2507
|
+
`)}},i*1e3),h=()=>{clearInterval(_),m(0)};process.once("SIGINT",h),process.once("SIGTERM",h)}):0}function bo(t,e){if(e===0||Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.byteLength(Uy,"utf8");if(n>=e)return jy(t,e);let s=e-n,i=jy(t,s);return`${Uy}${i}`}function jy(t,e){if(e<=0)return"";let r=Buffer.from(t,"utf8"),n=Math.max(0,r.length-e);for(;n<r.length&&(r[n]&192)===128;)n+=1;return r.subarray(n).toString("utf8")}function By(t){let e=qy(new Date(t.timestamp_ms))??"",r="";try{let i=JSON.parse(t.payload);typeof i.alias=="string"&&(r=`alias=${i.alias}`),typeof i.provider=="string"&&(r+=`${r?" ":""}provider=${i.provider}`),typeof i.tool=="string"&&(r+=`${r?" ":""}tool=${i.tool}`),typeof i.status=="string"&&(r+=`${r?" ":""}status=${i.status}`),(typeof i.tokens_in=="number"||typeof i.tokens_out=="number")&&(r+=`${r?" ":""}tokens=${i.tokens_in??0}/${i.tokens_out??0}`)}catch{}let n=r!==""?r:t.payload.slice(0,200),s=t.step_id===null?"":` step=${t.step_id}`;return`${e} ${t.kind}${s}: ${n}`}function Xy(t){return My(t,"--since")}function qy(t){if(t===void 0)return;let e=(0,Wy.formatLocalTimestamp)(t);return e==="unknown"?void 0:e}var Wy,jL,BL,WL,vo,HL,So,Uy,Jy=k(()=>{"use strict";Zt();Wy=_t(dt(),1);_e();Ue();Et();Tt();$y();jL={name:"tail",allowsBareTeamfile:!0,supportsRaw:!0},BL=4096,WL=2,vo=1,HL=`usage: lmctl tail [target] [alias]
|
|
2506
2508
|
lmctl tail --session <id> [--provider <name>]
|
|
2507
2509
|
lmctl tail --run <id>
|
|
2508
2510
|
[--lines N | --max-bytes N] [--since <duration|ISO8601>]
|
|
@@ -2530,7 +2532,7 @@ ignored under --json (a stderr note is printed if you passed it
|
|
|
2530
2532
|
explicitly); --lines still applies. --watch --json emits one JSON
|
|
2531
2533
|
object per poll tick with something new (NDJSON) -- a tick with
|
|
2532
2534
|
nothing new prints no line at all, same as text mode.`;So=-2;Uy=`\u2026 [truncated older output \u2014 raise with --max-bytes]
|
|
2533
|
-
`});var Ky={};se(Ky,{runExport:()=>
|
|
2535
|
+
`});var Ky={};se(Ky,{runExport:()=>GL});async function GL(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}:
|
|
2534
2536
|
${a.content}`);return o.length>0&&e.stdout.write(`${o.join(`
|
|
2535
2537
|
|
|
2536
2538
|
`)}
|
|
@@ -2543,8 +2545,8 @@ messages. No timestamps, tool activity, or truncation.
|
|
|
2543
2545
|
context, one paragraph per prompt with a blank line between prompts.
|
|
2544
2546
|
Codex prompts require native prompt metadata or user_message events;
|
|
2545
2547
|
unclassified user-role records are omitted in this compact mode.
|
|
2546
|
-
`});var zy={};se(zy,{runCost:()=>
|
|
2547
|
-
`),0;let r=oe(t,["--provider"],["--json"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <target> [alias]`);let n=X(r,"--json"),s=it(
|
|
2548
|
+
`});var zy={};se(zy,{runCost:()=>zL});function VL(t,e,r,n){let s=new Set,i=[];for(let o of e){let a=r===null?null:eo(t,o,r,n),l=a?.kind==="priced"||a?.kind==="estimated"?`id:${a.model.normalizedId}`:a?.kind==="known-unpriced"?`id:${a.id}`:`raw:${o.trim().toLowerCase()}`;s.has(l)||(s.add(l),i.push(o))}return i}async function zL(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${YL}
|
|
2549
|
+
`),0;let r=oe(t,["--provider"],["--json"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <target> [alias]`);let n=X(r,"--json"),s=it(JL,{target:r.positionals[0],alias:r.positionals[1],flags:{provider:W(r,"--provider")}});if(s.mode==="error")return A(e,s.message);if(s.mode==="managed")return A(e,"cost: managed-run targets are not supported (no per-run token/model rollup exists)");let i,o;if(s.mode==="ai-team")try{let I=await C(e,R=>fe(s.teamfile,s.alias,R));i=I.provider,o=I.sessionid}catch(I){if(I instanceof ie)return A(e,I.message);throw I}else if(o=s.sessionid,s.provider!==void 0)i=s.provider;else{let I=await rn(o);if(I.length===0)return A(e,`cost: session "${o}" not found in any provider store`);if(I.length>1)return A(e,`cost: session "${o}" matches multiple providers (${I.join(", ")}); pass --provider`);i=I[0]}let a;try{a=await xe(o,i)}catch(I){return A(e,`cost: failed to load session: ${I instanceof Error?I.message:String(I)}`)}if(a===null)return A(e,`cost: session not found: ${o} (provider=${i})`);let l=[...new Set(a.messages.map(I=>I.model).filter(I=>I!==void 0&&I!=="<synthetic>"))],c=[...a.messages].reverse().find(I=>I.model!==void 0&&I.model!=="<synthetic>")?.model,d=a.model??c??null,u={input:a.totalInputTokens??null,output:a.totalOutputTokens??null,cachedInput:a.totalCachedInputTokens??null},m=await Qi(),p=VL(i,l,m.catalog,m.aliases),_=p.length>1,h="unavailable",g=null,f=null,E=null,y=null,T=!1,b=null,v=null;if(d!==null&&m.catalog!==null){let I=Zg(i,d,m.catalog,m.aliases);if(h=I.state.kind,I.offer!==null)v=I.offer.pricing,g=I.offer.route,f=I.offer.source,E=I.offer.sourceModelId,y=I.provenance,T=I.offer.estimated;else switch(I.state.kind){case"unresolved":b=`alias "${I.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":b=`"${I.state.id}" is a known model with no published price row`;break;case"unknown":b=`model "${d}" not found in lmprice catalog for provider "${i}"`;break;case"wrong-provider":b=`model "${d}" is not offered by provider "${i}" (found under: ${I.state.otherProviders.join(", ")})`;break;default:b=`no lmprice catalog coverage for provider "${i}"`;break}}else d!==null&&(b="lmprice catalog unavailable");let S=v===null?null:{inputPer1m:v.input_per_1m_tokens,outputPer1m:v.output_per_1m_tokens,cachedInputPer1m:v.input_cache_read_per_1m_tokens},w=u.input===null||u.output===null?null:Wg({input:u.input,output:u.output,cachedInput:u.cachedInput??0},v),x={schema_version:KL,provider:i,sessionId:o,model:d,modelsUsed:p,approximate:_,tokens:u,pricePerModel:S,costUsd:w,priceResolution:h,priceRoute:g,priceSource:f,priceSourceModelId:E,priceProvenance:y,priceEstimated:T,costUnavailableReason:b,priceDataSource:m.source,priceDataGeneratedAt:m.generatedAt};return n?(re(e,x),0):(e.stdout.write(`Session: ${o}
|
|
2548
2550
|
`),e.stdout.write(` Provider: ${i}
|
|
2549
2551
|
`),e.stdout.write(` Model: ${d??"(unknown)"}
|
|
2550
2552
|
`),_&&e.stdout.write(` NOTE: this session used multiple models (${p.join(", ")}) -- cost below is approximate, priced at ${d}'s rate for the whole session.
|
|
@@ -2553,7 +2555,7 @@ unclassified user-role records are omitted in this compact mode.
|
|
|
2553
2555
|
`):e.stdout.write(` Cost: ~$${w.toFixed(4)}${_?" (approximate)":""}${T?" (estimated rate)":""}
|
|
2554
2556
|
`),g!==null&&e.stdout.write(` Price route: ${g}${T?" (manual/estimated row)":""}
|
|
2555
2557
|
`),e.stdout.write(` Price data: ${m.source}${m.generatedAt?` (generated ${m.generatedAt})`:""}
|
|
2556
|
-
`),0)}var Io,
|
|
2558
|
+
`),0)}var Io,JL,KL,YL,Qy=k(()=>{"use strict";Zt();Io=_t(dt(),1);Rc();Oc();_e();Ue();JL={name:"cost",allowsBareTeamfile:!1,supportsRaw:!0};KL=1,YL=`usage: lmctl cost <target> [alias] [--json]
|
|
2557
2559
|
lmctl cost <sessionid> [--provider <name>]
|
|
2558
2560
|
|
|
2559
2561
|
Estimate a session's dollar cost: aggregate token usage x the model's
|
|
@@ -2576,15 +2578,15 @@ unavailable) and
|
|
|
2576
2578
|
\`priceDataGeneratedAt\` says how fresh it is -- the online check has a
|
|
2577
2579
|
strict short timeout and NEVER blocks or fails this command: any network
|
|
2578
2580
|
error degrades silently to the local cache, then the bundled built-in
|
|
2579
|
-
copy, in that order.`});var eE={};se(eE,{runLs:()=>
|
|
2580
|
-
`),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"),_=
|
|
2581
|
+
copy, in that order.`});var eE={};se(eE,{runLs:()=>tC});import{resolve as yd}from"node:path";function eC(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 tC(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${QL}
|
|
2582
|
+
`),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"),_=ZL;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=>rC(e,g,_,h))}catch(g){return Je(e,g)}}let o=nC(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=eC(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}.
|
|
2581
2583
|
`)}return 0}if(a==="teamfile"){for(let p of m)e.stdout.write(`_MEMBER_ alias=- provider=${p.provider} sessionid=${p.sessionId} sessiondir=${p.cwd}
|
|
2582
|
-
`);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
|
|
2583
|
-
`),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
|
|
2584
|
+
`);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 rC(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.
|
|
2585
|
+
`),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 nC(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,QL,ZL,Zy,tE=k(()=>{"use strict";Le=_t(dt(),1);bt();_e();rd();QL=`usage: lmctl ls [--provider <name>] [--sessiondir <path>]
|
|
2584
2586
|
[--recursive] [--all] [--format table|teamfile|json] [--json]
|
|
2585
2587
|
lmctl ls --runs [--limit N] [--format table|json] [--json]
|
|
2586
2588
|
|
|
2587
|
-
List native provider sessions in scope, or list recent managed runs with --runs.`,
|
|
2589
|
+
List native provider sessions in scope, or list recent managed runs with --runs.`,ZL=50,Zy=500});var rE={};se(rE,{runInit:()=>iC});async function iC(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(sC),0;let n=t.includes("--force"),s=t.find(c=>c!=="--force"&&c!=="--help"&&c!=="-h");if(s!==void 0)return e.stderr.write(`error: unknown argument: ${s}
|
|
2588
2590
|
`),2;let i=r.configPath??_o(),o=mn(i);if(o!==null&&!n)return e.stdout.write(`${i} already exists:
|
|
2589
2591
|
|
|
2590
2592
|
`),e.stdout.write(yo(o)),e.stdout.write("\nEdit it directly, or run `lmctl init --force` to regenerate it from what's detected on this machine now (this OVERWRITES your edits).\n"),0;let a=(r.detectProviders??py)(),l=fy(a);return hy(l,i),e.stdout.write(`Wrote ${i}
|
|
@@ -2593,7 +2595,7 @@ List native provider sessions in scope, or list recent managed runs with --runs.
|
|
|
2593
2595
|
This is a starting point, not a fixed answer -- edit provider/model1/model2/model3 above before running lmctl plan or lmctl quickrun if it is not right.
|
|
2594
2596
|
`),a.length===0?e.stderr.write(`warning: no supported provider (claude, codex, agy, kimi) was detected on this machine -- using claude as a placeholder for all three slots. Edit the file above to match what you actually have.
|
|
2595
2597
|
`):a.length<3&&e.stderr.write(`notice: only ${a.length} provider${a.length===1?" was":"s were"} detected (${a.join(", ")}) -- duplicated to fill the remaining slot${a.length===1?"s":""}. Spreading slots across different providers (where you have them) balances load, but is never required.
|
|
2596
|
-
`),0}var
|
|
2598
|
+
`),0}var sC,nE=k(()=>{"use strict";Eo();sC=`usage: lmctl init [--force]
|
|
2597
2599
|
|
|
2598
2600
|
Writes ~/.lmctl/init.toml: three provider slots (Provider1/2/3), each
|
|
2599
2601
|
resolved to a provider and a starting model, detected from which provider
|
|
@@ -2611,8 +2613,8 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2611
2613
|
|
|
2612
2614
|
--force Overwrite ~/.lmctl/init.toml if it already exists
|
|
2613
2615
|
-h, --help display help for command
|
|
2614
|
-
`});import{execFileSync as
|
|
2615
|
-
`),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=
|
|
2616
|
+
`});import{execFileSync as oC}from"node:child_process";import{resolve as sE}from"node:path";function aC(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=oC("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=aC(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:()=>ys,estimateTokens:()=>dE,runTerminal:()=>Ed});import{spawn as lC}from"node:child_process";import{statSync as cC}from"node:fs";async function Ed(t,e){if(t.includes("--help")||t.includes("-h"))return _C(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(dC,{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=>uC(e,a.teamfile,a.alias,l,X(r,"--json")))}try{return await C(e,async s=>{let i=pC(e,s,r);if(typeof i=="number")return i;let o=W(r,"--alias");return X(r,"--size")?gC(e,s,i,o,X(r,"--json")):hC(e,s,i,o)})}catch(s){return Je(e,s)}}async function uC(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=mC(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),fC(n,c,d,u)}}function mC(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 fC(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(!Ui(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}
|
|
2617
|
+
`),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=lC(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 pC(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 hC(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=cC(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 gC(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;Ui(c)&&(u=await xe(l,c));let m=dE(u),p=m.est>ys;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:ys,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
2616
2618
|
`),t.stdout.write(`${cE}
|
|
2617
2619
|
`);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)
|
|
2618
2620
|
`),a.over_guide&&t.stdout.write(` \u26A0 ${a.alias}: estimated ~${a.est_tokens} tokens \u2014 ESTIMATE only, exceeds the 200K guide.
|
|
@@ -2620,7 +2622,7 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2620
2622
|
session yourself:
|
|
2621
2623
|
${a.resume_incantation??"(no resume incantation for provider "+a.provider+")"}
|
|
2622
2624
|
(or: lmctl terminal --team ${r.name} --alias ${a.alias})
|
|
2623
|
-
`)}return 0}function
|
|
2625
|
+
`)}return 0}function _C(t){return t.stdout.write(`usage: lmctl terminal <teamfile>:<alias> [--json]
|
|
2624
2626
|
lmctl terminal <teamfile> <alias> [--json]
|
|
2625
2627
|
lmctl terminal --run <id> [--alias A]
|
|
2626
2628
|
lmctl terminal [--project P] [--team T] [--alias A] [--size] [--json]
|
|
@@ -2653,12 +2655,12 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2653
2655
|
tokens it surfaces the resume incantation so YOU can
|
|
2654
2656
|
open & self-compact. Nothing is ever changed
|
|
2655
2657
|
automatically; ${ys} is a guide, not a gate.
|
|
2656
|
-
`),0}var
|
|
2658
|
+
`),0}var dC,ys,cE,wd=k(()=>{"use strict";Ut();Zt();_e();lE();Ue();Et();ut();js();Qe();yn();Qn();td();J();lr();dC={name:"terminal",allowsBareTeamfile:!1,supportsRaw:!1},ys=2e5,cE="est = rough local heuristic (~4 chars/token), NOT an exact provider token count \u2014 open the session to verify before acting."});var fE={};se(fE,{runQuickrun:()=>IC});import{existsSync as yC,mkdirSync as EC,writeFileSync as TC}from"node:fs";import{basename as wC,dirname as vC,join as mE}from"node:path";function bC(t){let e=wC(t),r=mE(t,`${e}.lmctl`),n=2;for(;yC(r);)r=mE(t,`${e}${n}.lmctl`),n+=1;return r}async function IC(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(SC),0;let n=t.includes("--no-seed"),s=t.includes("--no-terminal"),i=t.filter(g=>g!=="--no-seed"&&g!=="--no-terminal"&&g!=="--help"&&g!=="-h");if(i.length!==1)return e.stderr.write(`usage: lmctl quickrun <url-or-path>
|
|
2657
2659
|
`),2;let o=i[0],a=r.cwd??process.cwd(),l=r.fetchFn??fetch,c=mn(r.initConfigPath);if(c===null)return e.stderr.write("error: no ~/.lmctl/init.toml found. Run `lmctl init` first, then try quickrun again.\n"),1;let d;try{d=await sr(o,l,a)}catch(g){return e.stderr.write(`error: could not fetch ${o}: ${g instanceof Error?g.message:String(g)}
|
|
2658
|
-
`),1}let u=gy(d,c),m=
|
|
2660
|
+
`),1}let u=gy(d,c),m=bC(a);if(EC(vC(m),{recursive:!0}),TC(m,u,"utf8"),e.stdout.write(`Wrote ${m}
|
|
2659
2661
|
`),await xr([m],e)!==0)return e.stderr.write(`error: ${m} failed lint after substitution -- check the values in ~/.lmctl/init.toml.
|
|
2660
2662
|
`),1;if(n)return e.stdout.write(`Edit ${m} if needed, then run: lmctl seed ${m}
|
|
2661
|
-
`),0;let _=await kr([m],e);return _!==0?_:s?0:(r.openTerminal??Ed)([m,"Lead"],e)}var
|
|
2663
|
+
`),0;let _=await kr([m],e);return _!==0?_:s?0:(r.openTerminal??Ed)([m,"Lead"],e)}var SC,pE=k(()=>{"use strict";Eo();gs();At();wd();SC=`usage: lmctl quickrun <url-or-path>
|
|
2662
2664
|
|
|
2663
2665
|
Fetches a .lmctl teamfile template (any https:// URL or local file/dir
|
|
2664
2666
|
path -- lmctl.com publishes example templates, but this is not restricted
|
|
@@ -2675,11 +2677,11 @@ taken, so quickrun never overwrites an existing teamfile.
|
|
|
2675
2677
|
--no-seed Write the resolved teamfile but do not seed or open it
|
|
2676
2678
|
--no-terminal Seed, but do not open the Lead's terminal afterward
|
|
2677
2679
|
-h, --help display help for command
|
|
2678
|
-
`});var gE={};se(gE,{runHello:()=>
|
|
2680
|
+
`});var gE={};se(gE,{runHello:()=>RC});import{writeFileSync as xC}from"node:fs";import{join as kC}from"node:path";async function RC(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(AC),0;let n,s,i=[];for(let _=0;_<t.length;_+=1){let h=t[_];if(h==="-p"||h==="--prompt"){s=t[_+1],_+=1;continue}i.push(h)}if(i.length===1&&(n=i[0]),n===void 0||s===void 0)return e.stderr.write(`usage: lmctl hello <provider> -p "<prompt>"
|
|
2679
2681
|
`),2;let o=r.cwd??process.cwd(),a=r.fetchFn??fetch,l=`${hE}/${n}.lmctl`,c;try{c=await sr(l,a,o)}catch(_){return e.stderr.write(`error: could not fetch ${l}: ${_ instanceof Error?_.message:String(_)}
|
|
2680
|
-
`),1}let d=
|
|
2682
|
+
`),1}let d=kC(o,`${n}_hello.lmctl`);if(xC(d,c,"utf8"),e.stdout.write(`Wrote ${d}
|
|
2681
2683
|
`),await xr([d],e)!==0)return e.stderr.write(`error: ${d} failed lint -- lmctl.com's ${n}.lmctl example may be out of date.
|
|
2682
|
-
`),1;let m=await kr([d],e);return m!==0?m:(r.sendPrompt??nd)([d,"Lead",s],e)}var hE,
|
|
2684
|
+
`),1;let m=await kr([d],e);return m!==0?m:(r.sendPrompt??nd)([d,"Lead",s],e)}var hE,AC,_E=k(()=>{"use strict";gs();At();co();hE="https://lmctl.com/helloexample",AC=`usage: lmctl hello <provider> -p "<prompt>"
|
|
2683
2685
|
|
|
2684
2686
|
Downloads ${hE}/<provider>.lmctl, saves it as
|
|
2685
2687
|
<provider>_hello.lmctl in the current directory, seeds it, sends your
|
|
@@ -2691,10 +2693,10 @@ provider works at all.
|
|
|
2691
2693
|
|
|
2692
2694
|
Example:
|
|
2693
2695
|
lmctl hello claude -p "hi"
|
|
2694
|
-
`});import{execFileSync as vd}from"node:child_process";import{dirname as yE,resolve as
|
|
2696
|
+
`});import{execFileSync as vd}from"node:child_process";import{dirname as yE,resolve as NC}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
|
|
2695
2697
|
WHERE target_teamfile = ? AND target_alias = ? AND config_warnings IS NOT NULL
|
|
2696
|
-
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(
|
|
2697
|
-
`)}catch{}}async function
|
|
2698
|
+
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(NC(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),LC(i)]}));return new Map(r)}catch{return new Map}}function xo(t,e){return`${t}\0${e.toLowerCase()}`}function LC(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:CC(e)}}function CC(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=OC.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:DC(r.timestamp,s,i,o,a),reset_time:l,timezone:a,detected_at:r.timestamp.toISOString()}}return null}function DC(t,e,r,n,s){if(!Number.isFinite(t.getTime())||e<1||e>12||r<0||r>59)return null;let i=MC(e,n);try{let o=$C(t,s),a=SE(o.year,o.month,o.day,i,r,s);if(a.getTime()<=t.getTime()){let l=jC(o,1);a=SE(l.year,l.month,l.day,i,r,s)}return a.toISOString()}catch{return null}}function MC(t,e){return e==="am"?t===12?0:t:t===12?12:t+12}function $C(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=FC(new Date(o),i);o=Date.UTC(t,e-1,r,n,s,0,0)-l}return new Date(o)}function FC(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?UC:PC,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 jC(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 OC,PC,UC,IE=k(()=>{"use strict";OC=/you['\u2019]ve hit your session limit\s*(?:\u00b7|-|:)?\s*resets\s+([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;PC=new Map,UC=new Map});var PE={};se(PE,{appendIntent:()=>Cd,formatAge:()=>Es,formatDuration:()=>Lo,resolveIntentLogPath:()=>LE,runStatus:()=>zC,shortIdentity:()=>gt});import{appendFileSync as BC,existsSync as WC,mkdirSync as HC}from"node:fs";import{homedir as XC}from"node:os";import{basename as qC,dirname as NE,isAbsolute as GC,join as JC,resolve as VC}from"node:path";function LE(){return process.env.LMCTL_INTENT_LOG??JC(XC(),".lmctl","recent-intents.log")}function Cd(t){try{let e=LE();HC(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]});BC(e,`${r}
|
|
2699
|
+
`)}catch{}}async function zC(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(KC),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 ZC(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=TO(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=>mO(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 ZC(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(QC,{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 wO(t,n.teamfile,r.json,r.details):await kO(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 tO(t)}return await eO(t,r.identity)}async function eO(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=iO([...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=>nO(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 tO(t){let e=t.listRootTeams();return{scope:"db",identity:null,...CE(),teams:e.map(r=>rO(t,r)),activity:Dd(No(t)).map(r=>Md(r)),transcript_harvest:await OE(Od(t))}}function rO(t,e){if(!WC(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 nO(t,e,r){let n=r.teamfile===void 0?null:ge(GC(r.teamfile)?r.teamfile:VC(NE(e),r.teamfile),t),s=lt(t,e,r.alias),i=s.busy&&s.reason==="in-flight"?sO(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 sO(t,e,r,n){let s=n.sender_alias==="operator"?"operator":`${n.sender_teamfile}:${n.sender_alias}`,o=t.db.prepare(`
|
|
2698
2700
|
SELECT * FROM tracked_invocation
|
|
2699
2701
|
WHERE kind = 'chat'
|
|
2700
2702
|
AND status = 'running'
|
|
@@ -2704,27 +2706,27 @@ Example:
|
|
|
2704
2706
|
AND holder_pid IS ?
|
|
2705
2707
|
ORDER BY started_at DESC, id DESC
|
|
2706
2708
|
LIMIT 5
|
|
2707
|
-
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:
|
|
2709
|
+
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:EO(o.request_payload)}}function No(t,e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.target_teamfile!==void 0&&(r.push("target_teamfile = ?"),n.push(e.target_teamfile)),e.target_alias!==void 0&&(r.push("target_alias = ?"),n.push(e.target_alias));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`;return t.db.prepare(`
|
|
2708
2710
|
SELECT * FROM tracked_invocation
|
|
2709
2711
|
${s}
|
|
2710
2712
|
ORDER BY started_at DESC, id DESC
|
|
2711
|
-
`).all(...n)}function Od(t,e={}){return No(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&Ft(n)==="dead")}function
|
|
2713
|
+
`).all(...n)}function Od(t,e={}){return No(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&Ft(n)==="dead")}function iO(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(n));return r.sort((n,s)=>{let i=Date.parse(s.started_at)-Date.parse(n.started_at);return Number.isFinite(i)&&i!==0?i:s.id-n.id})}function Dd(t){return t.filter(e=>Ft(e)!=="dead")}async function OE(t){let e=[];for(let r of t)e.push(await oO(r));return e}async function oO(t){let e=t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,r={tracked_invocation_id:t.id,from_identity:t.from_identity,target:e??"(unknown)",started_at:t.started_at,tail_hint:e===null?"":`lmctl tail "${t.target_teamfile}" ${t.target_alias}`};if(e===null)return Rr(r,"missing-target",null,null);if(t.request_payload===null||t.request_payload.length===0)return Rr(r,"missing-request-payload",null,null);let n=aO(t.meta);if(n.provider===null||n.sessionid===null)return Rr(r,"missing-session-metadata",n.provider,n.sessionid);if(!lO(n.provider))return Rr(r,"unsupported-provider",n.provider,n.sessionid);let s;try{s=await xe(n.sessionid,n.provider)}catch{return Rr(r,"read-error",n.provider,n.sessionid)}if(s===null)return Rr(r,"session-not-found",n.provider,n.sessionid);let i=cO(t.request_payload,s.messages);return i.state!=="completed"?Rr(r,i.reason,n.provider,n.sessionid):{...r,state:"completed",reason:null,provider:n.provider,session_id:n.sessionid,result_payload:i.result,result_preview:FE(i.result),assistant_timestamp:i.assistantTimestamp,matched_user_index:i.userIndex}}function Rr(t,e,r,n){return{...t,state:"unreconciled",reason:e,provider:r,session_id:n,result_payload:null,result_preview:null,assistant_timestamp:null,matched_user_index:null}}function aO(t){if(t===null||t.trim()==="")return{provider:null,sessionid:null};try{let e=JSON.parse(t);return{provider:typeof e.provider=="string"&&e.provider.length>0?e.provider:null,sessionid:typeof e.sessionid=="string"&&e.sessionid.length>0?e.sessionid:null}}catch{return{provider:null,sessionid:null}}}function lO(t){return["claude","codex","gemini","copilot","opencode","lmplayer","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"].includes(t)}function cO(t,e){let r=e.map((i,o)=>({message:i,index:o})).filter(({message:i})=>i.role==="user"&&i.content===t);if(r.length===0)return{state:"unreconciled",reason:"request-not-found"};if(r.length>1)return{state:"unreconciled",reason:"duplicate-request"};let n=r[0].index,s=[];for(let i of e.slice(n+1)){if(i.role==="user")break;i.role==="assistant"&&i.content.trim().length>0&&s.push(i)}return s.length===0?{state:"unreconciled",reason:"no-assistant-response"}:{state:"completed",userIndex:n,result:s.map(i=>i.content).join(`
|
|
2712
2714
|
|
|
2713
|
-
`),assistantTimestamp:
|
|
2714
|
-
`)}function
|
|
2715
|
-
`)}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))
|
|
2716
|
-
`)}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(
|
|
2715
|
+
`),assistantTimestamp:dO(s[s.length-1]?.timestamp)}}function dO(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function uO(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=uO(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 mO(t,e){return t.scope==="self"?pO(t,e):hO(t,e)}function fO(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 pO(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"?fO(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(`
|
|
2716
|
+
`)}function hO(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(`
|
|
2717
|
+
`)}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))gO(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 gO(t,e,r){let n=yO(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} ${_O(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 _O(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function yO(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 EO(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 Es(t){return(0,Ce.formatRelativeTime)(t)}function gt(t){if(t==="operator")return t;try{let e=xt(t);return`${qC(e.teamfile)}:${e.alias}`}catch{return t}}function TO(t){if(t===void 0)return{iso:new Date(Date.now()-YC).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 wO(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(_)}
|
|
2718
|
+
`)}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(bO(s.teamName,s.teamfile,i,l,n,c)),0)}function vO(t){return t.sessionid??"(not seeded)"}function SO(t){return t.sessionid===null?"not seeded":Ao(t.liveness)}function bO(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(`
|
|
2717
2719
|
`)}
|
|
2718
|
-
`}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)(
|
|
2720
|
+
`}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)(vO(h)),(0,Ce.escapeCell)(h.reportPath),(0,Ce.escapeCell)(h.provider),(0,Ce.escapeCell)(h.observedModel??"(unknown)"),SO(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(IO(n)),Ke(null),Ke(xO(n))),m.push(p);let _=(0,Ce.formatTable)(m,{headers:l,align:c,margin:2}).split(`
|
|
2719
2721
|
`);if(o.push(_[0]),n.forEach((h,g)=>{if(o.push(_[g+1]),h.configWarnings!==void 0)for(let f of h.configWarnings)o.push(` config not applied: ${f}`)}),o.push(_[_.length-1]),d&&o.push("n/a = this provider does not expose a context/token total; absence is not a health signal."),o.push(`LAST CONTEXT = prompt size of the LAST COMPLETED turn, so it LAGS BY ONE TURN.
|
|
2720
2722
|
Right after a compaction the last completed turn IS the summarisation request, which carried the
|
|
2721
2723
|
full pre-compaction prompt \u2014 so this reads the OLD large number while the live context is already
|
|
2722
2724
|
small. Re-read after the next turn before concluding a compaction failed or gating on the value.`),u.length>0){o.push("Session limits:");for(let h of u)o.push(` ${h.reportPath}: LIMITED resets_at=${kd(h.sessionLimit)}`)}return`${o.join(`
|
|
2723
2725
|
`)}
|
|
2724
|
-
`}function
|
|
2726
|
+
`}function IO(t){let e=0;for(let r of t){let n=r.activitySinceLastCommit?.messageCount;n==null?e=void 0:e!==void 0&&(e+=n)}return e}function xO(t){let e=0;for(let r of t){let n=r.cumulativeTokens;n==null||n==="n/a"?e=void 0:e!==void 0&&(e+=n)}return e}async function kO(t,e,r,n){let s=await C(t,_=>fe(e,r,_)),i;try{i=await xe(s.sessionid,s.provider)}catch(_){return A(t,`status: failed to load session: ${_ instanceof Error?_.message:String(_)}`)}if(i===null)return A(t,`status: session not found: ${s.sessionid} (provider=${s.provider})`);let o=Ld(i.messages),l=(await xd(t,[{teamfile:s.teamfile,alias:s.alias}])).get(xo(s.teamfile,s.alias))??ko(),c=await bd(t,{teamfile:s.teamfile,alias:s.alias}),d=Ad(s.teamfile),u=d.kind==="repo"?d:null,m={provider:i.provider,sessionid:i.sessionId,seeded:!0,alias:s.alias,teamfile:s.teamfile,reportPath:s.alias,cwd:i.cwd,messageCount:i.messageCount??null,model:s.model??null,observed_model:i.model??null,lastContext:i.lastInputTokens??null,liveness:l,totalInputTokens:i.totalInputTokens??null,totalOutputTokens:i.totalOutputTokens??null,...i.totalCachedInputTokens!==void 0?{totalCachedInputTokens:i.totalCachedInputTokens}:{},sessionLimit:o,...c!==void 0?{config_warnings:c}:{},...u!==null?{activitySinceLastCommit:{messageCount:Rd(i,u.since),tokens:null},cumulativeTokens:Nd(i)}:{},createdAt:i.createdAt.toISOString(),modifiedAt:i.modifiedAt.toISOString()};if(n)return re(t,{schema_version:Pd,scope:"member",...m}),0;let p=[];if(p.push(`Session: ${i.sessionId}`),p.push(` Provider: ${i.provider}`),p.push(` Alias: ${s.alias}`),p.push(` Liveness: ${Ao(l)}`),p.push(` CWD: ${i.cwd}`),p.push(` Messages: ${Ke(i.messageCount)}`),p.push(` Model (declared): ${s.model??"(none)"}`),p.push(` Model (observed): ${i.model??"(unknown)"}`),c!==void 0)for(let _ of c)p.push(` Config NOT applied: ${_}`);if(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)p.push(" Tokens: n/a");else{let _=` Tokens: ${(0,Ce.formatCount)(i.totalInputTokens)} in / ${(0,Ce.formatCount)(i.totalOutputTokens)} out`;m.totalCachedInputTokens!==void 0&&(_+=` (cached: ${(0,Ce.formatCount)(m.totalCachedInputTokens)})`),p.push(_)}return(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)&&p.push(" n/a = this provider does not expose a context/token total; absence is not a health signal."),p.push(` lastContext = prompt size of the LAST COMPLETED turn; it LAGS BY ONE TURN. Right after a
|
|
2725
2727
|
compaction it still reports the pre-compaction size (the summarisation request itself).`),o!==null&&p.push(` SessionLimit: LIMITED resets_at=${kd(o)}`),p.push(` Created: ${m.createdAt}`),p.push(` Modified: ${m.modifiedAt}`),t.stdout.write(`${p.join(`
|
|
2726
2728
|
`)}
|
|
2727
|
-
`),0}var Ce,
|
|
2729
|
+
`),0}var Ce,KC,Pd,Ro,YC,xE,kE,QC,Ud=k(()=>{"use strict";Ce=_t(dt(),1);Qe();_e();Zn();nt();sn();Tt();Ue();vE();In();Zt();IE();KC=`usage: lmctl status [--json] [--since <duration|ISO8601>]
|
|
2728
2730
|
lmctl status <teamfile> [--details] [--json]
|
|
2729
2731
|
lmctl status <teamfile> <alias> [--json]
|
|
2730
2732
|
|
|
@@ -2743,26 +2745,26 @@ With a teamfile and an alias: single-member deep view (session detail, token
|
|
|
2743
2745
|
breakdown, liveness with terminal-lock/in-flight holder info).
|
|
2744
2746
|
|
|
2745
2747
|
--json emits { schema_version: 2, scope: 'self'|'db'|'team'|'member', ... }.
|
|
2746
|
-
`,Pd=2,Ro=5,
|
|
2747
|
-
`,1)[0];return e.length<=jE?e:`${e.slice(0,jE)}\u2026`}function Co(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Bd(t,e){let r=t.target_teamfile,n=t.target_alias;if(r===null||n===null)return jd;let s=e.get(r);if(s===void 0){try{s=Ae(r)}catch{s=null}e.set(r,s)}return s===null?jd:Cs(s,n)?.model??jd}function qd(t){return t.target!==null?gt(t.target):t.from_identity}function BE(t){return[(0,Ye.escapeCell)(qd(t)),t.kind,"running",t.holder_liveness,(0,Ye.escapeCell)(t.model),Es(t.started_at)]}function WE(t){return[(0,Ye.escapeCell)(qd(t)),t.kind,"DEAD","",(0,Ye.escapeCell)(t.model),`stale ${Es(t.started_at)}, holder process confirmed dead`]}function HE(t){let e=`ran ${Lo(t.ran_ms)}, idle ${Es(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,Ye.escapeCell)(
|
|
2748
|
+
`,Pd=2,Ro=5,YC=24*60*60*1e3,xE=72,kE=80;QC={name:"status",allowsBareTeamfile:!0,supportsRaw:!1}});var qE={};se(qE,{_setRunningWatchMaxTicksForTests:()=>NO,runRunning:()=>BO});function NO(t){Xd=t??void 0}function CO(t){let e=t.split(`
|
|
2749
|
+
`,1)[0];return e.length<=jE?e:`${e.slice(0,jE)}\u2026`}function Co(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Bd(t,e){let r=t.target_teamfile,n=t.target_alias;if(r===null||n===null)return jd;let s=e.get(r);if(s===void 0){try{s=Ae(r)}catch{s=null}e.set(r,s)}return s===null?jd:Cs(s,n)?.model??jd}function qd(t){return t.target!==null?gt(t.target):t.from_identity}function BE(t){return[(0,Ye.escapeCell)(qd(t)),t.kind,"running",t.holder_liveness,(0,Ye.escapeCell)(t.model),Es(t.started_at)]}function WE(t){return[(0,Ye.escapeCell)(qd(t)),t.kind,"DEAD","",(0,Ye.escapeCell)(t.model),`stale ${Es(t.started_at)}, holder process confirmed dead`]}function HE(t){let e=`ran ${Lo(t.ran_ms)}, idle ${Es(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,Ye.escapeCell)(CO(t.error))}`),[(0,Ye.escapeCell)(qd(t)),t.kind,t.status,"",(0,Ye.escapeCell)(t.model),e]}function Wd(t){return t.filter(e=>e!=="").join(" ")}function XE(t){let e=new Map(t.map(i=>[i.id,i])),r=new Map,n=[];for(let i of t){let o=i.parent_invocation_id;if(o!==null&&e.has(o)){let a=r.get(o)??[];a.push(i),r.set(o,a)}else n.push(i)}let s=(i,o)=>o.started_at.localeCompare(i.started_at);n.sort(s);for(let i of r.values())i.sort(s);return{roots:n,childrenByParent:r}}function DO(t){let{roots:e,childrenByParent:r}=XE(t),n=[],s=(i,o)=>{n.push(`${" ".repeat(o+1)}${i.line}`);for(let a of r.get(i.id)??[])s(a,o+1)};for(let i of e)s(i,0);return n}function MO(t,e,r){let n=[...t.map(a=>({state:"running",...a})),...e.map(a=>({state:"dead",...a})),...r.map(a=>({state:"idle",...a}))],{roots:s,childrenByParent:i}=XE(n),o=a=>({...a,children:(i.get(a.id)??[]).map(o)});return s.map(o)}function $O(t){if(t===void 0)return{windowMs:AO};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2];return{windowMs:(s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400)*1e3}}let r=Date.parse(t);return Number.isFinite(r)?{windowMs:Math.max(0,Date.now()-r)}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}function Hd(t,e){return!(e.teamfile!==void 0&&t.target_teamfile!==e.teamfile||e.member!==void 0&&(t.target_alias??"").toLowerCase()!==e.member)}function FO(t,e,r={}){let n=Date.now(),s=t.listAllRunningTrackedInvocations().filter(p=>Hd(p,e)),i=new Map,o=[],a=[];for(let p of s){let _=Ft(p),h=n-new Date(p.started_at).getTime(),g={id:p.id,kind:p.kind,origin:p.origin,from_identity:p.from_identity,target:Co(p),model:Bd(p,i),started_at:p.started_at,parent_invocation_id:p.parent_invocation_id};if(_==="dead"){if(Ta(t,p)!==null)continue;a.push({...g,stale_for_ms:h})}else o.push({...g,running_for_ms:h,holder_liveness:_??"unknown"})}let l=new Set(s.map(Co).filter(p=>p!==null)),c=new Date(n-e.idleWindowMs).toISOString(),d=t.listRecentlyFinishedTrackedInvocations(c).filter(p=>Hd(p,e)),u=new Set,m=[];for(let p of d){let _=Co(p);_===null||l.has(_)||u.has(_)||(u.add(_),m.push({id:p.id,kind:p.kind,origin:p.origin,from_identity:p.from_identity,target:_,model:Bd(p,i),status:p.status,started_at:p.started_at,ended_at:p.ended_at,idle_ms:n-new Date(p.ended_at).getTime(),ran_ms:new Date(p.ended_at).getTime()-new Date(p.started_at).getTime(),error:p.error,parent_invocation_id:p.parent_invocation_id}))}if(r.tree===!0){let p=new Set([...o.map(h=>h.id),...a.map(h=>h.id),...m.map(h=>h.id)]),_=[...p];for(;_.length>0;){let h=t.listFinishedTrackedInvocationChildren(_,c).filter(g=>!p.has(g.id)&&Hd(g,e));if(h.length===0)break;_=[];for(let g of h){p.add(g.id),_.push(g.id);let f=Co(g);m.push({id:g.id,kind:g.kind,origin:g.origin,from_identity:g.from_identity,target:f,model:Bd(g,i),status:g.status,started_at:g.started_at,ended_at:g.ended_at,idle_ms:n-new Date(g.ended_at).getTime(),ran_ms:new Date(g.ended_at).getTime()-new Date(g.started_at).getTime(),error:g.error,parent_invocation_id:g.parent_invocation_id})}}}return{running:o,dead:a,idle:m}}function PO(t,e){return e?{schema_version:UE,tree:MO(t.running,t.dead,t.idle)}:{schema_version:UE,...t}}function UO(t){let e=[...t.running.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Wd(BE(n))})),...t.dead.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Wd(WE(n))})),...t.idle.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Wd(HE(n))}))],r=DO(e);return`${r.length>0?r.join(`
|
|
2748
2750
|
`):" none"}
|
|
2749
|
-
`}function
|
|
2751
|
+
`}function jO(t,e){let r=[{title:`Running (${t.running.length}):`,rows:t.running.map(BE)},{title:`Dead (reclaimable) (${t.dead.length}):`,rows:t.dead.map(WE)},{title:`Idle, finished in the last ${Lo(e)} (${t.idle.length}):`,rows:t.idle.map(HE)}],n=["MEMBER","KIND","STATE","LIVENESS","MODEL","TIMING"],s=(0,Ye.measureColumns)([{rows:[],headers:n},...r.map(a=>a.rows)],{max:OO}),i=!1,o=[];return r.forEach((a,l)=>{if(l>0&&o.push(""),o.push(a.title),a.rows.length===0){o.push(" none");return}let c=!i;i=!0,o.push((0,Ye.renderGrid)(a.rows,{widths:s,margin:2,...c?{headers:n}:{}}))}),`${o.join(`
|
|
2750
2752
|
`)}
|
|
2751
|
-
`}async function
|
|
2752
|
-
`),0;let r=oe(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=X(r,"--tree"),i=X(r,"--watch"),o=W(r,"--team"),a=W(r,"--member"),l
|
|
2753
|
-
`):re(e,h),0}return e.stdout.write(s?
|
|
2754
|
-
`)}finally{_=!1}p+=1,Xd!==void 0&&p>=Xd&&h(E)}},f=setInterval(()=>{g(f)},d*1e3);g(f),process.once("SIGINT",()=>h(f)),process.once("SIGTERM",()=>h(f))}):u()}var Ye,
|
|
2755
|
-
`),jE=120;jd="default";
|
|
2753
|
+
`}async function BO(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${LO}
|
|
2754
|
+
`),0;let r=oe(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=X(r,"--tree"),i=X(r,"--watch"),o=W(r,"--team"),a=W(r,"--member"),l=$O(W(r,"--since"));if("error"in l)return A(e,l.error);let c=W(r,"--watch-interval"),d=c===void 0?RO:Number.parseInt(c.replace(/s$/,""),10);if(!Number.isFinite(d)||d<1)return A(e,`invalid --watch-interval "${c}" (expected <N>s, N\u22651)`);let u=()=>C(e,m=>{let p={...o!==void 0?{teamfile:ge(o,m)}:{},...a!==void 0?{member:a.toLowerCase()}:{},idleWindowMs:l.windowMs},_=FO(m,p,{tree:s});if(n){let h=PO(_,s);return i?e.stdout.write(`${JSON.stringify(h)}
|
|
2755
|
+
`):re(e,h),0}return e.stdout.write(s?UO(_):jO(_,l.windowMs)),0});return i?await new Promise(m=>{let p=0,_=!1,h=E=>{clearInterval(E),m(0)},g=async E=>{if(!_){_=!0;try{await u()}catch(y){e.stderr.write(`running: ${y instanceof Error?y.message:String(y)}
|
|
2756
|
+
`)}finally{_=!1}p+=1,Xd!==void 0&&p>=Xd&&h(E)}},f=setInterval(()=>{g(f)},d*1e3);g(f),process.once("SIGINT",()=>h(f)),process.once("SIGTERM",()=>h(f))}):u()}var Ye,AO,UE,RO,Xd,LO,jE,jd,OO,GE=k(()=>{"use strict";Ye=_t(dt(),1);Qe();Sn();Et();_e();Ud();Tt();AO=24*60*60*1e3,UE=3,RO=2;LO=["usage: lmctl running [--team <file>] [--member <alias>] [--since <duration|ISO8601>]"," [--tree] [--watch] [--watch-interval Ns] [--json]","","Shows tracked_invocation activity DB-wide across the whole fleet, split","into three sections (flat mode, the default):",' - Running: status="running" with a live (or unverifiable cross-host)'," holder -- genuinely in-flight work.",' - Dead (reclaimable): status="running" but the holder process is'," confirmed dead -- an orphaned record, not active work. Its elapsed",' time is reported as staleness, not as "running", so a dead worker'," is never mistaken for one that is genuinely still building."," - Idle: targets with nothing running or dead, showing their most"," recent finish from the last 24 hours and how long they've been"," idle since.","","--team <file> narrows the view to one teamfile (path is canonicalized","before matching); --member <alias> narrows it to one member alias","(case-insensitive; combinable with --team). --since sets the lookback","window for the Idle section -- a relative duration (<n>s|m|h|d, e.g. 7d)","or an absolute ISO8601 timestamp (default 24h). Running and Dead are","point-in-time current state and are not time-filtered.","","--watch re-renders the full snapshot every --watch-interval (default 2s)","until interrupted (SIGINT/SIGTERM). With --json, each snapshot is emitted","as ONE compact JSON object per line (NDJSON).","","--tree shows the same rows as one hierarchical dispatch-lineage view","instead: no section headers (each row already carries its own status),","indented under the session that dispatched it (who woke whom), sorted","by the most recent root session first. A node is a specific turn at a","specific time, not a team:alias identity -- the same member can appear","as multiple nodes for its different turns. Lineage is only known for","turns dispatched by a NESTED `lmctl prompt`/`lmctl terminal` call made","from within another turn's own tool calls; anything else (a human's","direct dispatch, or a turn from before this feature existed) has no","recorded parent and shows as its own root. Unlike the flat Idle section,","--tree does NOT collapse finished rows to one per target: every finished","descendant of a node in view (within the --since window) is rendered, so","a `lmctl batch` run shows as its batch root with ALL of its per-prompt","turns nested underneath.","","Every row also carries `model`: the target member's declared `model=`",'read straight from its teamfile (no session/provider query) -- "default"',"when the teamfile has no model= attribute, the alias/file can't be","resolved, or there is no target at all. This is the DECLARED value only,","not necessarily what actually ran (see the MODEL column in `lmctl status","<teamfile> --details`).","","--json emits { schema_version, running, dead, idle } (flat, one array","per section, matching the three flat-mode sections -- each row carries","its own status/timing/error fields). --tree --json instead emits","{ schema_version, tree } -- an array of root nodes, each row's full",'fields plus a "state" discriminant ("running"/"dead"/"idle") and a','"children" array of the same shape, nested per the dispatch lineage.',"","Queries lmctl's own database only -- never touches native provider","session files."].join(`
|
|
2757
|
+
`),jE=120;jd="default";OO=[26,void 0,void 0,void 0,24,void 0]});var YE={};se(YE,{_setRatelimitFsDepsForTests:()=>M_,_setRatelimitRunnerForTests:()=>D_,runRatelimit:()=>JO});function Gd(t){return typeof t=="object"&&t!==null}function WO(t){return(0,ve.formatPercent)(typeof t=="number"?t:null)}function HO(t,e){let r=typeof e.bucket_id=="string"&&e.bucket_id!==""?e.bucket_id:"unknown-bucket";return r==="session"?r="5h":r==="week-all-models"?r="weekly":r.startsWith("week-scoped-")&&(r=`weekly-${r.slice(12)}`),t!==""&&!r.startsWith(`${t}-`)&&(r=`${t}-${r}`),(0,ve.escapeCell)(r)}function qO(t,e){let r="unknown",n=null,s,i=null;if(typeof e.resets_at_iso=="string"&&e.resets_at_iso!==""){let c=Date.parse(e.resets_at_iso);i=Number.isFinite(c)?c-Date.now():null,i!==null&&(Math.abs(i)<1e3?r="now":i>0?r=`in ${(0,ve.formatDuration)(i,{maxUnit:"d",style:"compact"})}`:r=`${(0,ve.formatDuration)(-i,{maxUnit:"d",style:"compact"})} ago`,s=XO[typeof e.window_type=="string"?e.window_type:""],s!==void 0&&(n=Math.min(1,Math.max(0,1-i/s))))}n!==null&&(r=`${(0,ve.formatBar)(n)} ${r}`);let o="";if(n!==null&&s!==void 0&&i!==null&&typeof e.used_fraction=="number"&&Number.isFinite(e.used_fraction)){let c=e.used_fraction;if(c<=n){let d=n>0?Math.max(0,1-c/n):NaN;o=`unused +${(0,ve.formatPercent)(d)}`}else{let d=n*s,u=d>0?(1-c)/c*d:0,m=Math.max(0,i-u);o=`needing -${(0,ve.formatDuration)(m,{maxUnit:"d",style:"compact"})}`}}let a=[];e.is_exhausted===!0&&a.push("[EXHAUSTED]"),e.allowed===!1&&a.push("allowed=false"),e.limit_reached===!0&&a.push("limit_reached");let l=[HO(t,e),`${(0,ve.formatBar)(typeof e.used_fraction=="number"?e.used_fraction:null)} ${WO(e.used_fraction)}`,r];return o!==""&&l.push(o),a.length>0&&l.push(a.join(" ")),l}function GO(t){let e=typeof t.provider=="string"&&t.provider!==""?t.provider:"unknown",r=typeof t.status=="string"?t.status:"unknown",n=typeof t.source=="string"&&t.source!==""?t.source:"unknown source",s=typeof t.plan_type=="string"&&t.plan_type!==""?t.plan_type:"?",i=typeof t.read_at=="number"&&Number.isFinite(t.read_at)?(0,ve.formatClock)(t.read_at*1e3):"unknown",o=typeof t.reason=="string"?t.reason:"",a=`${e}: ${r} (${n}) plan=${s} read ${i}`;r==="auth_expired"?(a=`${e}: unavailable (${n}) plan=${s} read ${i}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`)):r==="provider_unavailable"&&KE.has(o)?(a=`${e}: not installed/configured (${n}) plan=${s} read ${i}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`)):r!=="ok"&&(a+=` -- ${o!==""?o:"no reason given"}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`),r==="provider_unavailable"&&(a+=` (${e} server-side, not lmctl \u2014 try again later)`));let l=typeof t.provider=="string"?t.provider:"",c=Array.isArray(t.buckets)?t.buckets.filter(Gd).map(u=>qO(l,u)):[],d=[];if(Gd(t.credits)){let u=t.credits,m=[];typeof u.has_credits=="boolean"&&m.push(`has_credits=${u.has_credits}`),u.unlimited===!0&&m.push("unlimited"),u.balance!==void 0&&u.balance!==null&&m.push(`balance=${String(u.balance)}`),d.push(` credits: ${m.length>0?m.join(" "):"present"}`)}if(Gd(t.spend_control)){let u=t.spend_control,m=` spend control: reached=${u.reached===!0}`;u.individual_limit!==void 0&&u.individual_limit!==null&&(m+=` individual_limit=${String(u.individual_limit)}`),d.push(m)}return{head:a,bucketRows:c,footers:d}}function Jd(t,e){return t.stderr.write(`error: ${e}
|
|
2756
2758
|
${VE}
|
|
2757
|
-
`),2}async function
|
|
2759
|
+
`),2}async function JO(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${VE}
|
|
2758
2760
|
`),0;let r=oe(t,["--timeout"],["--json"]);if(r.error!==void 0)return Jd(e,r.error);let n=X(r,"--json");for(let f of r.positionals)if(!JE.includes(f))return Jd(e,`unknown provider: ${f} (valid targets: ${JE.join(", ")})`);let s=r.positionals.length>0?r.positionals:["all"],i=15,o=W(r,"--timeout");if(o!==void 0){let f=Number(o);if(!Number.isFinite(f)||f<=0)return Jd(e,`invalid --timeout "${o}" (expected a positive number of seconds)`);i=f}let a=io({targets:s,timeoutSeconds:i,env:e.env??process.env,progress:f=>e.stderr.write(`${f}
|
|
2759
2761
|
`)});if(a.status==="error"){let f=a.error.startsWith("lmratelimit binary not found")?`${a.error}
|
|
2760
2762
|
Set LMCTL_RATELIMIT_BIN=<path> to point at the lmratelimit CLI.`:a.error;return e.stderr.write(`error: ${f}
|
|
2761
2763
|
`),1}let l=a.readings;if(n)return re(e,{readings:l}),0;let c=new Set(r.positionals),d=l.filter(f=>{let E=typeof f.status=="string"?f.status:"",y=typeof f.reason=="string"?f.reason:"";return E!=="provider_unavailable"||!KE.has(y)?!0:c.has(typeof f.provider=="string"?f.provider:"")});if(d.length===0)return e.stdout.write(`rate-limit: no readings returned.
|
|
2762
|
-
`),0;let u=["LIMIT","USED","RESET TIME","OVERSTOCK"],m=["left","left","left"],p=d.map(
|
|
2764
|
+
`),0;let u=["LIMIT","USED","RESET TIME","OVERSTOCK"],m=["left","left","left"],p=d.map(GO),_=(0,ve.measureColumns)([{rows:[],headers:u},...p.map(f=>f.bucketRows)]),h=!1,g=[];for(let f of p){if(g.length>0&&g.push(""),g.push(f.head),f.bucketRows.length>0){let E=!h;h=!0,g.push((0,ve.renderGrid)(f.bucketRows,{widths:_,margin:2,align:m,...E?{headers:u}:{}}))}g.push(...f.footers)}return e.stdout.write(`${g.join(`
|
|
2763
2765
|
`)}
|
|
2764
|
-
`),0}var ve,VE,KE,JE,
|
|
2765
|
-
`),KE=new Set(["agy_not_found","credentials_missing"]),JE=so;
|
|
2766
|
+
`),0}var ve,VE,KE,JE,XO,zE=k(()=>{"use strict";ve=_t(dt(),1);_e();oo();oo();VE=["usage: lmctl ratelimit [provider ...] [--json] [--timeout <seconds>]",""," Queries provider subscription rate limits in REAL TIME via the external"," lmratelimit readers -- stateless: nothing is read from or written to any"," database.",""," Providers: all (default), codex, agy, claude, kimi. Multiple allowed.",""," --timeout <seconds> Per-provider reader timeout (default 15).",' --json Emit {"readings": [...]} in the lmratelimit-v1 schema'," with every raw field preserved verbatim -- the same"," shape `lmratelimit all --pretty` prints, and the exact"," contract lmbee's collector parses, so consumers can"," read this output directly instead of re-implementing"," their own parser. Unknown future fields pass through.","",' Prints a "querying ..." note on stderr before the readers run: the spawn'," then blocks until every provider answers or its timeout expires.",""," Binary resolution: LMCTL_RATELIMIT_BIN, then"," ~/repos/tools/lmratelimit/bin/lmratelimit, then lmratelimit on PATH."].join(`
|
|
2767
|
+
`),KE=new Set(["agy_not_found","credentials_missing"]),JE=so;XO={five_hour:5*36e5,daily:864e5,weekly:7*864e5,monthly:30*864e5}});nt();import{pathToFileURL as VO}from"node:url";import{execFileSync as pT}from"node:child_process";import{existsSync as hT,readFileSync as gT}from"node:fs";import{join as nu}from"node:path";import{fileURLToPath as _T}from"node:url";function su(){return _T(new URL("../..",import.meta.url))}function Po(t=su()){try{let e=JSON.parse(gT(nu(t,"package.json"),"utf8"));if(typeof e.version=="string")return e.version}catch{}return"0.0.0"}function Fo(t,e){try{return pT("git",e,{cwd:t,stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim()}catch{return}}function Uo(t=su()){let e=Po(t);if(!hT(nu(t,".git")))return e;let r=Fo(t,["rev-parse","--short","HEAD"]);if(r===void 0)return e;let n=Fo(t,["describe","--tags","--exact-match","HEAD"]),s=Fo(t,["status","--porcelain"]),i=s!==void 0&&s.length>0;return n===`v${e}`&&!i?e:`${e}+${r}${i?".dirty":""}`}J();import{mkdirSync as NT,readFileSync as LT,renameSync as CT,writeFileSync as OT}from"node:fs";import{homedir as DT}from"node:os";import{dirname as MT,join as $T}from"node:path";function fu(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function AT(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function RT(t,e){return!AT(t)||fu(t)?null:`${e} must use https://: ${t}`}async function pu(t,e){let r=RT(t,e.description);if(r!==null||!fu(t))throw new Error(r??`${e.description} must use https://: ${t}`);let n=e.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let o;try{o=await fetch(t,{signal:s.signal,redirect:"manual"})}catch(a){throw mu(t,e.description,n,a)}if(o.type==="opaqueredirect"||o.status>=300&&o.status<400)throw new Error(`refusing to follow redirect from ${e.description} ${t} (https-only: the URL must serve the content directly, not redirect)`);if(!o.ok)throw new Error(`failed to fetch ${e.description} ${t}: HTTP ${o.status}${o.statusText?` ${o.statusText}`:""}`);try{return Buffer.from(await o.arrayBuffer())}catch(a){throw mu(t,e.description,n,a)}}finally{clearTimeout(i)}}function mu(t,e,r,n){let i=n instanceof Error&&n.name==="AbortError"?`timed out after ${r}ms`:n instanceof Error?n.message:String(n);return new Error(`failed to fetch ${e} ${t}: ${i}`)}var FT="https://registry.npmjs.org/@lmctl-ai/lmctl/latest",PT=60*60*1e3,UT=1500;function jT(){let t=process.env.HOME??DT();return $T(t,".lmctl",".update-check.json")}function BT(t){return t.isTTY===!0}function WT(t,e){let r=i=>{let o=/^(\d+)\.(\d+)\.(\d+)(?:$|[-+])/.exec(i.trim());if(o===null)return null;let a=o.slice(1).map(l=>Number(l));return a.some(l=>!Number.isSafeInteger(l)||l<0)?null:a},n=r(t),s=r(e);if(n===null||s===null)return 0;for(let i=0;i<3;i+=1){if(n[i]>s[i])return 1;if(n[i]<s[i])return-1}return 0}function Bo(t,e){return!!(process.env.LMCTL_NO_UPDATE_NOTIFIER==="1"||!BT(e.stderr)||t.includes("--json")||t.includes("--help")||t.includes("-h")||t[0]==="help"||t[0]==="mcp")}function HT(t,e){try{let r=JSON.parse(LT(t,"utf8"));if(typeof r.checkedAt=="number"&&Number.isFinite(r.checkedAt)&&typeof r.latest=="string"&&e-r.checkedAt<PT)return r.latest}catch{}return null}function XT(t,e){NT(MT(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;OT(r,`${JSON.stringify(e)}
|
|
2766
2768
|
`,"utf8"),CT(r,t)}async function qT(){let t=await pu(FT,{description:"lmctl npm metadata",timeoutMs:UT}),e=JSON.parse(t.toString("utf8"));if(typeof e.version!="string"||e.version.trim()==="")throw new Error("registry response missing version");return e.version}async function hu(t,e=[],r={}){try{if(Bo(e,t))return;let n=r.now?.()??Date.now(),s=r.cachePath??jT();if(HT(s,n)!==null)return;let o=await(r.fetchLatest??qT)();try{XT(s,{checkedAt:n,latest:o})}catch{return}let a=r.currentVersion?.()??Po();WT(o,a)>0&&t.stderr.write(`update available: ${a} \u2192 ${o} run: npm i -g @lmctl-ai/lmctl@latest
|
|
2767
2769
|
`)}catch{}}Ho();Ns();var fn=`usage: lmctl [--db PATH] [--debug] <command> [args]
|
|
2768
2770
|
`,Vd=`${fn}
|
|
@@ -2810,23 +2812,23 @@ ${fn}Run 'lmctl help' for usage.
|
|
|
2810
2812
|
${fn}Run 'lmctl help' for usage.
|
|
2811
2813
|
`),1):(t.stderr.write(`error: unknown command: ${e}
|
|
2812
2814
|
${fn}Run 'lmctl help' for usage.
|
|
2813
|
-
`),1)}async function
|
|
2814
|
-
`),0;if(i==="--help"||i==="-h"||i===void 0)return e.stdout.write(Vd),0;if(i==="help"){let[c,...d]=r.slice(1);return c===void 0||c==="--help"||c==="-h"?(e.stdout.write(Vd),0):QE.has(c)?eT(c,[...d,"--help"],e):tT(e,c)}$o(he(),e.stderr);let[o,...a]=r;if(o===void 0)return e.stdout.write(Vd),0;let l=Date.now();Kd(o,a,{phase:"start",started_at:new Date(l).toISOString()});try{let c=await eT(o,a,e);return Kd(o,a,{phase:"finish",outcome:c===0?"ok":"error",exit_code:c,duration_ms:Date.now()-l}),QE.has(o)&&!Bo(r,e)&&await hu(e,r),c}catch(c){let d=c instanceof Error?c:new Error(String(c));return Kd(o,a,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-l,error_class:d.name,error_message:d.message,error_stack:d.stack??null,causes:
|
|
2815
|
+
`),1)}async function KO(t,e={stdout:process.stdout,stderr:process.stderr}){let r=cu();try{return await YO(t,e)}finally{du(r)}}async function YO(t,e={stdout:process.stdout,stderr:process.stderr}){let r=[],n,s=0;for(;s<t.length;s+=1){let c=t[s];if(c==="--db"){let d=t[++s];if(d===void 0||d.startsWith("--"))return ZE(e,"missing value for --db");n=d;continue}if(c==="--debug"){lu();continue}if(c==="--allow-schema-skew"){process.env.LMCTL_ALLOW_SCHEMA_SKEW="1";continue}break}if(r.push(...t.slice(s)),n!==void 0){let c=r[0];if(bs()&&c!==void 0&&Is(c))return ZE(e,"--db cannot be combined with an infra command (lmctl and lmauto use separate databases)");process.env.LMCTL_DB=n}let i=r[0];if(i==="--version"||i==="-v"||i==="-V")return e.stdout.write(`lmctl ${Uo()}
|
|
2816
|
+
`),0;if(i==="--help"||i==="-h"||i===void 0)return e.stdout.write(Vd),0;if(i==="help"){let[c,...d]=r.slice(1);return c===void 0||c==="--help"||c==="-h"?(e.stdout.write(Vd),0):QE.has(c)?eT(c,[...d,"--help"],e):tT(e,c)}$o(he(),e.stderr);let[o,...a]=r;if(o===void 0)return e.stdout.write(Vd),0;let l=Date.now();Kd(o,a,{phase:"start",started_at:new Date(l).toISOString()});try{let c=await eT(o,a,e);return Kd(o,a,{phase:"finish",outcome:c===0?"ok":"error",exit_code:c,duration_ms:Date.now()-l}),QE.has(o)&&!Bo(r,e)&&await hu(e,r),c}catch(c){let d=c instanceof Error?c:new Error(String(c));return Kd(o,a,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-l,error_class:d.name,error_message:d.message,error_stack:d.stack??null,causes:QO(d)}),zO(c,o,a,e)}}function Kd(t,e,r){Se({event:t,record_kind:"cli_action",command:t,argv:e,cwd:process.cwd(),db_path:he(),lmctl_version:Uo(),node_version:process.version,...r})}function zO(t,e,r,n){let s=t instanceof Error?t:new Error(String(t));return s instanceof Ct&&r.includes("--json")?(n.stdout.write(`${JSON.stringify({error:s.message,schema_skew:{db_version:s.dbVersion,build_version:s.buildVersion,mode:"refused"}},null,2)}
|
|
2815
2817
|
`),1):(n.stderr.write(`error: ${s.message}
|
|
2816
2818
|
`),uu()?(n.stderr.write(`(debug details written to ~/.lmctl/debug-*.log)
|
|
2817
2819
|
`),1):(n.stderr.write(`(re-run with --debug for the full stack trace and context in ~/.lmctl/debug-*.log)
|
|
2818
|
-
`),1))}function
|
|
2819
|
-
`);let{runChat:n}=await Promise.resolve().then(()=>(co(),sd));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(Dy(),Oy));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(Jy(),Gy));return n(e,r)}case"export":{let{runExport:n}=await Promise.resolve().then(()=>(Yy(),Ky));return n(e,r)}case"cost":{let{runCost:n}=await Promise.resolve().then(()=>(Qy(),zy));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(tE(),eE));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>(At(),Vc));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>(At(),Vc)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(wo(),To));return s(r,"seed",e,i=>n(i,r))}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(gs(),by)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(wo(),To));return s(r,"plan",e,i=>n(i,r),{ownsForce:!0,extension:".txt"})}case"init":{let{runInit:n}=await Promise.resolve().then(()=>(nE(),rE));return n(e,r)}case"quickrun":{let{runQuickrun:n}=await Promise.resolve().then(()=>(pE(),fE));return n(e,r)}case"hello":{let{runHello:n}=await Promise.resolve().then(()=>(_E(),gE));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(wd(),uE));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Ud(),PE));return n(e,r)}case"running":{let{runRunning:n}=await Promise.resolve().then(()=>(GE(),qE));return n(e,r)}case"ratelimit":{let{runRatelimit:n}=await Promise.resolve().then(()=>(zE(),YE));return n(e,r)}case"db":return
|
|
2820
|
+
`),1))}function QO(t){let e=[],r=t.cause,n=0;for(;r!=null&&n<8;){let s=r instanceof Error?r:new Error(String(r));e.push({error_class:s.name,error_message:s.message,error_stack:s.stack??null}),r=s.cause,n+=1}return e}async function eT(t,e,r){switch(t){case"batch":{let{runBatch:n}=await Promise.resolve().then(()=>(pg(),fg));return n(e,r)}case"script":{let{runScript:n}=await Promise.resolve().then(()=>(H_(),W_));return n(e,r)}case"prompt":{let{runChat:n}=await Promise.resolve().then(()=>(co(),sd)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(wo(),To));return s(r,"prompt",e,i=>n(i,r))}case"chat":{process.stderr.write(`warning: 'lmctl chat' is being phased out -- use 'lmctl prompt' (same behaviour; a prompt is answered, it is not a conversation)
|
|
2821
|
+
`);let{runChat:n}=await Promise.resolve().then(()=>(co(),sd));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(Dy(),Oy));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(Jy(),Gy));return n(e,r)}case"export":{let{runExport:n}=await Promise.resolve().then(()=>(Yy(),Ky));return n(e,r)}case"cost":{let{runCost:n}=await Promise.resolve().then(()=>(Qy(),zy));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(tE(),eE));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>(At(),Vc));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>(At(),Vc)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(wo(),To));return s(r,"seed",e,i=>n(i,r))}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(gs(),by)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(wo(),To));return s(r,"plan",e,i=>n(i,r),{ownsForce:!0,extension:".txt"})}case"init":{let{runInit:n}=await Promise.resolve().then(()=>(nE(),rE));return n(e,r)}case"quickrun":{let{runQuickrun:n}=await Promise.resolve().then(()=>(pE(),fE));return n(e,r)}case"hello":{let{runHello:n}=await Promise.resolve().then(()=>(_E(),gE));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(wd(),uE));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Ud(),PE));return n(e,r)}case"running":{let{runRunning:n}=await Promise.resolve().then(()=>(GE(),qE));return n(e,r)}case"ratelimit":{let{runRatelimit:n}=await Promise.resolve().then(()=>(zE(),YE));return n(e,r)}case"db":return ZO(e,r);default:if(bs()&&Is(t)){let{runInfraCommand:n}=await Promise.resolve().then(()=>(Ho(),_u));return n(t,e,r)}return tT(r,t)}}async function ZO(t,e){let[r,...n]=t;return r==="--help"||r==="-h"||r==="help"?(e.stdout.write(`usage: lmctl db <subcommand>
|
|
2820
2822
|
|
|
2821
2823
|
backfill-events Replay the legacy tables into the event-log
|
|
2822
2824
|
(with --db <copy>) substrate and rebuild projections. Idempotent;
|
|
2823
2825
|
run against a COPY of the DB, never the live file.
|
|
2824
2826
|
downgrade --to <version> --confirm Documented stub (restore from backup).
|
|
2825
|
-
`),0):r==="backfill-events"?
|
|
2827
|
+
`),0):r==="backfill-events"?e0(n,e):r==="downgrade"?(e.stderr.write(`not yet implemented; restore from backup, or run lmctl migrate (forward-migrates ok)
|
|
2826
2828
|
`),1):(e.stderr.write(`usage: lmctl db <subcommand> (backfill-events | downgrade)
|
|
2827
|
-
`),1)}async function
|
|
2829
|
+
`),1)}async function e0(t,e){let{resolveDbPath:r}=await Promise.resolve().then(()=>(nt(),ru)),n=r();if(!((process.env.LMCTL_DB??"").length>0)&&!t.includes("--allow-live"))return e.stderr.write(`refusing to backfill the default live DB.
|
|
2828
2830
|
resolved target: ${n}
|
|
2829
2831
|
run against a COPY: cp <state.db> copy.db && lmctl --db copy.db db backfill-events
|
|
2830
2832
|
(or pass --allow-live to target the resolved DB deliberately).
|
|
2831
2833
|
`),1;let{migrate:i}=await Promise.resolve().then(()=>(Ns(),ku)),{backfillEventLog:o}=await Promise.resolve().then(()=>(zo(),Eu)),a=i({dbPath:n});try{let l=o(a);return e.stdout.write(`${JSON.stringify(l,null,2)}
|
|
2832
|
-
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===
|
|
2834
|
+
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===VO(process.argv[1]).href){let t=await KO(process.argv.slice(2));process.exitCode=t}export{QE as COMMANDS,KO as runCli};
|