@lmctl-ai/lmctl 0.2.9 → 0.2.10
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
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}var
|
|
3
|
-
`)}catch{}}function
|
|
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
|
|
5
|
-
`),1;let i=t===
|
|
6
|
-
`});import{existsSync as
|
|
1
|
+
var VE=Object.create;var Lo=Object.defineProperty;var KE=Object.getOwnPropertyDescriptor;var YE=Object.getOwnPropertyNames;var zE=Object.getPrototypeOf,QE=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var ZE=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ae=(t,e)=>{for(var r in e)Lo(t,r,{get:e[r],enumerable:!0})},eT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of YE(e))!QE.call(t,s)&&s!==r&&Lo(t,s,{get:()=>e[s],enumerable:!(n=KE(e,s))||n.enumerable});return t};var _t=(t,e,r)=>(r=t!=null?VE(zE(t)):{},eT(e||!t||!t.__esModule?Lo(r,"default",{value:t,enumerable:!0}):r,t));var Qd={};ae(Qd,{defaultDbPath:()=>Yd,describeStateLocation:()=>hn,isSlowWslMount:()=>zd,lmctlNextHome:()=>Kd,resolveDbPath:()=>fe,warnIfSlowDbPath:()=>Co});import{platform as Jd}from"node:os";import{homedir as tT}from"node:os";import{join as Vd}from"node:path";function Kd(){let t=process.env.LMCTL_HOME;return t!==void 0&&t.length>0?t:Vd(tT(),rT)}function Yd(){return Vd(Kd(),nT)}function fe(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:Yd()}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 zd(t,e=Jd()){return e!=="linux"?!1:t.startsWith("/mnt/c/")||t==="/mnt/c"}function Co(t,e=process.stderr,r=Jd()){zd(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 rT,nT,rt=k(()=>{"use strict";rT=".lmctl",nT="state.db"});import{readFileSync as nu,appendFileSync as lT,mkdirSync as cT,existsSync as VO,readdirSync as KO,unlinkSync as YO}from"node:fs";import{join as ws,dirname as dT}from"node:path";import{homedir as uT}from"node:os";function $o(){return ws(uT(),".lmctl")}function su(){Nr=!0,process.env.LMCTL_DEBUG="1"}function iu(){return{cliDebug:Nr,lmctlDebugEnv:process.env.LMCTL_DEBUG}}function ou(t){Nr=t.cliDebug,t.lmctlDebugEnv===void 0?delete process.env.LMCTL_DEBUG:process.env.LMCTL_DEBUG=t.lmctlDebugEnv}function K(){if(Nr||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-ru>=mT&&(tu=hT(),ru=t),tu}function au(){return Nr||process.env.LMCTL_DEBUG==="1"}function fT(){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 we(t,e){if(e?.verbose){if(!Nr)return}else if(!e?.always&&!K())return;try{pT();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};lT(Ts,JSON.stringify(r)+`
|
|
3
|
+
`)}catch{}}function pT(){if(!Ts){let e=fT().slice(0,13).replace("T","-");Ts=ws($o(),`debug-${e}.log`)}cT(dT(Ts),{recursive:!0})}function _e(...t){we({event:"legacy",msg:t.join(" ")})}function ye(...t){we({event:"legacy",msg:t.join(" ")},{verbose:!0})}function L(t){we(t,{always:!0})}function hT(){return gT()||_T()}function gT(){try{let t=nu(ws($o(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
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 _T(){try{let t=nu(ws($o(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Nr,tu,ru,mT,Ts,J=k(()=>{"use strict";Nr=!1,tu=!1,ru=0,mT=5e3;Ts=null});var fu={};ae(fu,{INFRA_CLI_CONTRACT_EXPECTED:()=>$T,INFRA_FLAT_COMMANDS:()=>mu,INFRA_NAMESPACE_COMMAND:()=>Po,infraCliEnabled:()=>vs,isInfraCommand:()=>Ss,runInfraCommand:()=>PT});function vs(t=process.env){return t.LMCTL_INFRA_CLI==="1"||t.LMCTL_INFRA_CLI==="true"}function Ss(t){return mu.includes(t)||t===Po}async function PT(t,e,r,n=UT){let s;try{s=await n()}catch{return r.stderr.write(FT),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
|
+
`),1;let i=t===Po?e:[t,...e],o=s.createRuntime();return s.dispatch(i,o)}async function UT(){throw new Error("infra CLI adapter target (lmt) is retired; no successor module currently implements this contract")}var $T,mu,Po,FT,Uo=k(()=>{"use strict";$T=1,mu=["lmchat","lmmail","lmnote","lmsheet","lmtext","lmsound","login","whoami","exec","tell","peers","site"],Po="auto";FT=`lmctl: infra commands (site/auto/exec/tell/peers/login/whoami/lmchat/lmmail/lmnote/lmsheet/lmtext/lmsound) are not available in this build.
|
|
6
|
+
`});import{existsSync as jT}from"node:fs";import{createRequire as BT}from"node:module";function WT(){return jo===null&&(jo=BT(import.meta.url)("node:sqlite").DatabaseSync),jo}function Bo(t){return t.length===1&&HT(t[0])?[t[0]]:t}function HT(t){if(!Xo(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Xo(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var jo,Wo,bs,Ho,qo=k(()=>{"use strict";jo=null;Wo=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!jT(e))throw new Error("unable to open database file");this.name=e,this.handle=new(WT())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new Ho(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return r?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...r)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...r);return this.exec("COMMIT"),s}catch(s){throw this.inTransaction&&this.exec("ROLLBACK"),s}}let n=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${n}`);try{let s=e(...r);return this.exec(`RELEASE ${n}`),s}catch(s){throw this.inTransaction&&(this.exec(`ROLLBACK TO ${n}`),this.exec(`RELEASE ${n}`)),s}}}get inTransaction(){return this.transactionDepth>0}close(){this.handle.close()}updateTransactionDepth(e){let r=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(r!==void 0){if(r==="BEGIN"||r==="SAVEPOINT"){this.transactionDepth+=1;return}if(r==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(r==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}r==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},bs=Wo,Ho=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...Bo(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...Bo(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...Bo(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Xo(e)?Object.values(e):Xo(e)?{...e}:e}}});import{createHash as XT}from"node:crypto";function qT(t,e,r){return XT("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function Oe(t,e,r){let n=qT(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=t.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
7
7
|
VALUES (?, ?, ?, ?, ?)
|
|
8
|
-
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return r(l),{appended:!0,seq:l,event_id:n}})()}var
|
|
8
|
+
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return r(l),{appended:!0,seq:l,event_id:n}})()}var Is=k(()=>{"use strict"});var hu={};ae(hu,{backfillEventLog:()=>Go,rebuildProjections:()=>pu});import{createHash as GT}from"node:crypto";function sr(t,e){return t==null?null:{teamfile:t,alias:e??""}}function JT(t,e,r){return`lease_${GT("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function xs(t,e,r,n){r.forEach((s,i)=>{Oe(t,{stream_id:e,event_type:s.event_type,payload:s.payload,observedLastSeq:i,ts:s.ts},()=>{}).appended?n.appended+=1:n.skipped+=1})}function VT(t){let e=`msg_tcl_${t.id}`,r=sr(t.sender_teamfile,t.sender_alias),n=sr(t.receiver_teamfile,t.receiver_alias),s={table:"team_chat_log",id:t.id},i={message_id:e,sender:r,receiver:n,root_teamfile:t.root_teamfile,legacy:s},o=[{event_type:V.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.message,origin:t.origin,correlation_status:"legacy-unavailable"}}];return t.status!=="running"&&o.push({event_type:V.HANDLED,ts:t.created_at,payload:{...i,outcome:t.status,receipt:t.response,error:t.error_detail,truncated:t.truncated===1}}),{streamId:e,events:o}}function KT(t){let e=`msg_mbx_${t.id}`,r=sr(t.sender_teamfile,t.sender_alias),n=sr(t.receiver_teamfile,t.receiver_alias),s={table:"agent_mailbox",id:t.id},i={message_id:e,sender:r,receiver:n,root_teamfile:t.root_teamfile,legacy:s},o=[];if(t.message_type==="response"){let a=t.request_mailbox_id!==null?`msg_mbx_${t.request_mailbox_id}`:null;return o.push({event_type:V.RESPONSE_CREATE,ts:t.created_at,payload:{...i,message_type:"response",content:t.payload,in_reply_to_message_id:a,correlation_status:"legacy-unavailable"}}),o.push({event_type:V.RESPONSE_ENQUEUE,ts:t.created_at,payload:{...i,message_type:"response",in_reply_to_message_id:a}}),t.delivered_at!==null&&o.push({event_type:V.RESPONSE_DELIVERED,ts:t.delivered_at,payload:{...i,message_type:"response",receipt:t.receipt}}),{streamId:e,events:o}}return o.push({event_type:V.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:V.ENQUEUE,ts:t.created_at,payload:{...i,message_type:"request"}}),t.waited_at!==null&&o.push({event_type:V.WAIT_REGISTER,ts:t.waited_at,payload:{...i,waited_by:t.waited_by}}),(t.delivering_at!==null||t.delivery_holder_pid!==null)&&o.push({event_type:V.DELIVER_CLAIM,ts:t.delivering_at??t.created_at,payload:{...i,pid:t.delivery_holder_pid,host:t.delivery_holder_host}}),t.delivered_at!==null&&o.push({event_type:V.DELIVERED,ts:t.delivered_at,payload:{...i,receipt:t.receipt}}),{streamId:e,events:o}}function YT(t){let e=`inv_${t.id}`,r=sr(t.target_teamfile,t.target_alias),n={table:"tracked_invocation",id:t.id},s=[{event_type:V.INVOCATION_START,ts:t.started_at,payload:{invocation_id:e,kind:t.kind,origin:t.origin,launch_source:t.launch_source,from_identity:t.from_identity,target:r,root_teamfile:t.root_teamfile,scope_teamfile:t.scope_teamfile,cwd:t.cwd,command:t.command,request_payload:t.request_payload,started_at:t.started_at,request_message_id:t.team_chat_log_id!==null?`msg_tcl_${t.team_chat_log_id}`:null,holder_pid:t.holder_pid,holder_host:t.holder_host,legacy:n}}];return t.notified_by!==null&&s.push({event_type:V.INVOCATION_NOTIFY_CLAIM,ts:t.notified_at??t.started_at,payload:{invocation_id:e,notified_by:t.notified_by,notified_at:t.notified_at,legacy:n}}),t.status!=="running"&&s.push({event_type:V.INVOCATION_FINISH,ts:t.ended_at??t.started_at,payload:{invocation_id:e,status:t.status,ended_at:t.ended_at,exit_code:t.exit_code,signal:t.signal,result_summary:t.result_summary,error:t.error,legacy:n}}),{streamId:e,events:s}}function zT(t){let e=JT(t.receiver_teamfile,t.receiver_alias,t.started_at),r=sr(t.receiver_teamfile,t.receiver_alias),n=sr(t.sender_teamfile,t.sender_alias);return{streamId:e,events:[{event_type:V.INFLIGHT_TAKE,ts:t.started_at,payload:{lease_id:e,receiver:r,sender:n,holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at,legacy:{table:"agent_inflight",receiver_teamfile:t.receiver_teamfile,receiver_alias:t.receiver_alias}}}]}}function ks(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Go(t){let e={appended:0,skipped:0},r={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};t.transaction(()=>{if(ks(t,"team_chat_log"))for(let i of t.prepare("SELECT * FROM team_chat_log ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=VT(i);xs(t,a,l,e),r.team_chat_log+=e.appended+e.skipped-o}if(ks(t,"agent_mailbox"))for(let i of t.prepare("SELECT * FROM agent_mailbox ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=KT(i);xs(t,a,l,e),r.agent_mailbox+=e.appended+e.skipped-o}if(ks(t,"tracked_invocation"))for(let i of t.prepare("SELECT * FROM tracked_invocation ORDER BY id").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=YT(i);xs(t,a,l,e),r.tracked_invocation+=e.appended+e.skipped-o}if(ks(t,"agent_inflight"))for(let i of t.prepare("SELECT * FROM agent_inflight ORDER BY receiver_teamfile, receiver_alias").all()){let o=e.appended+e.skipped,{streamId:a,events:l}=zT(i);xs(t,a,l,e),r.agent_inflight+=e.appended+e.skipped-o}pu(t)})();let s=i=>t.prepare(`SELECT count(*) AS n FROM ${i}`).get().n;return{appended:e.appended,skipped:e.skipped,bySource:r,projections:{agent_state:s("agent_state"),message_pending:s("message_pending"),invocation_state:s("invocation_state")}}}function pu(t){t.exec("DELETE FROM agent_state"),t.exec("DELETE FROM message_pending"),t.exec("DELETE FROM invocation_state");let e=t.prepare("SELECT seq, stream_id, event_type, payload FROM message_event ORDER BY seq").all();for(let r of e){let n=JSON.parse(r.payload);QT(t,r.seq,r.stream_id,r.event_type,n)}}function de(t,e,r){let n=t[e];return n!=null?n[r]??null:null}function QT(t,e,r,n,s){switch(n){case V.ENQUEUE:case V.RESPONSE_ENQUEUE:{let i=n===V.RESPONSE_ENQUEUE;t.prepare(`INSERT INTO message_pending
|
|
9
9
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
10
10
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
@@ -29,7 +29,7 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
29
29
|
cwd, command, request_message_id, request_payload, holder_pid, holder_host, status, started_at, last_seq)
|
|
30
30
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)
|
|
31
31
|
ON CONFLICT(invocation_id) DO NOTHING`).run(r,s.kind??"chat",s.origin??"unknown",s.launch_source??"",s.from_identity??"",de(s,"target","teamfile"),de(s,"target","alias"),s.root_teamfile??null,s.cwd??null,s.command??null,s.request_message_id??null,s.request_payload??null,s.holder_pid??null,s.holder_host??null,s.started_at??"",e);break;case V.INVOCATION_FINISH:t.prepare(`UPDATE invocation_state SET status=?, ended_at=?, result_summary=?, error=?, last_seq=?
|
|
32
|
-
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case V.INVOCATION_NOTIFY_CLAIM:t.prepare("UPDATE invocation_state SET notified_by=?, notified_at=?, last_seq=? WHERE invocation_id=?").run(s.notified_by??null,s.notified_at??null,e,r);break;default:break}}var V,
|
|
32
|
+
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case V.INVOCATION_NOTIFY_CLAIM:t.prepare("UPDATE invocation_state SET notified_by=?, notified_at=?, last_seq=? WHERE invocation_id=?").run(s.notified_by??null,s.notified_at??null,e,r);break;default:break}}var V,Jo=k(()=>{"use strict";Is();V={CREATE:"CREATE",ENQUEUE:"ENQUEUE",DELIVER_CLAIM:"DELIVER_CLAIM",DELIVER_CLAIM_RELEASE:"DELIVER_CLAIM_RELEASE",DELIVERED:"DELIVERED",HANDLED:"HANDLED",WAIT_REGISTER:"WAIT_REGISTER",RESPONSE_CREATE:"RESPONSE_CREATE",RESPONSE_ENQUEUE:"RESPONSE_ENQUEUE",RESPONSE_DELIVERED:"RESPONSE_DELIVERED",INFLIGHT_TAKE:"INFLIGHT_TAKE",INFLIGHT_RELEASE:"INFLIGHT_RELEASE",INFLIGHT_RECLAIM:"INFLIGHT_RECLAIM",TERMINAL_LOCK_TAKE:"TERMINAL_LOCK_TAKE",TERMINAL_LOCK_RELEASE:"TERMINAL_LOCK_RELEASE",TERMINAL_LOCK_EXPIRE:"TERMINAL_LOCK_EXPIRE",INVOCATION_START:"INVOCATION_START",INVOCATION_FINISH:"INVOCATION_FINISH",INVOCATION_NOTIFY_CLAIM:"INVOCATION_NOTIFY_CLAIM"}});var Su={};ae(Su,{CURRENT_USER_VERSION:()=>yt,SchemaSkewError:()=>Lt,_resetNewerSchemaWarningForTests:()=>uw,currentSchemaSkew:()=>mw,migrate:()=>gn});import{existsSync as ZT,mkdirSync as ew,readFileSync as _u}from"node:fs";import{randomUUID as tw}from"node:crypto";import{homedir as rw}from"node:os";import{dirname as yu,join as nw,resolve as Eu}from"node:path";import{fileURLToPath as sw,pathToFileURL as iw}from"node:url";function gn(t){t.dbPath!==":memory:"&&ew(yu(t.dbPath),{recursive:!0});let e=new bs(t.dbPath);try{e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=vu(e),n=t.buildVersionForTests??yt;if(r===0)e.exec(_u(wu,"utf8")),e.pragma(`user_version = ${yt}`);else if(r>n){let s=cw(e,r);if(Ko={dbVersion:r,buildVersion:n},s>n&&!t.allowSchemaSkew)throw e.close(),new Lt(t.dbPath,r,n);return dw(t.dbPath,r,n),e}return aw(e,r),lw(e),e}catch(r){try{e.close()}catch{}throw r}}function aw(t,e){let r=e;if(r<2&&r!==0&&(t.exec(`
|
|
33
33
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
34
34
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
35
35
|
team_name TEXT NOT NULL,
|
|
@@ -750,7 +750,7 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
750
750
|
ON tracked_invocation(scope_teamfile, status, started_at);
|
|
751
751
|
CREATE INDEX IF NOT EXISTS idx_tracked_invocation_status_ended
|
|
752
752
|
ON tracked_invocation(status, ended_at);
|
|
753
|
-
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(Ye(t,"agent_mailbox")&&
|
|
753
|
+
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(Ye(t,"agent_mailbox")&&Go(t),t.exec("DROP TABLE IF EXISTS agent_mailbox;"),t.pragma("user_version = 57"),r=57),r<58&&r!==0&&(Nt(t,"tracked_invocation"),X(t,"tracked_invocation").has("parent_invocation_id")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN parent_invocation_id INTEGER;"),t.pragma("user_version = 58"),r=58),r<59&&r!==0&&(t.exec(`
|
|
754
754
|
CREATE TABLE IF NOT EXISTS state_ledger_identity (
|
|
755
755
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
756
756
|
instance_id TEXT NOT NULL,
|
|
@@ -762,7 +762,7 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
762
762
|
value TEXT NOT NULL
|
|
763
763
|
);
|
|
764
764
|
INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '60');
|
|
765
|
-
`),t.pragma("user_version = 61"),r=61}
|
|
765
|
+
`),t.pragma("user_version = 61"),r=61}ZT(ow)}function lw(t){t.prepare("SELECT instance_id FROM state_ledger_identity WHERE singleton = 1").get()===void 0&&t.prepare("INSERT OR IGNORE INTO state_ledger_identity (singleton, instance_id, created_at) VALUES (1, ?, ?)").run(tw(),new Date().toISOString())}function X(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function Ye(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Nt(t,e){if(!Ye(t,e)&&(t.exec(_u(wu,"utf8")),!Ye(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function gu(t){let e=X(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
766
766
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
767
767
|
CREATE TABLE team_chat_log_v46 (
|
|
768
768
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -791,23 +791,23 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
791
791
|
FROM team_chat_log;
|
|
792
792
|
DROP TABLE team_chat_log;
|
|
793
793
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
794
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function vu(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function
|
|
794
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function vu(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function cw(t,e){try{if(!Ye(t,"schema_meta"))return e;let r=t.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();if(r===void 0)return e;let n=Number.parseInt(r.value,10);return Number.isInteger(n)&&n>0?n:e}catch{return e}}function dw(t,e,r=yt){Vo||(Vo=!0,process.stderr.write(`warning: ${t}: state.db is v${e}; this build understands v${r} -- some newer data or features may not be visible, proceeding best-effort. Update: npm install -g @lmctl-ai/lmctl@latest
|
|
795
795
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:r,mode:"best_effort"}})}
|
|
796
|
-
`))}function
|
|
796
|
+
`))}function uw(){Vo=!1,Ko=null}function mw(){return Ko}function fw(){return process.env.LMCTL_DB??nw(rw(),".lmctl","state.db")}var Tu,wu,ow,yt,Lt,Vo,Ko,As=k(()=>{"use strict";qo();Jo();Tu=yu(sw(import.meta.url)),wu=Eu(Tu,"schema.sql"),ow=Eu(Tu,"migrations"),yt=61,Lt=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}};Vo=!1;Ko=null;if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===iw(process.argv[1]).href){let t=gn({dbPath:process.argv[2]??fw()});try{process.stdout.write(`migrated user_version=${vu(t)}
|
|
797
797
|
`)}finally{t.close()}}});function bu(t){if(t.length===0||!t.startsWith("---"))throw new nt("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
798
|
-
`);if(e[0]!=="---")throw new nt("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 nt(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!
|
|
798
|
+
`);if(e[0]!=="---")throw new nt("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 nt(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!pw.has(c))throw new nt(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Rs.join(", ")}`);r[c]=d}if(n===-1)throw new nt("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Rs)if(r[o]===void 0)throw new nt(`missing required frontmatter key "${o}" \u2014 required: ${Rs.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 Rs,pw,nt,Iu=k(()=>{"use strict";Rs=["title","description","members"],pw=new Set(Rs),nt=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as hw,writeFileSync as S0,renameSync as b0,existsSync as ku}from"node:fs";import{basename as gw,resolve as Lr,dirname as Yo}from"node:path";function yw(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 Ew(t){return/^\s*_MEMBER_\s+\S/.test(t)}function Tw(t){return/^\s*_SESSION_\s+\S/.test(t)}function ww(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function Qo(t){let e=gw(t);return e.endsWith(".lmctl")?e.slice(0,-6):e}function ke(t){let e=hw(t,"utf-8"),r=Yo(Lr(t)),n=Zo(e,Qo(t),{baseDir:r,sourcePath:Lr(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Lr(r,s.sessiondir));return n}function Zo(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=bu(i)}catch(l){if(l instanceof nt)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
800
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(
|
|
801
|
-
allowed keys: ${xu.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 f={alias:u.alias,provider:u.provider||"",extra:{}};u.sessionid&&(f.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(f.sessiondir=u.sessiondir),u.teamfile&&(f.teamfile=u.teamfile),u.model&&(f.model=u.model),u.effort&&(f.effort=u.effort),n.push(f)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function
|
|
802
|
-
`)}){let n=pe(t,
|
|
803
|
-
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=
|
|
804
|
-
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Lu(n),isLead:Ct(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function st(t,e){let{target:r,alias:n,flags:s}=e;if(s.run!==void 0||s.project!==void 0||s.workflow!==void 0){if(r!==void 0)return{mode:"error",message:`lmctl ${t.name}: --run/--project/--workflow (managed mode) are mutually exclusive with a positional target "${r}" \u2014 pick one form.`};let o={mode:"managed"};return s.run!==void 0&&(o.run=s.run),s.project!==void 0&&(o.project=s.project),s.workflow!==void 0&&(o.workflow=s.workflow),o}if(r!==void 0){let o=
|
|
805
|
-
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(
|
|
800
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(Tw(c))throw new Error(`line ${d}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(ww(c)||!Ew(c))continue;let u=yw(c);for(let m of Object.keys(u))if(!xu.includes(m))throw new Error(`line ${d}: unknown key "${m}" on _MEMBER_ line: ${c.trim()}
|
|
801
|
+
allowed keys: ${xu.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 f={alias:u.alias,provider:u.provider||"",extra:{}};u.sessionid&&(f.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(f.sessiondir=u.sessiondir),u.teamfile&&(f.teamfile=u.teamfile),u.model&&(f.model=u.model),u.effort&&(f.effort=u.effort),n.push(f)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function ea(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()===zo.toLowerCase());n.length>1&&r.push({field:zo,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?Lr(e,i.teamfile):Lr(i.teamfile);if(!ku(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=ke(a),c=Ct(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 _w.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 Ct(t){return t.members.find(e=>e.alias.toLowerCase()===zo.toLowerCase())}function ta(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=Lr(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),!ku(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=ke(i),l=Ct(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return ta(l,Yo(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||Yo(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function Ns(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var zo,_w,xu,Et=k(()=>{"use strict";Iu();zo="Lead",_w=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"]);xu=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as vw}from"node:crypto";import{existsSync as Au,readFileSync as Ru,realpathSync as Sw}from"node:fs";import{dirname as bw,resolve as Nu}from"node:path";function pe(t,e){let r=Nu(t);if(Au(r))return Sw(r);if(e!==void 0){let n=xw(t,r,e);if(n!==null)return n}return r}function Cs(t,e){let r=bw(e),n=Zo(t,Qo(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Nu(r,s.sessiondir));return n}function We(t,e,r=n=>{process.stderr.write(`warning: ${n}
|
|
802
|
+
`)}){let n=pe(t,Iw(e)?e:void 0);if(Au(n)){let i=Ru(n,"utf8"),o=Cs(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&kw(o)&&Rw(e,n,o,i,r),o}let s=e?.getRootTeam(n)??null;throw s!==null?new Error(`teamfile missing on disk: ${n} (registered ${s.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${t}`)}function Iw(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function xw(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function kw(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=ra)}function na(t,e,r){let n=pe(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=ra);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=pe(i.teamfile_path),o===n)continue;a=Ru(o,"utf8")}catch(c){if(Aw(c))continue;throw c}let l=Cs(a,o);for(let c of s){let d=l.members.find(u=>u.teamfile===void 0&&u.session===c.session&&(u.session?.length??0)>=ra);if(d!==void 0)throw new Ls(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${d.alias} both use sessionid "${c.session}"`)}}}function Aw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Rw(t,e,r,n,s){try{na(t,e,r)}catch(o){if(!(o instanceof Ls))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:vw("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var ra,Ls,Tt=k(()=>{"use strict";Et();ra=5,Ls=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{existsSync as Nw}from"node:fs";import{dirname as Lu}from"node:path";function Dw(t){return Lw.test(t)||Cw.test(t)||Ow.test(t)}function Cu(t){return Os.test(t)}function Ds(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!r.endsWith(".lmctl")||!Os.test(n)?null:{teamfile:r,alias:n}}function ue(t,e,r){if(!t.endsWith(".lmctl"))throw new se(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl extension).`);if(!Cu(e))throw new se(`lmctl: "${e}" is not a valid alias (must match ${Os.source}).`);let n=pe(t,r);if(r===void 0&&!Nw(n))throw new se(`lmctl: teamfile not found: ${t}`);let s;try{s=We(n,r)}catch(o){throw new se(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new se(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=Ns(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new se(`lmctl: alias "${e}" not found in ${t}.
|
|
803
|
+
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=ta(i,Lu(n));return{teamfile:n,alias:i.alias,provider:o.provider,sessionid:o.session,sessiondir:o.sessiondir,isLead:!0,...o.model??i.model?{model:o.model??i.model}:{},...o.effort??i.effort?{effort:o.effort??i.effort}:{}}}if(i.session===void 0)throw new se(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
804
|
+
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Lu(n),isLead:Ct(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function st(t,e){let{target:r,alias:n,flags:s}=e;if(s.run!==void 0||s.project!==void 0||s.workflow!==void 0){if(r!==void 0)return{mode:"error",message:`lmctl ${t.name}: --run/--project/--workflow (managed mode) are mutually exclusive with a positional target "${r}" \u2014 pick one form.`};let o={mode:"managed"};return s.run!==void 0&&(o.run=s.run),s.project!==void 0&&(o.project=s.project),s.workflow!==void 0&&(o.workflow=s.workflow),o}if(r!==void 0){let o=Ds(r);if(o!==null)return n!==void 0&&n!==o.alias?{mode:"error",message:`lmctl ${t.name}: got "${r}" AND second positional "${n}" \u2014 pick one form.`}:{mode:"ai-team",teamfile:o.teamfile,alias:o.alias};if(r.endsWith(".lmctl"))return n!==void 0?Cu(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${Os.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
805
|
+
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(Dw(r)){if(n!==void 0)return{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.`};if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: "${r}" is a bare sessionid, but ${t.name} is teamfile-only (a sessionid carries no provider resume incantation).`};let a={mode:"ai-team-raw",sessionid:r};return s.provider!==void 0&&(a.provider=s.provider),a}return n!==void 0?{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.
|
|
806
806
|
Either drop the second arg, or pass <teamfile>.lmctl as the first arg.`}:{mode:"error",message:`lmctl ${t.name}: can't infer target type from "${r}".
|
|
807
807
|
Expected one of: <path>.lmctl, <path>.lmctl:<alias>, <sessionid>.`}}if(s.session!==void 0){if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: --session (raw mode) is not supported by ${t.name}.`};let o={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(o.provider=s.provider),o}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
808
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var se,
|
|
809
|
-
`,"utf8"),He.renameSync(r,t)}catch(n){try{He.unlinkSync(r)}catch{}throw n}}function
|
|
810
|
-
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Ou(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function
|
|
808
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var se,Lw,Cw,Ow,Os,Pe=k(()=>{"use strict";Et();Tt();se=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},Lw=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Cw=/^ses_[A-Za-z0-9_-]+$/,Ow=/^session_[A-Za-z0-9_-]+$/,Os=/^[A-Za-z][A-Za-z0-9_-]*$/});import{existsSync as Mw,mkdirSync as $w,readFileSync as Fw,renameSync as Pw,unlinkSync as Uw,writeFileSync as jw}from"node:fs";import{homedir as Du}from"node:os";import{dirname as _n,join as Ae,resolve as Bw}from"node:path";function Or(t,e,r){let n=_n(Bw(r)),s=new Set,i=new Map;for(let o of e.members){if(s.add(o.provider),o.teamfile!==void 0)continue;let a=o.sessiondir??n,l=i.get(a)??new Set;l.add(o.provider),i.set(a,l)}for(let[o,a]of i.entries())it(Ae(o,".mcp.json"),"mcpServers",[Ot(),Dt()]),a.has("opencode")&&it(Ae(o,".opencode","opencode.json"),"mcp",[Mu(),$u()]),a.has("kimi")&&it(Ae(o,".kimi-code","mcp.json"),"mcpServers",[Ot(),Dt()]);for(let o of s)Gw(o)}function Hw(t=sa??Du()){return Ae(t,".copilot","mcp-config.json")}function Xw(t,e){He.mkdirSync(_n(t),{recursive:!0});let r=Ae(_n(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{He.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
809
|
+
`,"utf8"),He.renameSync(r,t)}catch(n){try{He.unlinkSync(r)}catch{}throw n}}function qw(t,e){He.mkdirSync(_n(t),{recursive:!0});let r=Ae(_n(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{He.writeFileSync(r,e,"utf8"),He.renameSync(r,t)}catch(n){try{He.unlinkSync(r)}catch{}throw n}}function it(t,e,r){try{if(!He.existsSync(t))return;let n=JSON.parse(He.readFileSync(t,"utf8"));if(!Cr(n)||!Cr(n[e]))return;let s={...n[e]},i=[];for(let{name:o,shouldRemove:a}of r)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;n[e]=s,Xw(t,n),L({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Ot(){return{name:$s,shouldRemove:ev}}function Mu(){return{name:$s,shouldRemove:tv}}function Dt(){return{name:Ms,shouldRemove:Qw}}function $u(){return{name:Ms,shouldRemove:Zw}}function Gw(t){let e=sa??Du();switch(t){case"copilot":it(Hw(e),"mcpServers",[Ot(),Dt()]);return;case"claude":it(Ae(e,".claude.json"),"mcpServers",[Ot(),Dt()]);return;case"gemini":it(Ae(e,".gemini","settings.json"),"mcpServers",[Ot(),Dt()]);return;case"qwen":it(Ae(e,".qwen","settings.json"),"mcpServers",[Ot(),Dt()]);return;case"agy":it(Ae(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Ot(),Dt()]);return;case"opencode":it(Ae(e,".config","opencode","opencode.json"),"mcp",[Mu(),$u()]);return;case"kimi":it(Ae(sa===void 0?process.env.KIMI_CODE_HOME??Ae(e,".kimi-code"):Ae(e,".kimi-code"),"mcp.json"),"mcpServers",[Ot(),Dt()]);return;case"codex":Jw(Ae(e,".codex","config.toml"));return;default:return}}function Jw(t){try{if(!He.existsSync(t))return;let e=He.readFileSync(t,"utf8"),r=Vw(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=Fu(l);if(c===null)return;if(c!==void 0){if(Ou(c,r)){o=!0,a=c[1],i.add(a);continue}o=!1,a=void 0,s.push(l);continue}if(o){if(/^\s*(?:#.*)?$/.test(l)){s.push(l);continue}a!==void 0&&i.add(a);continue}let d=Yw(l);if(d===null)return;if(d!==void 0&&Ou(d,r)){i.add(d[1]);continue}s.push(l)}if(i.size===0)return;qw(t,s.join(`
|
|
810
|
+
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Ou(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function Vw(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Fu(s);if(i===null)return null;if(i!==void 0){r=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=Kw(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Ms&&c[1]!==$s)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=Pu(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=zw(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===Ms&&ju(i.command,i.args)&&n.add(s),s===$s&&Bu(i.command,i.args)&&n.add(s);return n}function Kw(t,e){if(t.startsWith("mcp_servers"))return Fs(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Fs(t);return r===null?null:[...e,...r]}function Fu(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Fs(e[1])}function Yw(t){let e=t.indexOf("=");if(e<0)return;let r=t.slice(0,e).trim();if(!(r.length===0||!r.startsWith("mcp_servers")))return Fs(r)}function Fs(t){let e=[],r=0,n=()=>{for(;r<t.length&&/\s/.test(t[r]);)r+=1};for(;r<t.length;){if(n(),r>=t.length)return null;if(t[r]==='"'){r+=1;let s="",i=!1;for(;r<t.length;){let o=t[r];if(o==="\\"){if(r+1>=t.length)return null;s+=t[r+1],r+=2;continue}if(o==='"'){r+=1,i=!0;break}s+=o,r+=1}if(!i)return null;e.push(s)}else{let s=r;for(;r<t.length&&/[A-Za-z0-9_-]/.test(t[r]);)r+=1;if(r===s)return null;e.push(t.slice(s,r))}if(n(),r>=t.length)break;if(t[r]!==".")return null;r+=1}return e.length>0?e:null}function Pu(t){let e=Uu(t).trim();if(e.startsWith('"'))try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function zw(t){let e=Uu(t).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).trim();if(r.length===0)return[];let n=r.split(",").map(s=>Pu(s.trim()));return n.some(s=>s===null)?null:n}function Uu(t){let e;for(let r=0;r<t.length;r+=1){let n=t[r];if(e!==void 0){if(e==='"'&&n==="\\"){r+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return t.slice(0,r)}return t}function Qw(t){return Cr(t)?t.type==="stdio"&&typeof t.command=="string"&&ju(t.command,t.args):!1}function Zw(t){return!Cr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Hu(t.command[0])&&t.command[1]==="mcp"||t.command.length===3&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&typeof t.command[2]=="string"&&Wu(t.command[0],[t.command[1],t.command[2]])}function ev(t){return Cr(t)?t.type==="stdio"&&Bu(t.command,t.args):!1}function tv(t){return!Cr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&Xu(t.command[0])&&t.command[1]==="mcp"}function ju(t,e){return Hu(t)&&qu(e)||Wu(t,e)}function Bu(t,e){return Xu(t)&&qu(e)}function Wu(t,e){return rv(t)&&Array.isArray(e)&&e.length===2&&nv(e[0])&&e[1]==="mcp"}function Hu(t){return typeof t=="string"&&ia(t)==="lmctl"}function Xu(t){return typeof t=="string"&&ia(t)==="lmctl0"}function rv(t){if(typeof t!="string")return!1;let e=ia(t).toLowerCase();return e==="node"||e==="node.exe"}function nv(t){if(typeof t!="string")return!1;let e=t.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function ia(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function qu(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Cr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Ms,$s,Ww,He,sa,Ps=k(()=>{"use strict";J();Ms="lmctl",$s="lmctl0",Ww={existsSync:Mw,mkdirSync:$w,readFileSync:Fw,writeFileSync:jw,renameSync:Pw,unlinkSync:Uw},He=Ww});function Vu(t){let e=Gu(t.registry,t.fromTeamfile);if(e===void 0)return Dr(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!Ju(e,t.fromAlias))return Dr(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Gu(t.registry,t.toTeamfile);return r===void 0?Dr(`target team is not registered in policy graph: ${t.toTeamfile}`):Ju(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Dr(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Dr(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Dr(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Gu(t,e){return t.teams.find(r=>r.teamfile===e)}function Ju(t,e){return t.aliases.some(r=>r===e)}function Dr(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var Ku=k(()=>{"use strict"});import{basename as sv}from"node:path";function Qu(t,e){let r=new Date(e.now.getTime()-ot()).toISOString(),n=tm(t,r).filter(m=>!m.sender.teamfile.startsWith("prompt:")),s=lv(e.sender,n),i=cv(e.sender,n);i!==null&&i.teamfile===e.root&&!zu(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(m=>zu(m,o)),c=l.map(m=>m.at).filter(m=>m!==null).sort((m,h)=>h-m)[0]??null,d=c!==null&&e.now.getTime()-c<iv,u=oa(e.sender,n).length;return{stop:l.length>=1&&d&&u>=ov,chain:dv(a)}}function Zu(t,e){let r=new Date(e.now.getTime()-ot()).toISOString(),n=tm(t,r),s=oa(e.sender,n);if(s.length===0)return null;let i=s[0];return i.sender.teamfile.startsWith("prompt:")?i.receiver.teamfile:i.sender.teamfile}function ot(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Yu;let r=Number(e);return!Number.isFinite(r)||r<=0?Yu:r}function em(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function av(t){return{sender:{teamfile:t.sender_teamfile,alias:t.sender_alias},receiver:{teamfile:t.receiver_teamfile,alias:t.receiver_alias},at:Date.parse(t.started_at)}}function tm(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(av).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function lv(t,e,r={}){let n=new Map;for(let a of e)n.set(ir(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([ir(t)]);for(let a=0;a<64;a+=1){let l=n.get(ir(i));if(l===void 0)break;s[0]={...s[0],at:s[0].at??l.at};let c={...l.sender,at:l.at};if(l.sender.teamfile.startsWith("prompt:")&&r.includePromptSender!==!0)break;let d=ir(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function oa(t,e){let r=ir(t),n=new Set([r]),s=[r],i=[];for(let o=0;s.length>0&&o<128;o+=1){let a=s.shift();for(let l of e){let c=ir(l.sender),d=ir(l.receiver);c!==a&&d!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(d)||(n.add(d),s.push(d)))}}return i.sort((o,a)=>o.at-a.at)}function cv(t,e){let r=oa(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function zu(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function ir(t){return`${t.teamfile}\0${t.alias}`}function dv(t){return t.map(e=>`${sv(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var iv,ov,Yu,yn=k(()=>{"use strict";iv=6e4,ov=2,Yu=8*60*60*1e3});function rm(t){return{getAgentInflight:t.prepare("SELECT * FROM agent_inflight WHERE receiver_teamfile = ? AND receiver_alias = ?"),listAgentInflight:t.prepare("SELECT * FROM agent_inflight ORDER BY started_at ASC, receiver_teamfile ASC, receiver_alias ASC"),acquireAgentInflight:t.prepare(`
|
|
811
811
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
812
812
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
813
813
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
@@ -1024,36 +1024,36 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
1024
1024
|
AND started_at = ?
|
|
1025
1025
|
AND last_heartbeat_at IS ?
|
|
1026
1026
|
`)}}function Xe(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(sm,"utf8"),n=Math.max(0,65536-r),s=Buffer.from(t,"utf8"),i=n;for(;i>0&&(s[i]&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}${sm}`}var sm,om=k(()=>{"use strict";sm=`
|
|
1027
|
-
...[truncated]`});function wn(t,e){return JSON.stringify([t,e])}function am(t){try{let e=JSON.parse(t);return typeof e.lock_id!="string"||typeof e.teamfile!="string"||typeof e.alias!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||!Array.isArray(e.holder_ips)||!e.holder_ips.every(r=>typeof r=="string")||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,teamfile:e.teamfile,alias:e.alias,holder_pid:e.holder_pid,holder_host:e.holder_host,holder_ips:e.holder_ips,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}var En,Tn,lm=k(()=>{"use strict";En="terminal_lock",Tn="member"});function Re(t){if(!Number.isInteger(t)||(t??0)<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}var or=k(()=>{"use strict"});import{hostname as
|
|
1027
|
+
...[truncated]`});function wn(t,e){return JSON.stringify([t,e])}function am(t){try{let e=JSON.parse(t);return typeof e.lock_id!="string"||typeof e.teamfile!="string"||typeof e.alias!="string"||typeof e.holder_pid!="number"||typeof e.holder_host!="string"||!Array.isArray(e.holder_ips)||!e.holder_ips.every(r=>typeof r=="string")||typeof e.started_at!="string"||typeof e.last_heartbeat!="string"?null:{lock_id:e.lock_id,teamfile:e.teamfile,alias:e.alias,holder_pid:e.holder_pid,holder_host:e.holder_host,holder_ips:e.holder_ips,started_at:e.started_at,last_heartbeat:e.last_heartbeat}}catch{return null}}var En,Tn,lm=k(()=>{"use strict";En="terminal_lock",Tn="member"});function Re(t){if(!Number.isInteger(t)||(t??0)<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}var or=k(()=>{"use strict"});import{hostname as Mr}from"node:os";function $r(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??uv);return r.unref?.(),r}function Mt(t,e){let r=new Date().toISOString(),n=new Date(Date.now()-e.ttlMs).toISOString(),s={receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,started_at:r},i=t.getAgentInflight(e.receiver_teamfile,e.receiver_alias),o=i===null||i.holder_pid===null,a=t.tryAcquireAgentInflight(s,{...o?{stale_before:n}:{},force:e.force,reclaim_reason:e.reclaimReason});if(a.acquired){let c=i===null?null:e.force===!0?e.reclaimReason??"force":i.holder_pid===null&&i.started_at<n?"stale":null;return{acquired:!0,lease:a.current??s,leaseId:a.lease_id,previous:i,reclaimReason:c}}if(!Us(a.current,n))return{acquired:!1,current:a.current};let l=t.tryAcquireAgentInflight(s,a.current.holder_pid===null?{stale_before:n}:{reclaim_observed:{sender_teamfile:a.current.sender_teamfile,sender_alias:a.current.sender_alias,started_at:a.current.started_at,holder_pid:a.current.holder_pid},reclaim_reason:"dead-pid"});return l.acquired?{acquired:!0,lease:l.current??s,leaseId:l.lease_id,previous:a.current,reclaimReason:a.current.holder_pid===null?"stale":"dead-pid"}:{acquired:!1,current:l.current}}function $t(t){return t.status!=="running"?null:t.holder_host===Mr()&&t.holder_pid!==null&&t.holder_pid>0?Re(t.holder_pid)?"live":"dead":"unknown"}function at(t,e,r){let n,s=t.getTerminalLock(e,r);if(s!==null){if(mv(s))return{busy:!0,reason:"terminal-held",source:"terminal-lock",terminalLock:s};n??={source:"terminal-lock",holder_pid:s.holder_pid,holder_host:s.holder_host,reason:s.holder_host===Mr()?"dead-pid":"stale"}}let i=fv(t,e,r);if(i!==null){if(pv(i))return{busy:!0,reason:"terminal-held",source:"terminal-invocation",terminalInvocation:i};n??={source:"terminal-invocation",holder_pid:i.holder_pid,holder_host:i.holder_host,reason:i.holder_pid!==null&&(i.holder_host===null||i.holder_host===Mr())?"dead-pid":"stale"}}let o=t.getAgentInflight(e,r);if(o!==null){let a=new Date(Date.now()-Fr()).toISOString();if(!Us(o,a))return{busy:!0,reason:"in-flight",inFlight:o};n??={source:"in-flight",holder_pid:o.holder_pid,holder_host:o.holder_pid===null?null:Mr(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function mv(t){if(t.holder_host===Mr())return Re(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=gv():!1}function fv(t,e,r){return t.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1028
1028
|
FROM tracked_invocation
|
|
1029
1029
|
WHERE target_teamfile = ?
|
|
1030
1030
|
AND target_alias = ?
|
|
1031
1031
|
AND status = 'running'
|
|
1032
1032
|
AND launch_source = 'terminal'
|
|
1033
1033
|
ORDER BY started_at DESC, id DESC
|
|
1034
|
-
LIMIT 1`,e,r)[0]??null}function
|
|
1034
|
+
LIMIT 1`,e,r)[0]??null}function pv(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===Mr())?Re(t.holder_pid):hv(t)}function hv(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=Fr():!1}function Us(t,e){return t.holder_pid===null?t.started_at<e:!Re(t.holder_pid)}function Fr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return cm;let r=Number(e);return!Number.isFinite(r)||r<=0?cm:r}function gv(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return dm;let r=Number(e);return!Number.isFinite(r)||r<=0?dm:r}var cm,dm,uv,ze=k(()=>{"use strict";or();cm=8*60*60*1e3,dm=12e4,uv=3e4});import{randomUUID as _v}from"node:crypto";import{hostname as yv}from"node:os";function Ft(t,e){return{teamfile:t,alias:e}}function um(t,e,r={}){return{teamfile:t,alias:e,...r.provider===void 0||r.provider===null?{}:{provider:r.provider},...r.sessionId===void 0||r.sessionId===null?{}:{session_id:r.sessionId}}}function aa(t,e){return t===null?null:Ft(t,e??"")}function wt(t){return`msg_tcl_${t}`}function ar(t){return`inv_${t}`}function Pr(t,e,r){return t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1035
1035
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1036
1036
|
terminal_invocation_id, currently_handling_message_id,
|
|
1037
1037
|
currently_handling_since, last_seq
|
|
1038
1038
|
FROM agent_state
|
|
1039
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function
|
|
1039
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function Tv(t,e,r){if(e===null||r===null)return null;let n=t.prepare(`SELECT currently_handling_message_id, currently_handling_since
|
|
1040
1040
|
FROM agent_state
|
|
1041
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r);if(n?.currently_handling_message_id===null||n?.currently_handling_message_id===void 0||n.currently_handling_since===null)return null;let s=Date.parse(n.currently_handling_since);return!Number.isFinite(s)||Date.now()-s>
|
|
1041
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r);if(n?.currently_handling_message_id===null||n?.currently_handling_message_id===void 0||n.currently_handling_since===null)return null;let s=Date.parse(n.currently_handling_since);return!Number.isFinite(s)||Date.now()-s>Ev?null:n.currently_handling_message_id}function wv(t,e,r){let n=Tv(t,e,r);return n===null?{}:{causation:{request_message_id:n}}}function la(t,e,r,n,s=new Date().toISOString()){t.prepare(`INSERT INTO agent_state
|
|
1042
1042
|
(receiver_teamfile, receiver_alias, currently_handling_message_id,
|
|
1043
1043
|
currently_handling_since, last_seq)
|
|
1044
1044
|
VALUES (?, ?, ?, ?, 0)
|
|
1045
1045
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
1046
1046
|
currently_handling_message_id = excluded.currently_handling_message_id,
|
|
1047
|
-
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function
|
|
1047
|
+
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function ca(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1048
1048
|
SET currently_handling_message_id = NULL,
|
|
1049
1049
|
currently_handling_since = NULL
|
|
1050
1050
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1051
|
-
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function
|
|
1051
|
+
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function vv(t,e){let r=e??new Date(Date.now()-Fr()).toISOString();return Us({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function Sv(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!Re(t.holder_pid)?"dead-pid":"stale"}function bv(t){return{sender:aa(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function Ur(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function da(t,e,r){let n=wt(e),s=aa(r.sender_teamfile,r.sender_alias),i=um(r.receiver_teamfile,r.receiver_alias,{provider:r.receiver_provider,sessionId:r.receiver_session_id}),o={message_id:n,message_type:"request",sender:s,receiver:i,root_teamfile:r.root_teamfile,legacy:{table:"team_chat_log",id:e}};return Oe(t,{stream_id:n,event_type:"CREATE",observedLastSeq:0,ts:r.created_at,payload:{...o,content:r.message,provider_prompt:r.provider_prompt??r.message,origin:r.origin,...wv(t,r.sender_teamfile,r.sender_alias)}},()=>{la(t,r.receiver_teamfile,r.receiver_alias,n,r.created_at)}),n}function js(t,e,r){let n=wt(e),s={message_id:n,message_type:"request",sender:aa(r.sender_teamfile,r.sender_alias),receiver:um(r.receiver_teamfile,r.receiver_alias,{provider:r.receiver_provider,sessionId:r.receiver_session_id}),root_teamfile:r.root_teamfile,legacy:{table:"team_chat_log",id:e}};return Oe(t,{stream_id:n,event_type:"HANDLED",observedLastSeq:1,ts:r.created_at,payload:{...s,outcome:r.status,receipt:r.response,error:r.error_detail,truncated:r.truncated===1}},()=>{ca(t,r.receiver_teamfile,r.receiver_alias,n)}),n}function Iv(t){return{sender:Ft(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at}}function mm(t,e,r,n){let s=t.prepare(`UPDATE agent_state
|
|
1052
1052
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1053
1053
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1054
1054
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1055
1055
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1056
|
-
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);
|
|
1056
|
+
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Ur(s.changes,n)}function fm(t,e,r,n,s=null,i=!1){let o=yv();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=Pr(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||vv(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let u=Sv(a,n,i),f=bv(a),m=a.lease_id;Oe(t,{stream_id:m,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:Ft(e.receiver_teamfile,e.receiver_alias),reason:u,previous_holder:f}},h=>mm(t,a,h,"INFLIGHT_RECLAIM")),a=Pr(t,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${_v()}`;return Oe(t,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:Ft(e.receiver_teamfile,e.receiver_alias),sender:Ft(e.sender_teamfile,e.sender_alias),holder_pid:e.holder_pid,holder_host:o,started_at:e.started_at}},d=>{if(a===null){t.prepare(`INSERT INTO agent_state
|
|
1057
1057
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1058
1058
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1059
1059
|
last_heartbeat_at, last_seq)
|
|
@@ -1062,18 +1062,18 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
1062
1062
|
holder_pid = ?, holder_host = ?, started_at = ?,
|
|
1063
1063
|
last_heartbeat_at = ?, last_seq = ?
|
|
1064
1064
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1065
|
-
AND lease_id IS NULL AND last_seq = ?`).run(c,e.sender_teamfile,e.sender_alias,e.holder_pid,o,e.started_at,e.started_at,d,e.receiver_teamfile,e.receiver_alias,a.last_seq);
|
|
1065
|
+
AND lease_id IS NULL AND last_seq = ?`).run(c,e.sender_teamfile,e.sender_alias,e.holder_pid,o,e.started_at,e.started_at,d,e.receiver_teamfile,e.receiver_alias,a.last_seq);Ur(u.changes,"INFLIGHT_TAKE")}),c}function pm(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1066
1066
|
SET last_heartbeat_at = ?
|
|
1067
1067
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1068
1068
|
AND lease_id = ?
|
|
1069
1069
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1070
|
-
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,r,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function vn(t,e,r,n){let s=
|
|
1070
|
+
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,r,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function vn(t,e,r,n){let s=Pr(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||Oe(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:Ft(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:Iv(e)}:{lease_id:s.lease_id}}},i=>mm(t,s,i,r))}function hm(t,e){let r=Pr(t,e.teamfile,e.alias),n=r?.last_seq??0;Oe(t,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:Ft(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at}},s=>{if(r===null){t.prepare(`INSERT INTO agent_state
|
|
1071
1071
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1072
1072
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1073
1073
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1074
|
-
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);
|
|
1074
|
+
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);Ur(i.changes,"TERMINAL_LOCK_TAKE")})}function ua(t,e,r=!1){let n=Pr(t,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||Oe(t,{stream_id:e.lock_id,event_type:r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:Ft(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host}},s=>{let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = NULL, last_seq = ?
|
|
1075
1075
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1076
|
-
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);
|
|
1076
|
+
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);Ur(i.changes,r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function gm(t,e,r){let n=Pr(t,r.targetTeamfile,r.targetAlias);if(n===null){t.prepare(`INSERT INTO agent_state
|
|
1077
1077
|
(receiver_teamfile, receiver_alias, terminal_invocation_id,
|
|
1078
1078
|
terminal_invocation_pid, terminal_invocation_host,
|
|
1079
1079
|
terminal_invocation_heartbeat_at, last_seq)
|
|
@@ -1082,7 +1082,7 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
1082
1082
|
terminal_invocation_host = ?,
|
|
1083
1083
|
terminal_invocation_heartbeat_at = ?, last_seq = ?
|
|
1084
1084
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1085
|
-
AND terminal_invocation_id IS NULL AND last_seq = ?`).run(r.invocationId,r.holderPid,r.holderHost,r.heartbeatAt,e,r.targetTeamfile,r.targetAlias,n.last_seq);
|
|
1085
|
+
AND terminal_invocation_id IS NULL AND last_seq = ?`).run(r.invocationId,r.holderPid,r.holderHost,r.heartbeatAt,e,r.targetTeamfile,r.targetAlias,n.last_seq);Ur(s.changes,"terminal INVOCATION_START")}function _m(t,e,r){return t.prepare(`UPDATE agent_state
|
|
1086
1086
|
SET terminal_invocation_heartbeat_at = ?
|
|
1087
1087
|
WHERE terminal_invocation_id = ?`).run(r,e).changes===1}function ym(t,e,r){let n=t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, terminal_lock_id,
|
|
1088
1088
|
terminal_invocation_id, last_seq
|
|
@@ -1091,15 +1091,15 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
1091
1091
|
terminal_invocation_host = NULL,
|
|
1092
1092
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1093
1093
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1094
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);
|
|
1094
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);Ur(s.changes,"terminal INVOCATION_FINISH")}var Ev,Bs=k(()=>{"use strict";Is();ze();or();Ev=60*60*1e3});function Em(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function ma(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function Tm(t,e){let r=ar(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;Oe(t,{stream_id:r,event_type:xv,observedLastSeq:0,ts:e.started_at,payload:{invocation_id:r,kind:e.kind,origin:e.origin,launch_source:e.launch_source,from_identity:e.from_identity,target:n,root_teamfile:e.root_teamfile,scope_teamfile:e.scope_teamfile,cwd:e.cwd,command:e.command,request_payload:e.request_payload,request_message_id:e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,legacy:{table:"tracked_invocation",id:e.id}}},i=>{t.prepare(`INSERT INTO invocation_state
|
|
1095
1095
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1096
1096
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1097
1097
|
status, started_at, last_heartbeat_at, last_seq)
|
|
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),
|
|
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),ma(e)&&gm(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function Ws(t,e){let r=ar(e.id),n=Em(t,r);return n===null?!1:(Oe(t,{stream_id:r,event_type:kv,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}`);
|
|
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}`);ma(e)&&ym(t,s,r)}),!0)}function wm(t,e,r,n){let s=ar(e.id),i=Em(t,s);return i===null?!1:(Oe(t,{stream_id:s,event_type:Av,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 vm(t,e,r){let n=ar(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),ma(e)&&_m(t,n,r)}function Sm(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,ar(e))}function bm(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,ar(e))}var xv,kv,Av,Im=k(()=>{"use strict";Is();Bs();xv="INVOCATION_START",kv="INVOCATION_FINISH",Av="INVOCATION_NOTIFY_CLAIM"});var Rv,Nv,lD,xm,km,Am,Rm=k(()=>{"use strict";Rv="other",Nv=["not_enough_information","dont_know","other_work"],lD=new Set([Rv,...Nv]),xm="@abort",km="invalid_decision",Am="workflow_escalation"});import{randomUUID as Nm}from"node:crypto";import{existsSync as Mm,mkdirSync as Lv,renameSync as Cv,rmdirSync as Ov}from"node:fs";import{hostname as fa}from"node:os";function pa(t){return t.provider_resolved??t.provider}function D(){return new Date().toISOString()}function Dv(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!Mm(t))return e;let r;try{r=new bs(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 Mv(t){if(t===":memory:"||!Mm(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{Cv(n,`${e}${r}`)}catch{}}return e}function Lm(t,e){let r=e instanceof Error?e.message:String(e);try{let n=Dv(t),s=Mv(t),i=new Hs(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
|
-
`)),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 Cm(t,e){let r;try{return r=gn({dbPath:t,allowSchemaSkew:e}),{dal:new
|
|
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 Cm(t,e){let r;try{return r=gn({dbPath:t,allowSchemaSkew:e}),{dal:new Hs(r)}}catch(n){if(n instanceof Lt)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 Uv(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function jv(t){if(t===":memory:")return!0;try{return Lv(`${t}${$m}`),!0}catch{return!1}}function Bv(t){if(t!==":memory:")try{Ov(`${t}${$m}`)}catch{}}function Qe(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<$v;n+=1)if(r=Cm(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<Fv;n+=1){if(jv(t.path))try{return Lm(t.path,r.cause)}finally{Bv(t.path)}Uv(Pv);let s=Cm(t.path,e);if(s.dal!==void 0)return s.dal}return Lm(t.path,r.cause)}function Om(t,e,r){let n=Dm(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 Dm(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 Dm(t){let e=Wv(t),r=e===null?null:Hv(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))Xs(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function Wv(t){try{let e=JSON.parse(t);return Xs(e)?e:null}catch{return null}}function Hv(t,e){let r=t[e];return Xs(r)?r:null}function Xs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Xv(t){try{let e=JSON.parse(t);return!Xs(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 qv(t,e){return t===null?!0:t.holder_host===fa()?!Re(t.holder_pid):t.last_heartbeat<e}function Gv(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)
|
|
1104
1104
|
VALUES (?, ?, ?, ?, ?)
|
|
1105
1105
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1506,65 +1506,65 @@ var qE=Object.create;var No=Object.defineProperty;var GE=Object.getOwnPropertyDe
|
|
|
1506
1506
|
response = NULL
|
|
1507
1507
|
WHERE id = ?
|
|
1508
1508
|
AND status = 'running'
|
|
1509
|
-
`),...im(t),...rm(t)}}function Xv(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Ov,$m,Dv,Mv,Bs,Pt=k(()=>{"use strict";Xo();xs();nm();om();lm();or();Us();Im();Rm();Ov=3,$m=".recovery.lock",Dv=20,Mv=50;Bs=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=Hv(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let g=this.getJob(a.id);return{claimed:!1,reason:g?.locked_until!==null&&g?.locked_until!==void 0&&g.locked_until>=i?"locked":"not_claimable",job_id:r,status:g?.status??a.status,locked_by:g?.locked_by??a.locked_by,locked_until:g?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>Xv("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Am)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==xm&&!a.includes(n))return{resumed:!1,reason:km};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=fm(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(r.receiver_teamfile,r.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...r){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...r)}insertWorkflow(e){Om(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,D()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,D());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Om(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,D());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,D())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,D());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,D()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,r){return this.stmts.setTriggerCursor.run(r,D(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(D(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,D());return this.stmts.getTeam.get(r.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,D());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,D(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,D());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",D());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,D());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=D(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,D(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,D(),e)??null}closeIssue(e,r,n){let s=D(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,D(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,D(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=D();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Nm(),s=D();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=D(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,D())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??D(),e.dedupe_key??null,e.concurrency_key??null,D());if(r.changes===1)return this.stmts.getJob.get(r.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:D();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,D()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,r){return this.stmts.setJobRun.run(r,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,D()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??D(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,D());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=D(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,D(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(D(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return ca(this.db,n,e),Ps(this.db,n,e),n})()}beginTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return ca(this.db,n,e),n})()}finishTeamChatLog(e,r){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);Ps(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{aa(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>la(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??D(),n=e.holder_host??ma(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Xe(e.command),r,e.holder_pid??null,n,s,Xe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Tm(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,r,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,r];n.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(n.sinceMs).toISOString())),n.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(n.untilMs).toISOString()));let o=Math.max(1,Math.trunc(n.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}listFinishedTrackedInvocationChildren(e,r){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1509
|
+
`),...im(t),...rm(t)}}function Jv(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var $v,$m,Fv,Pv,Hs,Pt=k(()=>{"use strict";qo();As();nm();om();lm();or();Bs();Im();Rm();$v=3,$m=".recovery.lock",Fv=20,Pv=50;Hs=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=Gv(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let h=this.getJob(a.id);return{claimed:!1,reason:h?.locked_until!==null&&h?.locked_until!==void 0&&h.locked_until>=i?"locked":"not_claimable",job_id:r,status:h?.status??a.status,locked_by:h?.locked_by??a.locked_by,locked_until:h?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>Jv("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==Am)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==xm&&!a.includes(n))return{resumed:!1,reason:km};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=fm(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(r.receiver_teamfile,r.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...r){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...r)}insertWorkflow(e){Om(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,D()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,D());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Om(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,D());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,D())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,D());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,D()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,r){return this.stmts.setTriggerCursor.run(r,D(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(D(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,D());return this.stmts.getTeam.get(r.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,D());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,D(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,D());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",D());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,D());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=D(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,D(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,D(),e)??null}closeIssue(e,r,n){let s=D(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,D(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,D(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=D();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,D(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Nm(),s=D();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=D(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,D())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??D(),e.dedupe_key??null,e.concurrency_key??null,D());if(r.changes===1)return this.stmts.getJob.get(r.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=D(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:D();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,D()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,r){return this.stmts.setJobRun.run(r,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,D()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??D(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,D());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=D(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,D(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(D(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return da(this.db,n,e),js(this.db,n,e),n})()}beginTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return da(this.db,n,e),n})()}finishTeamChatLog(e,r){this.db.transaction(()=>{if(this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e).changes!==1)throw new Error(`team_chat_log row disappeared during finish: ${e}`);js(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{la(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>ca(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??D(),n=e.holder_host??fa(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Xe(e.command),r,e.holder_pid??null,n,s,Xe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Tm(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,r,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,r];n.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(n.sinceMs).toISOString())),n.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(n.untilMs).toISOString()));let o=Math.max(1,Math.trunc(n.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}listFinishedTrackedInvocationChildren(e,r){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1510
1510
|
SELECT * FROM tracked_invocation
|
|
1511
1511
|
WHERE parent_invocation_id IN (${n})
|
|
1512
1512
|
AND ended_at IS NOT NULL
|
|
1513
1513
|
AND ended_at >= ?
|
|
1514
1514
|
ORDER BY started_at ASC, id ASC
|
|
1515
|
-
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??D();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Xe(r.result_summary),Xe(r.error),r.team_chat_log_id??null,Xe(r.meta),Xe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return
|
|
1516
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&vn(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(vn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(En,wn(e,r),Tn);return n===void 0?null:am(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&da(this.db,n,!0),this.stmts.upsertRuntimeState.run(En,wn(e.teamfile,e.alias),Tn,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&hm(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(En,wn(e,r),Tn,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(En,wn(e,r),Tn);return i.changes===1&&da(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:Bv(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=D()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!Wv(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Nm(),holder_pid:process.pid,holder_host:ma(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,D(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,D())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,D());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,D(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??D(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,D());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,D()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,D()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,D());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(D(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=D();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??D());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,D())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,D())}}});var ct=YE(De=>{"use strict";function Hs(t){if(!Array.isArray(t))throw new TypeError("Each row and headers must be an array of cells");return Array.from(t,e=>{let r=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("Cells must be single-line text without terminal control characters");return r})}function qv(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function Ut(t){let e=0;for(let r of t){let n=r.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){e+=2;continue}e+=1}}return e}function Fm(t,e,r){let n=" ".repeat(Math.max(0,e-Ut(t)));return r?n+t:t+n}function Gv(t){if(Array.isArray(t))return{rows:t};if(t!==null&&typeof t=="object"&&Array.isArray(t.rows))return t;throw new TypeError("each grid must be a rows array or { rows, headers }")}function Jv(t){if(t===void 0)return"\u2026";if(typeof t!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return t}function Vv(t,e,r="\u2026"){if(Ut(t)<=e)return t;let n=Ut(r)>e?"\u2026":r,s=Ut(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=Ut(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function Kv(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError("max must be an array of per-column width caps");return t.map(e=>{if(e!=null){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("max entries must be positive integers, null, or undefined");return e}})}function Um(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=Kv(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=Gv(i);o.headers!==void 0&&Hs(o.headers).forEach((a,l)=>{s(l,Ut(a))});for(let a of o.rows.map(Hs))a.forEach((l,c)=>{s(c,Ut(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}De.measureColumns=Um;function Yv(t){if(t===void 0)return"";if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return" ".repeat(t);if(typeof t=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(t))return t;throw new TypeError("margin must be a number of spaces or a single-line string")}function jm(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=Yv(o),d=qv(n),u=Jv(l),f=e??Um([{rows:t,headers:r}],{max:a}),m=t.map(Hs);r!==void 0&&m.unshift(Hs(r));let g=m.map(h=>{let _=h.length-1;for(;_>=0&&h[_]==="";)_--;return h.slice(0,_+1).map((p,y)=>{let T=f[y]||0,v=s&&T>0&&(y!==_||i)?Vv(p,T,u):p;return d[y]==="right"?Fm(v,T,!0):y===_?v:Fm(v,T,!1)}).join(" ")}).join(`
|
|
1517
|
-
`);return
|
|
1515
|
+
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??D();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Xe(r.result_summary),Xe(r.error),r.team_chat_log_id??null,Xe(r.meta),Xe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Ws(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??D();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Xe(n.result_summary),Xe(n.error),n.team_chat_log_id??null,Xe(n.meta),Xe(n.config_warnings),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Ws(this.db,o),o})()}heartbeatTrackedInvocation(e,r=D()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return vm(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(Sm(this.db,e,r),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,e).changes!==1?null:(bm(this.db,e,wt(r)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,r,n){return this.db.transaction(()=>{let s=D();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Xe(n),e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1)return null;let o=this.getTrackedInvocation(e);return Ws(this.db,o),o.team_chat_log_id!==null&&this.terminalizeLinkedChatMessage(o.team_chat_log_id,n),o})()}terminalizeLinkedChatMessage(e,r){let n=this.stmts.getTeamChatLogById.get(e);n===void 0||n.status!=="running"||this.stmts.terminalizeTeamChatLogIfRunning.run("error",r,e).changes!==1||js(this.db,e,{root_teamfile:n.root_teamfile,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,message:n.message,response:null,origin:n.origin,status:"error",error_detail:r,truncated:n.truncated,created_at:D()})}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${r.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,r,n=D()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return wm(this.db,i,r,n),i})()}listTrackedInvocations(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(r.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(r.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e)}getAgentInflight(e,r){return this.stmts.getAgentInflight.get(e,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,r){return this.tryAcquireAgentInflightTxn(e,r)}heartbeatAgentInflight(e,r,n=D()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:pm(this.db,s,r,n)})()}clearAgentInflight(e,r){this.db.transaction(()=>{let s=this.getAgentInflight(e,r);if(s===null)return;this.stmts.clearAgentInflight.run(e,r).changes===1&&vn(this.db,s,"INFLIGHT_RECLAIM","stale")})()}clearObservedTerminalAgentInflight(e,r,n){return this.db.transaction(()=>{let i=this.getAgentInflight(e,r),o=this.stmts.clearObservedTerminalAgentInflight.run({receiver_teamfile:e,receiver_alias:r,observed_sender_teamfile:n.sender_teamfile,observed_sender_alias:n.sender_alias,observed_started_at:n.started_at,observed_holder_pid:n.holder_pid});return o.changes===1&&i!==null&&vn(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,r){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(n===null||n.sender_teamfile!==e.sender_teamfile||n.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1516
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&vn(this.db,n,"INFLIGHT_RELEASE"),this.db.exec("COMMIT"),i.changes===1}let s=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),s.changes===1}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}clearAgentInflightOlderThan(e){return this.db.transaction(()=>{let n=this.listAgentInflight().filter(i=>i.started_at<e),s=0;for(let i of n)this.stmts.clearAgentInflight.run(i.receiver_teamfile,i.receiver_alias).changes===1&&(vn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(En,wn(e,r),Tn);return n===void 0?null:am(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&ua(this.db,n,!0),this.stmts.upsertRuntimeState.run(En,wn(e.teamfile,e.alias),Tn,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&hm(this.db,e)})()}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(En,wn(e,r),Tn,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(En,wn(e,r),Tn);return i.changes===1&&ua(this.db,s),this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:Xv(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=D()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!qv(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Nm(),holder_pid:process.pid,holder_host:fa(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,D(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,D())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,D());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,D(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??D(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,D());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,D()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,D()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,D());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(D(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=D();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??D());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,D())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,D())}}});var ct=ZE(De=>{"use strict";function qs(t){if(!Array.isArray(t))throw new TypeError("Each row and headers must be an array of cells");return Array.from(t,e=>{let r=e==null?"":String(e);if(/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("Cells must be single-line text without terminal control characters");return r})}function Vv(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function Ut(t){let e=0;for(let r of t){let n=r.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){e+=2;continue}e+=1}}return e}function Fm(t,e,r){let n=" ".repeat(Math.max(0,e-Ut(t)));return r?n+t:t+n}function Kv(t){if(Array.isArray(t))return{rows:t};if(t!==null&&typeof t=="object"&&Array.isArray(t.rows))return t;throw new TypeError("each grid must be a rows array or { rows, headers }")}function Yv(t){if(t===void 0)return"\u2026";if(typeof t!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(t))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return t}function zv(t,e,r="\u2026"){if(Ut(t)<=e)return t;let n=Ut(r)>e?"\u2026":r,s=Ut(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=Ut(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function Qv(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError("max must be an array of per-column width caps");return t.map(e=>{if(e!=null){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("max entries must be positive integers, null, or undefined");return e}})}function Um(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=Qv(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=Kv(i);o.headers!==void 0&&qs(o.headers).forEach((a,l)=>{s(l,Ut(a))});for(let a of o.rows.map(qs))a.forEach((l,c)=>{s(c,Ut(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}De.measureColumns=Um;function Zv(t){if(t===void 0)return"";if(typeof t=="number"&&Number.isInteger(t)&&t>=0)return" ".repeat(t);if(typeof t=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(t))return t;throw new TypeError("margin must be a number of spaces or a single-line string")}function jm(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=Zv(o),d=Vv(n),u=Yv(l),f=e??Um([{rows:t,headers:r}],{max:a}),m=t.map(qs);r!==void 0&&m.unshift(qs(r));let h=m.map(_=>{let g=_.length-1;for(;g>=0&&_[g]==="";)g--;return _.slice(0,g+1).map((p,y)=>{let E=f[y]||0,v=s&&E>0&&(y!==g||i)?zv(p,E,u):p;return d[y]==="right"?Fm(v,E,!0):y===g?v:Fm(v,E,!1)}).join(" ")}).join(`
|
|
1517
|
+
`);return h===""||c===""?h:`${c}${h.split(`
|
|
1518
1518
|
`).join(`
|
|
1519
|
-
${c}`)}`}De.renderGrid=jm;function Bm(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return jm(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function
|
|
1520
|
-
`)}De.formatTable=Bm;De.printTable=
|
|
1521
|
-
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}De.escapeCell=
|
|
1519
|
+
${c}`)}`}De.renderGrid=jm;function Bm(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return jm(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function eS(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,stream:l=process.stdout}={}){let c=Bm(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a});c&&l.write(`${c}
|
|
1520
|
+
`)}De.formatTable=Bm;De.printTable=eS;function Pm(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function tS(t,{now:e=Date.now()}={}){let r=Pm(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=Pm(t);if(!Number.isFinite(n))return"unknown";let s=n-r,i=Math.floor(Math.abs(s)/1e3);if(i===0)return"now";for(let[o,a]of[["w",604800],["d",86400],["h",3600],["m",60],["s",1]])if(i>=a)return`${Math.floor(i/a)}${o}${s<0?" ago":""}`}De.formatRelativeTime=tS;function rS(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=t<0?"-":"",r=Math.abs(t);if(r<1e3)return String(t);let n=Math.round(r/1e3);return n<1e3?`${e}${n}K`:`${e}${(r/1e6).toFixed(1)}M`}De.formatCount=rS;var ha=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function nS(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=ha.findIndex(([a])=>a===e);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(r!=="spaced"&&r!=="compact")throw new TypeError('style must be "spaced" or "compact"');let s=Math.floor(Math.max(0,t)/1e3);if(r==="compact"){let a=ha.slice(n).filter(([u])=>u!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,d=!1;for(let[u,f]of a){let m=Math.floor(c/f);if(c-=m*f,m>0&&!d){let h=u==="d"||u==="w"?`${m}${u}`:`${lt(m)}${u}`;l.push({text:h,zero:!1}),d=!0}else d&&l.push({text:`${lt(m)}${u}`,zero:m===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(u=>u.text).join("")}let i=s,o=[];for(let[a,l]of ha.slice(n))if(i>=l||a==="s"&&o.length===0){let c=Math.floor(i/l);if(i-=c*l,o.push(`${c}${a}`),o.length===2)break}return o.join(" ")}De.formatDuration=nS;function Wm(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function lt(t){return String(t).padStart(2,"0")}function Hm(t){let e=Wm(t);return Number.isNaN(e.getTime())?"unknown":`${lt(e.getHours())}:${lt(e.getMinutes())}:${lt(e.getSeconds())}`}De.formatClock=Hm;function sS(t){let e=Wm(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${lt(e.getMonth()+1)}-${lt(e.getDate())}`} ${Hm(e)}`}De.formatLocalTimestamp=sS;function iS(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}De.formatPercent=iS;function oS(t,{width:e=10,fill:r="#",empty:n=" ",unknown:s="?"}={}){if(typeof e!="number"||!Number.isInteger(e)||e<1)throw new TypeError("width must be a positive integer");for(let[o,a]of[["fill",r],["empty",n],["unknown",s]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||Ut(a)!==1)throw new TypeError(`${o} must be a single character with terminal display width 1`);if(typeof t!="number"||!Number.isFinite(t))return s.repeat(e);let i=Math.min(e,Math.max(0,Math.round(t*e)));return`${r.repeat(i)}${n.repeat(e-i)}`}De.formatBar=oS;function aS(t){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let e=Math.floor(Math.max(0,t)/1e3),r=Math.floor(e/86400);e-=r*86400;let n=Math.floor(e/3600);e-=n*3600;let s=Math.floor(e/60);e-=s*60;let i=`${lt(n)}:${lt(s)}:${lt(e)}`;return r>0?`${r}d ${i}`:i}De.formatTimer=aS;function lS(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
1521
|
+
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}De.escapeCell=lS});async function C(t,e){if(t.dal!==void 0)return e(t.dal);let r=Qe({path:fe()});try{return await e(r)}finally{r.close()}}function ie(t,e,r=["--json"]){let n=new Set(e),s=new Set(r),i=[],o={};for(let a=0;a<t.length;a+=1){let l=t[a];if(!l.startsWith("--")){i.push(l);continue}if(s.has(l)){o[l]=!0;continue}if(!n.has(l))return{positionals:i,flags:o,error:`unknown flag: ${l}`};let c=t[a+1];if(c===void 0||c.startsWith("--"))return{positionals:i,flags:o,error:`missing value for ${l}`};o[l]=c,a+=1}return{positionals:i,flags:o}}function B(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function H(t,e){return t.flags[e]===!0}function te(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1522
1522
|
`)}function A(t,e){return t.stderr.write(`error: ${e}
|
|
1523
1523
|
`),1}function Me(){return(0,qm.formatClock)()}function Ze(t,e,r=5e3){let n=Date.now(),s=n,i=setInterval(()=>{let o=Date.now();o-s<r||t.stderr.write(e(Math.round((o-n)/1e3)))},r);return i.unref(),{poke:()=>{s=Date.now()},stop:()=>clearInterval(i)}}function qe(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1524
|
-
`),2}function jt(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}function
|
|
1524
|
+
`),2}function jt(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}function Gs(t){if(t.stdout!==process.stdout||Xm)return;Xm=!0;let e=r=>{throw r.code==="EPIPE"&&process.exit(0),process.stdout.off("error",e),r};process.stdout.on("error",e)}var qm,Xm,he=k(()=>{"use strict";Pt();qm=_t(ct(),1);rt();Xm=!1});function ga(t,e){if($t(e)!=="dead")return null;let r=`holder process verified not alive; reconciled to aborted (invocation #${e.id}, holder pid ${e.holder_pid??"unknown"} on ${e.holder_host??"unknown"})`;return t.abortTrackedInvocationAndTerminalizeMessage(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},r)}function jr(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
1525
1525
|
FROM tracked_invocation
|
|
1526
1526
|
WHERE target_teamfile = ?
|
|
1527
1527
|
AND target_alias = ?
|
|
1528
|
-
AND status = 'running'`,e,r),s=0;for(let i of n)
|
|
1529
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function P(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ge(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var W,ve=k(()=>{"use strict";W=
|
|
1530
|
-
`):"";v&&!/^<(?:command-name>|local-command-)/u.test(v.trimStart())&&
|
|
1531
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let f=u.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=f}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let f=tf(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=tf(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let m=
|
|
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:
|
|
1528
|
+
AND status = 'running'`,e,r),s=0;for(let i of n)ga(t,i)!==null&&(s+=1);return s}var Sn=k(()=>{"use strict";Pe();Pt();ze()});import{realpathSync as cS}from"node:fs";import{resolve as dS}from"node:path";function _a(t){let e=dS(t);try{return cS(e)}catch{return e}}var Gm=k(()=>{"use strict"});import{platform as Jm}from"node:os";function Bt(t){let e=new bn;for(let r of t)e.registerAdapter(r);return e}var bn,ya=k(()=>{"use strict";Gm();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=_a(e.workspace);i=i.filter(a=>_a(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=Jm()==="darwin"||Jm()==="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 Vm}from"node:fs";import{createInterface as Km}from"node:readline";import{stat as uS}from"node:fs/promises";import{homedir as mS}from"node:os";function Ym(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*le(t){let e=Vm(t,{encoding:"utf-8"}),r=Km({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=Ym(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function Ue(t,e){let r=[],n=Vm(t,{encoding:"utf-8"}),s=Km({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Ym(o);if(a!==void 0&&r.push(a),r.length>=e)break}}finally{s.close(),n.destroy()}return r}async function ce(t){let e=await uS(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function z(t){return t.replace(/\\n/g,`
|
|
1529
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function P(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ge(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var W,ve=k(()=>{"use strict";W=mS()});import{readdir as Js,stat as zm,unlink as fS}from"node:fs/promises";import{join as Br,basename as Qm}from"node:path";function pS(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function hS(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 Zm(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of le(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=P(d.trim(),80)}}else if(c.type==="assistant"&&c.message){let d=c.message.content;if(Array.isArray(d))for(let f of d)f.type==="text"&&e++;let u=c.message.usage;if(u){let f=u.input_tokens||0,m=u.cache_creation_input_tokens||0,h=u.cache_read_input_tokens||0,_=u.output_tokens||0;r+=f+m+h,n+=h,s+=m,i+=_;let g=f+m+h;g&&(o=g),a={inputTokens:f,cacheWriteInputTokens:m,cachedInputTokens:h,outputTokens:_}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function gS(t){let e=_S(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 _S(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 Vs,ef=k(()=>{"use strict";ve();Vs=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Br(W,".claude"),this.projectsDir=Br(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Js(this.projectsDir)}catch{return e}for(let n of r){let s=Br(this.projectsDir,n);if(!(await zm(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Js(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Qm(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Br(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await Ue(e,50),s=await ce(e),i="",o,a,l,c,d,u;for(let m of n)if(!pS(m.type)&&(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!u&&m.timestamp&&(u=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let h=m.message.content;if(typeof h=="string"){if(h.includes("<command-name>")||h.includes("<local-command-"))continue;c||(c=P(h.trim(),80)),d=P(h.trim(),80)}}if(!i)return null;let f=await Zm(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:f.lastUserMessage??d,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await ce(r),s=[],i="",o,a,l,c,d,u,f,m=e,h,_=[];for await(let p of le(r))if(p.type!=="file-history-snapshot"&&!p.isSidechain){if(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!c&&p.gitBranch&&(c=p.gitBranch),!f&&p.timestamp&&(f=new Date(p.timestamp)),p.sessionId&&(m=p.sessionId),p.type==="system"||p.type==="progress"||p.type==="queue-operation"){s.push({role:"system",timestamp:new Date(p.timestamp||0),content:hS(p)});continue}if(p.type==="user"&&p.message){if(p.isMeta)continue;let y=new Date(p.timestamp||0),E=p.message.content;if(p.isCompactSummary!==!0&&p.isVisibleInTranscriptOnly!==!0&&p.promptSource!=="system"&&p.toolUseResult===void 0&&p.origin?.kind!=="task-notification"&&p.interruptedMessageId===void 0&&p.interruptedByShutdown!==!0&&p.scheduledTaskId===void 0&&p.scheduledFireId===void 0&&!(Array.isArray(E)&&E.some(v=>v.type==="tool_result"))){let v=typeof E=="string"?E:Array.isArray(E)?E.filter(b=>b.type==="text"&&typeof b.text=="string").map(b=>b.text).join(`
|
|
1530
|
+
`):"";v&&!/^<(?:command-name>|local-command-)/u.test(v.trimStart())&&_.push(v)}if(typeof E=="string"){if(E.includes("<command-name>")||E.includes("<local-command-"))continue;d||(d=P(E.trim(),80)),u=P(E.trim(),80),h=void 0,s.push({role:"user",timestamp:y,content:z(E.trim())})}else if(Array.isArray(E)){for(let v of E)if(v.type==="tool_result"){let b=typeof v.content=="string"?z(v.content):JSON.stringify(v.content);s.push({role:"tool_result",timestamp:y,content:b,toolCallId:v.tool_use_id})}}}if(p.type==="assistant"&&p.message){p.message.stop_reason===null||p.message.stop_reason==="tool_use"?h="in_progress":typeof p.message.stop_reason=="string"&&(h="complete"),p.message.model&&(l=p.message.model);let y=new Date(p.timestamp||0),E=p.message.content;if(Array.isArray(E))for(let v of E)v.type==="text"&&v.text?s.push({role:"assistant",timestamp:y,content:z(v.text),model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):v.type==="tool_use"?s.push({role:"tool_use",timestamp:y,content:v.name||"unknown tool",toolName:v.name,toolInput:JSON.stringify(v.input,null,2),toolInputData:v.input,toolCallId:v.id,model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):v.type==="thinking"&&v.thinking&&s.push({role:"thinking",timestamp:y,content:v.thinking})}}if(!i)return null;gS(s);let g=await Zm(r);return{provider:"claude",sessionId:m,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:h,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:_}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await fS(r),!0):!1}async resolveSessionFile(e){let r;try{r=await Js(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Br(this.projectsDir,o);if(!(await zm(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Js(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=Qm(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Br(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 Ue(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as yS,writeFileSync as JD,mkdirSync as VD}from"node:fs";import{join as ES,dirname as YD}from"node:path";import{homedir as TS}from"node:os";function vS(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function SS(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=vS(t.slice(e+1).trim());return r?{key:r,value:n}:null}function bS(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Ks(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function IS(){return ES(TS(),".lmctl","config.toml")}function Wr(t){let e=t??IS(),r;try{r=yS(e,"utf-8")}catch{return{tools:{}}}return xS(r)}function tf(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 xS(t){let e={},r={},n=t.split(`
|
|
1531
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let u=e[s.tool]??{};if(s.profile){let f=u.profiles?.[s.profile]??{};i.description&&(f.description=i.description),i.flags!==void 0&&(f.flags=i.flags),u.profiles||(u.profiles={}),u.profiles[s.profile]=f}else i.start&&(u.start=i.start),i.resume&&(u.resume=i.resume),i.agent&&(u.agent=i.agent),i.profile_flag!==void 0&&(u.profile_flag=i.profile_flag);e[s.tool]=u}else if(s.kind==="compact"){let u=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let f=tf(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=tf(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let m=bS(f);if(m!==null){if(o=!0,l(),m.startsWith("tool.")){let _=".profile.",g=m.indexOf(_);g!==-1?s={kind:"tool",tool:m.slice(5,g),profile:m.slice(g+_.length)}:s={kind:"tool",tool:m.slice(5),profile:null}}else m==="compact"?s={kind:"compact",provider:null}:m.startsWith("compact.")?s={kind:"compact",provider:m.slice(8)}:s={kind:"none"};continue}let h=SS(f);h&&s.kind!=="none"?i[h.key]=h.value:h&&!o&&(a[h.key]=h.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 rf(t){return t.site_name??null}function kS(t,e,r){if(!r)return"";let n=t.tools[e]??Ea[e],s=n?.profiles?.[r]?.flags??Ea[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 nf(t,e){return!!t.tools[e]}function sf(t,e,r,n,s){let i=t.tools[e]??Ea[e],o;if(i?.agent){let l=Ks(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=wS[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(Ks).join(" ");o=`printf '%s\\n' ${Ks(n)} | ${d}`}else o=c.map(Ks).join(" ")}let a=kS(t,e,s);return a&&(o+=" "+a),o}var Ea,wS,In=k(()=>{"use strict";Ea={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:""}}}},wS={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 of(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 af=k(()=>{"use strict"});var AS,G,Ys,$e=k(()=>{"use strict";AS="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: ${AS}`,Ys=`send this exact lmctl seed instruction: "${G}"`});import{existsSync as RS}from"node:fs";function lf(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&&!RS(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 Hr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function LS(t,e){return e===void 0||e.length===0?t:{...t??process.env,[Ta]:e}}function Ee(t,e,r,n="chat"){return{...LS(Hr(t,e),r),[NS]:n}}var Ta,NS,dt=k(()=>{"use strict";J();Ta="LMCTL_SELF_SESSIONID",NS="LMCTL_LAUNCH_SOURCE"});function xn(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var wa=k(()=>{"use strict"});import{spawn as cf}from"node:child_process";import{mkdirSync as CS}from"node:fs";var va,Q,je=k(()=>{"use strict";In();af();$e();dt();wa();va=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Q=class t{name;capabilities;injection;provider;binary;seedArgs;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 CS(e,{recursive:!0}),new Promise(n=>{let s;try{s=cf(this.binary,this.seedArgsFor(r),{cwd:e,env:Hr(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
|
+
`: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:Ys,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&&nf(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:h=>{a+=h,c(),n.onDelta?.(h)},onProgress:h=>{h.kind!=="api_retry"&&c(),n.onProgress?.(h)}},f=this.transportFn(r,u).then(h=>(d(),{...h,status:"ok"})).catch(h=>{throw d(),o==="external"?new va("Turn cancelled","external"):h}),m=new Promise(h=>{l=h});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=sf(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=of(r.env),c=cf(s,{shell:!0,cwd:r.cwd,env:Ee(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,f=setTimeout(()=>{u=!0,c.kill()},l),m="",h="";if(c.stdout?.on("data",_=>{let g=_.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",_=>{h+=_.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",_=>{if(d)return;d=!0,clearTimeout(f);let g=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):_===0||_===null?o({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(h.trim().slice(0,200)||`Agent command exited with code ${_}`))}),c.on("error",_=>{d||(d=!0,clearTimeout(f),a(_))})})}}});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 Wt,Z,kn,zs,An,lr=k(()=>{"use strict";Wt=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},Z=class extends Wt{},kn=class extends Wt{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},zs=class extends Wt{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},An=class extends Wt{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as ba from"node:child_process";function DS(t){if(typeof ba.spawnSync=="function")try{ba.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function df(t){return t.exitCode!==null||t.signalCode!==null}function Sa(t,e){return df(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??DS;if(df(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Sa(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 Sa(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Sa(t,OS)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var OS,Nn=k(()=>{"use strict";OS=1e3});function uf(t){K()&&we({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Ht(t,e){let r=$S[t];if(r)return r[e]??r.yolo}function PS(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 Se(t,e,r="yolo"){if(FS.has(t)){uf(`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"?Ht(t,"plan"):MS[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 Z(s)}if(!PS(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 Z(i)}uf(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var MS,$S,FS,vt=k(()=>{"use strict";lr();J();MS={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},$S={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"]}};FS=new Set(["codex","opencode","kimi","dsh","hermes","pi"])});async function Zs(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(Ia),e),n.unref?.(),r!==void 0&&(s=()=>i(Ia),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function Xt(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();HS(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function HS(t,e,r,n){let s=t.pollMs??US,i=t.maxHoldMs??Qs,o=t.settleMs??jS,a=t.backgroundGraceMs??BS,l=!1,c=null,d=u=>n({startedMs:r,held:l,reason:u});for(;;){if(e.isAborted())return d("aborted");if(e.hasChildExited())return d("child-exited");let u=i-(Date.now()-r);if(u<=0)return d("max-hold");let f;try{f=await Zs(t.hasOutstandingWork(),u,e.signal)}catch{return d("check-error")}if(f===Ia)return d(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(f)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-r<a){let _=a-(Date.now()-r);await new Promise(g=>setTimeout(g,Math.max(0,Math.min(s,WS,_))).unref?.());continue}if(!l||o<=0)return d("cleared");c===null&&(c=Date.now(),ye(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let h=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-h>=o)return d("cleared")}if(l||(l=!0,t.onHold?.(),ye(`${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 m=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(h=>setTimeout(h,m).unref?.())}}var US,Qs,jS,BS,WS,Ia,ei=k(()=>{"use strict";J();US=2e3,Qs=8*60*60*1e3,jS=5e3,BS=1e3,WS=50,Ia=Symbol("check-timed-out")});function mf(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
|
|
|
1534
1534
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1535
1535
|
|
|
1536
|
-
`+t[r]);return e.join("")}function
|
|
1536
|
+
`+t[r]);return e.join("")}function ti(t={}){let e=[],r="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}t.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(r=i.session_id||r),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&t.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=ff(e),i=mf(s.resultTexts);return{result:i,sessionId:s.sessionId||r,durationMs:s.durationMs,numTurns:s.numTurns,isError:s.isError&&i.trim().length===0,errorMessage:s.errorMessage}}}}function ff(t){let e=[],r=0,n=0,s="",i=!1,o;for(let a of t){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(r+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=c);let d=a.session_id;if(typeof d=="string"&&d&&(s=d),a.is_error===!0){i=!0;let u=a.errors,f=Array.isArray(u)?u.filter(h=>typeof h=="string").join("; "):void 0,m=typeof a.subtype=="string"?a.subtype:"unknown";o=f&&f.length>0?f:`result subtype=${m} (no error detail provided)`}}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s,isError:i,errorMessage:o}}var xa=k(()=>{"use strict"});import{spawn as hf}from"node:child_process";import{existsSync as gf}from"node:fs";import{join as ri}from"node:path";import{readdir as XS}from"node:fs/promises";function _f(){let t=process.env.LMCTL_RESULT_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 12e4;let e=Number(t);return Number.isFinite(e)&&e>0?e:12e4}function yf(){let t=process.env.LMCTL_TOOL_USE_GRACE_TIMEOUT_MS;if(t===void 0||t.trim().length===0)return 27e5;let e=Number(t);return Number.isFinite(e)&&e>0?e:27e5}function Ef(t){let r=t.message?.content;return Array.isArray(r)?r.some(n=>n?.type==="tool_use"):!1}function GS(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1537
1537
|
One possible cause: the provider stream ended before a complete response was delivered; for Claude Code this can appear as "API Error: Stream idle timeout - partial response received".`;return e?`Original provider error:
|
|
1538
1538
|
${e}
|
|
1539
1539
|
|
|
1540
|
-
${r}`:r}function Tf(t){let e=t.tool||"claude",r=t.binaryPath||
|
|
1541
|
-
`);u=Y.pop()||"";for(let
|
|
1542
|
-
`),ye(`stream-json: prompt sent (${t.length} chars)`)})}function
|
|
1543
|
-
`);F=j.pop()||"";for(let me of j)pn(me)}),i.on("error",O=>{if(c=new Z(`Failed to spawn ${r}: ${O.message}`,{cause:O}),L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:O.message}),
|
|
1544
|
-
`),ye(`stream-json bundle: prompt sent (${O.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(O=>{Xt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),O()},label:e})}):i.stdin?.end(),!a.exited)){let O=t.closeTimeoutMs??2e3;await Promise.race([w(),
|
|
1540
|
+
${r}`:r}function Tf(t){let e=t.tool||"claude",r=t.binaryPath||qS[e]||"claude",n=["-p","","--output-format","stream-json","--input-format","stream-json"];e==="claude"&&n.push("--verbose"),t.sessionId&&n.push("--resume",t.sessionId),t.model&&n.push("--model",t.model);let s=t.permissionMode??"yolo",i=Ht(e,s)??JS[e]??["--dangerously-skip-permissions"];if(n.push(...i),Se(e,n,s),t.cwd&&!gf(t.cwd))throw L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new Z(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=Ee(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?lf(o):o}}function wf(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Tf(e))}catch(F){return n(F instanceof Error?F:new Error(String(F)))}let c=hf(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",F=>{ye(`stream-json: stdin pipe error, ignored (exit handler reports): ${F.message}`)});let d=!1;if(e.signal){if(e.signal.aborted)return d=!0,L({event:"transport_abort",provider:i,phase:"pre_spawn"}),ne(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,L({event:"transport_abort",provider:i}),ne(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let u="",f=!1,m=!1,h=0,_=!1,g="",p="",y,E,v=null,b=null,T=!1,S=!1,w=_f(),x=yf();function I(){y!==void 0&&(clearTimeout(y),y=void 0)}function R(){E!==void 0&&(clearTimeout(E),E=void 0)}let N=null;function U(){return f||d||be.sawResult()}function re(F){return F==="text_done"?w:x}async function ee(F){if(F==="text_done"?y=void 0:E=void 0,U()||v!==null)return;N??=Date.now();let Y=re(F);if(e.holdOpen){let pn=(e.holdOpen.maxHoldMs??Qs)-(Date.now()-N),Ro=pn>0?await Zs(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),pn,e.signal):!1;if(U()||(F==="text_done"?y!==void 0:E!==void 0))return;if(Ro===!0){L({event:"transport_stall_grace_deferred",provider:i,grace_kind:F,grace_ms:Y,reason:"outstanding_dispatched_work"}),xe(F);return}}b=F,v=F==="text_done"?`${i} finished responding but never emitted its closing result event (${Y}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${Y}ms of silence)`,L({event:"transport_stall_grace_fired",provider:i,grace_kind:F,grace_ms:Y}),ne(c).catch(()=>{})}function xe(F){let Y=setTimeout(()=>{ee(F)},re(F));Y.unref?.(),F==="text_done"?(I(),y=Y):(R(),E=Y)}let be=ti({onEvent:F=>{h=Date.now(),_=F.type!=="result",F.type==="system"&&F.subtype==="init"&&(p=F.session_id||p),F.type==="assistant"?(T=!Ef(F),S=T&&F.message?.stop_reason==="pause_turn"):(F.type==="result"||F.type==="user")&&(T=!1,S=!1),I(),i==="claude"&&T&&!S&&!be.sawResult()&&xe("text_done"),R(),i==="claude"&&!be.sawResult()&&xe("tool_use_silence"),e.onEvent?.(F)},onText:F=>{g+=F,e.onText?.(F)}});function q(){m||(m=!0,Xt(e.holdOpen,{isAborted:()=>d,hasChildExited:()=>f,isTurnInFlight:()=>_,lastEventAtMs:()=>h,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function Ce(F){let Y=be.sawResult();be.processLine(F),!Y&&be.sawResult()&&q()}c.stdout?.on("data",F=>{u+=F.toString();let Y=u.split(`
|
|
1541
|
+
`);u=Y.pop()||"";for(let ys of Y)Ce(ys)});let gt="";c.stderr?.on("data",F=>{gt+=F.toString()}),c.on("error",F=>{L({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:F.message}),n(new Z(`Failed to spawn ${o}: ${F.message}`,{cause:F}))}),c.on("exit",F=>{if(f=!0,I(),R(),d)return;u.trim()&&Ce(u);let Y=be.finalize();Y?.isError?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:Y.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${Y.errorMessage??"unknown error"}`))):Y?(ye(`stream-json: result ${Y.result.slice(0,80)}${Y.result.length>80?"...":""} (${Y.durationMs}ms)`),r({result:Y.result,sessionId:Y.sessionId,durationMs:Y.durationMs,numTurns:Y.numTurns,exitCode:F})):v!==null&&b==="text_done"&&g.trim().length>0?(L({event:"transport_stall_finalized",provider:i,reason:v,text_len:g.length}),r({result:g,sessionId:p||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:F,warnings:[v]})):v!==null&&b==="tool_use_silence"?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:F,stderr_tail:gt.slice(0,500)}),n(new Error(`${v} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(e.sessionId?` (session=${e.sessionId})`:"")))):(L({event:"transport_error",provider:i,error_class:"Error",reason:v!==null?"provider_stalled_no_content":"provider_no_result",exit_code:F,stderr_tail:gt.slice(0,500)}),n(new Error(v!==null?`${v} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):GS({tool:i,exitCode:F,stderr:gt}))))});let Ar=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(Ar+`
|
|
1542
|
+
`),ye(`stream-json: prompt sent (${t.length} chars)`)})}function VS(t){return t==="qwen"?[ri(W,".qwen","projects")]:[ri(W,".claude","projects")]}async function pf(t,e,r){let n=r??VS(t),s=null;for(let a of n){let l;try{l=await XS(a)}catch{continue}for(let c of l){for(let d of[ri(a,c,`${e}.jsonl`),ri(a,c,"chats",`${e}.jsonl`)])if(gf(d)){s=d;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${n.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await Ue(s,5).catch(()=>[])).map(a=>a?.sessionId).find(a=>typeof a=="string"&&a.length>0);if(o!==e)throw new Error(`stream-json bundle: session file ${s} header does not match the requested session (expected "${e}", header carries ${o??"no sessionId"}) \u2014 the session was likely re-seeded externally; aborting instead of writing into the wrong session`)}async function vf(t){let{tool:e,binary:r,args:n,spawnEnv:s}=Tf(t),i=hf(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",O=>{ye(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${O.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=null,d="";i.stderr?.on("data",O=>{d+=O.toString()});let u="",f="",m=!1,h=!1,_=null,g=null,p=null,y,E,v=_f(),b=yf(),T=null,S=[],w=()=>a.exited?Promise.resolve():new Promise(O=>{S.push(O)}),x=()=>new Error(`stream-json bundle process (${e}) exited${a.exitCode!==null?` with code ${a.exitCode}`:""} after ${a.completedTurns} completed prompt(s); the bundle cannot continue`);function I(){y!==void 0&&(clearTimeout(y),y=void 0)}function R(){E!==void 0&&(clearTimeout(E),E=void 0)}function N(){return a.exited||T===null||T.aborted||T.processor.sawResult()}function U(O){return O==="text_done"?v:b}async function re(O){if(O==="text_done"?y=void 0:E=void 0,N()||_!==null)return;p??=Date.now();let j=U(O);if(t.holdOpen){let Rr=(t.holdOpen.maxHoldMs??Qs)-(Date.now()-p),Es=Rr>0?await Zs(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),Rr,void 0):!1;if(N()||(O==="text_done"?y!==void 0:E!==void 0))return;if(Es===!0){L({event:"transport_stall_grace_deferred",provider:e,grace_kind:O,grace_ms:j,reason:"outstanding_dispatched_work"}),ee(O);return}}g=O,_=O==="text_done"?`${e} finished responding but never emitted its closing result event (${j}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${j}ms of silence)`,L({event:"transport_stall_grace_fired",provider:e,grace_kind:O,grace_ms:j}),ne(i).catch(()=>{})}function ee(O){let j=setTimeout(()=>{re(O)},U(O));j.unref?.(),O==="text_done"?(I(),y=j):(R(),E=j)}let xe=!1,be,q,Ce=new Promise((O,j)=>{be=O,q=j});Ce.catch(()=>{});let gt=setTimeout(()=>{xe||(xe=!0,q(new Error(`stream-json bundle: ${e} emitted no init event within the open timeout \u2014 cannot verify the resumed session identity`)))},t.closeTimeoutMs!==void 0?Math.max(t.closeTimeoutMs,5e3):3e4);gt.unref?.();function Ar(O){xe||(xe=!0,clearTimeout(gt),O?q(O):be())}let F="";function Y(O){if(a.lastEventAtMs=Date.now(),O.type==="system"&&O.subtype==="init"){if(f=O.session_id||f,t.sessionId&&typeof O.session_id=="string"&&O.session_id.length>0&&O.session_id!==t.sessionId){let me=new Error(`stream-json bundle: provider resumed a different session (init reported "${O.session_id}", expected "${t.sessionId}")`);Ar(me),ne(i).catch(()=>{});return}Ar()}let j=T?.processor.sawResult()??!0;O.type==="assistant"?(m=!Ef(O),h=m&&O.message?.stop_reason==="pause_turn"):(O.type==="result"||O.type==="user")&&(m=!1,h=!1),I(),e==="claude"&&a.turnActive&&m&&!h&&!j&&ee("text_done"),R(),e==="claude"&&a.turnActive&&!j&&ee("tool_use_silence")}function ys(){let O=T;if(O===null)return;let j=O.processor.finalize();if(j!==null){if(T=null,a.turnActive=!1,I(),R(),j.isError){L({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:j.errorMessage}),O.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${j.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=j.sessionId||l,ye(`stream-json bundle: result ${j.result.slice(0,80)}${j.result.length>80?"...":""} (${j.durationMs}ms)`),O.resolve({result:j.result,sessionId:j.sessionId||l,durationMs:j.durationMs,numTurns:j.numTurns})}}function pn(O){if(!O.trim())return;let j;try{j=JSON.parse(O)}catch{return}Y(j);let me=T;if(me!==null){let Rr=me.processor.sawResult();me.processor.processLine(O),me.onEventForward?.(j),!Rr&&me.processor.sawResult()&&ys()}}i.stdout?.on("data",O=>{F+=O.toString();let j=F.split(`
|
|
1543
|
+
`);F=j.pop()||"";for(let me of j)pn(me)}),i.on("error",O=>{if(c=new Z(`Failed to spawn ${r}: ${O.message}`,{cause:O}),L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:O.message}),Ar(c),T!==null){let j=T;T=null,a.turnActive=!1,j.reject(c)}}),i.on("exit",O=>{a.exited=!0,a.exitCode=O,I(),R(),F.trim()&&pn(F),Ar(a.exited&&!xe?new Error(`stream-json bundle: ${e} exited (code ${String(O)}) before its init event`):void 0);let j=T;j!==null&&(T=null,a.turnActive=!1,j.aborted||(_!==null&&g==="text_done"&&u.trim().length>0?(L({event:"transport_stall_finalized",provider:e,reason:_,text_len:u.length}),j.resolve({result:u,sessionId:f||t.sessionId||"",durationMs:Date.now()-j.startMs,numTurns:1,warnings:[_]})):_!==null&&g==="tool_use_silence"?(L({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:O,stderr_tail:d.slice(0,500)}),j.reject(new Error(`${_} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")))):(L({event:"transport_error",provider:e,error_class:"Error",reason:_!==null?"provider_stalled_no_content":"provider_no_result",exit_code:O,stderr_tail:d.slice(0,500)}),j.reject(x()))));for(let me of S.splice(0))me()});try{t.sessionId&&await pf(e,t.sessionId,t.sessionFileRoots),await Ce}catch(O){let j=c??(O instanceof Error?O:new Error(String(O))),me=t.closeTimeoutMs??2e3;throw await ne(i,{softDelayMs:Math.min(1e3,me),killDelayMs:Math.min(1e3,me)}).catch(()=>{}),j}let Ro=O=>new Promise(j=>{setTimeout(j,O).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(O,j={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw x();if(T!==null)throw new Error(`stream-json bundle session (${e}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);let me=()=>(a.closed=!0,ne(i).catch(()=>{}),new Error("Aborted"));if(j.signal?.aborted)throw me();if(t.sessionId&&(await pf(e,t.sessionId,t.sessionFileRoots),a.exited))throw x();if(j.signal?.aborted)throw me();return u="",m=!1,h=!1,_=null,g=null,p=null,new Promise((Rr,Es)=>{let No={processor:ti({onText:Gd=>{u+=Gd,j.onText?.(Gd)}}),resolve:Rr,reject:Es,startMs:Date.now(),aborted:!1,onEventForward:j.onEvent};T=No,a.turnActive=!0;let GE=()=>{No.aborted=!0,L({event:"transport_abort",provider:e}),a.closed=!0,ne(i).catch(()=>{}),T===No&&(T=null,a.turnActive=!1),Es(new Error("Aborted"))};j.signal?.addEventListener("abort",GE,{once:!0});let JE=JSON.stringify({type:"user",message:{role:"user",content:O}});i.stdin?.write(`${JE}
|
|
1544
|
+
`),ye(`stream-json bundle: prompt sent (${O.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(O=>{Xt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),O()},label:e})}):i.stdin?.end(),!a.exited)){let O=t.closeTimeoutMs??2e3;await Promise.race([w(),Ro(O)]),a.exited||await ne(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),a.closing}}}var qS,JS,ka=k(()=>{"use strict";lr();Nn();vt();J();ei();dt();xa();ve();xa();qS={claude:"claude",qwen:"qwen"};JS={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function ni(t={}){return[]}var Aa=k(()=>{"use strict"});function Ra(t){return t==="plan"?"read-only":"danger-full-access"}function Sf(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function si(){return{agentItems:new Map,resultText:""}}function Xr(t,e,r,n){let s=t.method;if(!s)return!1;let i=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=typeof o.phase=="string"?o.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(o.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let o=i?.delta||"",a=typeof i?.itemId=="string"?i.itemId:void 0;if(!o)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=o),r?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,r?.(o)),!0}if(s==="item/completed"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=e.agentItems.get(o.id);if(a){if(a.phase!=="commentary"){let l=typeof o.text=="string"?o.text:a.buffer;if(n&&typeof o.text=="string"&&o.text!==a.buffer){let c=typeof i?.threadId=="string"?i.threadId:void 0,d=typeof i?.turnId=="string"?i.turnId:void 0;n({itemId:o.id,threadId:c,turnId:d,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function ii(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function bf(t){let e=t.params,r=e?.error,n=typeof r?.message=="string"?r.message:void 0,s=n&&n.length>0?n:"(no message)";return e?.willRetry===!0?{willRetry:!0}:{willRetry:!1,turnError:new Error(`Turn errored: ${s}`)}}function oi(){return{pendingCodexError:null}}function ai(t,e){let r=bf(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function li(t,e){if(e.pendingCodexError){let i=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:i}}let n=t.params?.turn;if((typeof n?.status=="string"?n.status:void 0)==="failed"){let i=n?.error,o=typeof i?.message=="string"?i.message:void 0,a=o&&o.length>0?o:"(no message)";return{shouldReject:!0,turnError:new Error(`Turn errored: ${a}`)}}return{shouldReject:!1}}var Na=k(()=>{"use strict"});import{spawn as If}from"node:child_process";import{createInterface as xf}from"node:readline";import{existsSync as KS,readFileSync as YS}from"node:fs";import{fileURLToPath as zS}from"node:url";function kf(){return Sf(QS)}function qt(t,e){ye(`[codex:${t}] ${JSON.stringify(e)}`)}function ZS(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1545
1545
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1546
1546
|
${e}
|
|
1547
1547
|
|
|
1548
|
-
${r}`:r}function Af(t){let e=t.binaryPath||"codex",r=["app-server","--listen","stdio://"];t.model&&r.push("-c",`model=${JSON.stringify(t.model)}`);let n=t.isLead??t.alias?.toLowerCase()==="lead",s=n?
|
|
1549
|
-
`)})}function v(
|
|
1550
|
-
`)}c.on("line",
|
|
1551
|
-
`),L({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:
|
|
1552
|
-
`)})}function
|
|
1553
|
-
`)}let
|
|
1548
|
+
${r}`:r}function Af(t){let e=t.binaryPath||"codex",r=["app-server","--listen","stdio://"];t.model&&r.push("-c",`model=${JSON.stringify(t.model)}`);let n=t.isLead??t.alias?.toLowerCase()==="lead",s=n?ni():[];r.push(...s),K()&&_e(JSON.stringify({event:"codex_mcp_inject",alias:t.alias??null,isLead:n,injected:s.length>0}));let i=t.permissionMode??"yolo",o=Ra(i);if(Se("codex",r,i),t.cwd&&!KS(t.cwd))throw L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`}),new Z(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:e,codexArgs:r,sandbox:o,permissionMode:i,spawnEnv:Ee(t.env,t.cwd,t.threadId)}}function Rf(t,e){return new Promise((r,n)=>{let s,i,o;try{({binary:s,codexArgs:i,sandbox:o}=Af(e))}catch(T){return n(T instanceof Error?T:new Error(String(T)))}let a=If(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:Ee(e.env,e.cwd,e.threadId)}),l=!1;if(e.signal){if(e.signal.aborted)return l=!0,L({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),ne(a).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{l=!0,L({event:"transport_abort",provider:"codex"}),ne(a).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let c=xf({input:a.stdout}),d=new Map,u=1,f=e.threadId||"",m="",h=!1,_=!1,g=Date.now(),p=si(),y=oi();function E(T,S={}){return new Promise((w,x)=>{let I=u++;d.set(I,{resolve:w,reject:x});let R=JSON.stringify({jsonrpc:"2.0",id:I,method:T,params:S});a.stdin?.write(R+`
|
|
1549
|
+
`)})}function v(T,S={}){let w=JSON.stringify({jsonrpc:"2.0",method:T,params:S});a.stdin?.write(w+`
|
|
1550
|
+
`)}c.on("line",T=>{let S;try{S=JSON.parse(T)}catch{return}if(typeof S.id=="number"&&d.has(S.id)){let I=d.get(S.id);if(d.delete(S.id),S.error){let R=S.error,N=typeof R?.message=="string"&&R.message.length>0?R.message:JSON.stringify(S.error);I.reject(Rn(`codex app-server error: ${N}`,R))}else I.resolve(S);e.onEvent?.(S);return}let w=S.method;if(!w){e.onEvent?.(S);return}if(w==="thread/started"){let R=S.params?.thread;R?.id&&(f=R.id)}let x=K()?I=>{qt("item.text/buffer-mismatch",{itemId:I.itemId,threadId:I.threadId??null,turnId:I.turnId??null,expectedFromItemText:I.expectedFromItemText,gotFromBuffer:I.gotFromBuffer,expectedLen:I.expectedFromItemText.length,gotLen:I.gotFromBuffer.length})}:void 0;if(w==="turn/started"){let I=S.params,R=I?.turn;R?.id&&(m=R.id),Xr(S,p,e.onDelta,x),K()&&qt("turn/started",{params:I??null})}if(K()&&(w==="item/started"||w==="item/completed")){let I=S.params;I?.item?.type==="agentMessage"&&qt(w,{params:I??null})}if(w==="item/started"||w==="item/agentMessage/delta"||w==="item/completed"){if(w==="item/agentMessage/delta"){let I=S.params;K()&&qt("agentMessage/delta",{params:I??null})}Xr(S,p,e.onDelta,x)}if(w==="turn/completed"){let I=S.params;if(K())for(let[N,U]of p.agentItems.entries())U.buffer&&qt("turn/completed/unflushed-item",{itemId:N,phase:U.phase,bufferLen:U.buffer.length});ii(p),K()&&qt("turn/completed",{params:I??null});let R=li(S,y);R.shouldReject?(K()&&qt("turn/completed/terminal-reject",{message:R.turnError.message}),_=!0,h=!0,a.stdin?.end(),n(R.turnError)):(h=!0,a.stdin?.end())}if(w==="error"){let I=ai(S,y);if(K()){let R=S.params,N=R?.error,U=typeof N?.message=="string"?N.message:"(no message)";qt(I.willRetry?"error/retry":"error/terminal-deferred",{message:U,willRetry:I.willRetry,params:R??null})}}e.onEvent?.(S)});let b="";a.stderr?.on("data",T=>{b+=T.toString()}),a.on("error",T=>{L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:T.message}),n(new Z(`Failed to spawn codex app-server: ${T.message}`,{cause:T}))}),a.on("exit",T=>{if(!l&&!_){if(h){r({result:p.resultText,threadId:f,turnId:m,durationMs:Date.now()-g,exitCode:T});return}if(y.pendingCodexError){n(y.pendingCodexError);return}L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:T,stderr_tail:b.slice(0,500)}),n(new Error(ZS({exitCode:T,stderr:b})))}}),(async()=>{try{if(await E("initialize",kf()),v("initialized",{}),e.threadId)try{let T=E("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),S=new Promise((w,x)=>setTimeout(()=>x(new Error("resume timeout")),3e4));await Promise.race([T,S]),f=e.threadId}catch(T){process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1551
|
+
`),L({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:T instanceof Error?T.message:String(T)});let w=(await E("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;w?.id&&(f=w.id)}else{let S=(await E("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;S?.id&&(f=S.id)}await E("turn/start",{threadId:f,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(T){ne(a).catch(()=>{}),n(T instanceof Error?T:new Error(String(T)))}})()})}async function Nf(t){let{binary:e,codexArgs:r,sandbox:n}=Af(t),s=If(e,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:Ee(t.env,t.cwd,t.threadId)}),i=Date.now(),o={exited:!1,exitCode:null,completedTurns:0,closed:!1,closing:null},a=t.threadId||"",l=null,c="";s.stderr?.on("data",b=>{c+=b.toString()});let d=xf({input:s.stdout}),u=new Map,f=1;function m(b,T={}){return new Promise((S,w)=>{let x=f++;u.set(x,{resolve:S,reject:w});let I=JSON.stringify({jsonrpc:"2.0",id:x,method:b,params:T});s.stdin?.write(I+`
|
|
1552
|
+
`)})}function h(b,T={}){let S=JSON.stringify({jsonrpc:"2.0",method:b,params:T});s.stdin?.write(S+`
|
|
1553
|
+
`)}let _=[],g=()=>o.exited?Promise.resolve():new Promise(b=>{_.push(b)}),p=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),y=null;function E(b){let T=y;T===null||T.settled||(T.settled=!0,y=null,b&&T.reject(b))}d.on("line",b=>{let T;try{T=JSON.parse(b)}catch{return}if(typeof T.id=="number"&&u.has(T.id)){let x=u.get(T.id);if(u.delete(T.id),T.error){let I=T.error,R=typeof I?.message=="string"&&I.message.length>0?I.message:JSON.stringify(T.error);x.reject(Rn(`codex app-server error: ${R}`,I))}else x.resolve(T);y?.onEvent?.(T);return}let S=T.method;if(!S){y?.onEvent?.(T);return}if(S==="thread/started"){let I=T.params?.thread;I?.id&&(a=I.id)}let w=y;if(S==="turn/started"&&w!==null){let I=T.params?.turn;I?.id&&(w.turnId=I.id),Xr(T,w.agentState,w.onDelta,void 0)}if(w!==null&&(S==="item/started"||S==="item/agentMessage/delta"||S==="item/completed")&&Xr(T,w.agentState,w.onDelta,void 0),S==="turn/completed"&&w!==null&&!w.settled){ii(w.agentState);let x=li(T,w.turnState);w.settled=!0,y=null,x.shouldReject?w.reject(x.turnError):(o.completedTurns+=1,w.resolve({text:w.agentState.resultText,sessionId:a,turnId:w.turnId,durationMs:Date.now()-w.startMs}))}S==="error"&&w!==null&&ai(T,w.turnState),w?.onEvent?.(T)}),s.on("error",b=>{l=new Z(`Failed to spawn codex app-server: ${b.message}`,{cause:b}),L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:b.message});for(let T of u.values())T.reject(l);u.clear(),E(l)}),s.on("exit",b=>{o.exited=!0,o.exitCode=b;let T=p();for(let w of u.values())w.reject(T);u.clear();let S=y;S!==null&&!S.settled&&(S.settled=!0,y=null,S.turnState.pendingCodexError?S.reject(S.turnState.pendingCodexError):(L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:b,stderr_tail:c.slice(0,500)}),S.reject(T)));for(let w of _.splice(0))w()});try{if(await m("initialize",kf()),h("initialized",{}),t.threadId){let b;try{b=await m("thread/resume",{threadId:t.threadId,sandbox:n,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(S){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${S instanceof Error?S.message:String(S)} (the thread/start fallback is disabled in bundle mode)`)}let T=b.result?.thread;if(typeof T?.id=="string"&&T.id.length>0){if(T.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${T.id}"`);a=T.id}}else{let T=(await m("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:n,...t.model?{model:t.model}:{}})).result?.thread;T?.id&&(a=T.id)}}catch(b){let T=l??(b instanceof Error?b:new Error(String(b))),S=t.closeTimeoutMs??2e3;throw await ne(s,{softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{}),T}let v=b=>new Promise(T=>{setTimeout(T,b).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(b,T={}){if(o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw p();if(y!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(T.signal?.aborted)throw new Error("Aborted");return new Promise((S,w)=>{let x={agentState:si(),turnState:oi(),resolve:S,reject:w,startMs:Date.now(),turnId:"",onDelta:T.onDelta,onEvent:T.onEvent,settled:!1};y=x;let I=()=>{x.settled||(x.settled=!0,y=null,x.turnId&&m("turn/interrupt",{threadId:a,turnId:x.turnId}).catch(()=>{}),w(new Error("Aborted")))};T.signal?.addEventListener("abort",I,{once:!0}),m("turn/start",{threadId:a,input:[{type:"text",text:b}],...t.model?{model:t.model}:{}}).catch(R=>{x.settled||(x.settled=!0,y=null,T.signal?.removeEventListener("abort",I),w(o.exited?p():R instanceof Error?R:new Error(String(R))))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,!o.exited&&(t.holdOpen!==void 0?await new Promise(b=>{Xt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>y!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),b()},label:"codex"})}):s.stdin?.end(),!o.exited)){let b=t.closeTimeoutMs??2e3;await Promise.race([g(),v(b)]),o.exited||await ne(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,b),killDelayMs:Math.min(1e3,b)}).catch(()=>{})}})()),o.closing}}}var QS,Lf=k(()=>{"use strict";J();J();lr();Nn();ei();vt();Aa();J();dt();Na();Na();QS=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(YS(zS(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function ci(t){let e=[...t.matchAll(eb)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return Cf(t.slice(n).trimStart())}return Cf(ib(t.replace(tb,"")))}function ib(t){let e=rb.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(nb)];if(n.length<2)return t;let s=n[0],i=(s.index??0)+s[0].length;return r.slice(i).trimStart()}function Cf(t){let e=[...t.matchAll(sb)];if(e.length===0)return t;let r=e[e.length-1],n=(r.index??0)+r[0].length;return t.slice(n).trimStart()}function Gt(t,e=""){let r=t.result;return typeof r?.sessionId=="string"&&r.sessionId.length>0?r.sessionId:e}function Df(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function di(t={}){let e="",r="",n="",s=!1,i=!1,o=t.isolateResult??(t.tool==="gemini"?ci:void 0),a=()=>({result:o?o(r):r,sessionId:e,stopReason:n});return{setSessionId(l){e=l},beginTurn(){r="",n="",s=!1,i=!0},completeTurn(l){return n=Df(l),s=!0,i=!1,a()},cancelTurn(){r="",n="",i=!1},processMessage(l){if(l.method!=="session/update")return!1;let d=l.params?.update;if(d?.sessionUpdate!=="agent_message_chunk")return!1;let u=d.content,f=typeof u?.text=="string"?u.text:"";return f&&i&&(r+=f,t.onDelta?.(f)),!0},finalize(){return s?a():null}}}var Of,eb,tb,rb,nb,sb,Ln=k(()=>{"use strict";Of="(?:png|jpe?g|webp|heic|pdf)",eb=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${Of}\\s*`,"gi"),tb=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${Of}\\s*`,"i"),rb=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,nb=/^STANCE:\s+\S+\s*$/gim,sb=/\[Thought:\s*true\]\s*/gi});import{createInterface as ob}from"node:readline";function Cn(t,e){let r=ob({input:t.stdout}),n=new Map,s=(o,a={})=>new Promise((l,c)=>{let d=ab++;n.set(d,{resolve:l,reject:c});let u=JSON.stringify({jsonrpc:"2.0",id:d,method:o,params:a});we({event:"acp_send",direction:"SEND",provider:e.provider,method:o,id:d,params:a}),t.stdin?.write(`${u}
|
|
1554
1554
|
`)}),i=(o,a={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:o,params:a})}
|
|
1555
1555
|
`)};return r.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(we({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let d=a.error,u=typeof d?.message=="string"&&d.message.length>0?d.message:JSON.stringify(a.error);c.reject(Rn(`ACP RPC error: ${u}`,d))}else c.resolve(a);return}let l=a.method;if(l){if(typeof a.id=="number"){L({event:"acp_unhandled_request",provider:e.provider,method:l,id:a.id,params:a.params});let c=JSON.stringify({jsonrpc:"2.0",id:a.id,error:{code:-32601,message:`Method not found: ${l} (lmctl does not implement server-side ACP methods)`}});we({event:"acp_send",direction:"SEND",provider:e.provider,replyTo:a.id,error:"method not found"}),t.stdin?.write(`${c}
|
|
1556
|
-
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new Z("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var
|
|
1556
|
+
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new Z("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var ab,La=k(()=>{"use strict";J();lr();ab=1});import{readFileSync as lb,readdirSync as Mf}from"node:fs";import{join as ui}from"node:path";function $f(t,e){let r=e.GEMINI_DIR??process.env.GEMINI_DIR??ui(W,".gemini"),n=ui(r,"tmp"),s;try{s=Mf(n)}catch{throw new Error(`gemini bundle: cannot read the gemini session store at ${n} \u2014 cannot verify session "${t}"`)}let i=`"sessionId": "${t}"`,o=`"sessionId":"${t}"`;for(let a of s){let l=ui(n,a,"chats"),c;try{c=Mf(l)}catch{continue}for(let d of c){if(!d.endsWith(".json"))continue;let u;try{u=lb(ui(l,d),"utf8").slice(0,8192)}catch{continue}if(u.includes(i)||u.includes(o))return}}throw new Error(`gemini bundle: no session "${t}" in the gemini chats store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var On,Ff=k(()=>{"use strict";Ln();ve();vt();On={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(t){let e=[...On.baseArgs];if(t.permissionMode==="plan"){let r=Ht("gemini","plan"),n=Ht("gemini","yolo");e=e.filter(s=>!(n??[]).includes(s)),r&&e.push(...r)}return t.model&&e.push("--model",t.model),e},isolateResult:ci,sessionIdentity:{verifyLoadedSession:t=>{$f(t.requestedSessionId,t.env)},recheckSession:t=>{$f(t.requestedSessionId,t.env)}}}});import{existsSync as cb,readFileSync as db}from"node:fs";import{join as Ca}from"node:path";function Pf(t,e){let r=e.COPILOT_HOME??process.env.COPILOT_HOME??Ca(W,".copilot"),n=Ca(r,"session-state",t),s=Ca(n,"workspace.yaml");if(!cb(s))throw new Error(`copilot bundle: no session "${t}" in the copilot session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`);let i;try{i=db(s,"utf8").slice(0,4096)}catch(a){throw new Error(`copilot bundle: cannot read ${s} \u2014 cannot verify session "${t}": `+(a instanceof Error?a.message:String(a)))}let o=/^id:\s*(\S+)\s*$/m.exec(i);if(o===null||o[1]!==t)throw new Error(`copilot bundle: session store entry ${s} belongs to ${o?.[1]??"no recorded id"}, not "${t}"`)}var Dn,Uf=k(()=>{"use strict";J();ve();Dn={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(t){return t.permissionMode==="plan"&&(process.stderr.write(`[acp] copilot has no plan-mode flag in --acp mode; --permission-mode plan is not honored (running yolo). See src/providers/yolo-contract.ts.
|
|
1557
1557
|
`),L({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),t.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${t.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1558
|
-
`),L({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...Dn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{Pf(t.requestedSessionId,t.env)},recheckSession:t=>{Pf(t.requestedSessionId,t.env)}}}});import{existsSync as Wf,mkdirSync as
|
|
1559
|
-
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function qf(t,e={}){let r=Mn(t,".opencode"),n=Mn(r,"opencode.json");if(!Wf(n)){
|
|
1558
|
+
`),L({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...Dn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{Pf(t.requestedSessionId,t.env)},recheckSession:t=>{Pf(t.requestedSessionId,t.env)}}}});import{existsSync as Wf,mkdirSync as ub,readFileSync as Hf,writeFileSync as jf}from"node:fs";import{join as Mn,resolve as mb}from"node:path";function Xf(t){if(t==="allow")return!0;if(t&&typeof t=="object"&&!Array.isArray(t)){let e=Object.entries(t);if(e.length===1&&e[0][0]==="*"&&e[0][1]==="allow")return!0}return!1}function Oa(t,e,r={existsSync:Wf,readFileSync:Hf}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=mb(e,s.sessiondir??e);for(let o of fb(i)){let a=pb(o,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(Xf(a.permission)||n.push(`[${s.alias}] ${o} sets a non-allow \`permission\`, which opencode merges over lmctl's YOLO (.opencode/opencode.json permission:"allow") \u2014 the member may hang on permission prompts. Set \`permission: "allow"\` in that file (or remove the key).`))}}return n}function fb(t){return[Mn(t,".opencode","opencode.jsonc"),Mn(t,"opencode.jsonc"),Mn(t,"opencode.json")]}function pb(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(hb(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function hb(t){let e="",r=!1,n="",s=!1;for(let i=0;i<t.length;i+=1){let o=t[i],a=t[i+1];if(r){e+=o,s?s=!1:o==="\\"?s=!0:o===n&&(r=!1,n="");continue}if(o==='"'||o==="'"){r=!0,n=o,e+=o;continue}if(o==="/"&&a==="/"){for(;i<t.length&&t[i]!==`
|
|
1559
|
+
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function qf(t,e={}){let r=Mn(t,".opencode"),n=Mn(r,"opencode.json");if(!Wf(n)){ub(r,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return jf(n,o+`
|
|
1560
1560
|
`,"utf-8"),!0}let s;try{s=JSON.parse(Hf(n,"utf-8"))}catch{return console.log(Bf.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(Bf.yellow(` .opencode/opencode.json at ${n} is not an object \u2014 skipping opencode config install.`)),!1;let i=!1;return s.permission===void 0&&(s.permission="allow",i=!0),Xf(s.permission)||L({event:"opencode_yolo_override",provider:"opencode",config_path:n,user_permission:s.permission,message:`opencode.json has a user-set 'permission' value other than 'allow' \u2014 lmctl's YOLO contract is NOT in effect; turns may hang waiting on permission prompts. Set permission: "allow" or remove the key to restore YOLO.`}),i&&jf(n,JSON.stringify(s,null,2)+`
|
|
1561
|
-
`,"utf-8"),i}var Bf,
|
|
1561
|
+
`,"utf-8"),i}var Bf,Da=k(()=>{"use strict";J();Bf={yellow:t=>t}});import{existsSync as $a,readdirSync as gb,statSync as Gf}from"node:fs";import{join as Jt}from"node:path";import{createRequire as _b}from"node:module";function Fa(){return Ma===null&&(Ma=_b(import.meta.url)("node:sqlite").DatabaseSync),Ma}function Jf(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Vf(t,e){if(!e)return;t.observed=!0;let r=e.input??0,n=e.output??0,s=e.reasoning??0,i=e.cache?.read??0,o=e.cache?.write??0;if(t.totalInputTokens+=r,t.totalCachedInputTokens+=i,t.totalCacheWriteInputTokens+=o,t.totalOutputTokens+=n,t.totalReasoningOutputTokens+=s,r+n+s+i+o>0){let a=r+i+o;t.lastInputTokens=a,t.lastTokenUsage={inputTokens:r,cachedInputTokens:i,cacheWriteInputTokens:o,outputTokens:n,reasoningOutputTokens:s,totalTokens:a+n+s}}}function Kf(t){return t.observed?{totalInputTokens:t.totalInputTokens,totalCachedInputTokens:t.totalCachedInputTokens,totalCacheWriteInputTokens:t.totalCacheWriteInputTokens,totalOutputTokens:t.totalOutputTokens,totalReasoningOutputTokens:t.totalReasoningOutputTokens,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}:{}}function Yf(){let t=process.env.XDG_DATA_HOME||Jt(W,".local","share"),e=process.env.XDG_CONFIG_HOME||Jt(W,".config");return[Jt(t,"opencode","opencode.db"),Jt(e,"opencode","opencode.db")]}function yb(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let t=process.env.XDG_DATA_HOME||Jt(W,".local","share"),e=Jt(t,"lmplayer"),r=Jt(e,"opencode-local.db"),n=[r];try{let s=gb(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>Jt(e,i)).filter(i=>i!==r).sort((i,o)=>{try{return Gf(o).mtimeMs-Gf(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function Eb(t){return t==="lmplayer"?yb():Yf()}function Pa(t,e){let r=e?.dbPath!==void 0?[e.dbPath]:Yf();for(let n of r){if(!$a(n))continue;let s=new(Fa())(n,{open:!0,readOnly:!0});try{s.exec("PRAGMA busy_timeout = 5000");let i=s.prepare("SELECT directory FROM session WHERE id = ?").get(t);if(i!==void 0)return{directory:typeof i.directory=="string"?i.directory:""}}finally{s.close()}}return null}var Ma,qr,mi=k(()=>{"use strict";ve();J();Ma=null;qr=class{name;startCommand;dbPaths;busyTimeoutMs;constructor(e){this.name=e?.providerName??"opencode",this.startCommand=e?.startCommand??this.name,this.busyTimeoutMs=e?.busyTimeoutMs??5e3,e?.dbPath?this.dbPaths=[e.dbPath]:this.dbPaths=Eb(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>$a(e))}openDb(e){if(!$a(e))return null;let r=new(Fa())(e,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),r}async discoverSessions(){let e=[];for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1562
1562
|
s.time_created, s.time_updated
|
|
1563
1563
|
FROM session s
|
|
1564
1564
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",d=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1565
|
-
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,m,
|
|
1566
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,f,m=Jf();for(let
|
|
1567
|
-
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(
|
|
1565
|
+
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,m,h,_=Jf(),g=[];for(let y of d){let E;try{E=JSON.parse(y.data)}catch{continue}h||(h=E.model?.modelID||E.modelID),(E.role==="user"||E.role==="assistant")&&u++,E.role==="user"&&g.push(y.id),E.role==="assistant"&&Vf(_,E.tokens)}let p=[...g.length>0?[g[0]]:[],...g.length>1?[g[g.length-1]]:[]];for(let y of p){let E=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(y),v=this.extractText(E);v&&(f||(f=P(v,80)),m=P(v,80))}e.push({provider:this.name,sessionId:a.id,slug:a.slug,cwd:c,createdAt:new Date(a.time_created),modifiedAt:new Date(a.time_updated),model:h,startCommand:this.startCommand,firstUserMessage:f,lastUserMessage:m,messageCount:u,filePath:r,...Kf(_)})}}catch(s){L({event:"opencode_discover_sessions_failed",provider:this.name,db_path:r,error_message:s instanceof Error?s.message:String(s)})}finally{n.close()}}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=this.findSessionRow(n,e);if(!s)continue;return this.buildSessionDetail(n,s,r)}catch{}finally{n.close()}}return null}buildSessionDetail(e,r,n){let s=e.prepare("SELECT id, worktree, name FROM project WHERE id = ?").get(r.project_id),i=r.directory||s?.worktree||"(unknown)",o=e.prepare(`SELECT id, session_id, time_created, time_updated, data
|
|
1566
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,f,m=Jf();for(let h of o){let _;try{_=JSON.parse(h.data)}catch{continue}d||(d=_.model?.modelID||_.modelID);let g=_.model?.modelID||_.modelID,p=new Date(_.time?.created||h.time_created),y=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(h.id);if(_.role==="user"){let E=this.extractText(y),v=this.extractText(y,!0);v&&l.push(v),E&&(u||(u=P(E,80)),f=P(E,80)),a.push({role:"user",timestamp:p,content:E||"(empty)"}),c++}else if(_.role==="assistant"){Vf(m,_.tokens);for(let E of y){let v;try{v=JSON.parse(E.data)}catch{continue}v.type==="text"&&v.text?a.push({role:"assistant",timestamp:p,content:v.text,model:g}):v.type==="reasoning"&&v.text?a.push({role:"thinking",timestamp:p,content:v.text}):v.type==="tool"&&v.tool&&(a.push({role:"tool_use",timestamp:p,content:`${v.tool}`,toolName:v.tool,toolCallId:v.callID,toolInput:v.state?.input?JSON.stringify(v.state.input):void 0,toolInputData:Ge(v.state?.input)}),v.state&&(v.state.status==="completed"||v.state.status==="error"||v.state.output!==void 0||v.state.error!==void 0)&&a.push({role:"tool_result",timestamp:p,content:v.state.error??v.state.output??"",toolCallId:v.callID}))}c++}}return{provider:this.name,sessionId:r.id,slug:r.slug,cwd:i,createdAt:new Date(r.time_created),modifiedAt:new Date(r.time_updated),model:d,startCommand:this.startCommand,firstUserMessage:u,lastUserMessage:f,messageCount:c,filePath:n,...Kf(m),messages:a,userPrompts:l}}extractText(e,r=!1){let n=[];for(let s of e){let i;try{i=JSON.parse(s.data)}catch{continue}r&&(i.synthetic===!0||i.ignored===!0)||i.type==="text"&&i.text&&n.push(i.text)}return n.join(`
|
|
1567
|
+
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(Fa())(r,{open:!0});try{let s=this.findSessionRow(n,e);if(!s)continue;return n.prepare("DELETE FROM session WHERE id = ?").run(s.id).changes>0}catch{}finally{n.close()}}return!1}findSessionRow(e,r){let n=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1568
1568
|
s.time_created, s.time_updated
|
|
1569
1569
|
FROM session s WHERE s.id = ?`).get(r);if(n)return n;let s=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1570
1570
|
s.time_created, s.time_updated
|
|
@@ -1572,72 +1572,72 @@ ${r}`:r}function Af(t){let e=t.binaryPath||"codex",r=["app-server","--listen","s
|
|
|
1572
1572
|
WHERE s.id LIKE ?
|
|
1573
1573
|
ORDER BY s.time_updated DESC
|
|
1574
1574
|
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function $n(t){return{id:t.id,onFailure:"non-fatal",applies:e=>t.value(e)!==void 0,run:async e=>{await e.sendRpc("session/set_config_option",{sessionId:e.sessionId,configId:t.configId,value:t.value(e)})},describeFailure:(e,r)=>{let n=t.value(e),s=r instanceof Error?r.message:String(r);return{event:"acp_config_option_failed",fields:{config_id:t.configId,value:n,error_message:s},stderrLine:`[acp] set_config_option(${t.configId}=${n}) failed: ${s}
|
|
1575
|
-
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var
|
|
1575
|
+
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var Ua=k(()=>{"use strict"});import{spawn as Tb}from"node:child_process";import{resolve as zf}from"node:path";function Fn(t){let e;try{e=Tb(t.binaryPath??cr.binary,[...cr.baseArgs],{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:Ee(t.env,t.cwd,void 0,"unknown")})}catch(s){return Promise.resolve({status:"unavailable",reason:"spawn",error:s instanceof Error?s.message:String(s)})}let r=Cn(e,{provider:"opencode"}),n=t.timeoutMs??5e3;return new Promise(s=>{let i=!1,o=(d,u=!0)=>{if(!i){if(i=!0,clearTimeout(c),e.removeListener("error",a),e.removeListener("exit",l),r.close(),!u){s(d);return}ne(e,{softDelayMs:100,killDelayMs:100}).finally(()=>s(d))}},a=d=>{o({status:"unavailable",reason:"spawn",error:d.message},!1)},l=(d,u)=>{o({status:"unavailable",reason:"handshake",error:`opencode ACP exited before verification (code=${String(d)}, signal=${String(u)})`},!1)};e.once("error",a),e.once("exit",l);let c=setTimeout(()=>{o({status:"unavailable",reason:"timeout"})},n);(async()=>{try{await r.sendRpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r.sendNotification("notifications/initialized");let d=await r.sendRpc("session/new",{cwd:t.cwd,mcpServers:[]}),u=Gt(d);try{await r.sendRpc("session/set_config_option",{sessionId:u,configId:"model",value:t.model})}catch(f){o({status:"rejected",option:"model",value:t.model,error:f instanceof Error?f.message:String(f)});return}if(t.effort!==void 0)try{await r.sendRpc("session/set_config_option",{sessionId:u,configId:"effort",value:t.effort})}catch(f){o({status:"rejected",option:"effort",value:t.effort,error:f instanceof Error?f.message:String(f)});return}o({status:"verified"})}catch(d){o({status:"unavailable",reason:"handshake",error:d instanceof Error?d.message:String(d)})}})()})}var cr,ja=k(()=>{"use strict";J();Da();mi();Ln();dt();Nn();La();Ua();cr={name:"opencode",binary:"opencode",baseArgs:["acp"],argv:()=>[...cr.baseArgs],preSpawn(t){try{qf(t.cwd)}catch(e){L({event:"opencode_config_install_failed",cwd:t.cwd,error_message:e instanceof Error?e.message:String(e)})}},sessionSetup:[$n({id:"model",provider:"opencode",configId:"model",value:t=>t.model}),$n({id:"effort",provider:"opencode",configId:"effort",value:t=>t.effort})],probe:Fn,sessionIdentity:{verifyLoadedSession:t=>{let e=Pa(t.requestedSessionId,{...t.env.OPENCODE_DB!==void 0?{dbPath:t.env.OPENCODE_DB}:{}});if(e===null)throw new Error(`opencode bundle: no session "${t.requestedSessionId}" in the opencode session store \u2014 the session must exist on disk before a bundle can resume it`);if(zf(e.directory)!==zf(t.cwd))throw new Error(`opencode bundle: session "${t.requestedSessionId}" belongs to ${e.directory}, not ${t.cwd} \u2014 refusing to resume another workspace's session`)},recheckSession:t=>{if(Pa(t.requestedSessionId,{...t.env.OPENCODE_DB!==void 0?{dbPath:t.env.OPENCODE_DB}:{}})===null)throw new Error(`opencode bundle: session "${t.requestedSessionId}" disappeared from the session store mid-bundle`)}}}});import{existsSync as wb}from"node:fs";import{readdir as vb}from"node:fs/promises";import{join as Ba,resolve as Sb}from"node:path";function Zf(t){let e=bb.exec(t);return e?e[0]:null}function Ib(t){if(!t.includes("notifications/initialized"))return t;let e=t.split(/\r?\n/),r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s.includes("Error handling notification")&&s.includes("notifications/initialized")){let i=[s],o=n;for(;o+1<e.length&&i.length<8&&(o++,i.push(e[o]),e[o].trim()!=="}"););let a=i.join(`
|
|
1576
1576
|
`);if(/\bcode:\s*-32601\b/.test(a)&&/Method not found[^]*notifications\/initialized/.test(a)){n=o;continue}}r.push(s)}return r.join(`
|
|
1577
|
-
`)}async function Qf(t,e){let r=
|
|
1578
|
-
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function jn(t){return
|
|
1577
|
+
`)}async function Qf(t,e){let r=Sb(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??Ba(W,".kimi-code")),n=Ba(r,"sessions"),s;try{s=await vb(n,{withFileTypes:!0})}catch{throw new Error(`kimi bundle: cannot read the kimi session store at ${n} \u2014 cannot verify session "${t}"`)}for(let i of s)if(i.isDirectory()&&wb(Ba(n,i.name,t,"agents","main","wire.jsonl")))return;throw new Error(`kimi bundle: no session "${t}" in the kimi session store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var bb,Wa,Pn,Ha=k(()=>{"use strict";J();ve();Ua();bb=/runtime\s+\S+\s+does not exist in workspace\s+\S+/;Wa=t=>t.permissionMode==="plan"?"plan":"auto";Pn={name:"kimi",binary:"kimi",baseArgs:["acp"],argv:()=>[...Pn.baseArgs],sessionSetup:[{id:"permission-mode",onFailure:"fail-closed",applies:()=>!0,run:async t=>{await t.sendRpc("session/set_config_option",{sessionId:t.sessionId,configId:"mode",value:Wa(t)})},describeFailure:(t,e)=>{let r=Wa(t),n=e instanceof Error?e.message:String(e);return{event:"acp_permission_mode_failed",fields:{config_id:"mode",value:r,error_message:n},message:`Cannot set Kimi ACP permission mode to ${r}: ${n}`}},successLog:t=>`acp: set_config_option(mode=${Wa(t)}) ok`},$n({id:"model",provider:"kimi",configId:"model",value:t=>t.model})],onExitFinalization(t){let e=Zf(t.result);e!==null&&L({event:"kimi_runtime_dead",provider:"kimi",session_id:t.sessionId,matched_text:e})},filterExpectedStderr:Ib,sessionIdentity:{verifyLoadedSession:async t=>{await Qf(t.requestedSessionId,t.env)},recheckSession:async t=>{await Qf(t.requestedSessionId,t.env)}}}});var Un,ep=k(()=>{"use strict";Un={name:"hermes",binary:"hermes",baseArgs:["acp"],argv(t){if(t.permissionMode==="plan")throw new Error('provider "hermes" does not support --permission-mode plan');return[...Un.baseArgs]},preSpawn(t){t.permissionMode==="yolo"&&(t.env.HERMES_YOLO_MODE="1")},modeVocabulary:{known:["default","accept_edits","dont_ask"],selectable:["accept_edits","dont_ask"]},sessionSetup:[{id:"session-mode",onFailure:"fail-closed",applies:t=>t.acpMode!==void 0,run:async t=>{await t.sendRpc("session/set_mode",{sessionId:t.sessionId,modeId:t.acpMode})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_session_mode_failed",fields:{mode_id:t.acpMode,error_message:r},message:`Cannot set hermes ACP session mode to ${String(t.acpMode)}: ${r}`}},successLog:t=>`acp: set_mode(modeId=${String(t.acpMode)}) ok`},{id:"model",onFailure:"fail-closed",applies:t=>{if(t.model===void 0)return!1;let e=t.response.result?.models?.currentModelId;return t.model!==e},run:async t=>{await t.sendRpc("session/set_model",{sessionId:t.sessionId,modelId:t.model})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_config_option_failed",fields:{config_id:"model",value:t.model,error_message:r},stderrLine:`[acp] set_model(modelId=${String(t.model)}) failed: ${r}
|
|
1578
|
+
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function jn(t){return xb[t]}var xb,kb,tp=k(()=>{"use strict";Ff();Uf();ja();Ha();ep();xb={gemini:On,copilot:Dn,opencode:cr,kimi:Pn,hermes:Un};kb={gemini:{binary:On.binary,args:On.baseArgs},copilot:{binary:Dn.binary,args:Dn.baseArgs},opencode:{binary:cr.binary,args:cr.baseArgs},kimi:{binary:Pn.binary,args:Pn.baseArgs},hermes:{binary:Un.binary,args:Un.baseArgs}}});import{spawn as rp}from"node:child_process";import{existsSync as Ab}from"node:fs";function np(t,e){let r=jn(t)?.modeVocabulary;if(!r)throw new Z(`ACP mode "${e}" requested for provider "${t}", which declares no ACP mode vocabulary. Add the provider's mode ids to its AcpProviderProfile modeVocabulary before setting a mode.`);if(!r.known.includes(e))throw new Z(`provider "${t}" has no ACP mode "${e}" (known: ${r.known.join(", ")}).`);if(!r.selectable.includes(e))throw new Z(`provider "${t}" ACP mode "${e}" is not selectable by lmctl (selectable: ${r.selectable.join(", ")}).`)}function Rb(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1579
1579
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1580
1580
|
${e}
|
|
1581
1581
|
|
|
1582
|
-
${r}`:r}function
|
|
1583
|
-
`),L({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let d=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=Gt(d),s.setSessionId(o),{sessionId:o,sessionResponse:d}}if(i){let c=Gt(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=Gt(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=Gt(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function lp(t,e){let r=jn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{np(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:w=>{o.push(w)}}},l,c,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=op(r,e,a))}catch(w){return s(w instanceof Error?w:new Error(String(w)))}let u=rp(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),m=!1,g=!1,h=0,_=!1,p=!1;if(e.signal){if(e.signal.aborted)return m=!0,L({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ne(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{m=!0,L({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),ne(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let y=e.sessionId||"",T=li({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});T.setSessionId(y);let v=Cn(u,{provider:e.tool,onEvent:w=>{h=Date.now(),sp(w)&&(p=!0),e.onEvent?.(w)},onNotification:w=>{h=Date.now(),T.processMessage(w)}}),{sendRpc:S,sendNotification:E}=v,b="";u.stderr?.on("data",w=>{b+=w.toString()}),u.on("error",w=>{v.close(w),L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:w.message,elapsed_ms:Date.now()-f}),s(new Z(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${w.message}`,{cause:w}))}),u.on("exit",w=>{if(g=!0,v.close(new Z(`ACP process exited with code ${String(w)}`)),m)return;let x=T.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:w}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-f,stopReason:x.stopReason,exitCode:w,...o.length>0?{warnings:o}:{}});else{let I=kb(e.tool,b);L({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:w,stderr_tail:I.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(xb({tool:e.tool,exitCode:w,stderr:I})))}}),(async()=>{try{let w=await ap({sendRpc:S,sendNotification:E,opts:e,outputProcessor:T});y=w.sessionId;let x=w.sessionResponse;await ip(r,a,{sessionId:y,response:x},S),T.beginTurn(),_=!0,ye(`acp: prompt sent (${t.length} chars)`);let I=await S("session/prompt",{sessionId:y,prompt:[{type:"text",text:t}]}),R=T.completeTurn(I);_=!1,ye(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),Xt(e.holdOpen,{isAborted:()=>m,hasChildExited:()=>g,isTurnInFlight:()=>_,lastEventAtMs:()=>h,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>p})}catch(w){ne(u).catch(()=>{}),s(w instanceof Error?w:new Error(String(w)))}})()})}async function cp(t){let e=jn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&np(t.tool,t.acpMode);let r=t.permissionMode??"yolo",n=[],s=!0,i={permissionMode:r,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:w=>{n.push(w)}}},{binary:o,spawnArgs:a,spawnEnv:l}=op(e,t,i),c=rp(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),d=Date.now(),u={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},f=t.sessionId||"",m=null,g="";c.stderr?.on("data",w=>{g+=w.toString()});let h,_,p=li({tool:t.tool,onDelta:w=>h?.(w),...e.isolateResult?{isolateResult:e.isolateResult}:{}});p.setSessionId(f);let y=Cn(c,{provider:t.tool,onEvent:w=>{u.lastEventAtMs=Date.now(),sp(w)&&(u.backgroundJobLaunched=!0),_?.(w)},onNotification:w=>{u.lastEventAtMs=Date.now(),p.processMessage(w)}}),T=()=>new Error(`ACP bundle process (${t.tool}) exited${u.exitCode!==null?` with code ${u.exitCode}`:""} after ${u.completedTurns} completed prompt(s); the bundle cannot continue`),v=[],S=()=>u.exited?Promise.resolve():new Promise(w=>{v.push(w)}),E=null;c.on("error",w=>{m=new Z(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${w.message}`,{cause:w}),L({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:w.message,elapsed_ms:Date.now()-d}),y.close(w)}),c.on("exit",w=>{if(u.exited=!0,u.exitCode=w,y.close(new Z(`ACP process exited with code ${String(w)}`)),!u.telemetryFired){u.telemetryFired=!0;let x=p.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:w})}if(E!==null){let x=E;E=null,x(T())}for(let x of v.splice(0))x()});try{let w=await ap({sendRpc:y.sendRpc,sendNotification:y.sendNotification,opts:t,outputProcessor:p,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});f=w.sessionId,await ip(e,i,{sessionId:w.sessionId,response:w.sessionResponse},y.sendRpc)}catch(w){let x=m??(w instanceof Error?w:new Error(String(w)));throw ne(c).catch(()=>{}),x}let b=w=>new Promise(x=>{setTimeout(x,w).unref?.()});return{tool:t.tool,get sessionId(){return f},get completedTurns(){return u.completedTurns},async sendTurn(w,x={}){if(u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw T();if(u.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:f,cwd:t.cwd,env:l}),u.exited)throw T();if(x.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,h=x.onDelta,_=x.onEvent;let I=Date.now();try{p.beginTurn(),ye(`acp: bundle prompt sent (${w.length} chars)`);let R=await new Promise((re,ee)=>{E=ee;let xe=()=>{p.cancelTurn(),y.sendNotification("session/cancel",{sessionId:f}),ee(new Error("Aborted"))},be=x.signal;be?.addEventListener("abort",xe,{once:!0}),y.sendRpc("session/prompt",{sessionId:f,prompt:[{type:"text",text:w}]}).then(q=>{be?.removeEventListener("abort",xe),re(q)},q=>{be?.removeEventListener("abort",xe),ee(q instanceof Error?q:new Error(String(q)))})});E=null;let N=p.completeTurn(R);u.turnInFlight=!1,u.completedTurns+=1,ye(`acp: bundle result received (${N.result.length} chars, stopReason=${N.stopReason})`);let U=s&&n.length>0?[...n]:void 0;return s=!1,{result:N.result,sessionId:N.sessionId,stopReason:N.stopReason,durationMs:Date.now()-I,...U!==void 0?{warnings:U}:{}}}catch(R){throw E=null,p.cancelTurn(),u.turnInFlight=!1,u.exited?T():R}finally{h=void 0,_=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(x=>{Xt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let w=t.closeTimeoutMs??2e3;await Promise.race([S(),b(w)]),u.exited||await ne(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,w),killDelayMs:Math.min(1e3,w)}).catch(()=>{})})()),u.closing}}}var Ha=k(()=>{"use strict";J();lr();Nn();Qs();vt();J();dt();Ln();Na();tp();Wa();Ua();Ln()});function oe(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function up(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=Ab){let n=t.keys().next().value;n!==void 0&&t.delete(n)}t.set(r.id,Date.now()),e(r);return}if(r.kind==="tool_result"&&typeof r.id=="string"&&r.elapsedMs===void 0){let n=t.get(r.id);if(n!==void 0){e({...r,elapsedMs:Date.now()-n}),t.delete(r.id);return}}e(r)}}function Rb(){let t=new Map;return(e,r)=>{Nb(e,up(t,r))}}function Nb(t,e){let r=t.type;if(r==="system"){let n=t.subtype;if(n==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(oe(a,60));let d=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:d});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(oe(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:n||"system",raw:t});return}if(r==="assistant"||r==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:oe(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,d="";c&&(typeof c.command=="string"?d=c.command:typeof c.file_path=="string"?d=c.file_path:typeof c.path=="string"?d=c.path:typeof c.pattern=="string"?d=c.pattern:typeof c.url=="string"?d=c.url:d=oe(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:oe(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:oe(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,d,u=i.content;if(typeof u=="string")d=`${u.split(`
|
|
1582
|
+
${r}`:r}function Nb(t,e){return jn(t)?.filterExpectedStderr?.(e)??e}function sp(t){if(t.method!=="session/update")return!1;let r=t.params?.update;if(r===void 0)return!1;let n=r.sessionUpdate;if(n!=="tool_call"&&n!=="tool_call_update")return!1;let s=r.status;return s!==void 0&&s!=="pending"&&s!=="in_progress"?!1:r.rawInput?.background===!0}async function ip(t,e,r,n){for(let s of t.sessionSetup??[]){let i={...e,sessionId:r.sessionId,response:r.response,sendRpc:n};if(s.applies(i))try{await s.run(i),s.successLog&&ye(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(L({event:a.event,provider:t.name,...a.fields}),a.stderrLine&&process.stderr.write(a.stderrLine),a.warning&&e.warnings.push(a.warning),s.onFailure==="fail-closed")throw new Error(a.message)}}}function op(t,e,r){let n=Ee(e.env,e.cwd,e.sessionId);t.preSpawn?.({...r,cwd:e.cwd,env:n});let s=e.binaryPath||t.binary,i=t.argv(r),o=t.yoloAssertion==="always-yolo"?"yolo":r.permissionMode;if(Se(e.tool,i,o),e.cwd&&!Ab(e.cwd))throw L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new Z(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function ap(t){let{sendRpc:e,sendNotification:r,opts:n,outputProcessor:s}=t,i=t.strictSessionIdentity===!0;await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r("notifications/initialized");let o=n.sessionId||"",a;if(n.sessionId){let l;try{l=await e("session/load",{sessionId:n.sessionId,cwd:n.cwd,mcpServers:[]})}catch(c){if(i||n.requireResume)throw new Error(`Cannot resume session ${n.sessionId} via ACP: ${c instanceof Error?c.message:String(c)}`);process.stderr.write(`[acp] session/load failed for ${n.sessionId}, creating new session
|
|
1583
|
+
`),L({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let d=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=Gt(d),s.setSessionId(o),{sessionId:o,sessionResponse:d}}if(i){let c=Gt(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=Gt(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=Gt(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function lp(t,e){let r=jn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{np(e.tool,e.acpMode)}catch(n){return Promise.reject(n)}return new Promise((n,s)=>{let i=e.permissionMode??"yolo",o=[],a={permissionMode:i,...e.model!==void 0?{model:e.model}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.acpMode!==void 0?{acpMode:e.acpMode}:{},purpose:"chat",warnings:{push:w=>{o.push(w)}}},l,c,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=op(r,e,a))}catch(w){return s(w instanceof Error?w:new Error(String(w)))}let u=rp(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),m=!1,h=!1,_=0,g=!1,p=!1;if(e.signal){if(e.signal.aborted)return m=!0,L({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ne(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{m=!0,L({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),ne(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let y=e.sessionId||"",E=di({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});E.setSessionId(y);let v=Cn(u,{provider:e.tool,onEvent:w=>{_=Date.now(),sp(w)&&(p=!0),e.onEvent?.(w)},onNotification:w=>{_=Date.now(),E.processMessage(w)}}),{sendRpc:b,sendNotification:T}=v,S="";u.stderr?.on("data",w=>{S+=w.toString()}),u.on("error",w=>{v.close(w),L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:w.message,elapsed_ms:Date.now()-f}),s(new Z(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${w.message}`,{cause:w}))}),u.on("exit",w=>{if(h=!0,v.close(new Z(`ACP process exited with code ${String(w)}`)),m)return;let x=E.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:w}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-f,stopReason:x.stopReason,exitCode:w,...o.length>0?{warnings:o}:{}});else{let I=Nb(e.tool,S);L({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:w,stderr_tail:I.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(Rb({tool:e.tool,exitCode:w,stderr:I})))}}),(async()=>{try{let w=await ap({sendRpc:b,sendNotification:T,opts:e,outputProcessor:E});y=w.sessionId;let x=w.sessionResponse;await ip(r,a,{sessionId:y,response:x},b),E.beginTurn(),g=!0,ye(`acp: prompt sent (${t.length} chars)`);let I=await b("session/prompt",{sessionId:y,prompt:[{type:"text",text:t}]}),R=E.completeTurn(I);g=!1,ye(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),Xt(e.holdOpen,{isAborted:()=>m,hasChildExited:()=>h,isTurnInFlight:()=>g,lastEventAtMs:()=>_,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>p})}catch(w){ne(u).catch(()=>{}),s(w instanceof Error?w:new Error(String(w)))}})()})}async function cp(t){let e=jn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&np(t.tool,t.acpMode);let r=t.permissionMode??"yolo",n=[],s=!0,i={permissionMode:r,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:w=>{n.push(w)}}},{binary:o,spawnArgs:a,spawnEnv:l}=op(e,t,i),c=rp(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),d=Date.now(),u={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},f=t.sessionId||"",m=null,h="";c.stderr?.on("data",w=>{h+=w.toString()});let _,g,p=di({tool:t.tool,onDelta:w=>_?.(w),...e.isolateResult?{isolateResult:e.isolateResult}:{}});p.setSessionId(f);let y=Cn(c,{provider:t.tool,onEvent:w=>{u.lastEventAtMs=Date.now(),sp(w)&&(u.backgroundJobLaunched=!0),g?.(w)},onNotification:w=>{u.lastEventAtMs=Date.now(),p.processMessage(w)}}),E=()=>new Error(`ACP bundle process (${t.tool}) exited${u.exitCode!==null?` with code ${u.exitCode}`:""} after ${u.completedTurns} completed prompt(s); the bundle cannot continue`),v=[],b=()=>u.exited?Promise.resolve():new Promise(w=>{v.push(w)}),T=null;c.on("error",w=>{m=new Z(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${w.message}`,{cause:w}),L({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:w.message,elapsed_ms:Date.now()-d}),y.close(w)}),c.on("exit",w=>{if(u.exited=!0,u.exitCode=w,y.close(new Z(`ACP process exited with code ${String(w)}`)),!u.telemetryFired){u.telemetryFired=!0;let x=p.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:w})}if(T!==null){let x=T;T=null,x(E())}for(let x of v.splice(0))x()});try{let w=await ap({sendRpc:y.sendRpc,sendNotification:y.sendNotification,opts:t,outputProcessor:p,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});f=w.sessionId,await ip(e,i,{sessionId:w.sessionId,response:w.sessionResponse},y.sendRpc)}catch(w){let x=m??(w instanceof Error?w:new Error(String(w)));throw ne(c).catch(()=>{}),x}let S=w=>new Promise(x=>{setTimeout(x,w).unref?.()});return{tool:t.tool,get sessionId(){return f},get completedTurns(){return u.completedTurns},async sendTurn(w,x={}){if(u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw E();if(u.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:f,cwd:t.cwd,env:l}),u.exited)throw E();if(x.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,_=x.onDelta,g=x.onEvent;let I=Date.now();try{p.beginTurn(),ye(`acp: bundle prompt sent (${w.length} chars)`);let R=await new Promise((re,ee)=>{T=ee;let xe=()=>{p.cancelTurn(),y.sendNotification("session/cancel",{sessionId:f}),ee(new Error("Aborted"))},be=x.signal;be?.addEventListener("abort",xe,{once:!0}),y.sendRpc("session/prompt",{sessionId:f,prompt:[{type:"text",text:w}]}).then(q=>{be?.removeEventListener("abort",xe),re(q)},q=>{be?.removeEventListener("abort",xe),ee(q instanceof Error?q:new Error(String(q)))})});T=null;let N=p.completeTurn(R);u.turnInFlight=!1,u.completedTurns+=1,ye(`acp: bundle result received (${N.result.length} chars, stopReason=${N.stopReason})`);let U=s&&n.length>0?[...n]:void 0;return s=!1,{result:N.result,sessionId:N.sessionId,stopReason:N.stopReason,durationMs:Date.now()-I,...U!==void 0?{warnings:U}:{}}}catch(R){throw T=null,p.cancelTurn(),u.turnInFlight=!1,u.exited?E():R}finally{_=void 0,g=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(x=>{Xt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let w=t.closeTimeoutMs??2e3;await Promise.race([b(),S(w)]),u.exited||await ne(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,w),killDelayMs:Math.min(1e3,w)}).catch(()=>{})})()),u.closing}}}var Xa=k(()=>{"use strict";J();lr();Nn();ei();vt();J();dt();Ln();La();tp();Ha();ja();Ln()});function oe(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function up(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=Lb){let n=t.keys().next().value;n!==void 0&&t.delete(n)}t.set(r.id,Date.now()),e(r);return}if(r.kind==="tool_result"&&typeof r.id=="string"&&r.elapsedMs===void 0){let n=t.get(r.id);if(n!==void 0){e({...r,elapsedMs:Date.now()-n}),t.delete(r.id);return}}e(r)}}function Cb(){let t=new Map;return(e,r)=>{Ob(e,up(t,r))}}function Ob(t,e){let r=t.type;if(r==="system"){let n=t.subtype;if(n==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(oe(a,60));let d=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:d});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(oe(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:n||"system",raw:t});return}if(r==="assistant"||r==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:oe(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,d="";c&&(typeof c.command=="string"?d=c.command:typeof c.file_path=="string"?d=c.file_path:typeof c.path=="string"?d=c.path:typeof c.pattern=="string"?d=c.pattern:typeof c.url=="string"?d=c.url:d=oe(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:oe(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:oe(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,d,u=i.content;if(typeof u=="string")d=`${u.split(`
|
|
1584
1584
|
`).length} lines, ${u.length} chars`;else if(Array.isArray(u)){let f=u.map(m=>typeof m=="object"&&m&&"text"in m?m.text:"").filter(Boolean).join("");f&&(d=`${f.split(`
|
|
1585
|
-
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:d,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function
|
|
1585
|
+
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:d,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function fi(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?Cb():void 0;if(e.bundleSession!==void 0){let i=e.bundleSession;if(i.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${i.provider}", turn targets "${r}"`);let o=await i.sendTurn(t,{onDelta:e.onDelta,onEvent:n?a=>n(a,e.onProgress):void 0,signal:e.signal});return{text:o.text,sessionId:o.sessionId,durationMs:o.durationMs,...o.warnings!==void 0&&o.warnings.length>0?{warnings:o.warnings}:{}}}let s=await wf(t,{sessionId:e.sessionId,cwd:e.cwd,env:e.env,tool:r,binaryPath:e.progPath,model:e.model,permissionMode:e.permissionMode,onText:e.onDelta,onEvent:n?i=>n(i,e.onProgress):void 0,signal:e.signal,holdOpen:e.holdOpen});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,numTurns:s.numTurns,...s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{}}}async function pi(t){let e=t.binary==="qwen"?"qwen":"claude",r=await vf({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s={}){let i=await r.sendTurn(n,{onText:s.onDelta,onEvent:s.onEvent,signal:s.signal});return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>r.close()}}function Db(){let t=new Map;return(e,r)=>{Mb(e,up(t,r))}}function Mb(t,e){if(t.method!=="session/update")return;let s=t.params?.update;if(!s)return;let i=s.sessionUpdate;if(i){if(i==="agent_message_chunk"){let a=s.content?.text||"";a&&e({kind:"text",summary:oe(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:oe(a)});return}if(i==="tool_call"){let o=s.title||s.kind||"tool",a=typeof s.toolCallId=="string"?s.toolCallId:void 0,l="",c=s.rawInput;c&&(typeof c.command=="string"?l=c.command:typeof c.file_path=="string"?l=c.file_path:typeof c.path=="string"?l=c.path:l=oe(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:oe(l),id:a});return}if(i==="tool_call_update"){let o=s.status||"",a=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(o==="completed"||o==="failed")e({kind:"tool_result",summary:o,status:o==="failed"?"error":"ok",id:a});else if(o==="in_progress"){let l=s.content,c=typeof l=="string"?l:typeof l?.text=="string"?l.text:"",d=c?`running\u2026 ${oe(c,80)}`:"running\u2026";e({kind:"other",summary:d,id:a})}return}e({kind:"other",summary:i})}}async function ut(t,e){let r=e.acpTool||e.binary,n=e.onProgress?Db():void 0;if(e.bundleSession!==void 0){let a=e.bundleSession;if(a.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${a.provider}", turn targets "${r}"`);let l=await a.sendTurn(t,{onDelta:e.onDelta,onEvent:n?c=>n(c,e.onProgress):void 0,signal:e.signal});return{text:l.text,sessionId:l.sessionId,durationMs:l.durationMs,stopReason:l.stopReason,...l.warnings!==void 0?{warnings:l.warnings}:{}}}let s=[];if(e.model&&r==="copilot"){let a="copilot --acp does not implement per-session model selection";we({event:"model_ignored",provider:r,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await lp(t,{tool:r,sessionId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,effort:e.effort,alias:e.alias,permissionMode:e.permissionMode,acpMode:e.acpMode,requireResume:e.requireResume,onDelta:e.onDelta,onEvent:n?a=>n(a,e.onProgress):void 0,signal:e.signal,holdOpen:e.holdOpen}),o=[...s,...i.warnings??[]];return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...o.length>0?{warnings:o}:{}}}async function mt(t){let e=t.acpTool||t.binary,r=await cp({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,effort:t.effort,alias:t.alias,permissionMode:t.permissionMode,acpMode:t.acpMode,requireResume:!0,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s){let i=await r.sendTurn(n,s);return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>r.close()}}function dp(t,e){let r=t.method;if(!r)return;let n=t.params;if(r==="turn/started"){e({kind:"system",summary:"turn started"});return}if(r==="turn/completed"){e({kind:"system",summary:"turn completed"});return}if(r==="error"){let s=n?.error,i=typeof s?.message=="string"?s.message:void 0,o=i&&i.length>0?i:"(no message)",a=n?.willRetry===!0;e(a?{kind:"api_retry",summary:`codex retry: ${oe(o,120)}`}:{kind:"other",summary:`codex error: ${oe(o,120)}`});return}if(r==="item/started"||r==="item/completed"){let s=n?.item;if(!s)return;let i=s.type,o=r==="item/started";switch(i){case"commandExecution":{let a=typeof s.id=="string"?s.id:void 0,l=s.command,c=Array.isArray(l)?l.join(" "):typeof l=="string"?l:"";if(o)e({kind:"tool_use",tool:"Bash",summary:oe(c||"(command)"),id:a});else{let d=s.exitCode,u=s.status||"",f=typeof s.durationMs=="number"?s.durationMs:void 0,m=typeof d=="number"?`exit ${d}`:u||"done",h=[];typeof d=="number"?h.push(`exit ${d}`):u&&h.push(u),typeof f=="number"&&h.push(`${Math.round(f/1e3)}s`),e({kind:"tool_result",summary:h.join(", ")||"done",status:m,elapsedMs:f,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(o){let l=s.changes,c=Array.isArray(l)?l.map(d=>d.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:oe(c||"(edit)"),id:a})}else{let l=s.status||"done";e({kind:"tool_result",summary:l,status:l,id:a})}return}case"mcpToolCall":{let a=typeof s.id=="string"?s.id:void 0,l=s.server||"mcp",c=s.tool||"tool";if(o)e({kind:"tool_use",tool:`${l}/${c}`,summary:"",id:a});else{let d=s.status||"done";e({kind:"tool_result",summary:d,status:d,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary:oe(s.query||""),id:a}:{kind:"tool_result",summary:"done",status:"done",id:a});return}case"reasoning":{o&&e({kind:"thinking",summary:""});return}case"agentMessage":case"userMessage":return;default:{i&&e({kind:o?"tool_use":"tool_result",tool:i,summary:""});return}}}if(r==="item/agentMessage/delta"){let s=n?.delta||"";if(s){let i=typeof n?._lmctlItemPhase=="string"?n._lmctlItemPhase:void 0;e(i==="commentary"?{kind:"thinking",summary:oe(s)}:{kind:"text",summary:oe(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:oe(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
1586
1586
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${oe(o,60)}`:oe(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r==="item/commandExecution/terminalInteraction"||r==="item/commandExecution/outputChunk"||r==="item/commandExecution/output"){let s=(typeof n?.stdin=="string"?n.stdin:"")||(typeof n?.delta=="string"?n.delta:"")||(typeof n?.output=="string"?n.output:"")||(typeof n?.text=="string"?n.text:"")||(typeof n?.content=="string"?n.content:"")||(typeof n?.chunk=="string"?n.chunk:"")||"";if(s){let i=s.split(`
|
|
1587
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${oe(o,60)}`:oe(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r.startsWith("item/")){e({kind:"other",summary:r.slice(5)});return}}async function mp(t,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>dp(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await Rf(t,{threadId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?n=>dp(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function fp(t){let e=await Nf({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var
|
|
1588
|
-
`);try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1589
|
-
`);w.includes("user.text")&&x&&(!
|
|
1590
|
-
`);w.trim()&&Wn(s,
|
|
1591
|
-
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:mp})}openSession(e){return fp({...e,model:e.model??
|
|
1592
|
-
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let d=c;if(typeof d.id=="string"){let u=o.get(d.id);u?
|
|
1587
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${oe(o,60)}`:oe(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r.startsWith("item/")){e({kind:"other",summary:r.slice(5)});return}}async function mp(t,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>dp(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await Rf(t,{threadId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?n=>dp(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function fp(t){let e=await Nf({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var Lb,St=k(()=>{"use strict";ka();ka();Lf();Xa();J();Lb=256});import{join as pp}from"node:path";function Ga(t){return new qa(t)}var qa,Ja=k(()=>{"use strict";ef();je();ve();St();$e();qa=class extends Q{claudeDir;constructor(e){super({provider:new Vs(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",G,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:fi}),this.claudeDir=e?.claudeDir??pp(W,".claude")}openSession(e){return pi({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[pp(this.claudeDir,"projects")]})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as $b,stat as hp,unlink as Fb}from"node:fs/promises";import{join as Bn,basename as Pb}from"node:path";function Ub(t,e,r){return`${t}|${e.toISOString()}|${r}`}function Wn(t,e,r){let n=Ub(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function gp(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function jb(t){if(!t)return;let e=t.cached_input_tokens??t.cache_read_input_tokens;return{inputTokens:t.input_tokens,cachedInputTokens:e,outputTokens:t.output_tokens,reasoningOutputTokens:t.reasoning_output_tokens,totalTokens:t.total_tokens}}function Gr(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return t.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){let n=r;if(typeof n.text=="string")return n.text;if(typeof n.image_url=="string")return"[input_image]";if(typeof n.type=="string")return`[${n.type}]`}return Gr(r)}).filter(r=>r.length>0).join(`
|
|
1588
|
+
`);try{return JSON.stringify(t)}catch{return String(t)}}function Bb(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch{return}return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Wb(t,e){if(e===void 0)return;let r={input:e};if(t!=="apply_patch"||typeof e!="string")return r;let n=[...e.matchAll(/^\*\*\* (?:(Add|Update|Delete) File|(Move) to): (.+)\r?$/gm)].map(s=>({kind:s[1]??s[2],path:s[3]?.trim()})).filter(s=>!!(s.kind&&s.path));return n.length>0&&(r.path=n[0].path,r.paths=n.map(s=>s.path),r.kinds=n.map(s=>s.kind)),r}async function _p(t){let e=0,r=0,n=0,s=0,i=0,o,a,l;for await(let c of le(t)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let d=c.payload.message||c.payload.text;d&&(l=P(d.trim(),80))}if(c.type==="response_item"&&c.payload){let d=c.payload;if(d.type==="message"&&d.role==="user"&&d.content)for(let u of d.content)u.type==="input_text"&&typeof u.text=="string"&&u.text&&(e++,l=P(u.text.trim(),80));else if(d.type==="message"&&d.role==="assistant"&&d.content)for(let u of d.content)u.type==="output_text"&&typeof u.text=="string"&&u.text&&e++}if(c.payload&&typeof c.payload.model_context_window=="number"&&(a=c.payload.model_context_window),c.type==="event_msg"&&c.payload?.type==="token_count"&&c.payload.info?.total_token_usage){let d=c.payload.info.total_token_usage;r=d.input_tokens??r,n=d.cached_input_tokens??d.cache_read_input_tokens??n,s=d.output_tokens??s,i=d.reasoning_output_tokens??i;let u=jb(c.payload.info.last_token_usage);u&&(o=u),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:r,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var hi,yp=k(()=>{"use strict";ve();hi=class{name="codex";codexDirs;constructor(e={}){let r=[Bn(W,".codex"),Bn(W,".code")];if(e.codexDirs&&e.codexDirs.length>0){this.codexDirs=[...new Set(e.codexDirs)];return}let n=[e.codexDir||r[0],e.codeDir||r[1]];this.codexDirs=[...new Set(n)]}getWatchPaths(){return this.codexDirs.map(e=>({directory:Bn(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=Bn(r,"sessions");try{await hp(n),e.push(n)}catch{}}return e}async discoverSessions(){let e=[],r=await this.getSessionsDirs();for(let n of r){let s=await this.findSessionFiles(n);for(let i of s)try{let o=await this.extractSummary(i);o&&e.push(o)}catch{}}return e}async findSessionFiles(e){let r=[],n;try{n=await $b(e)}catch{return r}for(let s of n){let i=Bn(e,s),o=await hp(i).catch(()=>null);if(o)if(o.isDirectory()){let a=await this.findSessionFiles(i);r.push(...a)}else s.endsWith(".jsonl")&&r.push(i)}return r}extractSessionIdFromFilename(e){let r=Pb(e,".jsonl"),n=r.match(/rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async extractSummary(e){let r=await Ue(e,30),n=await ce(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,d,u,f;for(let h of r){if(h.type==="session_meta"&&h.payload&&(h.payload.id&&(s=h.payload.id),h.payload.cwd&&(i=h.payload.cwd),h.payload.cli_version&&(o=h.payload.cli_version),h.payload.timestamp&&(l=new Date(h.payload.timestamp)),h.payload.originator&&(u=h.payload.originator),h.payload.source&&(f=h.payload.source)),h.type==="turn_context"&&h.payload&&(h.payload.model&&(a=h.payload.model),!i&&h.payload.cwd&&(i=h.payload.cwd)),h.type==="event_msg"&&h.payload?.type==="user_message"){let _=h.payload.message||h.payload.text;_&&(c||(c=P(_.trim(),80)),d=P(_.trim(),80))}if(h.type==="response_item"&&h.payload?.type==="message"&&h.payload.role==="user"&&h.payload.content){let _=h.payload.content.find(g=>g.type==="input_text"&&typeof g.text=="string"&&g.text);typeof _?.text=="string"&&(c||(c=P(_.text.trim(),80)),d=P(_.text.trim(),80))}}if(!i)return null;let m=await _p(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:gp(u,f),firstUserMessage:c,lastUserMessage:m.lastUserMessage??d,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:m.lastTokenUsage,modelContextWindow:m.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await ce(r),s=[],i="",o,a,l,c,d,u=e,f,m,h=new Set,_=[],g=new Set,p=[],y=(b,T)=>{let S=p.find(w=>!w.mirrored&&w.source!==T&&w.text===b);S?S.mirrored=!0:p.push({text:b,source:T,mirrored:!1})},E=()=>{_.push(...p.map(b=>b.text)),p=[]};for await(let b of le(r)){let T=b.timestamp?new Date(b.timestamp):new Date;if(b.type==="session_meta"&&b.payload){b.payload.id&&(u=b.payload.id),b.payload.cwd&&(i=b.payload.cwd),b.payload.cli_version&&(o=b.payload.cli_version),b.payload.timestamp&&(l=new Date(b.payload.timestamp)),f=gp(b.payload.originator,b.payload.source);continue}if(b.type==="turn_context"&&b.payload){b.payload.model&&(a=b.payload.model),!i&&b.payload.cwd&&(i=b.payload.cwd);continue}if(b.type==="response_item"&&b.payload){let S=b.payload;if(S.type==="message"){if(S.role==="user"&&S.content){let w=S.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(w)){let x=S.content.filter((I,R)=>w[R]==="user.text"&&typeof I.text=="string").map(I=>I.text).join(`
|
|
1589
|
+
`);w.includes("user.text")&&x&&(!S.id||!g.has(S.id))&&(y(x,"metadata"),S.id&&g.add(S.id))}for(let x of S.content)if(x.type==="input_text"&&typeof x.text=="string"&&x.text){let I=x.text.trim();c||(c=P(I,80)),d=P(I,80),Wn(s,h,{role:"user",timestamp:T,content:z(I)})}continue}if(S.role==="assistant"&&S.content){for(let w of S.content)w.type==="output_text"&&typeof w.text=="string"&&w.text&&Wn(s,h,{role:"assistant",timestamp:T,content:z(w.text),model:a});continue}if(S.role!=="user"&&S.role!=="assistant"&&S.content){for(let w of S.content)(w.type==="input_text"||w.type==="output_text")&&typeof w.text=="string"&&w.text&&Wn(s,h,{role:"system",timestamp:T,content:z(w.text.trim())});continue}}if(S.type==="function_call"){s.push({role:"tool_use",timestamp:T,content:S.name||"unknown tool",toolName:S.name,toolInput:S.arguments!==void 0?z(Gr(S.arguments)):void 0,toolInputData:Bb(S.arguments),toolCallId:S.call_id});continue}if(S.type==="function_call_output"){s.push({role:"tool_result",timestamp:T,content:z(Gr(S.output)),toolCallId:S.call_id});continue}if(S.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:T,content:S.name||"unknown tool",toolName:S.name,toolInput:S.input!==void 0?z(Gr(S.input)):void 0,toolInputData:Wb(S.name,S.input),toolCallId:S.call_id});continue}if(S.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:T,content:z(Gr(S.output)),toolCallId:S.call_id});continue}if(S.type==="reasoning"&&S.summary){let w=S.summary.map(x=>Gr(x.text)).join(`
|
|
1590
|
+
`);w.trim()&&Wn(s,h,{role:"thinking",timestamp:T,content:z(w)});continue}}if(b.type==="event_msg"&&b.payload&&(b.payload.type==="task_started"?(E(),m="in_progress"):b.payload.type==="task_complete"?m="complete":b.payload.type==="turn_aborted"&&(m="aborted"),b.payload.type==="user_message"&&typeof b.payload.message=="string"&&y(b.payload.message,"event"),b.payload.type==="agent_reasoning")){let S=b.payload.message||b.payload.text;S&&Wn(s,h,{role:"thinking",timestamp:T,content:z(S)})}}if(!i)return null;E();let v=await _p(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,turnStatus:m,firstUserMessage:c,lastUserMessage:d,messageCount:v.messageCount,filePath:r,totalInputTokens:v.totalInputTokens||void 0,totalCachedInputTokens:v.totalCachedInputTokens||void 0,totalOutputTokens:v.totalOutputTokens||void 0,totalReasoningOutputTokens:v.totalReasoningOutputTokens||void 0,lastInputTokens:v.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:v.lastTokenUsage,modelContextWindow:v.modelContextWindow,messages:s,userPrompts:_}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Fb(r),!0):!1}async resolveSessionFile(e){let r=await this.getSessionsDirs(),n=[];for(let i of r){let o=await this.findSessionFiles(i);n.push(...o)}for(let i of n)if(this.extractSessionIdFromFilename(i)===e)return i;let s=[];for(let i of n)this.extractSessionIdFromFilename(i).startsWith(e)&&s.push(i);if(s.length===1)return s[0];for(let i of n){let o=await Ue(i,1);if(o.length>0&&o[0].type==="session_meta"){let a=o[0].payload?.id;if(a===e||a&&a.startsWith(e))return i}}return null}}});function Ya(t){return new Ka(t)}var Va,Ka,za=k(()=>{"use strict";yp();je();St();$e();Va="gpt-5.6-sol",Ka=class extends Q{constructor(e){super({provider:new hi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append"},binary:"codex",seedArgs:["exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","-"],seedStdin:`${G}
|
|
1591
|
+
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:mp})}openSession(e){return fp({...e,model:e.model??Va})}seedArgsFor(e){let r=super.seedArgsFor(e),n=e?.model??Va;return[...r.slice(0,-1),"--model",n,r[r.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Va}}}});function Hn(t){if(!t.trim())return"unknown";let e=t.split(/\r?\n/).filter(n=>n.trim().length>0);if(e.length>1)try{let n=JSON.parse(e[0]);if(n!==null&&typeof n=="object"&&!Array.isArray(n)&&"kind"in n)return"jsonl"}catch{}let r;try{r=JSON.parse(t)}catch{return"unknown"}if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let n=r;if(Array.isArray(n.messages))return"json";if("kind"in n)return"jsonl"}return"unknown"}function gi(t){let e=Hn(t);if(e==="unknown")throw new Error("gemini session content matches neither known format (old .json with messages[] or new .jsonl with kind metadata)");if(e==="json"){let a=JSON.parse(t);return{sessionId:a.sessionId,projectHash:a.projectHash,startTime:a.startTime,lastUpdated:a.lastUpdated,kind:a.kind,messages:Array.isArray(a.messages)?a.messages:[]}}let r=t.split(`
|
|
1592
|
+
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let d=c;if(typeof d.id=="string"){let u=o.get(d.id);u?Hb(u,d):(i.push(d),o.set(d.id,d))}else i.push(d)}}return{sessionId:typeof s.sessionId=="string"?s.sessionId:void 0,projectHash:typeof s.projectHash=="string"?s.projectHash:void 0,startTime:typeof s.startTime=="string"?s.startTime:void 0,lastUpdated:typeof s.lastUpdated=="string"?s.lastUpdated:void 0,kind:typeof s.kind=="string"?s.kind:void 0,messages:i}}function Hb(t,e){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="tokens"&&Ep(t.tokens)&&Ep(n)){t.tokens={...t.tokens,...n};continue}t[r]=n}}function Ep(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Tp(t,e){if(e==="json")return JSON.stringify(t,null,2);let{messages:r,...n}=t,s=[JSON.stringify(n)];for(let i of r)s.push(JSON.stringify(i));return s.join(`
|
|
1593
1593
|
`)+`
|
|
1594
|
-
`}var
|
|
1595
|
-
`).trim();
|
|
1596
|
-
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:
|
|
1597
|
-
`)){let n=r.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function ur(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function
|
|
1598
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function
|
|
1599
|
-
`).trim():""}function Dp(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1600
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return mr(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),r=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&r.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let n;try{n=await Np(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=mr(this.sessionsDir,s.name),o;try{o=await Np(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=mr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Rp(this.indexPath(),"utf-8")}catch{return new Map}let r=new Map;for(let n of e.split(/\r?\n/))if(n.trim())try{let s=JSON.parse(n);if(typeof s.sessionId!="string")continue;s.deleted===!0?r.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&r.set(s.sessionId,{sessionId:s.sessionId,sessionDir:
|
|
1601
|
-
`);for(;p>=0;){let y=l.slice(0,p);l=l.slice(p+1),
|
|
1602
|
-
`)}}),i.stderr?.on("data",
|
|
1594
|
+
`}var Qa=k(()=>{"use strict"});import{createHash as Xb}from"node:crypto";import{readdir as Xn,readFile as wp,stat as _i,unlink as qb}from"node:fs/promises";import{join as Be,basename as Gb,dirname as Jb}from"node:path";import{cwd as Vb}from"node:process";function Za(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function vp(t){return t==="user"}function el(t){return t==="gemini"||t==="assistant"}function dr(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Kb(t){return`${t.sessionId}\0${t.cwd}`}function Yb(t,e){let r=t.filePaths??[t.filePath],n=e.filePaths??[e.filePath],s=[...new Set([...r,...n])],i=e.modifiedAt.getTime()>=t.modifiedAt.getTime()?e:t;return{...i,createdAt:t.createdAt.getTime()<=e.createdAt.getTime()?t.createdAt:e.createdAt,modifiedAt:i.modifiedAt,filePath:i.filePath,filePaths:s}}function yi(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function Sp(t){let e=0,r=0,n=0,s=0,i=0,o;for(let a of t){if(!el(a.type)||!a.tokens)continue;let l=yi(a.tokens.input),c=yi(a.tokens.cached),d=Math.max(l-c,0),u=yi(a.tokens.output),f=yi(a.tokens.thoughts);e+=l,r+=c,n+=u,s+=f,i=l,o={inputTokens:d,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:u,reasoningOutputTokens:f,totalTokens:l+u+f}}return{totalInputTokens:e,totalCachedInputTokens:r,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function zb(t){return Xb("sha256").update(t).digest("hex")}function qn(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=Jb(r);if(n===r)break;r=n}}var Ei,bp=k(()=>{"use strict";ve();Qa();J();Ei=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||Be(W,".gemini");this.geminiProjectsFile=Be(r,"projects.json"),this.geminiTmpDir=Be(r,"tmp");let n=e.claudeDir||Be(W,".claude");this.claudeProjectsDir=Be(n,"projects");let s=[Be(W,".codex"),Be(W,".code")],i=e.codexDirs&&e.codexDirs.length>0?e.codexDirs:[e.codexDir||s[0],e.codeDir||s[1]];this.codexSessionDirs=[...new Set(i)].map(o=>Be(o,"sessions")),this.extraWorkspacePaths=e.extraWorkspacePaths||[]}getWatchPaths(){return[{directory:this.geminiTmpDir,filePattern:/\.jsonl?$/}]}async discoverSessions(){let e=await this.findSessionFiles(),r=new Map;for(let n of e)try{let s=await this.extractSummary(n);if(!s)continue;let i=Kb(s),o=r.get(i);r.set(i,o?Yb(o,s):s)}catch{}return[...r.values()]}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n;try{n=await this.readSessionFile(r)}catch{return null}if(!n)return null;let s=await ce(r),i=[],o=[],a=n.messages||[],l=n.sessionId||this.extractSessionIdFromFilename(r),c=n.projectHash||"",d=await this.resolveWorkspace(c),u,f,m;for(let p of a){let y=dr(p.timestamp),E=p.type,v=z(Za(p.content));if(vp(E)){let T=Za(p.content);T&&o.push(T);let S=v.trim();S&&(u||(u=P(S,80)),f=P(S,80)),i.push({role:"user",timestamp:y,content:S||v});continue}if(el(E)){p.model&&(m=p.model);for(let T of p.thoughts||[]){let S=[T.subject,T.description].filter(Boolean).join(`
|
|
1595
|
+
`).trim();S&&i.push({role:"thinking",timestamp:dr(T.timestamp,y),content:z(S)})}i.push({role:"assistant",timestamp:y,content:v,model:p.model});continue}let b=E?`[${E}] `:"";i.push({role:"system",timestamp:y,content:`${b}${v}`.trim()})}let h=dr(n.startTime,s.createdAt),_=dr(n.lastUpdated,s.modifiedAt),g=Sp(a);return{provider:"gemini",sessionId:l,cwd:d,createdAt:h,modifiedAt:_,model:m,startCommand:"gemini",firstUserMessage:u,lastUserMessage:f,messageCount:i.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:r,totalInputTokens:g.totalInputTokens||void 0,totalCachedInputTokens:g.totalCachedInputTokens||void 0,totalOutputTokens:g.totalOutputTokens||void 0,totalReasoningOutputTokens:g.totalReasoningOutputTokens||void 0,lastInputTokens:g.lastInputTokens||void 0,lastTokenUsage:g.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await ce(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let m of s)if(vp(m.type)){u++;let h=Za(m.content).trim();h&&(l||(l=P(z(h),80)),c=P(z(h),80))}else el(m.type)&&(u++,m.model&&(d=m.model));let f=Sp(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:dr(r.startTime,n.createdAt),modifiedAt:dr(r.lastUpdated,n.modifiedAt),model:d,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCachedInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,totalReasoningOutputTokens:f.totalReasoningOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async readSessionFile(e){let r=await wp(e,"utf-8");if(Hn(r)==="unknown")return L({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.slice(0,120),message:`gemini session file at ${e} matches neither old (.json with messages[]) nor new (.jsonl with kind metadata) format. Skipping; lmctl ls / audit / stats will not see this session.`}),null;try{return gi(r)}catch{return null}}extractSessionIdFromFilename(e){let r=Gb(e).replace(/\.jsonl?$/,""),n=r.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async findSessionFiles(){let e=[],r;try{r=await Xn(this.geminiTmpDir)}catch{return e}for(let n of r){let s=Be(this.geminiTmpDir,n,"chats");if(!(await _i(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Xn(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(Be(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await qb(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){let i=await this.readSessionFile(s).catch(()=>null),o=this.extractSessionIdFromFilename(s),a=i?.sessionId||o,l=a===e||a.startsWith(e),c=o===e||o.startsWith(e)||o.length>=8&&e.startsWith(o);if(!l&&!c)continue;let d=await ce(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:dr(i?.lastUpdated,d.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;qn(e,Vb());for(let n of this.extraWorkspacePaths)qn(e,n);for(let n of await this.collectGeminiProjectPaths())qn(e,n);for(let n of await this.collectCodexCwds())qn(e,n);for(let n of await this.collectClaudeCwds())qn(e,n);let r=new Map;for(let n of e)r.set(zb(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await wp(this.geminiProjectsFile,"utf-8")}catch{return[]}try{let n=JSON.parse(e).projects;return!n||typeof n!="object"||Array.isArray(n)?[]:Object.keys(n)}catch{return[]}}async collectCodexCwds(){let e=new Set;for(let r of this.codexSessionDirs){let n=await this.findJsonlFiles(r);for(let s of n){let o=(await Ue(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await Xn(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=Be(this.claudeProjectsDir,n);if(!(await _i(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Xn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Be(s,a),d=(await Ue(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await _i(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await Xn(e)}catch{return r}for(let i of s){let o=Be(e,i),a=await _i(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);r.push(...l)}else i.endsWith(".jsonl")&&r.push(o)}return r}}});import{readFileSync as Qb,writeFileSync as Zb,mkdirSync as eI}from"node:fs";import{join as tI,dirname as rI}from"node:path";import{randomUUID as nI}from"node:crypto";function rl(t){return new tl(t)}var tl,nl=k(()=>{"use strict";bp();je();St();$e();Qa();tl=class extends Q{geminiDir;constructor(e){super({provider:new Ei(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!0,forkSupport:"automatic",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",G,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>ut(r,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return mt({...e,env:this.geminiDir!==void 0?{...e.env??process.env,GEMINI_DIR:this.geminiDir}:e.env,binary:"gemini",acpTool:"gemini"})}forkHint(e){return["Gemini fork: copies the session file with a new ID.","The forked session has the same conversation history","but diverges from that point forward."].join(`
|
|
1596
|
+
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:Ys,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,r){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=Qb(n,"utf-8"),i=Hn(s),o=gi(s),a=nI();o.sessionId=a,o.kind="main";let l=rI(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=i==="jsonl"?".jsonl":".json",u=`session-${c}-${a.slice(0,8)}${d}`,f=tI(l,u);return eI(l,{recursive:!0}),Zb(f,Tp(o,i),"utf-8"),{success:!0,sessionId:a,filePath:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as Ip,readFile as sI,rm as iI,stat as Jr}from"node:fs/promises";import{basename as oI,join as et}from"node:path";function aI(t){if(!t)return null;let e={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,reasoningTokens:0},r=!1;for(let n of Object.values(t))n?.usage&&(r=!0,e.inputTokens+=n.usage.inputTokens??0,e.outputTokens+=n.usage.outputTokens??0,e.cacheReadTokens+=n.usage.cacheReadTokens??0,e.cacheWriteTokens+=n.usage.cacheWriteTokens??0,e.reasoningTokens+=n.usage.reasoningTokens??0);return r?e:null}function sl(){return{shutdownTotals:null,assistantOutputSum:0}}function kp(t,e){if(e.type==="assistant.message"){let r=e.data?.outputTokens;typeof r=="number"&&(t.assistantOutputSum+=r,t.lastAssistantOutputTokens=r)}else if(e.type==="session.shutdown"){let r=aI(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function xp(t){let e=t.shutdownTotals,r=t.lastAssistantOutputTokens!==void 0?{outputTokens:t.lastAssistantOutputTokens}:void 0;return{totalInputTokens:e?.inputTokens,totalCachedInputTokens:e?.cacheReadTokens,totalCacheWriteInputTokens:e?.cacheWriteTokens,totalOutputTokens:e?.outputTokens??(t.lastAssistantOutputTokens===void 0?void 0:t.assistantOutputSum),totalReasoningOutputTokens:e?.reasoningTokens,lastTokenUsage:r}}function lI(t){let e={};for(let r of t.split(`
|
|
1597
|
+
`)){let n=r.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function ur(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function cI(t){let e=0,r=sl(),n;for await(let s of le(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=P(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;kp(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function dI(t){let e=uI(t),r=new Map;for(let n of t){if(n.role!=="tool_use"||n.toolCallId===void 0)continue;if(n.toolName==="bash"){let l=e.get(n.toolCallId),d=[l?.content,l?.toolDetailedContent].filter(f=>typeof f=="string").join(`
|
|
1598
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(d===void 0)continue;let u=`copilot-shell:${d}:${n.toolCallId}`;r.set(d,u),n.backgroundTaskId=u,l!==void 0&&(l.backgroundTaskId=u);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function uI(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 Ti,Ap=k(()=>{"use strict";ve();Ti=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||et(W,".copilot");this.sessionStateDir=et(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Ip(this.sessionStateDir)}catch{return e}for(let n of r){let s=et(this.sessionStateDir,n);if((await Jr(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,n);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.resolveSessionDir(e);if(!r)return null;let n=await this.readWorkspaceYaml(r),s=et(r,"events.jsonl"),i=await Jr(s).catch(()=>null),o=i?s:et(r,"workspace.yaml"),a=await ce(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,f,m,h,_,g,p=n?.id||oI(r)||e,y=sl();if(i)for await(let E of le(s)){let v=ur(E.timestamp)||a.modifiedAt;if(kp(y,E),E.type==="session.start"&&E.data){E.data.sessionId&&(p=E.data.sessionId),E.data.copilotVersion&&(f=E.data.copilotVersion),E.data.startTime&&(g=ur(E.data.startTime)),E.data.selectedModel&&(u=E.data.selectedModel),E.data.context&&(E.data.context.cwd&&(d=E.data.context.cwd),E.data.context.branch&&(m=E.data.context.branch));continue}if(E.type==="session.model_change"&&E.data?.newModel){u=E.data.newModel;continue}if(E.type==="user.message"&&E.data){let b=E.data.content||"";b&&c.push(b);let T=b.trim();T&&(h||(h=P(T,80)),_=P(T,80)),l.push({role:"user",timestamp:v,content:z(T||b)});continue}if(E.type==="assistant.message"&&E.data){let b=(E.data.content||"").trim();if(b&&l.push({role:"assistant",timestamp:v,content:z(b),model:u}),E.data.toolRequests)for(let T of E.data.toolRequests)l.push({role:"tool_use",timestamp:v,content:T.name||"unknown tool",toolName:T.name,toolInput:T.arguments?JSON.stringify(T.arguments,null,2):void 0,toolInputData:Ge(T.arguments),toolCallId:T.toolCallId});continue}if(E.type==="tool.execution_complete"&&E.data){let b=E.data.result?.content||"",T=E.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:v,content:z(b),toolDetailedContent:T?z(T):void 0,toolCallId:E.data.toolCallId});continue}if(E.type==="assistant.reasoning"&&E.data?.content){l.push({role:"thinking",timestamp:v,content:z(E.data.content)});continue}if(E.type==="session.error"||E.type==="session.warning"||E.type==="session.info"||E.type==="system.message"){let b=E.data?.message||"";b.trim()&&l.push({role:"system",timestamp:v,content:z(b)});continue}}if(!h){let E=(n?.summary||"").trim();E&&(h=P(E,80))}return dI(l),{provider:"copilot",sessionId:p,cwd:d,createdAt:g??ur(n?.created_at)??a.createdAt,modifiedAt:ur(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",gitBranch:m,firstUserMessage:h,lastUserMessage:_,messageCount:l.filter(E=>E.role==="user"||E.role==="assistant").length,filePath:o,...xp(y),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=et(e,"events.jsonl"),i=await Jr(s).catch(()=>null),o=i?s:et(e,"workspace.yaml"),a=await ce(i?s:e),l=i?await Ue(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,f,m,h,_;for(let p of l)if(p.type==="session.start"&&p.data&&(p.data.sessionId&&(c=p.data.sessionId),p.data.copilotVersion&&(f=p.data.copilotVersion),p.data.startTime&&(m=ur(p.data.startTime)),p.data.selectedModel&&(u=p.data.selectedModel),p.data.context?.cwd&&(d=p.data.context.cwd)),p.type==="session.model_change"&&p.data?.newModel&&(u||(u=p.data.newModel)),p.type==="user.message"&&p.data){let y=(p.data.content||"").trim();y&&(h||(h=P(y,80)),_=P(y,80))}if(!h){let p=(n?.summary||"").trim();p&&(h=P(p,80))}let g=i?await cI(s):{messageCount:0,tokens:sl()};return{provider:"copilot",sessionId:c,cwd:d,createdAt:m??ur(n?.created_at)??a.createdAt,modifiedAt:ur(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",firstUserMessage:h,lastUserMessage:g.lastUserMessage??_,messageCount:g.messageCount,filePath:o,...xp(g.tokens)}}async readWorkspaceYaml(e){let r=et(e,"workspace.yaml");try{let n=await sI(r,"utf-8");return lI(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await iI(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await Ip(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=et(this.sessionStateDir,e);if((await Jr(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=et(this.sessionStateDir,s);(await Jr(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=et(this.sessionStateDir,s);if(!(await Jr(i).catch(()=>null))?.isDirectory())continue;let a=await this.readWorkspaceYaml(i);if(a&&(a.id===e||a.id?.startsWith(e)))return i}return null}}});function ol(t){return new il(t)}var il,al=k(()=>{"use strict";Ap();je();St();J();$e();il=class extends Q{copilotDir;constructor(e){super({provider:new Ti(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",G,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>ut(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return mt({...e,env:this.copilotDir!==void 0?{...e.env??process.env,COPILOT_HOME:this.copilotDir}:e.env,binary:"copilot",acpTool:"copilot"})}async seed(e,r){let n=await super.seed(e,r);if(r?.model===void 0||r.model.trim().length===0)return n;let s="copilot seed does not implement per-session model selection";return we({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function cl(){return new ll}var ll,dl=k(()=>{"use strict";mi();je();St();$e();ll=class extends Q{constructor(){super({provider:new qr,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"custom-tool",leaderSetupHint:"OpenCode supports custom tools via .opencode/tools/ directory"},binary:"opencode",seedArgs:["run",G],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>ut(e,{...r,acpTool:"opencode"})})}openSession(e){return mt({...e,binary:"opencode",acpTool:"opencode"})}seedArgsFor(e){let r=["run"];return e?.model&&r.push("--model",e.model),e?.effort&&r.push("--variant",e.effort),r.push(e?.prompt??G),r}}});import{appendFile as mI,mkdir as fI,readFile as Rp,readdir as Np,rm as pI,stat as Lp}from"node:fs/promises";import{basename as hI,dirname as gI,isAbsolute as Cp,join as mr,relative as _I,resolve as ul}from"node:path";function ml(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function wI(t){return typeof t=="number"?new Date(t):ml(t)??new Date(0)}function Op(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
1599
|
+
`).trim():""}function Dp(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function vI(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:Dp(t)??""}function SI(t){let e=bI(t),r=new Set;for(let n of t){if(n.role!=="tool_use"||n.toolName!=="Bash"||n.toolInputData?.run_in_background!==!0||n.toolCallId===void 0)continue;let s=e.get(n.toolCallId);if(s===void 0)continue;let i=s.content.match(/(?:^|\n)task_id:\s*([^\s]+)/)?.[1];i!==void 0&&(r.add(i),n.backgroundTaskId=i,s.backgroundTaskId=i)}for(let n of t){if(n.role!=="tool_use"||n.toolName!=="TaskOutput"&&n.toolName!=="TaskStop"||n.toolCallId===void 0)continue;let s=n.toolInputData?.task_id;if(typeof s!="string"||!r.has(s))continue;n.backgroundTaskId=s;let i=e.get(n.toolCallId);i!==void 0&&(i.backgroundTaskId=s)}}function bI(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 yI,EI,TI,wi,Mp=k(()=>{"use strict";ve();yI="1.4",EI="1.5",TI=new Set([yI,EI]),wi=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=ul(e?.kimiHome??process.env.KIMI_CODE_HOME??mr(W,".kimi-code")),this.sessionsDir=mr(this.homeDir,"sessions")}async discoverSessions(){let e=[];for(let r of await this.sessionFiles())try{let n=await this.summary(r);n&&e.push(n)}catch{}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){let r=await this.findSession(e);if(!r)return null;let n=await this.summary(r);if(!n)return null;let s=await this.parseWire(r.wirePath);return{...n,messages:s.messages,userPrompts:s.userPrompts}}async resolveSessionPath(e){return(await this.findSession(e))?.wirePath??null}async deleteSession(e){let r=await this.findSession(e);return r?(await pI(r.sessionDir,{recursive:!0,force:!0}),await fI(gI(this.indexPath()),{recursive:!0,mode:448}),await mI(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
1600
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return mr(this.homeDir,"session_index.jsonl")}async sessionFiles(){let e=await this.readIndex(),r=new Map;for(let s of e.values())this.validSessionDir(s.sessionDir,s.sessionId)&&r.set(s.sessionId,this.filesFor(s.sessionId,s.sessionDir,s.workDir));let n;try{n=await Np(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=mr(this.sessionsDir,s.name),o;try{o=await Np(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=mr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Rp(this.indexPath(),"utf-8")}catch{return new Map}let r=new Map;for(let n of e.split(/\r?\n/))if(n.trim())try{let s=JSON.parse(n);if(typeof s.sessionId!="string")continue;s.deleted===!0?r.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&r.set(s.sessionId,{sessionId:s.sessionId,sessionDir:ul(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:mr(r,"state.json"),wirePath:mr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!Cp(e)||hI(e)!==r)return!1;let n=_I(this.sessionsDir,ul(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!Cp(n)}async findSession(e){let r=await this.sessionFiles(),n=r.find(i=>i.sessionId===e);if(n)return n;let s=r.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let r=JSON.parse(await Rp(e,"utf-8"));return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}async summary(e){let r=await this.readState(e.statePath);if(!r)return null;let n;try{n=await Lp(e.wirePath)}catch{return null}let s=await Lp(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=ml(r.createdAt)??s.birthtime,a=ml(r.updatedAt)??(s.mtime>n.mtime?s.mtime:n.mtime);return{provider:"kimi",sessionId:e.sessionId,slug:r.title,cwd:r.workDir??e.indexedWorkDir??"(unknown)",createdAt:o,modifiedAt:a,model:i.model,startCommand:"kimi",firstUserMessage:i.firstUserMessage,lastUserMessage:i.lastUserMessage??(r.lastPrompt?P(r.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,f=0,m=!1,h=0,_,g;for await(let p of le(e)){let y=wI(p.time??p.created_at);if(i&&(i=!1,p.type==="metadata"&&!TI.has(p.protocol_version))){let v=`Kimi transcript wire protocol version ${JSON.stringify(p.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:y,content:v}],userPrompts:[],messageCount:1,firstUserMessage:v,lastUserMessage:v}}if((p.type==="config.update"||p.type==="profile.bind")&&p.modelAlias&&(o=p.modelAlias),p.type==="usage.record"){p.model&&(o=p.model),m||=p.usage!==void 0;let v=p.usage?.inputOther??0,b=p.usage?.inputCacheRead??0,T=p.usage?.inputCacheCreation??0,S=p.usage?.output??0;c+=v,d+=b,u+=T,f+=S,p.usageScope==="turn"&&(_=v+b+T,g={inputTokens:v,cachedInputTokens:b,cacheWriteInputTokens:T,outputTokens:S,totalTokens:_+S});continue}if(p.type==="turn.prompt"&&p.origin?.kind==="user"){let v=Op(p.input);v&&((!p.promptId||!s.has(p.promptId))&&(n.push(v),p.promptId&&s.add(p.promptId)),a??=P(v,80),l=P(v,80),r.push({role:"user",timestamp:y,content:v}),h++);continue}if(p.type==="turn.steer"){let v=Op(p.input);v&&(r.push({role:"system",timestamp:y,content:v}),h++);continue}if(p.type!=="context.append_loop_event"||!p.event)continue;let E=p.event;E.type==="content.part"&&E.part?.type==="text"&&E.part.text?(r.push({role:"assistant",timestamp:y,content:E.part.text,model:o}),h++):E.type==="content.part"&&E.part?.type==="think"&&E.part.think?r.push({role:"thinking",timestamp:y,content:E.part.think,model:o}):E.type==="tool.call"?r.push({role:"tool_use",timestamp:y,content:E.name??"tool",toolName:E.name,toolInput:Dp(E.args),toolInputData:Ge(E.args),toolCallId:E.toolCallId,model:o}):E.type==="tool.result"&&r.push({role:"tool_result",timestamp:y,content:vI(E.result),toolCallId:E.toolCallId,model:o})}return SI(r),{messages:r,userPrompts:n,messageCount:h,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:m?c:void 0,totalCachedInputTokens:m?d:void 0,totalCacheWriteInputTokens:m?u:void 0,totalOutputTokens:m?f:void 0,lastInputTokens:_,lastTokenUsage:g}}}});function pl(t){return new fl(t)}var fl,hl=k(()=>{"use strict";Mp();je();St();$e();fl=class extends Q{kimiHome;constructor(e){super({provider:new wi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Kimi supports skills through ~/.kimi-code/skills and --skills-dir."},binary:"kimi",seedArgs:["-p",G,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>ut(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return mt({...e,env:this.kimiHome!==void 0?{...e.env??process.env,KIMI_CODE_HOME:this.kimiHome}:e.env,binary:"kimi",acpTool:"kimi"})}seedArgsFor(e){let r=[];return e?.model&&r.push("--model",e.model),r.push("-p",e?.prompt??G,"--output-format","stream-json"),r}}});import{spawn as II}from"node:child_process";import{mkdirSync as xI}from"node:fs";function _l(t){return new gl(t)}async function kI(t,e){let r=Date.now(),n=$p({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});Se("lmplayer",n,e.permissionMode??"yolo");let s=await Pp(e.binary,n,{cwd:e.cwd,env:Ee(e.env,e.cwd,e.sessionId),signal:e.signal,onText:i=>{e.onProgress?.({kind:"text",summary:i.slice(0,120)}),e.onDelta?.(i)}});if(s.code!==0&&s.code!==null)throw new Error(Fp(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function $p(t){let e=["run"];return t.model&&e.push("--model",t.model),t.sessionId&&e.push("--session",t.sessionId),t.formatJson&&e.push("--format","json"),t.effort&&e.push("--effort",t.effort),e.push(...Ht("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function Fp(t){if(t.error)return t.error;let e=xn(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function Pp(t,e,r){return new Promise((n,s)=>{let i;try{i=II(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(_){s(_);return}let o="",a="",l="",c,d,u,f=[],m=!1,h=_=>{let g=_.trim();if(!g)return;let p;try{p=JSON.parse(g)}catch{f.push(_),r.onText?.(_);return}if(!Vr(p))return;let y=vi(p,!1);c===void 0&&y!==void 0&&(c=y),d=vi(p,!0)??d;let E=AI(p);E!==void 0&&(u=E);let v=Up(p);v&&(f.push(v),r.onText?.(v))};i.stdout?.on("data",_=>{let g=_.toString("utf8");o+=g,l+=g;let p=l.indexOf(`
|
|
1601
|
+
`);for(;p>=0;){let y=l.slice(0,p);l=l.slice(p+1),h(y),p=l.indexOf(`
|
|
1602
|
+
`)}}),i.stderr?.on("data",_=>{a+=_.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",_=>{m||(m=!0,l.length>0&&h(l),n({code:_,stdout:o,stderr:a,sessionId:c??d,text:f.join(""),error:u}))}),i.on("error",_=>{m||(m=!0,s(_))})})}function AI(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Vr(e)){let r=e.data;if(Vr(r)&&typeof r.message=="string"&&r.message.length>0)return typeof e.name=="string"?`${e.name}: ${r.message}`:r.message;if(typeof e.message=="string"&&e.message.length>0)return e.message}}function Up(t){for(let e of["text","content","delta","output","message"]){let r=t[e];if(typeof r=="string")return r}for(let e of["data","event","payload","part"]){let r=t[e];if(Vr(r)){let n=Up(r);if(n)return n}}}function vi(t,e){for(let n of["sessionID","sessionId","session_id"]){let s=t[n];if(typeof s=="string"&&s.length>0)return s}let r=t.session;if(typeof r=="string"&&r.length>0)return r;if(Vr(r)){let n=vi(r,e);if(n!==void 0)return n}if(e){let n=t.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=t[n];if(Vr(s)){let i=vi(s,e);if(i!==void 0)return i}}}function Vr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var gl,yl=k(()=>{"use strict";mi();je();$e();vt();dt();wa();gl=class extends Q{constructor(e){super({provider:new qr({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none"},binary:"lmplayer",seedArgs:["run","--format","json","--dangerously-skip-permissions",G],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:kI})}seedArgsFor(e){return $p({prompt:e?.prompt??G,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){xI(e,{recursive:!0});let n=this.seedArgsFor(r);Se("lmplayer",n);try{let s=await Pp(this.binary,n,{cwd:e,env:Hr(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:Fp(s)}:s.sessionId?{success:!0,sessionId:s.sessionId}:{success:!1,error:"lmplayer seed failed; provider did not report a sessionID"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}manualSeedHint(e){return{launchCommand:`cd ${e} && lmplayer run --format json --dangerously-skip-permissions "${G}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as Si,readFile as RI,rm as NI}from"node:fs/promises";import{basename as jp,join as Vt}from"node:path";function LI(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Gn(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function CI(t,e){if(!e)return;t.observed=!0;let r=Gn(e.promptTokenCount),n=Gn(e.cachedContentTokenCount),s=Gn(e.candidatesTokenCount),i=Gn(e.thoughtsTokenCount);t.totalInputTokens+=r,t.totalCachedInputTokens+=n,t.totalOutputTokens+=s,t.totalReasoningOutputTokens+=i,t.lastInputTokens=r,t.lastTokenUsage={inputTokens:Math.max(r-n,0),cachedInputTokens:n,outputTokens:s,reasoningOutputTokens:i,totalTokens:Gn(e.totalTokenCount)||r+s}}function OI(t){return{totalInputTokens:t.observed?t.totalInputTokens:void 0,totalCachedInputTokens:t.observed?t.totalCachedInputTokens:void 0,totalOutputTokens:t.observed?t.totalOutputTokens:void 0,totalReasoningOutputTokens:t.observed?t.totalReasoningOutputTokens:void 0,lastInputTokens:t.lastInputTokens,lastTokenUsage:t.lastTokenUsage}}function Bp(t){return t.type==="user"||t.message?.role==="user"}function Wp(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function Hp(t){let e=t.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(r=>r.type==="text").map(r=>r.text||"").join(`
|
|
1603
1603
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1604
|
-
`):"":""}function Xp(t){return t.model||t.message?.model}function LI(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:Gp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Jn(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function CI(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Jn(e.output??e.error??t)}return Jn(t)}function Gp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function qp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Jn(t.args,!0),toolInputData:Ge(t.args),toolCallId:t.id,model:r}}var vi,Jp=k(()=>{"use strict";ve();vi=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Vt(W,".qwen")}async discoverSessions(){let e=Vt(this.baseDir,"projects"),r;try{r=await wi(e)}catch{return[]}let n=[];for(let s of r){let i=Vt(e,s,"chats"),o;try{o=await wi(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Vt(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await ce(e),i="(unknown)",o,a,l,c,d=0;for await(let u of le(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Bp(u)){let f=Hp(u).trim();f&&(l||(l=P(f,80)),c=P(f,80),d++)}if(Wp(u)){let f=Xp(u);f&&(o=f),d+=LI(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=jp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await ce(e),s="(unknown)",i,o,a,l,c,d,u=[],f=AI();for await(let m of le(e)){if(RI(f,m.usageMetadata),m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.gitBranch&&(a=m.gitBranch)),m.type==="system"&&m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.model&&(i=m.model),m.gitBranch&&(a=m.gitBranch)),!m.message)continue;let g=m.message,h=m.timestamp?new Date(m.timestamp):n.modifiedAt;if(m.type==="tool_result"){let _=Gp(m).filter(p=>p.functionResponse!==void 0);_.length===0&&m.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:h,content:Jn(m.toolCallResult.resultDisplay??m.toolCallResult.error??m.toolCallResult.status)??"tool result",toolCallId:m.toolCallResult.callId});for(let p of _){let y=p.functionResponse,T=CI(y.response),v=Jn(m.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:h,content:v??T??m.toolCallResult?.status??"tool result",toolName:y.name,toolCallId:m.toolCallResult?.callId??y.id,...T!==void 0?{toolDetailedContent:T}:{}})}}else if(Bp(m)){let _=Hp(m);_.trim()&&(c||(c=P(_.trim(),80)),d=P(_.trim(),80)),u.push({role:"user",timestamp:h,content:_})}else if(Wp(m)){let _=Xp(m);if(_&&(i=_),Array.isArray(g.content))for(let p of g.content)p.type==="text"&&p.text?u.push({role:"assistant",timestamp:h,content:p.text,model:_}):p.type==="thinking"&&p.thinking?u.push({role:"thinking",timestamp:h,content:p.thinking}):p.functionCall&&u.push(qp(p.functionCall,h,_));else if(typeof g.content=="string")u.push({role:"assistant",timestamp:h,content:g.content,model:_});else if(Array.isArray(g.parts))for(let p of g.parts)if(p.thought||p.type==="thinking"){let y=p.thinking||p.text;y&&u.push({role:"thinking",timestamp:h,content:y})}else p.functionCall?u.push(qp(p.functionCall,h,_)):p.text&&u.push({role:"assistant",timestamp:h,content:p.text,model:_})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...NI(f),messages:u}}async resolveSessionPath(e){let r=Vt(this.baseDir,"projects");try{let n=await wi(r),s=[];for(let i of n){let o=Vt(r,i,"chats",`${e}.jsonl`);try{return await xI(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Vt(r,i,"chats"),a;try{a=await wi(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;jp(l,".jsonl").startsWith(e)&&s.push(Vt(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await kI(r),!0}catch{return!1}}}});function El(){return new yl}var yl,Tl=k(()=>{"use strict";Jp();je();St();$e();yl=class extends Q{constructor(){super({provider:new vi,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",G,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:ui})}openSession(e){return mi({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Vp,readFile as Kp,rm as Yp,stat as zp}from"node:fs/promises";import{basename as wl,join as ft}from"node:path";import{fileURLToPath as OI}from"node:url";async function DI(t){let e=await Promise.all(t.map(r=>ce(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function MI(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Qp(t){return t.type==="USER_INPUT"}function Zp(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function $I(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function eh(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function th(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function FI(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function PI(t){for await(let e of le(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=UI(s);if(i)return i}let n=jI(e.content);if(n)return n}return null}function UI(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function jI(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function BI(t,e){if(t.status!=="RUNNING"||!t.content)return;let r=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!r||r[1]!==e)&&!(t.step_index===void 0||Number(r[3])!==t.step_index))return r[2]}function WI(t,e){let r=new Set;for(let n of e){let s=HI(t,r,n);if(!s)continue;r.add(s);let i=n.event.step_index===void 0?void 0:`agy-step-${n.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=n.message.backgroundTaskId,n.message.toolName=s.name,n.message.toolCallId=i}}function HI(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:JI(r.event.content);if(n!==void 0)return rh(t.filter(i=>!e.has(i)&&VI(i)===n),r.event.step_index);let s=GI(r.event);if(s!==void 0)return rh(t.filter(i=>!e.has(i)&&XI(i.name,r.event.type)&&sh(qI(i))===s),r.event.step_index)}function rh(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let r=t.map(n=>({call:n,distance:n.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-n.stepIndex)})).sort((n,s)=>n.distance-s.distance);return r[0].distance<r[1].distance?r[0].call:void 0}function XI(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function qI(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function GI(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),sh(e)}function sh(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return OI(e)}catch{return}}function JI(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function VI(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,r=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof r!="string"?void 0:`Timer: ${e}s, Prompt: ${r}`}}function nh(t){if(t.endsWith(".db"))return wl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Si,ih=k(()=>{"use strict";ve();Si=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||ft(W,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:ft(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=ft(this.baseDir,"conversations"),r;try{r=await Vp(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=wl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return ft(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return ft(this.baseDir,"brain",e,".system_generated","logs",r?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let r of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await zp(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await DI([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of le(n)){let f=th(u.content);if(f&&(a=f),Qp(u)){let m=eh(u.content).trim();m&&(l||(l=P(m,80)),c=P(m,80)),d++}else Zp(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=nh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,d=[],u=[];if(i)for await(let f of le(i)){let m=MI(f.created_at,s.modifiedAt),g=th(f.content);if(g&&(a=g),Qp(f)){let h=eh(f.content),_=h.trim();_&&(l||(l=P(_,80)),c=P(_,80)),o.push({role:"user",timestamp:m,content:h});continue}if(Array.isArray(f.tool_calls))for(let h of f.tool_calls){let _=h.name||"tool",p=FI(h.args),y=Ge(h.args),T={role:"tool_use",timestamp:m,content:p,toolName:_,toolInput:p,toolInputData:y};o.push(T),d.push({name:_,stepIndex:f.step_index,input:y,message:T})}if(Zp(f)&&f.content)o.push({role:"assistant",timestamp:m,content:f.content,model:a});else if($I(f)&&f.content){let h=BI(f,n),_=h===void 0?null:await this.readTaskLog(n,h),p={role:"tool_result",timestamp:_?.modifiedAt??m,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:h,..._===null?{}:{toolDetailedContent:_.content}};o.push(p),u.push({event:f,message:p})}f.thinking&&o.push({role:"thinking",timestamp:m,content:f.thinking})}return WI(d,u),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(f=>f.role==="user"||f.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await zp(r),r}catch{}let n=ft(this.baseDir,"conversations");try{let s=[];for(let i of await Vp(n)){if(!i.endsWith(".db"))continue;wl(i,".db").startsWith(e)&&s.push(ft(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=nh(r);return n?(await Yp(this.conversationPath(n),{force:!0}),await Yp(ft(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await PI(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=ft(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Kp(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,r){if(!/^task-\d+$/.test(r))return null;let n=ft(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Kp(n,"utf8"),ce(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as KI}from"node:child_process";import{StringDecoder as oh}from"node:string_decoder";function bi(t){return async(e,r)=>{let n=Date.now(),s=t.buildArgs(e,r);t.assertArgs?.(s,r),r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await YI(t.label,r.binary,s,{cwd:r.cwd,env:Ee(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function YI(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=KI(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new oh("utf8"),d=new oh("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,m)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let g=m?`signal ${m}`:`exit code ${f}`,h=l.trim()||a.trim();i(new Error(`${t} failed (${g})${h?`: ${h}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var vl=k(()=>{"use strict";dt()});function bl(t){return new Sl(t)}function QI(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Sl,zI,Il=k(()=>{"use strict";ih();je();$e();vt();vl();Sl=class extends Q{constructor(e){super({provider:new Si(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",G,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:zI})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},zI=bi({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",QI(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Se("agy",t,e.permissionMode??"yolo")})});import ZI from"node:zlib";function lx(t,e){return t[e]===tx&&t[e+1]===rx&&t[e+2]===nx&&t[e+3]===sx}function ah(t,e){return(t[e]&240)===80&&t[e+1]===ix&&t[e+2]===ox&&t[e+3]===ax}function cx(t,e){if(ah(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!lx(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,f=c>>3;if(r+=3,u===3||(r+=u===1?1:f,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function dx(t){let e=[],r=0;for(;r+4<=t.length;){let n=cx(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Ii(t){let e=[];for(let r of dx(t))ah(r,0)||e.push(ex(r).toString("utf8"));return e.join("")}var ex,tx,rx,nx,sx,ix,ox,ax,xl=k(()=>{"use strict";ex=ZI.zstdDecompressSync,tx=40,rx=181,nx=47,sx=253,ix=42,ox=77,ax=24});import{readdir as kl,rm as ux,stat as mx}from"node:fs/promises";import{join as Kt}from"node:path";function fx(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Al(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"&&e.push(r.text);return e.join("")}function px(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&e.push(r.text);return e}function lh(t){let e=[];for(let r of t){let n=r.data??{},s=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:Al(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of px(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Al(i?.content),model:i?.source?.model})}else if(r.type==="tool/call"){let i=n,o;if(typeof i.arguments=="string")try{o=JSON.parse(i.arguments)}catch{}else i.arguments&&typeof i.arguments=="object"&&(o=i.arguments);e.push({role:"tool_use",timestamp:s,content:typeof i.arguments=="string"?i.arguments:JSON.stringify(i.arguments??{}),toolName:i.name,toolCallId:i.callId,toolInputData:o})}else if(r.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:Al(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function hx(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function ch(t,e,r){let n=t.find(m=>m.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let m of t)if(m.type==="request/header"){let g=m.data?.header;g?.config?.model&&(a=g.config.model)}let l=t.map(m=>m.time).filter(m=>typeof m=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,f=r.filter(m=>m.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...gx(t)}}function gx(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=xi(c.inputTokens),u=xi(c.cacheReadTokens),f=xi(c.outputTokens),m=xi(c.reasoningTokens);r+=d,n+=u,s+=f,i+=m,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:f,reasoningOutputTokens:m,totalTokens:d+u+f}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function xi(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var ki,dh=k(()=>{"use strict";ve();xl();ki=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||Kt(W,".dsh");this.sessionsDir=Kt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await kl(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await kl(Kt(this.sessionsDir,n))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(n,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.findSessionDir(e);if(!r)return null;let n=await this.readRecords(r.cwdDir,r.sessionDir);if(n.length===0)return null;let s=lh(n),i=ch(n,r.filePath,s);return i?{...i,turnStatus:hx(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let r=await this.findSessionDir(e);return r?(await ux(Kt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return Kt(this.sessionsDir,fx(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await kl(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=Kt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await mx(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=Kt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Ii(i),a=[];for(let l of o.split(`
|
|
1605
|
-
`))if(l.trim())try{let c=JSON.parse(l);if(c.type?.endsWith("-chunks")||c.type==="assistant/chunk")continue;a.push(c)}catch{}return a}async readSummary(e,r){let n=await this.readRecords(e,r);if(n.length===0)return null;let s=Kt(this.sessionsDir,e,r,"session.jsonl.zstd");return ch(n,s,lh(n))}}});import{spawn as
|
|
1606
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function
|
|
1604
|
+
`):"":""}function Xp(t){return t.model||t.message?.model}function DI(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:Gp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Jn(t,e=!1){if(t!==void 0){if(typeof t=="string")return t;try{return JSON.stringify(t,null,e?2:void 0)}catch{return String(t)}}}function MI(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Jn(e.output??e.error??t)}return Jn(t)}function Gp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function qp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Jn(t.args,!0),toolInputData:Ge(t.args),toolCallId:t.id,model:r}}var bi,Jp=k(()=>{"use strict";ve();bi=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Vt(W,".qwen")}async discoverSessions(){let e=Vt(this.baseDir,"projects"),r;try{r=await Si(e)}catch{return[]}let n=[];for(let s of r){let i=Vt(e,s,"chats"),o;try{o=await Si(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Vt(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await ce(e),i="(unknown)",o,a,l,c,d=0;for await(let u of le(e)){if(n=!0,u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Bp(u)){let f=Hp(u).trim();f&&(l||(l=P(f,80)),c=P(f,80),d++)}if(Wp(u)){let f=Xp(u);f&&(o=f),d+=DI(u)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=jp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await ce(e),s="(unknown)",i,o,a,l,c,d,u=[],f=LI();for await(let m of le(e)){if(CI(f,m.usageMetadata),m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.gitBranch&&(a=m.gitBranch)),m.type==="system"&&m.cwd&&(s=m.cwd,m.version&&(o=m.version),m.model&&(i=m.model),m.gitBranch&&(a=m.gitBranch)),!m.message)continue;let h=m.message,_=m.timestamp?new Date(m.timestamp):n.modifiedAt;if(m.type==="tool_result"){let g=Gp(m).filter(p=>p.functionResponse!==void 0);g.length===0&&m.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:_,content:Jn(m.toolCallResult.resultDisplay??m.toolCallResult.error??m.toolCallResult.status)??"tool result",toolCallId:m.toolCallResult.callId});for(let p of g){let y=p.functionResponse,E=MI(y.response),v=Jn(m.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:_,content:v??E??m.toolCallResult?.status??"tool result",toolName:y.name,toolCallId:m.toolCallResult?.callId??y.id,...E!==void 0?{toolDetailedContent:E}:{}})}}else if(Bp(m)){let g=Hp(m);g.trim()&&(c||(c=P(g.trim(),80)),d=P(g.trim(),80)),u.push({role:"user",timestamp:_,content:g})}else if(Wp(m)){let g=Xp(m);if(g&&(i=g),Array.isArray(h.content))for(let p of h.content)p.type==="text"&&p.text?u.push({role:"assistant",timestamp:_,content:p.text,model:g}):p.type==="thinking"&&p.thinking?u.push({role:"thinking",timestamp:_,content:p.thinking}):p.functionCall&&u.push(qp(p.functionCall,_,g));else if(typeof h.content=="string")u.push({role:"assistant",timestamp:_,content:h.content,model:g});else if(Array.isArray(h.parts))for(let p of h.parts)if(p.thought||p.type==="thinking"){let y=p.thinking||p.text;y&&u.push({role:"thinking",timestamp:_,content:y})}else p.functionCall?u.push(qp(p.functionCall,_,g)):p.text&&u.push({role:"assistant",timestamp:_,content:p.text,model:g})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...OI(f),messages:u}}async resolveSessionPath(e){let r=Vt(this.baseDir,"projects");try{let n=await Si(r),s=[];for(let i of n){let o=Vt(r,i,"chats",`${e}.jsonl`);try{return await RI(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Vt(r,i,"chats"),a;try{a=await Si(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;jp(l,".jsonl").startsWith(e)&&s.push(Vt(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await NI(r),!0}catch{return!1}}}});function Tl(){return new El}var El,wl=k(()=>{"use strict";Jp();je();St();$e();El=class extends Q{constructor(){super({provider:new bi,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",G,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:fi})}openSession(e){return pi({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Vp,readFile as Kp,rm as Yp,stat as zp}from"node:fs/promises";import{basename as vl,join as ft}from"node:path";import{fileURLToPath as $I}from"node:url";async function FI(t){let e=await Promise.all(t.map(r=>ce(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function PI(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Qp(t){return t.type==="USER_INPUT"}function Zp(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function UI(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function eh(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function th(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function jI(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function BI(t){for await(let e of le(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=WI(s);if(i)return i}let n=HI(e.content);if(n)return n}return null}function WI(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function HI(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function XI(t,e){if(t.status!=="RUNNING"||!t.content)return;let r=/task id:\s*([^/\s]+)\/(task-(\d+))\b/.exec(t.content);if(!(!r||r[1]!==e)&&!(t.step_index===void 0||Number(r[3])!==t.step_index))return r[2]}function qI(t,e){let r=new Set;for(let n of e){let s=GI(t,r,n);if(!s)continue;r.add(s);let i=n.event.step_index===void 0?void 0:`agy-step-${n.event.step_index}`;s.message.toolCallId=i,s.message.backgroundTaskId=n.message.backgroundTaskId,n.message.toolName=s.name,n.message.toolCallId=i}}function GI(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:YI(r.event.content);if(n!==void 0)return rh(t.filter(i=>!e.has(i)&&zI(i)===n),r.event.step_index);let s=KI(r.event);if(s!==void 0)return rh(t.filter(i=>!e.has(i)&&JI(i.name,r.event.type)&&sh(VI(i))===s),r.event.step_index)}function rh(t,e){if(t.length===0)return;if(t.length===1)return t[0];if(e===void 0)return;let r=t.map(n=>({call:n,distance:n.stepIndex===void 0?Number.POSITIVE_INFINITY:Math.abs(e-n.stepIndex)})).sort((n,s)=>n.distance-s.distance);return r[0].distance<r[1].distance?r[0].call:void 0}function JI(t,e){return e==="VIEW_FILE"?t==="view_file":e!=="CODE_ACTION"?!1:t==="write_to_file"||t==="replace_file_content"||t==="multi_replace_file_content"}function VI(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function KI(t){if(!t.content)return;let e;return t.type==="VIEW_FILE"?e=/File Path:\s*`?([^`\n]+)`?/.exec(t.content)?.[1]:t.type==="CODE_ACTION"&&(e=/Created file\s+(.+?)\s+with requested content/.exec(t.content)?.[1]??/changes were made by .*? tool to:\s*(.+?)\.\s*(?:If relevant|$)/s.exec(t.content)?.[1]),sh(e)}function sh(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return $I(e)}catch{return}}function YI(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function zI(t){if(t.name==="run_command"){let e=t.input?.CommandLine;return typeof e=="string"?e:void 0}if(t.name==="schedule"){let e=t.input?.DurationSeconds,r=t.input?.Prompt;return typeof e!="string"&&typeof e!="number"||typeof r!="string"?void 0:`Timer: ${e}s, Prompt: ${r}`}}function nh(t){if(t.endsWith(".db"))return vl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ii,ih=k(()=>{"use strict";ve();Ii=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||ft(W,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:ft(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=ft(this.baseDir,"conversations"),r;try{r=await Vp(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=vl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return ft(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return ft(this.baseDir,"brain",e,".system_generated","logs",r?"transcript_full.jsonl":"transcript.jsonl")}async existingTranscriptPath(e){for(let r of[this.transcriptPath(e,!0),this.transcriptPath(e,!1)])try{return await zp(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await FI([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of le(n)){let f=th(u.content);if(f&&(a=f),Qp(u)){let m=eh(u.content).trim();m&&(l||(l=P(m,80)),c=P(m,80)),d++}else Zp(u)&&u.content&&d++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=nh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,d=[],u=[];if(i)for await(let f of le(i)){let m=PI(f.created_at,s.modifiedAt),h=th(f.content);if(h&&(a=h),Qp(f)){let _=eh(f.content),g=_.trim();g&&(l||(l=P(g,80)),c=P(g,80)),o.push({role:"user",timestamp:m,content:_});continue}if(Array.isArray(f.tool_calls))for(let _ of f.tool_calls){let g=_.name||"tool",p=jI(_.args),y=Ge(_.args),E={role:"tool_use",timestamp:m,content:p,toolName:g,toolInput:p,toolInputData:y};o.push(E),d.push({name:g,stepIndex:f.step_index,input:y,message:E})}if(Zp(f)&&f.content)o.push({role:"assistant",timestamp:m,content:f.content,model:a});else if(UI(f)&&f.content){let _=XI(f,n),g=_===void 0?null:await this.readTaskLog(n,_),p={role:"tool_result",timestamp:g?.modifiedAt??m,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:_,...g===null?{}:{toolDetailedContent:g.content}};o.push(p),u.push({event:f,message:p})}f.thinking&&o.push({role:"thinking",timestamp:m,content:f.thinking})}return qI(d,u),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(f=>f.role==="user"||f.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await zp(r),r}catch{}let n=ft(this.baseDir,"conversations");try{let s=[];for(let i of await Vp(n)){if(!i.endsWith(".db"))continue;vl(i,".db").startsWith(e)&&s.push(ft(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=nh(r);return n?(await Yp(this.conversationPath(n),{force:!0}),await Yp(ft(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await BI(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=ft(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Kp(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}async readTaskLog(e,r){if(!/^task-\d+$/.test(r))return null;let n=ft(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Kp(n,"utf8"),ce(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as QI}from"node:child_process";import{StringDecoder as oh}from"node:string_decoder";function xi(t){return async(e,r)=>{let n=Date.now(),s=t.buildArgs(e,r);t.assertArgs?.(s,r),r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot started (no streaming events)`});let{stdout:i}=await ZI(t.label,r.binary,s,{cwd:r.cwd,env:Ee(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function ZI(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=QI(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new oh("utf8"),d=new oh("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,m)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let h=m?`signal ${m}`:`exit code ${f}`,_=l.trim()||a.trim();i(new Error(`${t} failed (${h})${_?`: ${_}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var Sl=k(()=>{"use strict";dt()});function Il(t){return new bl(t)}function tx(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var bl,ex,xl=k(()=>{"use strict";ih();je();$e();vt();Sl();bl=class extends Q{constructor(e){super({provider:new Ii(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",G,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:ex})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},ex=xi({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",tx(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Se("agy",t,e.permissionMode??"yolo")})});import rx from"node:zlib";function ux(t,e){return t[e]===sx&&t[e+1]===ix&&t[e+2]===ox&&t[e+3]===ax}function ah(t,e){return(t[e]&240)===80&&t[e+1]===lx&&t[e+2]===cx&&t[e+3]===dx}function mx(t,e){if(ah(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!ux(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,d=(c&1)!==0,u=c>>1&3,f=c>>3;if(r+=3,u===3||(r+=u===1?1:f,r>t.length))return;if(d)break}if(o&&(r+=4),!(r>t.length))return r-e}}function fx(t){let e=[],r=0;for(;r+4<=t.length;){let n=mx(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function ki(t){let e=[];for(let r of fx(t))ah(r,0)||e.push(nx(r).toString("utf8"));return e.join("")}var nx,sx,ix,ox,ax,lx,cx,dx,kl=k(()=>{"use strict";nx=rx.zstdDecompressSync,sx=40,ix=181,ox=47,ax=253,lx=42,cx=77,dx=24});import{readdir as Al,rm as px,stat as hx}from"node:fs/promises";import{join as Kt}from"node:path";function gx(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Rl(t){if(typeof t=="string")return t;if(!Array.isArray(t))return"";let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string"&&e.push(r.text);return e.join("")}function _x(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&e.push(r.text);return e}function lh(t){let e=[];for(let r of t){let n=r.data??{},s=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:Rl(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of _x(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Rl(i?.content),model:i?.source?.model})}else if(r.type==="tool/call"){let i=n,o;if(typeof i.arguments=="string")try{o=JSON.parse(i.arguments)}catch{}else i.arguments&&typeof i.arguments=="object"&&(o=i.arguments);e.push({role:"tool_use",timestamp:s,content:typeof i.arguments=="string"?i.arguments:JSON.stringify(i.arguments??{}),toolName:i.name,toolCallId:i.callId,toolInputData:o})}else if(r.type==="tool/result"){let i=n,a=(Array.isArray(i.message?.content)?i.message.content:[])[0];e.push({role:"tool_result",timestamp:s,content:Rl(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function yx(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function ch(t,e,r){let n=t.find(m=>m.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let m of t)if(m.type==="request/header"){let h=m.data?.header;h?.config?.model&&(a=h.config.model)}let l=t.map(m=>m.time).filter(m=>typeof m=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,f=r.filter(m=>m.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(m=>m.role==="user"||m.role==="assistant").length,filePath:e,...Ex(t)}}function Ex(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let d=Ai(c.inputTokens),u=Ai(c.cacheReadTokens),f=Ai(c.outputTokens),m=Ai(c.reasoningTokens);r+=d,n+=u,s+=f,i+=m,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:f,reasoningOutputTokens:m,totalTokens:d+u+f}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function Ai(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var Ri,dh=k(()=>{"use strict";ve();kl();Ri=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||Kt(W,".dsh");this.sessionsDir=Kt(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Al(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Al(Kt(this.sessionsDir,n))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(n,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.findSessionDir(e);if(!r)return null;let n=await this.readRecords(r.cwdDir,r.sessionDir);if(n.length===0)return null;let s=lh(n),i=ch(n,r.filePath,s);return i?{...i,turnStatus:yx(n),messages:s}:null}async resolveSessionPath(e){return(await this.findSessionDir(e))?.filePath??null}async deleteSession(e){let r=await this.findSessionDir(e);return r?(await px(Kt(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return Kt(this.sessionsDir,gx(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Al(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=Kt(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await hx(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=Kt(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=ki(i),a=[];for(let l of o.split(`
|
|
1605
|
+
`))if(l.trim())try{let c=JSON.parse(l);if(c.type?.endsWith("-chunks")||c.type==="assistant/chunk")continue;a.push(c)}catch{}return a}async readSummary(e,r){let n=await this.readRecords(e,r);if(n.length===0)return null;let s=Kt(this.sessionsDir,e,r,"session.jsonl.zstd");return ch(n,s,lh(n))}}});import{spawn as Tx}from"node:child_process";async function Ni(t,e=r=>Nl.spawn(r)){if(Yt){let r=await Yt.catch(()=>{});if(r?.alive)return r;Yt=void 0}return Yt=e(t),Yt}async function Vn(){if(!Yt)return;(await Yt.catch(()=>{}))?.shutdown(),Yt=void 0}var wx,uh,Kr,Nl,Yt,mh=k(()=>{"use strict";wx=/dsh web:\s*(https?:\/\/\S+)/,uh=2e4,Kr=class t extends Error{method;detail;constructor(e,r){super(`dsh RPC ${e} failed: ${JSON.stringify(r)}`),this.name="DshRpcCallError",this.method=e,this.detail=r,Object.setPrototypeOf(this,t.prototype)}},Nl=class t{baseUrl;child;constructor(e,r){this.baseUrl=e,this.child=r}static forTesting(e){return new t(e,void 0)}async rpc(e,r){let n=`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s;try{s=await fetch(`${this.baseUrl}/api/${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({type:"client-request",rpcId:n,method:e,payload:r})})}catch(a){throw new Kr(e,`transport error: ${a instanceof Error?a.message:String(a)}`)}let i;try{i=await s.json()}catch{i=void 0}if(!s.ok)throw new Kr(e,i??s.statusText);let o=i&&typeof i=="object"?i.result:void 0;if(!o||typeof o!="object"||typeof o.ok!="boolean")throw new Kr(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new Kr(e,o.error??o);return"value"in o?o.value:void 0}get alive(){return this.child!==void 0&&this.child.exitCode===null&&this.child.signalCode===null}shutdown(){this.child!==void 0&&this.alive&&this.child.kill("SIGTERM")}static spawn(e){return new Promise((r,n)=>{let s=Tx("dsh",["web","--no-open","--port","0"],{env:e,stdio:["ignore","pipe","pipe"]}),i=!1,o="",a="",l=setTimeout(()=>{i||(i=!0,s.kill("SIGTERM"),n(new Error(`dsh web sidecar did not report a boot URL within ${uh}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},uh);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let d=wx.exec(o);d&&(i=!0,clearTimeout(l),r(new t(d[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,d)=>{if(i)return;i=!0,clearTimeout(l);let u=d?`signal ${d}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${u}): ${a.slice(0,500)}`))})})}}});import{randomUUID as vx}from"node:crypto";import{existsSync as fh}from"node:fs";import{readFile as Sx,mkdir as bx}from"node:fs/promises";function Dl(t){return new Ol(t)}function Cl(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function xx(t){let e=t?.kind??"unknown",r=t?.error?.message;return r?`dsh turn ended with reason=${e}: ${r}`:`dsh turn ended with reason=${e} and no assistant text`}function Li(t){return t instanceof Error?t.message:String(t)}async function kx(t){let e=await ph(t),r=-1;for(let n of e)n.type==="turn/end"&&typeof n.seq=="number"&&n.seq>r&&(r=n.seq);return r}async function ph(t){let e;try{e=await Sx(t)}catch{return[]}let r=ki(e),n=[];for(let s of r.split(`
|
|
1606
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function Ax(t){let r=t.data?.message?.content;if(typeof r=="string")return r;if(!Array.isArray(r))return"";let n=[];for(let s of r)s&&typeof s=="object"&&s.type==="text"&&typeof s.text=="string"&&n.push(s.text);return n.join("")}var Ix,Ll,Ol,Ml=k(()=>{"use strict";je();dh();kl();mh();$e();vt();Ix=500,Ll=8*60*60*1e3;Ol=class extends Q{dshProvider;constructor(e){let r=new Ri(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(n,s)=>this.dshPromptTurn(n,s)}),this.dshProvider=r}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,r){await bx(e,{recursive:!0});let n=`session-${vx()}`,s=Cl(process.env);Se("dsh",[],"yolo");try{let i;try{i=await Ni(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Li(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Li(a)}`}}if(r?.model)try{await i.rpc("session.selectModel",{sessionId:n,provider:"deepseek-official",model:r.model})}catch(a){return{success:!1,error:`session.selectModel("${r.model}") failed: ${Li(a)}`}}let o=r?.prompt??G;try{await this.promptAndWait(i,e,n,o,Ll)}catch(a){return{success:!1,error:`seed turn failed: ${Li(a)}`}}return{success:!0,sessionId:n}}finally{await Vn()}}async dshPromptTurn(e,r){let n=Date.now();if(r.bundleSession!==void 0){let o=r.bundleSession;if(o.provider!=="dsh")throw new Error(`bundle session provider mismatch: session serves "${o.provider}", turn targets "dsh"`);let a=await o.sendTurn(e,{signal:r.signal});return{text:a.text,sessionId:a.sessionId,durationMs:a.durationMs,...a.warnings!==void 0?{warnings:a.warnings}:{}}}let s=Cl(r.env??process.env);Se("dsh",[],r.permissionMode??"yolo");let i;try{let o=await Ni(s);r.model&&(await o.rpc("session.selectModel",{sessionId:r.sessionId,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,r.cwd,r.sessionId,e,r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Ll)}finally{await Vn()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:r.sessionId,durationMs:Date.now()-n}}async openSession(e){let r=Cl(e.env??process.env);Se("dsh",[],e.permissionMode??"yolo");let n=await Ni(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!fh(s))throw await Vn(),new Error(`dsh bundle: session file does not exist for session "${e.sessionId}" (${s}) \u2014 the session must exist before a bundle can resume it`);e.model&&await n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,d=!1,u=!1,f=async()=>{u||(u=!0,await Vn())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(m,h={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(d)throw new Error("dsh bundle session has a turn still in flight");if(h.signal?.aborted)throw new Error("Aborted");if(!fh(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);d=!0;let _=Date.now();try{let g=o.promptAndWait(n,e.cwd,i,m,Ll,h.signal);g.catch(()=>{});let p=await Promise.race([g,new Promise((y,E)=>{h.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await f()})().finally(()=>E(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:p,sessionId:i,durationMs:Date.now()-_}}finally{d=!1}},close(){return c!==null||(c=(async()=>{l=!0,await f()})()),c}}}async promptAndWait(e,r,n,s,i,o){let a=this.dshProvider.sessionFilePath(r,n),l=await kx(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=Date.now()+i;for(;;){if(o?.aborted)throw new Error("Aborted");let d=await ph(a),u=d.find(f=>f.type==="turn/end"&&(f.seq??-1)>l);if(u){let f=u.data?.reason,m=[...d].reverse().find(_=>_.type==="assistant/message"),h=m?Ax(m):"";if(f?.kind!=="completed"&&!h)throw new Error(xx(f));return h}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(f=>setTimeout(f,Ix))}}}});import{existsSync as Rx}from"node:fs";import{join as Eh,resolve as Nx}from"node:path";import{createRequire as Lx}from"node:module";function Cx(){return $l===null&&($l=Lx(import.meta.url)("node:sqlite").DatabaseSync),$l}function Fl(t={}){return Nx(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||Eh(W,".hermes"))}function Ox(t={}){return Eh(Fl(t),"state.db")}function Kn(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function Fe(t){return typeof t=="string"&&t.length>0?t:void 0}function Dx(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function _h(t){return Fe(t.cwd)??Fe(Dx(t.model_config).cwd)??"(unknown)"}function Mx(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function $x(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string")return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function yh(t){let e=t.input_tokens??0,r=t.output_tokens??0,n=t.cache_read_tokens??0,s=t.cache_write_tokens??0,i=t.reasoning_tokens??0;return(t.message_count??0)>0&&e+r+n+s+i>0?{totalInputTokens:e,totalCachedInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:r,totalReasoningOutputTokens:i}:{}}var $l,hh,gh,Ci,Th=k(()=>{"use strict";ve();J();$l=null;hh="acp";gh=`id, source, model, model_config, started_at,
|
|
1607
1607
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
1608
|
-
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;
|
|
1608
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;Ci=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=Ox(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!Rx(this.dbPath))return null;let e=null;try{return e=new(Cx())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(r){return e?.close(),L({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}}selectSessionRow(e,r){return e.prepare(`SELECT ${gh} FROM sessions WHERE id = ? AND source = ?`).get(r,hh)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let r=e.prepare(`SELECT ${gh} FROM sessions
|
|
1609
1609
|
WHERE source = ?
|
|
1610
1610
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1611
1611
|
LIMIT ?`).all(hh,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:Fe(s.title),cwd:_h(s),createdAt:Kn(s.started_at),modifiedAt:Kn(s.last_activity_at??s.started_at),model:Fe(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...yh(s)})}return n}catch(r){return L({event:"hermes_discover_sessions_failed",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),[]}finally{e.close()}}activeMessageRows(e,r){let n=new Set(e.prepare("PRAGMA table_info(messages)").all().map(a=>a.name)),i=`id, session_id, role, content, tool_call_id, tool_calls, tool_name,
|
|
1612
1612
|
timestamp, finish_reason${["_compressed_summary","display_kind"].filter(a=>n.has(a)).map(a=>`, ${a}`).join("")}`,o="WHERE session_id = ? AND role IN ('user', 'assistant', 'tool')";try{return e.prepare(`SELECT ${i} FROM messages ${o} AND active = 1 ORDER BY id ASC`).all(r)}catch(a){if(!/no such column/i.test(a instanceof Error?a.message:String(a)))throw a;return e.prepare(`SELECT ${i} FROM messages ${o} ORDER BY id ASC`).all(r)}}previewTexts(e,r){try{let[n,s]=["ASC","DESC"].map(i=>{let o=`SELECT content FROM messages WHERE session_id = ?
|
|
1613
|
-
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(r)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(r)}return a?P(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Kn(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=P(u,80)),l=P(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:Fe(c.tool_call_id),toolName:Fe(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Fe(n.model),stopReason:Fe(c.finish_reason)});for(let f of Cx(c.tool_calls)){let m=Ox(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Fe(f.function?.name)??"tool_call",toolName:Fe(f.function?.name),toolCallId:Fe(f.call_id)??Fe(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:Ge(m)})}}return{provider:this.name,sessionId:n.id,slug:Fe(n.title),cwd:_h(n),createdAt:Kn(n.started_at),modifiedAt:Kn(n.last_activity_at??n.started_at),model:Fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...yh(n),messages:i,userPrompts:o}}catch(n){return L({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as Dx}from"node:fs/promises";function $x(t){return Mx.test(t)}function wh(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return Fx}function Pl(t){return new Fl(t)}var Mx,Fx,Fl,Ul=k(()=>{"use strict";je();Th();St();$e();J();Mx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Fx="dont_ask";Fl=class extends Q{hermesProvider;hermesHome;constructor(e){let r=new Ni(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(n,s)=>ut(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:wh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=$l(e)}async openSession(e){return mt({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:wh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Dx(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??G,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return $x(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as vh,rm as Px,stat as Ux}from"node:fs/promises";import{join as jl}from"node:path";function Bl(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function Sh(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Li,bh=k(()=>{"use strict";ve();Li=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||jl(W,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await vh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=jl(this.baseDir,n);try{if(!(await Ux(s)).isDirectory())continue;for(let i of await vh(s))i.endsWith(".jsonl")&&r.push(jl(s,i))}catch{}}return r}async readHeader(e){for await(let r of le(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await ce(e),s,i,o,a=0,l=0,c=0,d=0,u=0,f=0,m=0,g;for await(let h of le(e)){if(h.type==="model_change"&&h.provider&&h.modelId){s=`${h.provider}/${h.modelId}`;continue}if(h.type!=="message"||!h.message)continue;let _=h.message;if(_.provider&&_.model&&(s=`${_.provider}/${_.model}`),_.role==="user"){let p=Bl(_).trim();p&&(i||(i=P(p,80)),o=P(p,80)),a++}else if(_.role==="assistant"){a++;let p=_.usage;p&&(l+=p.input??0,c+=p.cacheRead??0,d+=p.cacheWrite??0,u+=p.output??0,f+=p.reasoning??0,m=p.input??0,g={inputTokens:p.input,cachedInputTokens:p.cacheRead,cacheWriteInputTokens:p.cacheWrite,outputTokens:p.output,reasoningOutputTokens:p.reasoning,totalTokens:p.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:m,lastTokenUsage:g}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of le(r)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:Bl(a)});else if(a.role==="assistant"&&Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?s.push({role:"assistant",timestamp:l,content:c.text,model:i}):c.type==="thinking"&&c.thinking?s.push({role:"thinking",timestamp:l,content:c.thinking}):c.type==="toolCall"&&s.push({role:"tool_use",timestamp:l,content:Sh(c.arguments),toolName:c.name??"tool",toolInput:Sh(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Bl(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let r=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(r))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let r=await this.resolveSessionPath(e);return r?(await Px(r,{force:!0}),!0):!1}}});function Hl(t){return new Wl(t)}var Wl,jx,Xl=k(()=>{"use strict";bh();je();$e();vt();vl();Wl=class extends Q{constructor(e){super({provider:new Li(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",G],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:jx})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && pi`,postLaunchNote:"Send the lmctl seed instruction, wait for the session file to write, then exit.",lsCommand:`lmctl ls --provider pi --sessiondir ${e}`}}},jx=bi({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Se("pi",t,e.permissionMode??"yolo")})});import{createHash as Bx}from"node:crypto";import{existsSync as Wx,mkdirSync as Gl,readFileSync as Hx,renameSync as Xx,rmdirSync as Ch,statSync as qx,writeFileSync as Gx}from"node:fs";import{dirname as Yl,join as Ih,resolve as ql}from"node:path";function Jx(t){return Bx("sha256").update(t).digest("hex").slice(0,8)}function Vx(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function Kx(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function Oh(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Ci(t){return Math.max(1,Math.ceil(t.length/4))}function Yr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return ql(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Ih(Yl(ql(r)),".lmctl-claude-mock","sessions.json"):Ih(ql(t),".lmctl-claude-mock","sessions.json")}function xh(){return{schemaVersion:1,sessions:{}}}function Yn(t){if(!Wx(t))return xh();try{let e=JSON.parse(Hx(t,"utf8")),r=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Jl(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return xh()}}function Dh(t,e){Gl(Yl(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;Gx(r,`${JSON.stringify(e,null,2)}
|
|
1614
|
-
`,"utf8"),Xx(r,t)}function Qx(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Zx(t){let e=`${t}.lock`;Gl(Yl(t),{recursive:!0});let r=Date.now()+kh;for(;;)try{return Gl(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-qx(e).mtimeMs>Yx){try{Ch(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${kh}ms: ${e}`);Qx(zx)}}function ek(t){try{Ch(t)}catch{}}function Mh(t,e){let r=Zx(t);try{return e()}finally{ek(r)}}function tk(t){return{...t,timestamp:t.timestamp.toISOString()}}function rk(t){return{...t,timestamp:new Date(t.timestamp)}}function nk(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(tk)}}function $h(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(rk)}}function Oi(t,e=process.cwd()){let r=Kr.get(t);if(r!==void 0)return r;let s=Yn(Yr(e)).sessions[t];if(s===void 0)return;let i=$h(s);return Kr.set(i.sessionId,i),i}function Ah(t){Kr.set(t.sessionId,t);let e=Yr(t.cwd);Mh(e,()=>{let r=Yn(e);r.sessions[t.sessionId]=nk({...t,filePath:e}),Dh(e,r)})}function sk(t,e=process.cwd()){let r=Yr(e);return Mh(r,()=>{let n=Yn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Dh(r,n)),s})}function ik(){let t=Yn(Yr()),e=Object.values(t.sessions).map($h);for(let r of e)Kr.set(r.sessionId,r);return e}function Jl(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Rh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Jl(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Jl(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Nh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function ok(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Rh(r[t]??r[Oh(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Rh(n[s]);if(i!==void 0)return i}}}function Lh(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function zl(){return new Kl}var Kr,Yx,zx,kh,Vl,Kl,Ql=k(()=>{"use strict";Kr=new Map;Yx=5e3,zx=15,kh=1e4;Vl=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of ik())e.set(r.sessionId,r);for(let r of Kr.values())e.set(r.sessionId,r);return[...e.values()].map(Lh)}async loadSession(e){let r=Oi(e);return r===void 0?null:{...Lh(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Oi(e)?.filePath??null}async deleteSession(e){let r=Kr.delete(e),n=sk(e);return r||n}},Kl=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Vl;discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return[]}async seed(e,r){let n=Vx(Kx(e,r)),s=`mock-${n}-${Jx(`${e}:${n}`)}`,i=new Date,o=Yr(e),a=Oi(s,e),l=r?.prompt??"ClaudeMock seed",c=Ci(l),d={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=Ci("ACK: ClaudeMock seeded"),Ah(d),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Oi(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Yn(Yr(r.cwd)),a=ok(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Nh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Oh(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Ci(e),s.totalOutputTokens+=Ci(c),Ah(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Nh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function zt(t){let e=[qa({claudeDir:t?.claudeDir}),Ka({codexDir:t?.codexDir,codeDir:t?.codeDir}),tl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),il({copilotDir:t?.copilotDir}),ll(),fl({kimiHome:t?.kimiHome}),gl({lmplayerDbPath:t?.lmplayerDbPath}),El(),bl({agyDir:t?.agyDir}),Ol({dshHome:t?.dshHome}),Pl({hermesHome:t?.hermesHome}),Hl({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(zl()),e}var Zl=k(()=>{"use strict";Ga();Ya();rl();ol();cl();pl();_l();Tl();Il();Dl();Ul();Xl();Ql();Ga();Ya();rl();ol();cl();pl();_l();Tl();Il();Dl();Ul();Xl();Ql()});var fr,zr,Fh=k(()=>{"use strict";fr=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],zr=["agy","pi","lmplayer"]});var nc={};ae(nc,{BUNDLE_CAPABLE_PROVIDERS:()=>fr,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>zr,ProviderRegistry:()=>bn,TransportConnectionError:()=>Z,TransportError:()=>Wt,TransportJsonError:()=>Ks,TransportProcessError:()=>kn,TransportRpcError:()=>An,_resetDefaultRegistryForTests:()=>ak,bundleSupportedProviders:()=>Zr,chat:()=>pr,countTokens:()=>ck,createAdapterRegistry:()=>Bt,createAllAdapters:()=>zt,listSessions:()=>rc,openBundleSession:()=>zn,seed:()=>tc});function Qr(){return Di===null&&(Di=Bt(zt())),Di}function ak(){Di=null}function ec(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function pr(t){let e=t.registry??Qr(),r=ec(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function Zr(t){return(t??Qr()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function zn(t){let e=t.registry??Qr(),r=ec(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${Zr(e).join(", ")})`);return r.openSession(t)}async function tc(t){let e=t.registry??Qr(),r=ec(e,t.provider),n=await Ph(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await Ph(e,t.provider,t.cwd),a=lk(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function Ph(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function lk(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function rc(t={}){return(t.registry??Qr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function ck(t){let r=await(t.registry??Qr()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var Di,bt=k(()=>{"use strict";_a();Zl();_a();Zl();Fh();lr();Di=null});function Mi(t){return uk.has(t)}function ic(){return sc===null&&(sc=Bt(zt())),sc}function oc(t,e,r={}){if(!Mi(t))return null;try{let n=ic().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?ti({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?dk[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...Uh[t]??[]]}catch{return null}}function Bh(t,e,r={}){let n=oc(t,e,r);return n===null?null:n.join(" ")}function Ie(t,e){return ic().getSession(t,e)}async function en(t){return(await ic().resolveSessions(t)).map(r=>r.provider.name)}var Uh,dk,uk,jh,sc,Qt=k(()=>{"use strict";bt();ka();Uh={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},dk={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},uk=new Set(Object.keys(Uh)),jh=/^[\w.:-]+$/;sc=null});function mk(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Wh;let r=Number(e);return!Number.isFinite(r)||r<=0?Wh:r}async function fk(t,e,r){try{let n=ue(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await en(s);if(c.length!==1)return null;i=c[0]}let o=await Ie(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function Hh(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??mk(),o=await fk(t,r,n),a=o!==null&&o>=i;return a&&L({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var Wh,Xh=k(()=>{"use strict";J();Qt();Pe();Wh=36e5});function pk(t){return t===null?null:Re(t)?"live":"dead"}function ac(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:pk(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function hk(t){return(0,qh.formatDuration)(t)}function lc(t){let e=[];return t.idle_ms!==null&&e.push(`active ${hk(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var qh,Gh=k(()=>{"use strict";or();qh=_t(ct(),1)});import{randomUUID as gk}from"node:crypto";import{hostname as Jh,networkInterfaces as _k}from"node:os";function Vh(t){let e=(t.now??new Date).toISOString();return{lock_id:gk(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??Jh(),holder_ips:t.ips??vk(),started_at:e,last_heartbeat:e}}function Kh(t=process.env){return Yh(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,yk)}function Tk(t=process.env){return Yh(t.LMCTL_TERMINAL_LOCK_STALE_MS,Ek)}function cc(t,e={}){let r=e.now??new Date,n=e.localHost??Jh(),s=e.staleMs??Tk();if(t.holder_host===n)return(e.isProcessAlive??wk)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function hr(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function Yh(t,e){if(t===void 0||t.trim()==="")return e;let r=t.trim(),n=Number.parseInt(r,10);return!Number.isFinite(n)||n<=0||String(n)!==r?e:n}function wk(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function vk(){let t=new Set;for(let e of Object.values(_k()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var yk,Ek,Qn=k(()=>{"use strict";yk=15e3,Ek=12e4});function Sk(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
1613
|
+
AND role = 'user' AND content != ''`,a;try{a=e.prepare(`${o} AND active = 1 ORDER BY id ${i} LIMIT 1`).get(r)}catch(l){if(!/no such column: active/i.test(String(l)))throw l;a=e.prepare(`${o} ORDER BY id ${i} LIMIT 1`).get(r)}return a?P(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let d=Kn(c.timestamp),u=c.content??"";if(c.role==="user"){u&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(u),u.length>0&&(a||(a=P(u,80)),l=P(u,80)),i.push({role:"user",timestamp:d,content:u||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:d,content:u,toolCallId:Fe(c.tool_call_id),toolName:Fe(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Fe(n.model),stopReason:Fe(c.finish_reason)});for(let f of Mx(c.tool_calls)){let m=$x(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Fe(f.function?.name)??"tool_call",toolName:Fe(f.function?.name),toolCallId:Fe(f.call_id)??Fe(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:Ge(m)})}}return{provider:this.name,sessionId:n.id,slug:Fe(n.title),cwd:_h(n),createdAt:Kn(n.started_at),modifiedAt:Kn(n.last_activity_at??n.started_at),model:Fe(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...yh(n),messages:i,userPrompts:o}}catch(n){return L({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as Fx}from"node:fs/promises";function Ux(t){return Px.test(t)}function wh(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return jx}function Ul(t){return new Pl(t)}var Px,jx,Pl,jl=k(()=>{"use strict";je();Th();St();$e();J();Px=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;jx="dont_ask";Pl=class extends Q{hermesProvider;hermesHome;constructor(e){let r=new Ci(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(n,s)=>ut(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:wh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Fl(e)}async openSession(e){return mt({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:wh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Fx(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??G,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return Ux(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as vh,rm as Bx,stat as Wx}from"node:fs/promises";import{join as Bl}from"node:path";function Wl(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>e.type==="text"&&e.text).map(e=>e.text).join(" "):""}function Sh(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Oi,bh=k(()=>{"use strict";ve();Oi=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Bl(W,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await vh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=Bl(this.baseDir,n);try{if(!(await Wx(s)).isDirectory())continue;for(let i of await vh(s))i.endsWith(".jsonl")&&r.push(Bl(s,i))}catch{}}return r}async readHeader(e){for await(let r of le(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await ce(e),s,i,o,a=0,l=0,c=0,d=0,u=0,f=0,m=0,h;for await(let _ of le(e)){if(_.type==="model_change"&&_.provider&&_.modelId){s=`${_.provider}/${_.modelId}`;continue}if(_.type!=="message"||!_.message)continue;let g=_.message;if(g.provider&&g.model&&(s=`${g.provider}/${g.model}`),g.role==="user"){let p=Wl(g).trim();p&&(i||(i=P(p,80)),o=P(p,80)),a++}else if(g.role==="assistant"){a++;let p=g.usage;p&&(l+=p.input??0,c+=p.cacheRead??0,d+=p.cacheWrite??0,u+=p.output??0,f+=p.reasoning??0,m=p.input??0,h={inputTokens:p.input,cachedInputTokens:p.cacheRead,cacheWriteInputTokens:p.cacheWrite,outputTokens:p.output,reasoningOutputTokens:p.reasoning,totalTokens:p.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:m,lastTokenUsage:h}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of le(r)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:Wl(a)});else if(a.role==="assistant"&&Array.isArray(a.content))for(let c of a.content)c.type==="text"&&c.text?s.push({role:"assistant",timestamp:l,content:c.text,model:i}):c.type==="thinking"&&c.thinking?s.push({role:"thinking",timestamp:l,content:c.thinking}):c.type==="toolCall"&&s.push({role:"tool_use",timestamp:l,content:Sh(c.arguments),toolName:c.name??"tool",toolInput:Sh(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Wl(a),toolName:a.toolName,toolCallId:a.toolCallId})}return{...n,model:i,messages:s}}async resolveSessionPath(e){let r=`_${e}.jsonl`,n=[];for(let s of await this.listSessionFiles()){if(s.endsWith(r))return s;s.split("_").pop()?.replace(/\.jsonl$/,"")?.startsWith(e)&&n.push(s)}return n.length===1?n[0]:null}async deleteSession(e){let r=await this.resolveSessionPath(e);return r?(await Bx(r,{force:!0}),!0):!1}}});function Xl(t){return new Hl(t)}var Hl,Hx,ql=k(()=>{"use strict";bh();je();$e();vt();Sl();Hl=class extends Q{constructor(e){super({provider:new Oi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",G],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:Hx})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && pi`,postLaunchNote:"Send the lmctl seed instruction, wait for the session file to write, then exit.",lsCommand:`lmctl ls --provider pi --sessiondir ${e}`}}},Hx=xi({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>Se("pi",t,e.permissionMode??"yolo")})});import{createHash as Xx}from"node:crypto";import{existsSync as qx,mkdirSync as Jl,readFileSync as Gx,renameSync as Jx,rmdirSync as Ch,statSync as Vx,writeFileSync as Kx}from"node:fs";import{dirname as zl,join as Ih,resolve as Gl}from"node:path";function Yx(t){return Xx("sha256").update(t).digest("hex").slice(0,8)}function zx(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function Qx(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function Oh(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Di(t){return Math.max(1,Math.ceil(t.length/4))}function zr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Gl(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Ih(zl(Gl(r)),".lmctl-claude-mock","sessions.json"):Ih(Gl(t),".lmctl-claude-mock","sessions.json")}function xh(){return{schemaVersion:1,sessions:{}}}function Yn(t){if(!qx(t))return xh();try{let e=JSON.parse(Gx(t,"utf8")),r=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=Vl(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return xh()}}function Dh(t,e){Jl(zl(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;Kx(r,`${JSON.stringify(e,null,2)}
|
|
1614
|
+
`,"utf8"),Jx(r,t)}function tk(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function rk(t){let e=`${t}.lock`;Jl(zl(t),{recursive:!0});let r=Date.now()+kh;for(;;)try{return Jl(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Vx(e).mtimeMs>Zx){try{Ch(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${kh}ms: ${e}`);tk(ek)}}function nk(t){try{Ch(t)}catch{}}function Mh(t,e){let r=rk(t);try{return e()}finally{nk(r)}}function sk(t){return{...t,timestamp:t.timestamp.toISOString()}}function ik(t){return{...t,timestamp:new Date(t.timestamp)}}function ok(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(sk)}}function $h(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(ik)}}function Mi(t,e=process.cwd()){let r=Yr.get(t);if(r!==void 0)return r;let s=Yn(zr(e)).sessions[t];if(s===void 0)return;let i=$h(s);return Yr.set(i.sessionId,i),i}function Ah(t){Yr.set(t.sessionId,t);let e=zr(t.cwd);Mh(e,()=>{let r=Yn(e);r.sessions[t.sessionId]=ok({...t,filePath:e}),Dh(e,r)})}function ak(t,e=process.cwd()){let r=zr(e);return Mh(r,()=>{let n=Yn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Dh(r,n)),s})}function lk(){let t=Yn(zr()),e=Object.values(t.sessions).map($h);for(let r of e)Yr.set(r.sessionId,r);return e}function Vl(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Rh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Vl(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=Vl(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Nh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function ck(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Rh(r[t]??r[Oh(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Rh(n[s]);if(i!==void 0)return i}}}function Lh(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function Ql(){return new Yl}var Yr,Zx,ek,kh,Kl,Yl,Zl=k(()=>{"use strict";Yr=new Map;Zx=5e3,ek=15,kh=1e4;Kl=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of lk())e.set(r.sessionId,r);for(let r of Yr.values())e.set(r.sessionId,r);return[...e.values()].map(Lh)}async loadSession(e){let r=Mi(e);return r===void 0?null:{...Lh(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Mi(e)?.filePath??null}async deleteSession(e){let r=Yr.delete(e),n=ak(e);return r||n}},Yl=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Kl;discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return[]}async seed(e,r){let n=zx(Qx(e,r)),s=`mock-${n}-${Yx(`${e}:${n}`)}`,i=new Date,o=zr(e),a=Mi(s,e),l=r?.prompt??"ClaudeMock seed",c=Di(l),d={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=Di("ACK: ClaudeMock seeded"),Ah(d),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Mi(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Yn(zr(r.cwd)),a=ck(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Nh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Oh(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:c,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Di(e),s.totalOutputTokens+=Di(c),Ah(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Nh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function zt(t){let e=[Ga({claudeDir:t?.claudeDir}),Ya({codexDir:t?.codexDir,codeDir:t?.codeDir}),rl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),ol({copilotDir:t?.copilotDir}),cl(),pl({kimiHome:t?.kimiHome}),_l({lmplayerDbPath:t?.lmplayerDbPath}),Tl(),Il({agyDir:t?.agyDir}),Dl({dshHome:t?.dshHome}),Ul({hermesHome:t?.hermesHome}),Xl({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Ql()),e}var ec=k(()=>{"use strict";Ja();za();nl();al();dl();hl();yl();wl();xl();Ml();jl();ql();Zl();Ja();za();nl();al();dl();hl();yl();wl();xl();Ml();jl();ql();Zl()});var fr,Qr,Fh=k(()=>{"use strict";fr=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],Qr=["agy","pi","lmplayer"]});var sc={};ae(sc,{BUNDLE_CAPABLE_PROVIDERS:()=>fr,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Qr,ProviderRegistry:()=>bn,TransportConnectionError:()=>Z,TransportError:()=>Wt,TransportJsonError:()=>zs,TransportProcessError:()=>kn,TransportRpcError:()=>An,_resetDefaultRegistryForTests:()=>dk,bundleSupportedProviders:()=>en,chat:()=>pr,countTokens:()=>mk,createAdapterRegistry:()=>Bt,createAllAdapters:()=>zt,listSessions:()=>nc,openBundleSession:()=>zn,seed:()=>rc});function Zr(){return $i===null&&($i=Bt(zt())),$i}function dk(){$i=null}function tc(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function pr(t){let e=t.registry??Zr(),r=tc(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function en(t){return(t??Zr()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function zn(t){let e=t.registry??Zr(),r=tc(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${en(e).join(", ")})`);return r.openSession(t)}async function rc(t){let e=t.registry??Zr(),r=tc(e,t.provider),n=await Ph(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await Ph(e,t.provider,t.cwd),a=uk(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function Ph(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function uk(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function nc(t={}){return(t.registry??Zr()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function mk(t){let r=await(t.registry??Zr()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var $i,bt=k(()=>{"use strict";ya();ec();ya();ec();Fh();lr();$i=null});function Fi(t){return pk.has(t)}function oc(){return ic===null&&(ic=Bt(zt())),ic}function ac(t,e,r={}){if(!Fi(t))return null;try{let n=oc().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?ni({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?fk[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...Uh[t]??[]]}catch{return null}}function Bh(t,e,r={}){let n=ac(t,e,r);return n===null?null:n.join(" ")}function Ie(t,e){return oc().getSession(t,e)}async function tn(t){return(await oc().resolveSessions(t)).map(r=>r.provider.name)}var Uh,fk,pk,jh,ic,Qt=k(()=>{"use strict";bt();Aa();Uh={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],pi:[],lmplayer:["--auto"],kimi:[],hermes:[]},fk={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t],kimi:t=>["--model",t],hermes:t=>["--model",t],pi:t=>["--model",t]},pk=new Set(Object.keys(Uh)),jh=/^[\w.:-]+$/;ic=null});function hk(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Wh;let r=Number(e);return!Number.isFinite(r)||r<=0?Wh:r}async function gk(t,e,r){try{let n=ue(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await tn(s);if(c.length!==1)return null;i=c[0]}let o=await Ie(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function Hh(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??hk(),o=await gk(t,r,n),a=o!==null&&o>=i;return a&&L({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var Wh,Xh=k(()=>{"use strict";J();Qt();Pe();Wh=36e5});function _k(t){return t===null?null:Re(t)?"live":"dead"}function lc(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:_k(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function yk(t){return(0,qh.formatDuration)(t)}function cc(t){let e=[];return t.idle_ms!==null&&e.push(`active ${yk(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var qh,Gh=k(()=>{"use strict";or();qh=_t(ct(),1)});import{randomUUID as Ek}from"node:crypto";import{hostname as Jh,networkInterfaces as Tk}from"node:os";function Vh(t){let e=(t.now??new Date).toISOString();return{lock_id:Ek(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??Jh(),holder_ips:t.ips??Ik(),started_at:e,last_heartbeat:e}}function Kh(t=process.env){return Yh(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,wk)}function Sk(t=process.env){return Yh(t.LMCTL_TERMINAL_LOCK_STALE_MS,vk)}function dc(t,e={}){let r=e.now??new Date,n=e.localHost??Jh(),s=e.staleMs??Sk();if(t.holder_host===n)return(e.isProcessAlive??bk)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function hr(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function Yh(t,e){if(t===void 0||t.trim()==="")return e;let r=t.trim(),n=Number.parseInt(r,10);return!Number.isFinite(n)||n<=0||String(n)!==r?e:n}function bk(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return(e!==null&&typeof e=="object"&&"code"in e?e.code:void 0)!=="ESRCH"}}function Ik(){let t=new Set;for(let e of Object.values(Tk()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var wk,vk,Qn=k(()=>{"use strict";wk=15e3,vk=12e4});function xk(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
1615
1615
|
manually, outside a member session that lmctl started. Running lmctl this way is
|
|
1616
1616
|
not officially supported.
|
|
1617
1617
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function It(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
1618
1618
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
1619
1619
|
Consulted ${hn(fe())}
|
|
1620
1620
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function zh(t){return`unknown option --from
|
|
1621
|
-
${
|
|
1622
|
-
`)}function
|
|
1623
|
-
`});let y=t.env??process.env,T=await C(r,N=>N.getRootTeam(_)?.name??null);T!==null&&(y.LMBEE_TEAM_NAME=T),i=await Ck(r,{receiverTeamfile:m,receiverAlias:f.alias,sender:h,rootTeamfile:_,provider:f.provider,model:f.model,sessionId:f.sessionid,cwd:f.sessiondir,prompt:t.prompt,origin:g.origin,parentInvocationId:jt(y.LMCTL_INVOCATION_ID)}),o=$k(r,i),i!==null&&(y.LMCTL_INVOCATION_ID=String(i));try{Cr(r,ke(m),m)}catch{}n={root_teamfile:_,sender_teamfile:h?.teamfile??null,sender_alias:h?.alias??null,receiver_teamfile:m,receiver_alias:f.alias,receiver_provider:f.provider,receiver_session_id:f.sessionid,origin:g.origin,message_type:t.messageType??null,policy:p};let v=await sg(r,m,f.alias);if(v!==null){let N=hr(v);return gr(i,n,t.prompt,N,"unavailable"),d=uc(N,null),{status:"busy",message:N,teamChatLogId:null}}let S=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,re=>{let ee=re.getAgentInflight(m,f.alias);return ee===null||ee.sender_teamfile!==N.row.sender_teamfile||ee.sender_alias!==N.row.sender_alias||ee.started_at!==N.row.started_at||ee.holder_pid!==process.pid?!1:re.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let re=`bundle lease lost for ${f.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return gr(i,n,t.prompt,re,"unavailable"),d=ts(re,null),{status:"error",errorKind:"provider",message:re,teamChatLogId:null,messageId:null}}}else{let N=await Rk(r,m,f.alias);if(N.busy){let U=await Nk(r,m,f.alias);return U+=await Lk(r,m,f.alias),gr(i,n,t.prompt,U,"unavailable"),d=uc(U,null),{status:"busy",message:U,teamChatLogId:null}}S=N.idleReclaim}if(h!==null&&h.teamfile!==m){let N=await C(r,U=>Qu(U,{root:_,sender:h,receiverTeamfile:m,receiverAlias:f.alias,now:new Date}));if(N.stop){let U=em(N.chain);return gr(i,n,t.prompt,U,"cycle"),d=ts(U,null),{status:"error",errorKind:"cycle",message:U,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await Xk(r,{receiver_teamfile:m,receiver_alias:f.alias,sender_teamfile:h?.teamfile??m,sender_alias:h?.alias??"operator",...S?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let U=ig(m,f.alias,N.current);return U+=` ${lc(ac({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,gr(i,n,t.prompt,U,"unavailable"),d=uc(U,null),{status:"busy",message:U,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=Mr(U=>C(r,re=>re.heartbeatAgentInflight(s.row,s.leaseId,U)),{intervalMs:rg,onError:U=>{K()&&_e(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:U instanceof Error?U.message:String(U)}))}})}let E=await Qh({sender:h??{teamfile:m,alias:"operator"},receiver:{teamfile:m,alias:f.alias,provider:f.provider,sessionId:f.sessionid,cwd:f.sessiondir,...f.model!==void 0?{model:f.model}:{},...f.effort!==void 0?{effort:f.effort}:{},...f.isLead!==void 0?{isLead:f.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:f.alias,event:N}),onPromptBuilt:async N=>{u=N,l===null&&(l=await Gk(r,{...n,message:N}),l!==null&&(t.onAccepted?.(wt(l)),i!==null&&await Mk(r,i,l))),i!==null&&await Dk(r,i,N)}});u=E.prompt;let b=E.status==="stalled",w=null,x=b?`provider stalled${E.stalledAfterMs!==void 0?` after ${E.stalledAfterMs}ms`:""}`:E.status==="error"?E.error??E.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,I=b||E.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await tg(r,l,{...n,message:u,response:E.receipt,status:I,error_detail:x}),c=!0,w=l):w=await Vk(r,{...n,message:u,response:E.receipt,status:I,error_detail:x});let R=E.status!=="error"?E.warnings:void 0;if(b){let N=x;gr(i,n,u,N,"error"),d=ts(N,w,E.receipt,R)}else d=Fk(E.receipt,w,R);return{status:b?"stalled":"ok",replyText:E.receipt,wroteDelta:E.wroteDelta,teamChatLogId:w,messageId:w===null?null:wt(w),durationMs:E.durationMs}}catch(f){let m=f instanceof Error?f.message:String(f);return l!==null&&!c&&n!==null&&(await tg(r,l,{...n,message:u,response:null,status:"error",error_detail:m}),c=!0),gr(i,n,u,m,"error"),d=ts(m,l),{status:"error",errorKind:f instanceof se?"target":"provider",message:m,teamChatLogId:l,messageId:l===null?null:wt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Jk(r,n,wt(l)),s!==null&&await qk(r,s.row,s.leaseId),i!==null&&await Ok(r,i,d??ts("chat turn exited without a terminal outcome",null))}}function Ak(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function Rk(t,e,r){let n=await C(t,i=>(Ur(i,e,r),at(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>Hh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function Nk(t,e,r){let n=await sg(t,e,r);if(n!==null)return hr(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?ig(e,r,s):`${r} is busy; wait and retry`}async function Lk(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${lc(ac({holderPid:n.holder_pid,since:n.started_at}))}`}async function Ck(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:Pk(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 K()&&_e(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function Ok(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Dk(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Mk(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function $k(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{K()&&_e(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},rg);return r.unref?.(),r}function ng(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function Fk(t,e,r){return{status:"done",result_summary:rs(t),error:null,team_chat_log_id:e,...ng(r)}}function uc(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,...ng(n)}}function rs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function Pk(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function Uk(t,e){let r=tn(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 jk(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>pe(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>Zu(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function Bk(t,e){return await C(t,r=>Vu({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:Wk(r,e.sender.teamfile,e.receiverTeamfile)}))}function Wk(t,e,r){return{teams:[e,r].map(s=>Hk(s,t))}}function Hk(t,e){let r=We(t,e),n=Ct(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function Xk(t,e){return await C(t,r=>{let n=K(),s=Mt(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:ot(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&_e(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:eg(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&_e(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:eg(s.current)})),{acquired:!1,current:s.current})})}async function sg(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(cc(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:cc(s).live?s:null})}function eg(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 qk(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
|
-
`)}}function ig(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
|
|
1621
|
+
${xk(t)}`}function rn(t,e){let r=uc(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function uc(t,e){let r=t[Ta];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=We(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 nn=k(()=>{"use strict";dt();rt();Tt()});function xt(t){let e=Ds(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";Pe()});function es(t,e,r){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=Qe({path:fe()})),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&&Re(a.holder_pid)),pollMs:kk,settleMs:Ak,maxHoldMs:Fr(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 Qh(t){let e=Rk(t.newMessage,{newMessageFrom:t.newMessageFrom??Nk(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=K(),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 pr(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&&_e(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}:{}}:{status:"ok",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function Rk(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
1622
|
+
`)}function Nk(t){return`${t.teamfile}:${t.alias}`}var rj,kk,Ak,Pi=k(()=>{"use strict";bt();J();Pt();rt();or();ze();rj=60*60*1e3,kk=2e3,Ak=5e3});async function _r(t){let e=t.onEvent??(()=>{}),r=Lk(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,d=null,u=t.prompt;try{let f=await C(r,N=>ue(t.teamfile,t.alias,N));if(t.expectedSession!==void 0&&(f.provider!==t.expectedSession.provider||f.sessionid!==t.expectedSession.sessionid))throw new se(`session changed for ${f.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${f.provider}:${f.sessionid}`);let m=f.teamfile,h=await C(r,N=>Wk(N,t.env??process.env)),_=h.sender,g=await Hk(r,{explicitRoot:t.rootFlag,sender:_,receiverTeamfile:m,operatorOrigin:h.origin==="operator"}),p=_===null?null:await Xk(r,{rootTeamfile:g,sender:_,receiverTeamfile:m,receiverAlias:f.alias});p!==null&&!p.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${p.reason}
|
|
1623
|
+
`});let y=t.env??process.env,E=await C(r,N=>N.getRootTeam(g)?.name??null);E!==null&&(y.LMBEE_TEAM_NAME=E),i=await Mk(r,{receiverTeamfile:m,receiverAlias:f.alias,sender:_,rootTeamfile:g,provider:f.provider,model:f.model,sessionId:f.sessionid,cwd:f.sessiondir,prompt:t.prompt,origin:h.origin,parentInvocationId:jt(y.LMCTL_INVOCATION_ID)}),o=Uk(r,i),i!==null&&(y.LMCTL_INVOCATION_ID=String(i));try{Or(r,ke(m),m)}catch{}n={root_teamfile:g,sender_teamfile:_?.teamfile??null,sender_alias:_?.alias??null,receiver_teamfile:m,receiver_alias:f.alias,receiver_provider:f.provider,receiver_session_id:f.sessionid,origin:h.origin,message_type:t.messageType??null,policy:p};let v=await sg(r,m,f.alias);if(v!==null){let N=hr(v);return gr(i,n,t.prompt,N,"unavailable"),d=mc(N,null),{status:"busy",message:N,teamChatLogId:null}}let b=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,re=>{let ee=re.getAgentInflight(m,f.alias);return ee===null||ee.sender_teamfile!==N.row.sender_teamfile||ee.sender_alias!==N.row.sender_alias||ee.started_at!==N.row.started_at||ee.holder_pid!==process.pid?!1:re.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let re=`bundle lease lost for ${f.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return gr(i,n,t.prompt,re,"unavailable"),d=ts(re,null),{status:"error",errorKind:"provider",message:re,teamChatLogId:null,messageId:null}}}else{let N=await Ck(r,m,f.alias);if(N.busy){let U=await Ok(r,m,f.alias);return U+=await Dk(r,m,f.alias),gr(i,n,t.prompt,U,"unavailable"),d=mc(U,null),{status:"busy",message:U,teamChatLogId:null}}b=N.idleReclaim}if(_!==null&&_.teamfile!==m){let N=await C(r,U=>Qu(U,{root:g,sender:_,receiverTeamfile:m,receiverAlias:f.alias,now:new Date}));if(N.stop){let U=em(N.chain);return gr(i,n,t.prompt,U,"cycle"),d=ts(U,null),{status:"error",errorKind:"cycle",message:U,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await Jk(r,{receiver_teamfile:m,receiver_alias:f.alias,sender_teamfile:_?.teamfile??m,sender_alias:_?.alias??"operator",...b?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let U=ig(m,f.alias,N.current);return U+=` ${cc(lc({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,gr(i,n,t.prompt,U,"unavailable"),d=mc(U,null),{status:"busy",message:U,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=$r(U=>C(r,re=>re.heartbeatAgentInflight(s.row,s.leaseId,U)),{intervalMs:rg,onError:U=>{K()&&_e(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:U instanceof Error?U.message:String(U)}))}})}let T=await Qh({sender:_??{teamfile:m,alias:"operator"},receiver:{teamfile:m,alias:f.alias,provider:f.provider,sessionId:f.sessionid,cwd:f.sessiondir,...f.model!==void 0?{model:f.model}:{},...f.effort!==void 0?{effort:f.effort}:{},...f.isLead!==void 0?{isLead:f.isLead}:{}},newMessage:t.prompt,newMessageFrom:_===null?"operator":`${_.teamfile}:${_.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:f.alias,event:N}),onPromptBuilt:async N=>{u=N,l===null&&(l=await Kk(r,{...n,message:N}),l!==null&&(t.onAccepted?.(wt(l)),i!==null&&await Pk(r,i,l))),i!==null&&await Fk(r,i,N)}});u=T.prompt;let S=T.status==="stalled",w=null,x=S?`provider stalled${T.stalledAfterMs!==void 0?` after ${T.stalledAfterMs}ms`:""}`:T.status==="error"?T.error??T.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,I=S||T.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await tg(r,l,{...n,message:u,response:T.receipt,status:I,error_detail:x}),c=!0,w=l):w=await zk(r,{...n,message:u,response:T.receipt,status:I,error_detail:x});let R=T.status!=="error"?T.warnings:void 0;if(S){let N=x;gr(i,n,u,N,"error"),d=ts(N,w,T.receipt,R)}else d=jk(T.receipt,w,R);return{status:S?"stalled":"ok",replyText:T.receipt,wroteDelta:T.wroteDelta,teamChatLogId:w,messageId:w===null?null:wt(w),durationMs:T.durationMs}}catch(f){let m=f instanceof Error?f.message:String(f);return l!==null&&!c&&n!==null&&(await tg(r,l,{...n,message:u,response:null,status:"error",error_detail:m}),c=!0),gr(i,n,u,m,"error"),d=ts(m,l),{status:"error",errorKind:f instanceof se?"target":"provider",message:m,teamChatLogId:l,messageId:l===null?null:wt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Yk(r,n,wt(l)),s!==null&&await Vk(r,s.row,s.leaseId),i!==null&&await $k(r,i,d??ts("chat turn exited without a terminal outcome",null))}}function Lk(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function Ck(t,e,r){let n=await C(t,i=>(jr(i,e,r),at(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>Hh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function Ok(t,e,r){let n=await sg(t,e,r);if(n!==null)return hr(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?ig(e,r,s):`${r} is busy; wait and retry`}async function Dk(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${cc(lc({holderPid:n.holder_pid,since:n.started_at}))}`}async function Mk(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:Bk(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 K()&&_e(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function $k(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Fk(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function Pk(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){K()&&_e(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function Uk(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{K()&&_e(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},rg);return r.unref?.(),r}function ng(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function jk(t,e,r){return{status:"done",result_summary:rs(t),error:null,team_chat_log_id:e,...ng(r)}}function mc(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,...ng(n)}}function rs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function Bk(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function Wk(t,e){let r=rn(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 Hk(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>pe(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>Zu(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function Xk(t,e){return await C(t,r=>Vu({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:qk(r,e.sender.teamfile,e.receiverTeamfile)}))}function qk(t,e,r){return{teams:[e,r].map(s=>Gk(s,t))}}function Gk(t,e){let r=We(t,e),n=Ct(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function Jk(t,e){return await C(t,r=>{let n=K(),s=Mt(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:ot(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&_e(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:eg(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&_e(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:eg(s.current)})),{acquired:!1,current:s.current})})}async function sg(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(dc(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:dc(s).live?s:null})}function eg(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 Vk(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
|
+
`)}}function ig(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 Kk(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 tg(t,e,r){let n=ns(r.message),s=r.response===null?null:ns(r.response);try{await C(t,i=>i.finishTeamChatLog(e,{root_teamfile:r.root_teamfile,sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias,receiver_provider:r.receiver_provider,receiver_session_id:r.receiver_session_id,provider_prompt:r.message,message:n.text,response:s?.text??null,origin:r.origin,status:r.status,error_detail:r.error_detail,truncated:n.truncated||s?.truncated?1:0,created_at:new Date().toISOString()}))}catch(i){t.stderr.write(`warning: failed to finish chat log ${e}: ${i instanceof Error?i.message:String(i)}
|
|
1626
|
-
`)}}async function
|
|
1627
|
-
`)}}async function
|
|
1628
|
-
`),null}}function gr(t,e,r,n,s){t!==null||e===null||L({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:rs(r)})}function ns(t){return t.length<=Zh?{text:t,truncated:!1}:{text:t.slice(0,Zh),truncated:!0}}var Zh,rg,
|
|
1629
|
-
`);if(l=a?[y.trim()].filter(
|
|
1630
|
-
`);try{return d?await
|
|
1626
|
+
`)}}async function Yk(t,e,r){if(e!==null)try{await C(t,n=>{n.clearCurrentlyHandlingMessage(e.receiver_teamfile,e.receiver_alias,r)})}catch(n){t.stderr.write(`warning: failed to clear chat causal pointer: ${n instanceof Error?n.message:String(n)}
|
|
1627
|
+
`)}}async function zk(t,e){let r=ns(e.message),n=e.response===null?null:ns(e.response);try{return await C(t,s=>s.insertTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
1628
|
+
`),null}}function gr(t,e,r,n,s){t!==null||e===null||L({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:rs(r)})}function ns(t){return t.length<=Zh?{text:t,truncated:!1}:{text:t.slice(0,Zh),truncated:!0}}var Zh,rg,Ui=k(()=>{"use strict";Pe();Et();Ps();Ku();Tt();yn();J();he();ze();Sn();Xh();Gh();Qn();nn();Zn();Pi();Bs();Zh=256*1024,rg=3e4});var lg={};ae(lg,{runBatch:()=>Zk});import{readFileSync as Qk}from"node:fs";async function Zk(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(og),0;let r=ie(t,[],["--legacy","--single"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==3)return A(e,og.trimEnd());let[n,s,i]=r.positionals,o=r.flags["--legacy"]===!0,a=r.flags["--single"]===!0,l,c;try{let y=Qk(i,"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
1629
|
+
`);if(l=a?[y.trim()].filter(E=>E.length>0):y.split(/\n\s*\n/u).map(E=>E.trim()).filter(Boolean),l.length===0)return A(e,`batch: ${i}: no prompts found`);c=ue(n,s,e.dal)}catch(y){return A(e,`batch: ${y instanceof Error?y.message:String(y)}`)}let d=!o&&l.length>1&&await rA(c),u={...e.env??process.env},f=await nA(e,{member:c,batchfile:i,promptCount:l.length,parentInvocationId:jt(u.LMCTL_INVOCATION_ID)}),m={status:"error",error:"batch exited without a terminal outcome"},h=y=>{m=y},_=y=>{f!==null&&(iA(e,f,{status:"cancelled",signal:y,error:`batch interrupted by ${y}`}),process.exit(y==="SIGINT"?130:143))},g=()=>_("SIGINT"),p=()=>_("SIGTERM");f!==null&&(u.LMCTL_INVOCATION_ID=String(f),process.once("SIGINT",g),process.once("SIGTERM",p)),e.stderr.write(`batch ${Me()}: starting ${l.length} prompt${l.length===1?"":"s"} -> ${c.alias} (teamfile=${n} input=${i})
|
|
1630
|
+
`);try{return d?await eA(e,{member:c,prompts:l,env:u,setRootFinish:h,teamfile:n,batchfile:i}):await fc(e,{member:c,prompts:l,env:u,setRootFinish:h,teamfile:n,batchfile:i})}finally{f!==null&&(process.removeListener("SIGINT",g),process.removeListener("SIGTERM",p),await sA(e,f,m))}}async function fc(t,e){let{member:r,prompts:n,env:s}=e;for(let[i,o]of n.entries()){t.stderr.write(`batch ${Me()}: prompt ${i+1}/${n.length} -> ${r.alias}
|
|
1631
1631
|
`);let a=Ze(t,l=>`batch ${Me()}: prompt ${i+1}/${n.length} still running (${l}s elapsed)
|
|
1632
1632
|
`);try{let l=await _r({teamfile:r.teamfile,alias:r.alias,prompt:o,expectedSession:{provider:r.provider,sessionid:r.sessionid},permissionMode:"yolo",env:{...s},messageType:"batch",...e.heldLease!==void 0?{heldLease:e.heldLease}:{},...e.bundleSession!==void 0?{bundleSession:e.bundleSession}:{},io:t,onEvent:c=>{a.poke(),c.kind==="warning"&&t.stderr.write(c.message)}});if((l.status==="ok"||l.status==="stalled")&&l.replyText&&t.stdout.write(`${l.replyText}${l.replyText.endsWith(`
|
|
1633
1633
|
`)?"":`
|
|
1634
1634
|
`}
|
|
1635
1635
|
`),l.status!=="ok"){let c=l.status==="stalled"?"provider stalled":l.message,d=`batch: stopped at prompt ${i+1}/${n.length} (${i} completed): ${c}; later prompts were not sent`;return e.setRootFinish({status:l.status==="busy"?"busy":"error",exit_code:1,error:d,result_summary:`${i}/${n.length} prompts completed`}),A(t,d)}}catch(l){let c=`batch: stopped at prompt ${i+1}/${n.length} (${i} completed): ${l instanceof Error?l.message:String(l)}; later prompts were not sent`;return e.setRootFinish({status:"error",exit_code:1,error:c,result_summary:`${i}/${n.length} prompts completed`}),A(t,c)}finally{a.stop()}}return t.stderr.write(`batch ${Me()}: completed ${n.length}/${n.length} prompts
|
|
1636
|
-
`),e.setRootFinish({status:"done",exit_code:0,result_summary:`batch completed ${n.length}/${n.length} prompts`}),0}async function
|
|
1637
|
-
`);try{let f={...s};try{let m=await C(t,
|
|
1638
|
-
`)}}function
|
|
1639
|
-
`),null}}async function
|
|
1640
|
-
`)}}function
|
|
1636
|
+
`),e.setRootFinish({status:"done",exit_code:0,result_summary:`batch completed ${n.length}/${n.length} prompts`}),0}async function eA(t,e){let{member:r,prompts:n,env:s}=e,i=await C(t,f=>(jr(f,r.teamfile,r.alias),at(f,r.teamfile,r.alias)));if(i.busy){let f=i.reason==="in-flight"?`${r.alias} is servicing ${i.inFlight.sender_alias} (${i.inFlight.sender_teamfile}) since ${i.inFlight.started_at} \u2014 wait and retry`:i.source==="terminal-lock"?hr(i.terminalLock):`${r.alias} is busy (interactive terminal); wait and retry`;return e.setRootFinish({status:"busy",exit_code:1,error:f,result_summary:"0 prompts completed"}),A(t,`batch: cannot start bundle: ${f}`)}let o=await C(t,f=>tA(s,f)),a=await C(t,f=>Mt(f,{receiver_teamfile:r.teamfile,receiver_alias:r.alias,sender_teamfile:o?.teamfile??r.teamfile,sender_alias:o?.alias??"operator",ttlMs:ot()}));if(!a.acquired){let f=`${r.alias} is servicing ${a.current.sender_alias} (${a.current.sender_teamfile}) since ${a.current.started_at} \u2014 wait and retry`;return e.setRootFinish({status:"busy",exit_code:1,error:f,result_summary:"0 prompts completed"}),A(t,`batch: cannot start bundle: ${f}`)}let l={row:a.lease,leaseId:a.leaseId},c=$r(f=>C(t,m=>m.heartbeatAgentInflight(l.row,l.leaseId,f))),d,u=Ze(t,f=>`batch ${Me()}: opening provider session (${f}s elapsed)
|
|
1637
|
+
`);try{let f={...s};try{let m=await C(t,h=>h.getRootTeam(r.teamfile)?.name??null);m!==null&&(f.LMBEE_TEAM_NAME=m)}catch{}d=await zn({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,env:f,...r.model!==void 0?{model:r.model}:{},...r.effort!==void 0?{effort:r.effort}:{},alias:r.alias,isLead:r.isLead,permissionMode:"yolo",holdOpen:es(t,{teamfile:r.teamfile,alias:r.alias},f)})}catch{return clearInterval(c),await ag(t,l),fc(t,{member:r,prompts:n,env:s,setRootFinish:e.setRootFinish,teamfile:e.teamfile,batchfile:e.batchfile})}finally{u.stop()}try{return await fc(t,{member:r,prompts:n,env:s,setRootFinish:e.setRootFinish,teamfile:e.teamfile,batchfile:e.batchfile,heldLease:l,bundleSession:d})}finally{await d.close(),clearInterval(c),await ag(t,l)}}async function ag(t,e){try{await C(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
1638
|
+
`)}}function tA(t,e){let r=rn(t,e);if(r.ok)return xt(r.identity);if(r.reason==="unset")return null;throw new Error(It("batch"))}async function rA(t){let e=t.provider.trim().toLowerCase();return Qr.includes(e)||Wr().tools[e]?.agent!==void 0||!fr.includes(e)?!1:en().includes(e)}async function nA(t,e){try{let{member:r}=e;return await C(t,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:r.teamfile,from_identity:`${r.teamfile}:batch`,target_teamfile:r.teamfile,target_alias:r.alias,root_teamfile:r.teamfile,cwd:r.sessiondir,command:`lmctl batch ${r.teamfile} ${r.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:r.provider,sessionid:r.sessionid,...r.model!==void 0?{model:r.model}:{}})}).id)}catch(r){return t.stderr.write(`warning: failed to start batch root invocation: ${r instanceof Error?r.message:String(r)}
|
|
1639
|
+
`),null}}async function sA(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){t.stderr.write(`warning: failed to finish batch root invocation: ${n instanceof Error?n.message:String(n)}
|
|
1640
|
+
`)}}function iA(t,e,r){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let n=Qe({path:fe()});try{n.finishTrackedInvocation(e,r)}finally{n.close()}}catch{}}var og,cg=k(()=>{"use strict";Ui();he();rt();Pe();Pt();ze();Sn();yn();Qn();nn();Zn();In();Pi();bt();og=`usage: lmctl batch <teamfile> <alias> <batchfile> [--legacy] [--single]
|
|
1641
1641
|
|
|
1642
1642
|
Send blank-line-separated paragraphs as prompts, one completed turn at a
|
|
1643
1643
|
time, to the same existing member session. Accepts export --prompt-only
|
|
@@ -1664,13 +1664,13 @@ lease) -- the pre-bundle behavior -- as an opt-out while bundle is new.
|
|
|
1664
1664
|
--single sends the WHOLE file as ONE prompt: blank lines are content, not
|
|
1665
1665
|
separators. A single prompt (one paragraph, or --single) never bundles and
|
|
1666
1666
|
never takes a batch-level lease -- one plain turn.
|
|
1667
|
-
`});import{spawn as dg,spawnSync as
|
|
1667
|
+
`});import{spawn as dg,spawnSync as hc}from"node:child_process";import{randomUUID as oA}from"node:crypto";import{tmpdir as aA}from"node:os";import*as $ from"node:fs";import*as ge from"node:path";import*as _g from"node:readline";import{fileURLToPath as yg}from"node:url";function Eg(t,e){let r=t.file&&t.file!=="<main>"?`${t.file}:${t.line}:${t.column}`:`${t.line}:${t.column}`,n=e;if(t.file&&(!n||n&&t.file!=="<main>"&&t.file!=="<std>"))try{$.existsSync(t.file)&&$.statSync(t.file).isFile()&&(n=$.readFileSync(t.file,"utf-8"))}catch{}if(!n)return`[${t.severity.toUpperCase()} at ${r}] ${t.message}`;let s=n.split(`
|
|
1668
1668
|
`),i=String(t.line),o=t.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,d=" ".repeat(Math.max(0,t.column-1));return`[${t.severity.toUpperCase()} at ${r}] ${t.message}
|
|
1669
1669
|
`+l+`
|
|
1670
1670
|
${c}${a}
|
|
1671
1671
|
${l}${d}^`}function Tg(t){if(typeof t!="string"||t.length!==1||/["\r\n]/.test(t))throw new Error("CSV delimiter must be one character other than a quote or newline")}function pt(t,e){return t!=null&&Object.hasOwn(t,e)?t[e]:void 0}function tr(t,e,r){String(e)==="__proto__"?Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}):t[e]=r}function wg(t){if(typeof t!="string"||!t.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(t)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let r=`
|
|
1672
1672
|
const target = process.argv[1];
|
|
1673
|
-
const maxBytes = ${
|
|
1673
|
+
const maxBytes = ${gc};
|
|
1674
1674
|
const controller = new AbortController();
|
|
1675
1675
|
const timer = setTimeout(() => controller.abort(), 30000);
|
|
1676
1676
|
try {
|
|
@@ -1696,19 +1696,19 @@ try {
|
|
|
1696
1696
|
} finally {
|
|
1697
1697
|
clearTimeout(timer);
|
|
1698
1698
|
}
|
|
1699
|
-
`,n=
|
|
1699
|
+
`,n=hc(process.execPath,["--input-type=module","-e",r,t],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:gc+4096,windowsHide:!0});if(n.error)throw n.error.code==="ETIMEDOUT"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${n.error.message}`);if(n.status!==0)throw new Error(`urlget() failed: ${String(n.stderr||"child process exited")}`.trim());return String(n.stdout||"")}async function lA(t){if(typeof t!="string"||!t.trim())throw new Error("urlget() requires a non-empty URL string");let e;try{e=new URL(t)}catch{throw new Error("urlget() requires a valid HTTP(S) URL")}if(e.protocol!=="http:"&&e.protocol!=="https:"||e.username||e.password)throw new Error("urlget() only permits HTTP(S) URLs without embedded credentials");let r=new AbortController,n=setTimeout(()=>r.abort(),3e4),s;try{let i=await fetch(e.toString(),{method:"GET",redirect:"follow",signal:r.signal});if(!i.ok)throw r.abort(),new Error("HTTP "+i.status+" "+i.statusText);s=i.body?.getReader();let o=[],a=0;if(s)for(;;){let l=await s.read();if(l.done)break;if(a+=l.value.byteLength,a>gc)throw await s.cancel().catch(()=>{}),r.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(r.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}function Hi(t,e,r,n=null,s=!1,i=0,o=null){return{stdout:t,stderr:e,code:r,signal:n,timed_out:s,duration_ms:i,pid:o}}function vg(t){let e=String(t);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function Sg(t,e=6e4){if(!Number.isSafeInteger(e)||e<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");let r=performance.now(),n;if(Array.isArray(t)){if(t.length===0)throw new Error("system() argv array must not be empty");let d=String(t[0]),u=t.slice(1).map(String);n=hc(d,u,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=hc(t,{shell:!0,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"});let s=Math.max(0,Math.round(performance.now()-r)),i=typeof n.pid=="number"?n.pid:null;if(n.error){if(n.error.code==="ETIMEDOUT"){let d=n.stdout!=null?String(n.stdout):"",u=n.stderr!=null?String(n.stderr):"";return Hi(d,u,null,n.signal||"SIGKILL",!0,s,i)}throw n.error}let o=n.stdout!=null?String(n.stdout):"",a=n.stderr!=null?String(n.stderr):"",l=n.status!==null?n.status:null,c=n.signal!==null?String(n.signal):null;return Hi(o,a,l,c,!1,s,i)}function bg(t,e=6e4){return new Promise((r,n)=>{if(!Number.isSafeInteger(e)||e<0){n(new Error("system() timeout must be a non-negative safe integer in milliseconds"));return}let s=performance.now();try{let i=process.platform!=="win32",o;if(Array.isArray(t)){if(t.length===0){n(new Error("system() argv array must not be empty"));return}let E=String(t[0]),v=t.slice(1).map(String);o=dg(E,v,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]})}else o=dg(t,{shell:!0,detached:i,stdio:["ignore","pipe","pipe"]});Wi.add(o);let a="",l="",c=null,d=null,u=0,f=!1,m=!1,h,_=!1,g,p=()=>{if(_)return;_=!0,Wi.delete(o),g&&clearTimeout(g);try{o.stdout?.destroy(),o.stderr?.destroy()}catch{}let E=Math.max(0,Math.round(performance.now()-s)),v=typeof o.pid=="number"?o.pid:null;if(h){n(h);return}if(m){r(Hi(a,l,null,d||"SIGKILL",!0,E,v));return}r(Hi(a,l,c,d,!1,E,v))};e>0&&(g=setTimeout(()=>{m=!0,d="SIGKILL";try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}p()},e));let y=10*1024*1024;o.stdout?.setEncoding("utf-8"),o.stderr?.setEncoding("utf-8"),o.stdout?.on("data",E=>{let v=Buffer.byteLength(E,"utf-8");if(u+v>y){if(!f){f=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1700
1700
|
`)?`
|
|
1701
|
-
`:"")+"system() output exceeds 10 MiB limit",
|
|
1701
|
+
`:"")+"system() output exceeds 10 MiB limit",h=new Error("system() output exceeds 10 MiB limit"),p()}return}u+=v,a+=E}),o.stderr?.on("data",E=>{let v=Buffer.byteLength(E,"utf-8");if(u+v>y){if(!f){f=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1702
1702
|
`)?`
|
|
1703
|
-
`:"")+"system() output exceeds 10 MiB limit",
|
|
1703
|
+
`:"")+"system() output exceeds 10 MiB limit",h=new Error("system() output exceeds 10 MiB limit"),p()}return}u+=v,l+=E}),o.on("error",E=>{h||(h=E)}),o.on("close",(E,v)=>{E!==null?(c=E,d=null):(c=null,d=v?String(v):null),p()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function cA(t,e=null){if(typeof t!="string")return t??e;let r=t.trim();if(r.length===0)return e;try{return JSON.parse(r)}catch{}let n=r.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n&&n[1])try{return JSON.parse(n[1].trim())}catch{}let s=r.indexOf("{"),i=r.lastIndexOf("}");if(s!==-1&&i>s)try{return JSON.parse(r.slice(s,i+1))}catch{}let o=r.indexOf("["),a=r.lastIndexOf("]");if(o!==-1&&a>o)try{return JSON.parse(r.slice(o,a+1))}catch{}return e}function as(t){if(typeof process>"u"||!process.stdin||!process.stdin.isTTY)return null;t!=null&&process.stdout&&typeof process.stdout.write=="function"&&process.stdout.write(String(t));try{let e=Buffer.alloc(1024),r="";for(;;){let n=0;try{n=$.readSync(0,e,0,1,null)}catch{return r.length>0?r:null}if(n===0)return r.length>0?r:null;let s=e.toString("utf-8",0,n);if(s===`
|
|
1704
1704
|
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function ls(t,e=typeof process<"u"?process.stdin:null,r=typeof process<"u"?process.stdout:null){return new Promise(n=>{if(!e||typeof e.on!="function"){n(null);return}if(e.destroyed||e.readableEnded){n(null);return}if(e.isTTY===!1||typeof process<"u"&&e===process.stdin&&!process.stdin.isTTY){n(null);return}t!=null&&r&&typeof r.write=="function"&&r.write(String(t));let s=_g.createInterface({input:e,output:r,terminal:!!e.isTTY}),i=!1,o=()=>{s.close()};s.question("",a=>{i||(i=!0,o(),n(a))}),s.on("close",()=>{i||(i=!0,n(null))}),s.on("error",()=>{i||(i=!0,o(),n(null))})})}function ug(t,e=!0,r=","){Tg(r);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let u=0;u<t.length;u++){let f=t[u],m=t[u+1];if(l=!0,o)f==='"'?m==='"'?(i+='"',u++):(o=!1,a=!0):i+=f;else{if(a&&f!==r&&f!=="\r"&&f!==`
|
|
1705
1705
|
`)throw new Error("Invalid CSV: unexpected character after closing quote");if(f==='"'){if(i.length>0)throw new Error("Invalid CSV: quote inside unquoted field");o=!0}else f===r?(a=!1,s.push(i),i=""):f==="\r"?(m===`
|
|
1706
1706
|
`&&u++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):f===`
|
|
1707
|
-
`?(s.push(i),n.push(s),s=[],i="",a=!1,l=!1):i+=f}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),n.push(s)),!e)return n.map(u=>u.map(mg));if(n.length===0)return[];let c=n[0].map(u=>u.trim()),d=[];for(let u=1;u<n.length;u++){let f=n[u],m={};for(let
|
|
1708
|
-
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>
|
|
1709
|
-
`)}return t.map(n=>
|
|
1710
|
-
`)}function
|
|
1711
|
-
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}function
|
|
1707
|
+
`?(s.push(i),n.push(s),s=[],i="",a=!1,l=!1):i+=f}}if(o)throw new Error("Invalid CSV: unterminated quoted field");if(l&&(s.push(i),n.push(s)),!e)return n.map(u=>u.map(mg));if(n.length===0)return[];let c=n[0].map(u=>u.trim()),d=[];for(let u=1;u<n.length;u++){let f=n[u],m={};for(let h=0;h<c.length;h++)tr(m,c[h],h<f.length?mg(f[h]):null);d.push(m)}return d}function mg(t){let e=t.trim();if(e==="")return"";if(/^-?\d+$/.test(e)){let r=Number(e);if(!Number.isNaN(r))return r}if(/^-?\d+\.\d+$/.test(e)){let r=Number(e);if(!Number.isNaN(r))return r}return e.toLowerCase()==="true"?!0:e.toLowerCase()==="false"?!1:e.toLowerCase()==="null"?null:t}function fg(t,e=","){if(Tg(e),!Array.isArray(t)||t.length===0)return"";let r=t[0];if(Array.isArray(r))return t.map(n=>n.map(s=>Bi(s,e)).join(e)).join(`
|
|
1708
|
+
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>Bi(o,e)).join(e),i=t.map(o=>n.map(a=>Bi(pt(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
1709
|
+
`)}return t.map(n=>Bi(n,e)).join(`
|
|
1710
|
+
`)}function Bi(t,e){let r=t==null?"":String(t);return r===""||r.includes(e)||r.includes('"')||r.includes(`
|
|
1711
|
+
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}function _c(t,e){if(!(!t||typeof t!="object")){"line"in t&&"column"in t&&!t.file&&(t.file=e);for(let r of Object.keys(t)){let n=t[r];if(Array.isArray(n))for(let s of n)_c(s,e);else n&&typeof n=="object"&&_c(n,e)}}}function uA(){if(!pc){let e=new ss(dA,"<std>").tokenize(),n=new is(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);pc=n}return{kind:"Program",statements:[...pc.statements],line:1,column:1,file:"<std>"}}function mA(t,e={}){let r=e.file||"<main>",n=e.baseDir||(e.file?ge.dirname(ge.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(g,p){if(e.moduleResolver)return e.moduleResolver(g,p).path;let y=n;p&&p!=="<main>"&&p!=="<std>"&&(y=ge.dirname(p));let E=ge.resolve(y,g);try{return $.realpathSync(E)}catch{return E}}function a(g,p){let y,E;if(e.moduleResolver){let w=e.moduleResolver(g,p);y=w.path,E=w.source}else{if(y=o(g,p),s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};try{E=$.readFileSync(y,"utf-8")}catch(w){throw new M(`Cannot resolve import '${g}': ${w?.message||String(w)}`,1,1,"PARSER",p)}}if(s.has(y))return s.get(y);if(i.has(y))return{kind:"Program",statements:[],line:1,column:1,file:y};i.add(y);let b=new ss(E,y).tokenize(),S=new is(b,y).parse();for(let w of S.statements)if(w.kind!=="FunctionDeclStmt"&&w.kind!=="ImportStmt")throw new M(`Library '${y}' cannot contain top-level executable statements; libraries must only declare functions. Found '${w.kind}'.`,w.line,w.column,"CHECKER",y);for(let w of S.statements)w.kind==="ImportStmt"&&a(w.path,y);return i.delete(y),s.set(y,S),S}let c=new ss(t,r).tokenize(),u=new is(c,r).parse(),f=r!=="<main>"?o(r):"<main>";s.set(f,u);for(let g of u.statements)g.kind==="ImportStmt"&&a(g.path,r);let m=[];if(!e.noStdlib){let g=uA();for(let p of g.statements)p.kind==="FunctionDeclStmt"&&m.push(p)}for(let[g,p]of s.entries())if(g!==f)for(let y of p.statements)y.kind==="FunctionDeclStmt"&&m.push(y);for(let g of u.statements)g.kind!=="ImportStmt"&&m.push(g);let h={kind:"Program",statements:m,line:u.line,column:u.column,file:r},_=Array.from(s.keys());return{program:h,loadedFiles:_}}function gA(t,e){if(e===void 0)return`${t}(...args: any): any`;if(typeof e=="number"){let i=Array.from({length:e},(o,a)=>`arg${a+1}: any`);return`${t}(${i.join(", ")}): any`}let r=Array.from({length:e.min},(i,o)=>`arg${o+1}: any`),n=e.max===void 0?[]:Array.from({length:e.max-e.min},(i,o)=>`[arg${e.min+o+1}: any]`),s=e.max===void 0?["...args: any"]:[];return`${t}(${[...r,...n,...s].join(", ")}): any`}function hg(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function os(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}async function _A(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1712
1712
|
`);let t=new rr,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
|
|
1713
1713
|
fn factorial(n) {
|
|
1714
1714
|
if (n <= 1) {
|
|
@@ -1732,7 +1732,7 @@ try {
|
|
|
1732
1732
|
assert(sumVal == 12, "sum must be 12");
|
|
1733
1733
|
`);n.success?(console.log(n.output.map(y=>" [out] "+y).join(`
|
|
1734
1734
|
`)),console.log(` -> Passed!
|
|
1735
|
-
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),t.registerFunction("base64Encode",y=>Buffer.from(y).toString("base64"),1,"Base64 encodes a string"),t.registerFunction("addVectors",(y,
|
|
1735
|
+
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),t.registerFunction("base64Encode",y=>Buffer.from(y).toString("base64"),1,"Base64 encodes a string"),t.registerFunction("addVectors",(y,E)=>y.map((v,b)=>v+(E[b]||0)),2,"Adds two numeric arrays element-wise");let i=t.run(`
|
|
1736
1736
|
let text = "TypeScript Engine";
|
|
1737
1737
|
let encoded = base64Encode(text);
|
|
1738
1738
|
print("Encoded base64:", encoded);
|
|
@@ -1846,7 +1846,7 @@ try {
|
|
|
1846
1846
|
print("Local config dot access:", localConfig.app, "tags:", localConfig.tags[0]);
|
|
1847
1847
|
`);m.success?(console.log(m.output.map(y=>" [out] "+y).join(`
|
|
1848
1848
|
`)),console.log(` -> Passed!
|
|
1849
|
-
`)):(console.error(" -> Failed:",m.diagnostics),e=!1),console.log("Test Suite 7: File I/O & Advanced Data Structures");let
|
|
1849
|
+
`)):(console.error(" -> Failed:",m.diagnostics),e=!1),console.log("Test Suite 7: File I/O & Advanced Data Structures");let _=t.run(`
|
|
1850
1850
|
// 1. Raw file write and read
|
|
1851
1851
|
let tmpFile = "scratch_test.txt";
|
|
1852
1852
|
write_file(tmpFile, "line 1\\nline 2\\nline 3");
|
|
@@ -1908,9 +1908,9 @@ try {
|
|
|
1908
1908
|
print("Has department?", has_key(userMap, "department"));
|
|
1909
1909
|
delete_key(userMap, "department");
|
|
1910
1910
|
print("After delete_key has department?", has_key(userMap, "department"));
|
|
1911
|
-
`);
|
|
1911
|
+
`);_.success?(console.log(_.output.map(y=>" [out] "+y).join(`
|
|
1912
1912
|
`)),console.log(` -> Passed!
|
|
1913
|
-
`)):(console.error(" -> Failed:",
|
|
1913
|
+
`)):(console.error(" -> Failed:",_.diagnostics),e=!1),console.log("Test Suite 8: Concurrency & Synchronized State Access");let p=await t.runAsync(`
|
|
1914
1914
|
let counter = 0;
|
|
1915
1915
|
let list = [];
|
|
1916
1916
|
let state = map();
|
|
@@ -1935,7 +1935,7 @@ try {
|
|
|
1935
1935
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
1936
1936
|
`);return p.success?(console.log(p.output.map(y=>" [out] "+y).join(`
|
|
1937
1937
|
`)),console.log(` -> Passed!
|
|
1938
|
-
`)):(console.error(" -> Failed:",p.diagnostics),e=!1),e}async function
|
|
1938
|
+
`)):(console.error(" -> Failed:",p.diagnostics),e=!1),e}async function yA(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await _A()||(process.exitCode=1);return}let e="Usage: lmscript.ts [--check|--dry-run|--lint] [--check-files] <file> | [check options] -e <source> | --test | --help";if(t.length===1&&t[0]==="--help"){console.log(e);return}let r=!1,n=!1;for(;["--check","--dry-run","--lint","--check-files"].includes(t[0]);)r=!0,t.shift()==="--check-files"&&(n=!0);let s=t[0]==="-e";if(s?t.length!==2:t.length!==1||t[0].startsWith("-")){console.error(e),process.exitCode=1;return}try{let i=s?void 0:ge.resolve(t[0]),o=s?t[1]:$.readFileSync(i,"utf-8"),a=new rr,l=r?a.scanAndCheck(o,{checkFiles:n,file:i}):await a.runAsync(o,{file:i});if("output"in l)for(let c of l.output)console.log(c);for(let c of l.diagnostics)console.error(Eg(c,o));l.diagnostics.some(c=>c.severity==="error")&&(process.exitCode=1)}catch(i){console.error(`Execution failed: ${i instanceof Error?i.message:String(i)}`),process.exitCode=1}}var M,Je,gc,Wi,ji,pg,ss,is,dA,pc,yr,yc,sn,Zt,er,on,tt,Xi,Ec,qi,fA,pA,hA,rr,gg,Tc=k(()=>{"use strict";M=class extends Error{message;line;column;stage;file;constructor(e,r,n,s,i){let o=i&&i!=="<main>"?`${i}:${r}:${n}`:`${r}:${n}`;super(`[${s} Error at ${o}] ${e}`),this.name="LMScriptError",this.message=e,this.line=r,this.column=n,this.stage=s,this.file=i}},Je=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};gc=10*1024*1024;Wi=new Set,ji=1e3;process.on("exit",()=>{for(let t of Wi)try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,"SIGKILL"):t.kill("SIGKILL")}catch{}Wi.clear()});pg={fn:"FN",function:"FN",let:"LET",if:"IF",else:"ELSE",while:"WHILE",for:"FOR",return:"RETURN",break:"BREAK",continue:"CONTINUE",true:"TRUE",false:"FALSE",null:"NULL",parallel:"PARALLEL",sync:"SYNC",import:"IMPORT"},ss=class{source;length;file;pos=0;line=1;column=1;constructor(e,r){this.source=e,this.length=e.length,this.file=r}tokenize(){let e=[];for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let r=this.line,n=this.column,s=this.peek();if(this.isDigit(s)||s==="."&&this.isDigit(this.peekNext())){e.push(this.readNumber(r,n));continue}if(s==='"'||s==="'"){e.push(this.readString(s,r,n));continue}if(s==="<"&&this.peekNext()==="<"){let i=this.tryReadHeredoc(r,n);if(i){e.push(i);continue}}if(this.isAlpha(s)){e.push(this.readIdentifier(r,n));continue}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:r,column:n});break;case":":e.push({type:"COLON",value:":",line:r,column:n});break;case"(":e.push({type:"LPAREN",value:"(",line:r,column:n});break;case")":e.push({type:"RPAREN",value:")",line:r,column:n});break;case"{":e.push({type:"LBRACE",value:"{",line:r,column:n});break;case"}":e.push({type:"RBRACE",value:"}",line:r,column:n});break;case"[":e.push({type:"LBRACKET",value:"[",line:r,column:n});break;case"]":e.push({type:"RBRACKET",value:"]",line:r,column:n});break;case",":e.push({type:"COMMA",value:",",line:r,column:n});break;case";":e.push({type:"SEMICOLON",value:";",line:r,column:n});break;case"+":e.push({type:"PLUS",value:"+",line:r,column:n});break;case"-":e.push({type:"MINUS",value:"-",line:r,column:n});break;case"*":e.push({type:"STAR",value:"*",line:r,column:n});break;case"/":e.push({type:"SLASH",value:"/",line:r,column:n});break;case"%":e.push({type:"PERCENT",value:"%",line:r,column:n});break;case"=":this.match("=")?e.push({type:"EQUAL",value:"==",line:r,column:n}):e.push({type:"ASSIGN",value:"=",line:r,column:n});break;case"!":this.match("=")?e.push({type:"NOT_EQUAL",value:"!=",line:r,column:n}):e.push({type:"NOT",value:"!",line:r,column:n});break;case"<":this.match("=")?e.push({type:"LESS_EQUAL",value:"<=",line:r,column:n}):e.push({type:"LESS",value:"<",line:r,column:n});break;case">":this.match("=")?e.push({type:"GREATER_EQUAL",value:">=",line:r,column:n}):e.push({type:"GREATER",value:">",line:r,column:n});break;case"&":if(this.match("&"))e.push({type:"AND",value:"&&",line:r,column:n});else throw new M("Unexpected character '&'. Did you mean '&&'?",r,n,"LEXER",this.file);break;case"|":if(this.match("|"))e.push({type:"OR",value:"||",line:r,column:n});else throw new M("Unexpected character '|'. Did you mean '||'?",r,n,"LEXER",this.file);break;default:throw new M(`Unexpected character: '${s}'`,r,n,"LEXER",this.file)}}return e.push({type:"EOF",value:"",line:this.line,column:this.column}),e}peek(){return this.source[this.pos]||""}peekNext(){return this.source[this.pos+1]||""}advance(){let e=this.source[this.pos++];return e===`
|
|
1939
1939
|
`?(this.line++,this.column=1):this.column++,e}match(e){return this.pos>=this.length||this.source[this.pos]!==e?!1:(this.advance(),!0)}isDigit(e){return e>="0"&&e<="9"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_"}isAlphaNumeric(e){return this.isAlpha(e)||this.isDigit(e)}skipWhitespaceAndComments(){for(;this.pos<this.length;){let e=this.peek();if(e===" "||e===" "||e==="\r"||e===`
|
|
1940
1940
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
1941
1941
|
`;)this.advance();else if(e==="/"&&this.peekNext()==="*"){let r=this.line,n=this.column;this.advance(),this.advance();let s=!1;for(;this.pos<this.length;){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance(),s=!0;break}this.advance()}if(!s)throw new M("Unterminated block comment",r,n,"LEXER",this.file)}else break}}readNumber(e,r){let n="";for(;this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(n+=this.advance();this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();return{type:"NUMBER",value:n,literal:parseFloat(n),line:e,column:r}}readString(e,r,n){this.advance();let s="";for(;this.pos<this.length&&this.peek()!==e;){if(this.peek()===`
|
|
@@ -1943,10 +1943,10 @@ try {
|
|
|
1943
1943
|
`;break;case"t":s+=" ";break;case"r":s+="\r";break;case"\\":s+="\\";break;case'"':s+='"';break;case"'":s+="'";break;default:s+=i;break}}else s+=this.advance()}if(this.pos>=this.length)throw new M("Unterminated string literal at end of file",r,n,"LEXER",this.file);return this.advance(),{type:"STRING",value:s,literal:s,line:r,column:n}}tryReadHeredoc(e,r){let n=this.pos+2;if(!this.isAlpha(this.source[n]))return;for(n++;n<this.length&&this.isAlphaNumeric(this.source[n]);)n++;let s=this.source.slice(this.pos+2,n),i=this.source[n]==="\r"&&this.source[n+1]===`
|
|
1944
1944
|
`?2:this.source[n]===`
|
|
1945
1945
|
`?1:0;if(i===0)return;let o=n+i-this.pos;for(let l=0;l<o;l++)this.advance();let a=this.pos;for(;this.pos<this.length;){let l=this.pos,c=this.pos;for(;c<this.length&&this.source[c]!=="\r"&&this.source[c]!==`
|
|
1946
|
-
`;)c++;let d=this.source.slice(l,c),u=d===`${s};`;if(d===s||u){let
|
|
1946
|
+
`;)c++;let d=this.source.slice(l,c),u=d===`${s};`;if(d===s||u){let h=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1947
1947
|
`?2:this.source[c]===`
|
|
1948
|
-
`||this.source[c]==="\r"?1:0,
|
|
1949
|
-
`?2:c<this.length?1:0,m=c+f-this.pos;for(let g=0;g<m;g++)this.advance()}throw new M(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(pg,n)?pg[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};is=class{tokens;current=0;file;constructor(e,r){this.tokens=e,this.file=r}parse(){let e=[],r=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:r.line,column:r.column,file:this.file};return this.file&&gc(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new M("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(r){throw r instanceof M?r:new M(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new M("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),r=this.parseExpression();if(this.consumeOptionalSemicolon(),r.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:r.target,value:r.value,line:e.line,column:e.column};if(r.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:r.target,index:r.index,value:r.value,line:e.line,column:e.column};if(r.kind==="CallExpr")return{kind:"SyncCallStmt",call:r,line:e.line,column:e.column};throw new M("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new M("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:r.line,column:r.column}}throw new M("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new M("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new M("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:r.line,column:r.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let r=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:r.line,column:r.column}:{kind:"TupleExpr",elements:n,line:r.line,column:r.column}}if(this.match("LBRACKET")){let r=[];if(!this.check("RBRACKET"))do r.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:r,line:e.line,column:e.column}}if(this.match("LBRACE")){let r=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new M("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:r.line,column:r.column}}throw new M(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new M(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},aA=`# LMScript Standard Library (std.lms)
|
|
1948
|
+
`||this.source[c]==="\r"?1:0,_=this.source.slice(a,l),p=s.length+(u?0:h);for(let y=0;y<p;y++)this.advance();return{type:"STRING",value:_,literal:_,line:e,column:r}}let f=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1949
|
+
`?2:c<this.length?1:0,m=c+f-this.pos;for(let h=0;h<m;h++)this.advance()}throw new M(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(pg,n)?pg[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};is=class{tokens;current=0;file;constructor(e,r){this.tokens=e,this.file=r}parse(){let e=[],r=this.peek();for(;!this.isAtEnd();)e.push(this.parseDeclaration(!0));let n={kind:"Program",statements:e,line:r.line,column:r.column,file:this.file};return this.file&&_c(n,this.file),n}parseDeclaration(e=!1){try{if(this.match("FN"))return this.parseFunctionDecl();if(this.match("LET"))return this.parseVarDecl();if(this.match("IMPORT")){if(!e)throw new M("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.parseImportStmt()}return this.parseStatement()}catch(r){throw r instanceof M?r:new M(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new M("'import' statement is only allowed at the top level of a file",this.previous().line,this.previous().column,"PARSER",this.file);return this.match("SYNC")?this.parseSyncStatement():this.match("IF")?this.parseIfStatement():this.match("WHILE")?this.parseWhileStatement():this.match("FOR")?this.parseForStatement():this.match("RETURN")?this.parseReturnStatement():this.match("BREAK")?this.parseBreakStatement():this.match("CONTINUE")?this.parseContinueStatement():this.match("LBRACE")?this.parseBlockBody(this.previous()):this.parseExpressionStatement()}parseSyncStatement(){let e=this.previous(),r=this.parseExpression();if(this.consumeOptionalSemicolon(),r.kind==="AssignExpr")return{kind:"SyncAssignStmt",target:r.target,value:r.value,line:e.line,column:e.column};if(r.kind==="IndexAssignExpr")return{kind:"SyncIndexAssignStmt",target:r.target,index:r.index,value:r.value,line:e.line,column:e.column};if(r.kind==="CallExpr")return{kind:"SyncCallStmt",call:r,line:e.line,column:e.column};throw new M("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new M("Destructuring assignment target must be an identifier",i.line,i.column,"PARSER",this.file);s.push(i.name)}return{kind:"TupleAssignExpr",targets:s,value:n,line:r.line,column:r.column}}throw new M("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new M("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new M("Each task in parallel([...]) must be a direct function call expression",s.line,s.column,"PARSER",this.file);n.push(s)}while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' closing array in 'parallel([ ... ])'"),this.consume("RPAREN","Expected ')' closing 'parallel(...)'"),{kind:"ParallelExpr",tasks:n,line:r.line,column:r.column}}if(this.match("IDENTIFIER"))return{kind:"IdentifierExpr",name:this.previous().value,line:e.line,column:e.column};if(this.match("LPAREN")){let r=this.previous(),n=[],s=!1;if(!this.check("RPAREN"))do if(n.push(this.parseExpression()),this.match("COMMA"))s=!0;else break;while(!this.check("RPAREN")&&!this.isAtEnd());return this.consume("RPAREN","Expected ')' after expression"),n.length===1&&!s?{kind:"GroupingExpr",expression:n[0],line:r.line,column:r.column}:{kind:"TupleExpr",elements:n,line:r.line,column:r.column}}if(this.match("LBRACKET")){let r=[];if(!this.check("RBRACKET"))do r.push(this.parseExpression());while(this.match("COMMA"));return this.consume("RBRACKET","Expected ']' after array elements"),{kind:"ArrayExpr",elements:r,line:e.line,column:e.column}}if(this.match("LBRACE")){let r=this.previous(),n=[];if(!this.check("RBRACE"))do{let s="";if(this.match("IDENTIFIER","STRING"))s=this.previous().value;else throw new M("Expected object key (identifier or string)",this.peek().line,this.peek().column,"PARSER",this.file);this.consume("COLON","Expected ':' after object key");let i=this.parseExpression();n.push({key:s,value:i})}while(this.match("COMMA"));return this.consume("RBRACE","Expected '}' after object literal"),{kind:"ObjectExpr",properties:n,line:r.line,column:r.column}}throw new M(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new M(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},dA=`# LMScript Standard Library (std.lms)
|
|
1950
1950
|
|
|
1951
1951
|
# String Utilities
|
|
1952
1952
|
fn is_blank(s) {
|
|
@@ -2041,47 +2041,47 @@ fn clamp(val, low, high) {
|
|
|
2041
2041
|
}
|
|
2042
2042
|
return val;
|
|
2043
2043
|
}
|
|
2044
|
-
`,fc=null;yr=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},_c=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new yr;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,r={}){this.options=r;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new yr,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,n]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);for(let r of e.statements)this.checkStmt(r);return this.diagnostics}addError(e,r,n,s){this.diagnostics.push({message:e,line:r,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let r=new Set;for(let n of e.params)r.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),r.add(n);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"ImportStmt":break;case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let r=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new yr(r);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=r;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(e.name)&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let r of e.names)this.currentScope.hasInCurrent(r)&&this.addError(`Variable '${r}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(r);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new yr(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let r=this.currentScope;this.currentScope=new yr(r);for(let n of e.statements)this.checkStmt(n);this.currentScope=r;break}case"SyncAssignStmt":{this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let r=e.call;r.args.length===0&&this.addError(`Synchronized call '${r.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(r.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${r.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr);break}}}checkReadPath(e){let r=e.args[0];for(;r.kind==="GroupingExpr";)r=r.expression;if(r.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof r.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!$.statSync(r.value).isFile())throw new Error("path is not a regular file");$.accessSync(r.value,$.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(r.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let r of e.targets)this.currentScope.resolve(r)||this.currentScope.define(r);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},nn=class{value;constructor(e){this.value=e}},Zt=class{},er=class{},sn=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},tt=class t{static nextId=1;id=t.nextId++;values=new Map;parent;constructor(e){this.parent=e}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},Wi=class{holderTaskId;depth=0;waiters=[];acquire(e=0,r=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;r>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${r}ms (possible deadlock)`)))},r));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,r=0,n=1e4){await this.acquire(r,n);try{return await e()}finally{this.release()}}},yc=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new Wi,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new Wi,this.objectLocks.set(e,r)),r}},Hi=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new yc;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,r=o=>console.log(o),n=!1,s,i){this.stdout=r,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new tt,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(..._)=>{let p=_.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(p),p},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(..._)=>{let p=_.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(p),p},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(_,...p)=>{let y=os(_,p);return this.stdout(y),y},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(..._)=>{let p=_.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stderr?this.stderr(`error: ${p}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${p}
|
|
2045
|
-
`):console.error(`error: ${p}`),this.recordedErrors.push(p),p},description:"Prints error message to stderr and records it for execution error summary",isDefault:!0});let d=e.get("system");(!d||d.isDefault)&&this.hostFunctions.set("system",{fn:(
|
|
2046
|
-
`)+(
|
|
2047
|
-
`:""),w=
|
|
2048
|
-
`)+(
|
|
2049
|
-
`:""),w=E.exitCode!==void 0?E.exitCode:E.success?0:1,x={success:E.success&&w===0,stdout:b,output:[...E.output],value:E.value,exit_code:w,code:w,errors:E.errors??[]};return x.toString=()=>b,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let g=e.get("urlget");(!g||g.isDefault)&&this.hostFunctions.set("urlget",{fn:_=>this.isAsync?iA(_):wg(_),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let h=e.get("sleep");(!h||h.isDefault)&&this.hostFunctions.set("sleep",{fn:_=>{if(typeof _!="number"||!Number.isFinite(_)||_<0)throw new Error("sleep() duration must be a non-negative finite number");if(_>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(y=>setTimeout(y,_));let p=Date.now()+_;for(;Date.now()<p;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new tt,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new tt(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof Zt)break;if(s instanceof er)continue;throw s}}return}case"ForStmt":{let n=new tt(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof Zt)break;if(!(i instanceof er))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new nn(n)}case"BreakStmt":throw new Zt;case"ContinueStmt":throw new er;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),tr(n,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)tr(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:pt(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof sn)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>Pi)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${Pi})`,s,i,"RUNTIME",o);let l=new tt(this.globalEnv);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof nn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof Je||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new sn(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new tt,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new tt(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof Zt)break;if(i instanceof er)continue;throw i}}return}case"ForStmt":{let s=new tt(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof Zt)break;if(!(o instanceof er))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new nn(s)}case"BreakStmt":throw new Zt;case"ContinueStmt":throw new er;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),tr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),tr(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)tr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:pt(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>Pi)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${Pi})`,s,i,"RUNTIME",a);let u=new tt(this.globalEnv);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof nn)return f.value;throw f}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof Je||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},dA=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],uA=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string.",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test).",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null.",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match).",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match).",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all).",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence.',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches.",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],mA=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];rr=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of dA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of uA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of mA)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,r)}finally{this.currentRegisteringModule=n}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(r=>(r.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
2044
|
+
`,pc=null;yr=class{variables=new Set;parent;constructor(e){this.parent=e}define(e){this.variables.add(e)}hasInCurrent(e){return this.variables.has(e)}resolve(e){return this.variables.has(e)?!0:this.parent?this.parent.resolve(e):!1}},yc=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new yr;loopDepth=0;inFunction=!1;hasConcurrency=!1;constructor(e,r={}){this.options=r;for(let[n,s]of e.entries())this.hostFunctions.set(n,s),this.functions.set(n,{name:n,paramCount:typeof s.arity=="number"?s.arity:-1,params:[],isHost:!0,line:0,column:0})}check(e){if(this.diagnostics=[],this.hasConcurrency=!1,this.loopDepth=0,this.inFunction=!1,this.currentScope=new yr,this.options.globals)for(let r of this.options.globals)this.currentScope.define(r);this.functions.clear();for(let[r,n]of this.hostFunctions.entries())this.functions.set(r,{name:r,paramCount:typeof n.arity=="number"?n.arity:-1,params:[],isHost:!0,line:0,column:0});for(let r of e.statements)r.kind==="FunctionDeclStmt"&&this.collectFunction(r);for(let r of e.statements)this.checkStmt(r);return this.diagnostics}addError(e,r,n,s){this.diagnostics.push({message:e,line:r,column:n,severity:"error",file:s})}collectFunction(e){if(this.functions.has(e.name)){let n=this.functions.get(e.name);if(n.isHost){this.addError(`Cannot redefine host function '${e.name}'`,e.line,e.column,e.file);return}if(n.isStdlib){this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:!1,file:e.file,line:e.line,column:e.column});return}let s=n.file?`${n.file}:${n.line}`:`line ${n.line}`;this.addError(`Duplicate function declaration '${e.name}' (already defined at ${s})`,e.line,e.column,e.file);return}let r=new Set;for(let n of e.params)r.has(n)&&this.addError(`Duplicate parameter name '${n}' in function '${e.name}'`,e.line,e.column,e.file),r.add(n);this.functions.set(e.name,{name:e.name,paramCount:e.params.length,params:e.params,isHost:!1,isStdlib:e.isStdlib||!1,file:e.file,line:e.line,column:e.column})}checkStmt(e){switch(e.kind){case"ImportStmt":break;case"FunctionDeclStmt":{if(this.inFunction||this.currentScope.parent){this.addError("Function declarations are only allowed at top level",e.line,e.column,e.file);break}let r=this.currentScope,n=this.inFunction;this.inFunction=!0,this.currentScope=new yr(r);for(let s of e.params)this.currentScope.define(s);for(let s of e.body.statements)this.checkStmt(s);this.inFunction=n,this.currentScope=r;break}case"VarDeclStmt":{this.currentScope.hasInCurrent(e.name)&&this.addError(`Variable '${e.name}' is already declared in this scope`,e.line,e.column,e.file),e.initializer&&this.checkExpr(e.initializer),this.currentScope.define(e.name);break}case"TupleVarDeclStmt":{this.checkExpr(e.initializer);for(let r of e.names)this.currentScope.hasInCurrent(r)&&this.addError(`Variable '${r}' is already declared in this scope`,e.line,e.column,e.file),this.currentScope.define(r);break}case"IfStmt":{this.checkExpr(e.condition),this.checkStmt(e.thenBranch),e.elseBranch&&this.checkStmt(e.elseBranch);break}case"WhileStmt":{this.checkExpr(e.condition),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new yr(r),e.init&&this.checkStmt(e.init),e.condition&&this.checkExpr(e.condition),e.update&&this.checkExpr(e.update),this.loopDepth++,this.checkStmt(e.body),this.loopDepth--,this.currentScope=r;break}case"ReturnStmt":{this.inFunction||this.addError("'return' statement is only allowed inside a function",e.line,e.column,e.file),e.value&&this.checkExpr(e.value);break}case"BreakStmt":{this.loopDepth===0&&this.addError("'break' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"ContinueStmt":{this.loopDepth===0&&this.addError("'continue' statement is only allowed inside a loop",e.line,e.column,e.file);break}case"BlockStmt":{let r=this.currentScope;this.currentScope=new yr(r);for(let n of e.statements)this.checkStmt(n);this.currentScope=r;break}case"SyncAssignStmt":{this.hasConcurrency=!0,this.currentScope.resolve(e.target)||this.addError(`Synchronized assignment target '${e.target}' must be declared beforehand`,e.line,e.column,e.file),this.checkExpr(e.value);break}case"SyncIndexAssignStmt":{this.hasConcurrency=!0,this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"SyncCallStmt":{this.hasConcurrency=!0;let r=e.call;r.args.length===0&&this.addError(`Synchronized call '${r.callee}' requires at least one argument (the target container)`,e.line,e.column,e.file);let n=this.hostFunctions.get(r.callee);(!n||!n.isContainerMutation)&&this.addError(`Synchronized call '${r.callee}' is not an authorized container mutation operation`,e.line,e.column,e.file),this.checkExpr(e.call);break}case"ExprStmt":{this.checkExpr(e.expr);break}}}checkReadPath(e){let r=e.args[0];for(;r.kind==="GroupingExpr";)r=r.expression;if(r.kind!=="LiteralExpr"){this.diagnostics.push({message:`Cannot preflight dynamic file path in '${e.callee}'; check it at runtime with file_exists(path)`,line:e.line,column:e.column,severity:"warning",file:e.file});return}if(typeof r.value!="string"){this.addError(`File path in '${e.callee}' must be a string`,e.line,e.column,e.file);return}try{if(!$.statSync(r.value).isFile())throw new Error("path is not a regular file");$.accessSync(r.value,$.constants.R_OK)}catch(n){this.addError(`Cannot read file ${JSON.stringify(r.value)}: ${n instanceof Error?n.message:String(n)}`,e.line,e.column,e.file)}}checkExpr(e){switch(e.kind){case"LiteralExpr":break;case"IdentifierExpr":{!this.currentScope.resolve(e.name)&&!this.functions.has(e.name)&&this.addError(`Undeclared variable '${e.name}'`,e.line,e.column,e.file);break}case"AssignExpr":{this.checkExpr(e.value),this.currentScope.resolve(e.target)||this.currentScope.define(e.target);break}case"TupleAssignExpr":{this.checkExpr(e.value);for(let r of e.targets)this.currentScope.resolve(r)||this.currentScope.define(r);break}case"IndexAssignExpr":{this.checkExpr(e.target),this.checkExpr(e.index),this.checkExpr(e.value);break}case"UnaryExpr":{this.checkExpr(e.operand);break}case"BinaryExpr":{this.checkExpr(e.left),this.checkExpr(e.right);break}case"GroupingExpr":{this.checkExpr(e.expression);break}case"TupleExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ArrayExpr":{for(let r of e.elements)this.checkExpr(r);break}case"ObjectExpr":{for(let r of e.properties)this.checkExpr(r.value);break}case"IndexExpr":{this.checkExpr(e.target),this.checkExpr(e.index);break}case"ParallelExpr":{this.hasConcurrency=!0;for(let r of e.tasks)this.checkExpr(r);break}case"CallExpr":{let r=this.functions.get(e.callee);r?r.paramCount>=0&&e.args.length!==r.paramCount&&this.addError(`Function '${e.callee}' expects ${r.paramCount} argument(s), but received ${e.args.length}`,e.line,e.column,e.file):this.currentScope.resolve(e.callee)||this.addError(`Call to undefined function '${e.callee}'`,e.line,e.column,e.file);let n=this.hostFunctions.get(e.callee),s=n?.arity;typeof s=="object"&&(e.args.length<s.min||e.args.length>(s.max??1/0))&&this.addError(`Function '${e.callee}' expects ${s.min}..${s.max??"unlimited"} argument(s), but received ${e.args.length}`,e.line,e.column,e.file),this.options.checkFiles&&n?.readsFile&&e.args.length>0&&this.checkReadPath(e);for(let i of e.args)this.checkExpr(i);break}}}},sn=class{value;constructor(e){this.value=e}},Zt=class{},er=class{},on=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},tt=class t{static nextId=1;id=t.nextId++;values=new Map;parent;constructor(e){this.parent=e}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},Xi=class{holderTaskId;depth=0;waiters=[];acquire(e=0,r=1e4){return this.depth===0?(this.holderTaskId=e,this.depth=1,Promise.resolve()):this.holderTaskId===e?(this.depth++,Promise.resolve()):new Promise((n,s)=>{let i;r>0&&(i=setTimeout(()=>{let a=this.waiters.findIndex(l=>l.resolve===o);a!==-1&&(this.waiters.splice(a,1),s(new Error(`Lock acquisition timed out after ${r}ms (possible deadlock)`)))},r));let o=()=>{i&&clearTimeout(i),this.holderTaskId=e,this.depth=1,n()};this.waiters.push({taskId:e,resolve:o})})}release(){this.depth<=0||(this.depth--,this.depth===0&&(this.holderTaskId=void 0,this.waiters.length>0&&this.waiters.shift().resolve()))}async withLock(e,r=0,n=1e4){await this.acquire(r,n);try{return await e()}finally{this.release()}}},Ec=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new Xi,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new Xi,this.objectLocks.set(e,r)),r}},qi=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new Ec;isAsync;nextTaskId=1;initialGlobals;callDepth=0;asyncCallDepth=new Map;recordedErrors=[];constructor(e,r=o=>console.log(o),n=!1,s,i){this.stdout=r,this.stderr=i,this.isAsync=n,this.initialGlobals=s,this.globalEnv=new tt,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...g)=>{let p=g.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(p),p},description:"Prints formatted values to output log",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...g)=>{let p=g.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stdout(p),p},description:"Prints line to output log",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(g,...p)=>{let y=os(g,p);return this.stdout(y),y},description:"Formats a template using %s/%d/%f/%% substitution and prints it",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...g)=>{let p=g.map(y=>typeof y=="object"?JSON.stringify(y):String(y)).join(" ");return this.stderr?this.stderr(`error: ${p}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${p}
|
|
2045
|
+
`):console.error(`error: ${p}`),this.recordedErrors.push(p),p},description:"Prints error message to stderr and records it for execution error summary",isDefault:!0});let d=e.get("system");(!d||d.isDefault)&&this.hostFunctions.set("system",{fn:(g,p=6e4)=>{if(!Number.isSafeInteger(p)||p<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?bg(g,p):Sg(g,p)},arity:{min:1,max:2},description:"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",isDefault:!0});let u=e.get("prompt_human");(!u||u.isDefault)&&this.hostFunctions.set("prompt_human",{fn:g=>this.isAsync?ls(g):as(g),arity:{min:0,max:1},description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",isDefault:!0});let f=e.get("shell_quote");(!f||f.isDefault)&&this.hostFunctions.set("shell_quote",{fn:g=>vg(g),arity:1,description:"Quotes string safely for POSIX shell command execution",isDefault:!0});let m=e.get("run_script");(!m||m.isDefault)&&this.hostFunctions.set("run_script",{fn:(g,p=[])=>{let y=ge.resolve(String(g));if(!$.existsSync(y))throw new Error(`run_script: file not found: '${y}'`);let E=$.readFileSync(y,"utf-8"),v=Array.isArray(p)?p.map(String):[],b=new rr;for(let[T,S]of this.hostFunctions)b.hasFunction(T)?S.isDefault||b.registerFunction(T,S.fn,S.arity,{description:S.description,allowOverwrite:!0},!1,S.isContainerMutation):b.registerFunction(T,S.fn,S.arity,S.description,S.isDefault,S.isContainerMutation);if(b.setGlobal("args",[...v]),b.setGlobal("ARGV",[y,...v]),this.isAsync)return(async()=>{let T=await b.runAsync(E,{file:y}),S=T.output.join(`
|
|
2046
|
+
`)+(T.output.length>0?`
|
|
2047
|
+
`:""),w=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&w===0,stdout:S,output:[...T.output],value:T.value,exit_code:w,code:w,errors:T.errors??[]};return x.toString=()=>S,x})();{let T=b.run(E,{file:y}),S=T.output.join(`
|
|
2048
|
+
`)+(T.output.length>0?`
|
|
2049
|
+
`:""),w=T.exitCode!==void 0?T.exitCode:T.success?0:1,x={success:T.success&&w===0,stdout:S,output:[...T.output],value:T.value,exit_code:w,code:w,errors:T.errors??[]};return x.toString=()=>S,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let h=e.get("urlget");(!h||h.isDefault)&&this.hostFunctions.set("urlget",{fn:g=>this.isAsync?lA(g):wg(g),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let _=e.get("sleep");(!_||_.isDefault)&&this.hostFunctions.set("sleep",{fn:g=>{if(typeof g!="number"||!Number.isFinite(g)||g<0)throw new Error("sleep() duration must be a non-negative finite number");if(g>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(y=>setTimeout(y,g));let p=Date.now()+g;for(;Date.now()<p;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new tt,this.initialGlobals)for(let[n,s]of this.initialGlobals.entries())this.globalEnv.define(n,s);this.userFunctions.clear(),this.callDepth=0;for(let n of e.statements)n.kind==="FunctionDeclStmt"&&this.userFunctions.set(n.name,n);let r;for(let n of e.statements)n.kind!=="FunctionDeclStmt"&&(r=this.execStmt(n,this.globalEnv));return r}execStmt(e,r){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let n=new tt(r);for(let s of e.statements)this.execStmt(s,n);return}case"VarDeclStmt":{let n=null;return e.initializer&&(n=this.evalExpr(e.initializer,r)),r.define(e.name,n),n}case"TupleVarDeclStmt":{let n=this.evalExpr(e.initializer,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.names.length;s++){let i=s<n.length?n[s]:null;r.define(e.names[s],i)}return n}case"IfStmt":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.execStmt(e.thenBranch,r):e.elseBranch?this.execStmt(e.elseBranch,r):void 0}case"WhileStmt":{let n=0;for(;this.isTruthy(this.evalExpr(e.condition,r));){if(++n>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,r)}catch(s){if(s instanceof Zt)break;if(s instanceof er)continue;throw s}}return}case"ForStmt":{let n=new tt(r);e.init&&this.execStmt(e.init,n);let s=0;for(;;){if(e.condition){let i=this.evalExpr(e.condition,n);if(!this.isTruthy(i))break}if(++s>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{this.execStmt(e.body,n)}catch(i){if(i instanceof Zt)break;if(!(i instanceof er))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new sn(n)}case"BreakStmt":throw new Zt;case"ContinueStmt":throw new er;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new M("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new M("'parallel(...)' requires asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let n=this.evalExpr(e.value,r);return r.set(e.target,n),n}case"TupleAssignExpr":{let n=this.evalExpr(e.value,r);if(!Array.isArray(n))throw new M(`Cannot destructure non-array value (got ${typeof n})`,e.line,e.column,"RUNTIME",e.file);for(let s=0;s<e.targets.length;s++){let i=s<n.length?n[s]:null;r.set(e.targets[s],i)}return n}case"IndexAssignExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r),i=this.evalExpr(e.value,r);if(Array.isArray(n)||typeof n=="object"&&n!==null)return Array.isArray(n)&&typeof s=="number"&&s<0&&(s=n.length+s),tr(n,s,i),i;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return this.evalExpr(e.expression,r);case"TupleExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ArrayExpr":return e.elements.map(n=>this.evalExpr(n,r));case"ObjectExpr":{let n={};for(let s of e.properties)tr(n,s.key,this.evalExpr(s.value,r));return n}case"IndexExpr":{let n=this.evalExpr(e.target,r),s=this.evalExpr(e.index,r);if(n==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(n)&&typeof s=="number"&&s<0?n[n.length+s]:pt(n,s)}case"UnaryExpr":{let n=this.evalExpr(e.operand,r),s=e.operator;if(s==="!")return!this.isTruthy(n);if(s==="-")return-n;throw new M(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return n/s;case"%":return n%s;case"==":return n===s;case"!=":return n!==s;case"<":return n<s;case"<=":return n<=s;case">":return n>s;case">=":return n>=s;default:throw new M(`Unknown binary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let n=e.args.map(i=>this.evalExpr(i,r)),s=this.resolveCallTarget(e.callee,r);return this.invokeNamed(s,n,r,e.line,e.column,e.file)}}}resolveCallTarget(e,r){if(this.userFunctions.has(e)||this.hostFunctions.has(e))return e;if(r.has(e)){let n=r.get(e);if(n instanceof on)return n.name}return e}invokeNamed(e,r,n,s,i,o){if(this.userFunctions.has(e)){let a=this.userFunctions.get(e);if(this.callDepth++,this.callDepth>ji)throw this.callDepth--,new M(`Execution fuel exhausted: maximum function call depth exceeded (${ji})`,s,i,"RUNTIME",o);let l=new tt(this.globalEnv);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof sn)return c.value;throw c}finally{this.callDepth--}return null}if(this.hostFunctions.has(e)){let a=this.hostFunctions.get(e);try{return a.fn(...r)}catch(l){throw l instanceof Je||l?.name==="LMScriptExit"||l?.isControlFlow?l:new M(`Error in host function '${e}': ${l?.message||String(l)}`,s,i,"RUNTIME",o)}}throw n.has(e)&&!(this.userFunctions.has(e)||this.hostFunctions.has(e))?new M(`'${e}' is not a function`,s,i,"RUNTIME",o):new M(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new on(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new tt,this.initialGlobals)for(let[s,i]of this.initialGlobals.entries())this.globalEnv.define(s,i);this.userFunctions.clear(),this.asyncCallDepth.clear();for(let s of e.statements)s.kind==="FunctionDeclStmt"&&this.userFunctions.set(s.name,s);let r=this.nextTaskId++,n;for(let s of e.statements)s.kind!=="FunctionDeclStmt"&&(n=await this.execStmtAsync(s,this.globalEnv,r));return n}async execStmtAsync(e,r,n){switch(e.kind){case"ImportStmt":return;case"BlockStmt":{let s=new tt(r);for(let i of e.statements)await this.execStmtAsync(i,s,n);return}case"VarDeclStmt":{let s=null;return e.initializer&&(s=await this.evalExprAsync(e.initializer,r,n)),r.define(e.name,s),s}case"TupleVarDeclStmt":{let s=await this.evalExprAsync(e.initializer,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.names.length;i++){let o=i<s.length?s[i]:null;r.define(e.names[i],o)}return s}case"IfStmt":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.execStmtAsync(e.thenBranch,r,n):e.elseBranch?await this.execStmtAsync(e.elseBranch,r,n):void 0}case"WhileStmt":{let s=0;for(;this.isTruthy(await this.evalExprAsync(e.condition,r,n));){if(++s>1e6)throw new M("Execution fuel exhausted: while loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,r,n)}catch(i){if(i instanceof Zt)break;if(i instanceof er)continue;throw i}}return}case"ForStmt":{let s=new tt(r);e.init&&await this.execStmtAsync(e.init,s,n);let i=0;for(;;){if(e.condition){let o=await this.evalExprAsync(e.condition,s,n);if(!this.isTruthy(o))break}if(++i>1e6)throw new M("Execution fuel exhausted: for loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME");try{await this.execStmtAsync(e.body,s,n)}catch(o){if(o instanceof Zt)break;if(!(o instanceof er))throw o}e.update&&await this.evalExprAsync(e.update,s,n)}return}case"ReturnStmt":{let s=e.value?await this.evalExprAsync(e.value,r,n):null;throw new sn(s)}case"BreakStmt":throw new Zt;case"ContinueStmt":throw new er;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new M(`Synchronized assignment target '${e.target}' is not defined`,e.line,e.column,"RUNTIME",e.file);let i=`bind:${s.env.id}:${s.name}`;await this.lockManager.getBindingLock(i).withLock(async()=>{let a=await this.evalExprAsync(e.value,r,n);s.env.set(s.name,a)},n);return}case"SyncIndexAssignStmt":{let s=await this.evalExprAsync(e.target,r,n);if(s==null||typeof s!="object"&&typeof s!="function")throw new M("Cannot perform synchronized assignment on non-object",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(s).withLock(async()=>{let o=await this.evalExprAsync(e.index,r,n),a=await this.evalExprAsync(e.value,r,n);Array.isArray(s)&&typeof o=="number"&&o<0&&(o=s.length+o),tr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new M("Synchronized call requires at least one argument (the target container)",e.line,e.column,"RUNTIME",e.file);let i=this.hostFunctions.get(s.callee);if(!i||!i.isContainerMutation)throw new M(`Function '${s.callee}' is not an authorized container mutation operation`,e.line,e.column,"RUNTIME",e.file);let o=await this.evalExprAsync(s.args[0],r,n);if(o==null||typeof o!="object"&&typeof o!="function")throw new M("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new M(`Cannot destructure non-array value (got ${typeof s})`,e.line,e.column,"RUNTIME",e.file);for(let i=0;i<e.targets.length;i++){let o=i<s.length?s[i]:null;r.set(e.targets[i],o)}return s}case"IndexAssignExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n),o=await this.evalExprAsync(e.value,r,n);if(Array.isArray(s)||typeof s=="object"&&s!==null)return Array.isArray(s)&&typeof i=="number"&&i<0&&(i=s.length+i),tr(s,i,o),o;throw new M("Cannot index-assign to non-array / non-object",e.line,e.column,"RUNTIME",e.file)}case"GroupingExpr":return await this.evalExprAsync(e.expression,r,n);case"TupleExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ArrayExpr":{let s=[];for(let i of e.elements)s.push(await this.evalExprAsync(i,r,n));return s}case"ObjectExpr":{let s={};for(let i of e.properties)tr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let d=this.nextTaskId++;return this.asyncCallDepth.set(d,s),await this.evalExprAsync(c,r,d)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new M("Cannot read property of null or undefined",e.line,e.column,"RUNTIME",e.file);return Array.isArray(s)&&typeof i=="number"&&i<0?s[s.length+i]:pt(s,i)}case"UnaryExpr":{let s=await this.evalExprAsync(e.operand,r,n),i=e.operator;if(i==="!")return!this.isTruthy(s);if(i==="-")return-s;throw new M(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new M("Division by zero",e.line,e.column,"RUNTIME",e.file);return s/i;case"%":return s%i;case"==":return s===i;case"!=":return s!==i;case"<":return s<i;case"<=":return s<=i;case">":return s>i;case">=":return s>=i;default:throw new M(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),d=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,d),d>ji)throw this.asyncCallDepth.set(o,d-1),new M(`Execution fuel exhausted: maximum function call depth exceeded (${ji})`,s,i,"RUNTIME",a);let u=new tt(this.globalEnv);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof sn)return f.value;throw f}finally{this.asyncCallDepth.set(o,d-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let d=c.fn(...r);return d instanceof Promise?await d:d}catch(d){throw d instanceof Je||d?.name==="LMScriptExit"||d?.isControlFlow?d:new M(`Error in host function '${l}': ${d?.message||String(d)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new M(`'${l}' is not a function`,s,i,"RUNTIME",a):new M(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},fA=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function.",example:"fn add(a, b) { return a + b; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],pA=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string.",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test).",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null.",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match).",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match).",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all).",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence.',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches.",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],hA=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];rr=class t{hostFunctions=new Map;functionDocs=new Map;registeredModules=new Map;functionOriginModule=new Map;currentRegisteringModule="core";outputLogs=[];isAsyncMode=!1;constructor(){this.registeredModules.set("core",{name:"core",description:"LMScript core language built-ins and standard library"}),this.registerPredefinedFunctions(),this.registerDefaultDocs()}registerDefaultDocs(){for(let e of fA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of pA)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of hA)this.functionDocs.set(e.name,{...e,module:e.module??"core"})}registerFunctionDoc(e){return this.functionDocs.set(e.name,{...e,module:e.module??this.currentRegisteringModule}),this}registerModule(e,r){if(this.registeredModules.has(e.name))throw new Error(`Module '${e.name}' is already registered`);this.registeredModules.set(e.name,e);let n=this.currentRegisteringModule;this.currentRegisteringModule=e.name;try{if(e.docs)for(let s of e.docs)this.registerFunctionDoc({...s,module:s.module??e.name});typeof e.register=="function"&&e.register(this,r)}finally{this.currentRegisteringModule=n}return this}getModules(){return Array.from(this.registeredModules.values())}getModule(e){return this.registeredModules.get(e)}getFunctionsByModule(e){return Array.from(this.functionDocs.values()).filter(r=>(r.module??"core").toLowerCase()===e.toLowerCase())}getFunctionDocs(){return Array.from(this.functionDocs.values())}getFunctionDoc(e){return this.functionDocs.get(e)}getFunctionCategories(){let e=new Set;for(let r of this.functionDocs.values())e.add(r.category);return Array.from(e)}getFunctionsByCategory(e){return Array.from(this.functionDocs.values()).filter(r=>r.category.toLowerCase()===e.toLowerCase())}registerPredefinedFunctions(){this.registerFunction("read_file",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>$.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=$.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
2050
2050
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
2051
2051
|
`)&&(r=r.slice(0,-1)),n?r.length===0?[""]:r.split(/\r?\n/):[]},1,"Reads file as an array of string lines"),this.registerFunction("write_lines",(e,r)=>{if(!Array.isArray(r))throw new Error("write_lines: second argument must be an array of lines");let n=r.length===0?"":r.map(String).join(`
|
|
2052
2052
|
`)+`
|
|
2053
|
-
`;return $.writeFileSync(e,n,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from($.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return $.readdirSync(ge.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>($.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=$.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>($.writeFileSync(e,JSON.stringify(r,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,r=!0,n=",")=>{let s=$.readFileSync(e,"utf-8");return ug(s,r,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,r,n=",")=>($.writeFileSync(e,fg(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",ug,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",fg,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=ge.resolve(
|
|
2053
|
+
`;return $.writeFileSync(e,n,"utf-8"),!0},2,"Writes an array of lines to a file with trailing newline"),this.registerFunction("glob",e=>{try{return Array.from($.globSync(e))}catch{return[]}},1,"Finds files matching a glob pattern and returns an array of matching paths"),this.registerFunction("list_dir",e=>{try{return $.readdirSync(ge.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>($.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("append_file",(e,r)=>($.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=$.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>($.writeFileSync(e,JSON.stringify(r,null,n),"utf-8"),!0),{min:2,max:3},"Serializes data and writes formatted JSON to file"),this.registerFunction("read_csv",(e,r=!0,n=",")=>{let s=$.readFileSync(e,"utf-8");return ug(s,r,n)},{min:1,max:3},"Reads CSV file and parses into array of objects or rows"),this.registerFunction("write_csv",(e,r,n=",")=>($.writeFileSync(e,fg(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",ug,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",fg,{min:1,max:2},"Serializes records or rows to CSV text");for(let e of["read","read_file","read_lines","read_json","read_csv","glob","list_dir"])this.hostFunctions.get(e).readsFile=!0;this.registerFunction("temp_file",()=>{let e=ge.resolve(aA(),`lmscript-${oA()}`),r=$.openSync(e,"wx",384);return $.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>$.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new Je(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>$.existsSync(e)?($.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,r=!0)=>($.mkdirSync(e,{recursive:!!r}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,r=!1)=>$.existsSync(e)?(r?$.rmSync(e,{recursive:!0,force:!0}):$.rmdirSync(e),!0):!1,{min:1,max:2},"Removes a directory; pass true for recursive removal of a non-empty directory"),this.registerFunction("copy_file",(e,r)=>($.copyFileSync(e,r),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,r)=>($.renameSync(e,r),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,r)=>ge.basename(e,r),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>ge.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>ge.join(...e),void 0,"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>ge.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,r)=>(process.env[e]=String(r),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("array",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("push",(e,...r)=>(e.push(...r),e),void 0,"Pushes item(s) to end of array and returns the array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...r)=>(e.unshift(...r),e),void 0,"Adds item(s) to front of array and returns the array",!0,!0),this.registerFunction("insert",(e,r,n)=>{let s=r<0?e.length+r:r;return e.splice(s,0,n),e},3,"Inserts item at index and returns the array",!0,!0),this.registerFunction("remove_at",(e,r)=>{let n=r<0?e.length+r:r,s=e.splice(n,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...r)=>e.concat(...r),void 0,"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,r)=>{if(!Array.isArray(e))return e;let n=[...e];return r?n.sort((s,i)=>{let o=s?s[r]:void 0,a=i?i[r]:void 0;return o<a?-1:o>a?1:0}):n.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},void 0,"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("sorted",(e,r)=>this.hostFunctions.get("sort").fn(e,r),void 0,"Sorts array numerically, alphabetically, or by object key (alias for sort)"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((r,n)=>r+(typeof n=="number"?n:Number(n)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((n,s)=>n+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let r of Object.keys(e))delete e[r];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,r=6e4)=>{if(!Number.isSafeInteger(r)||r<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsyncMode?bg(e,r):Sg(e,r)},{min:1,max:2},"Executes shell command or argv array directly with shell:false and optional timeoutMs (default 60000), returning {stdout, stderr, code, signal, timed_out, duration_ms, pid}",!0),this.registerFunction("run_script",(e,r=[])=>{let n=ge.resolve(String(e));if(!$.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=$.readFileSync(n,"utf-8"),i=Array.isArray(r)?r.map(String):[],o=new t;for(let[a,l]of this.hostFunctions)o.hasFunction(a)?l.isDefault||o.registerFunction(a,l.fn,l.arity,{description:l.description,allowOverwrite:!0},!1,l.isContainerMutation):o.registerFunction(a,l.fn,l.arity,l.description,l.isDefault,l.isContainerMutation);if(o.setGlobal("args",[...i]),o.setGlobal("ARGV",[n,...i]),this.isAsyncMode)return(async()=>{let a=await o.runAsync(s,{file:n}),l=a.output.join(`
|
|
2054
2054
|
`)+(a.output.length>0?`
|
|
2055
2055
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
2056
2056
|
`)+(a.output.length>0?`
|
|
2057
2057
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,d={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return d.toString=()=>l,d}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
2058
|
-
`):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>wg(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?ls(e):as(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)=>oA(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)=>{if(e==null)return n;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o of s){if(i==null||typeof i!="object")return n;i=pt(i,o)}return i!==void 0?i:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("set",(e,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];(pt(i,a)==null||typeof pt(i,a)!="object")&&tr(i,a,{}),i=pt(i,a)}return s.length>0&&tr(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=>pt(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&pt(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&&pt(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=os(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 sn,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>vg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let f=Number(u);o+=f<r.length?a(r[f]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>os(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)=>hg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>hg(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 sn?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,m=this.functionOriginModule.get(e);if(m&&m!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${m}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:fA(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}=cA(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new _c(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 Hi(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 Je||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let g=typeof c.exitCode=="number"?c.exitCode:0;return{success:g===0,value:g,exitCode:g,diagnostics:i,output:n,errors:d}}let u=c instanceof M?c.line:1,f=c instanceof M?c.column:1,m=c instanceof M&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:m}],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 Hi(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 Je||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let m=typeof l.exitCode=="number"?l.exitCode:0;return{success:m===0,value:m,exitCode:m,diagnostics:i,output:n,errors:c}}let d=l instanceof M?l.line:1,u=l instanceof M?l.column:1,f=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:f}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};gg=ge.basename(yg(import.meta.url));(gg==="lmscript.ts"||gg==="lmscript.js")&&process.argv[1]&&$.existsSync(process.argv[1])&&$.realpathSync(yg(import.meta.url))===$.realpathSync(ge.resolve(process.argv[1]))&&hA()});import{spawnSync as gA}from"node:child_process";import{existsSync as _A}from"node:fs";import{homedir as Tc}from"node:os";import{delimiter as yA,join as wc}from"node:path";function kg(t,e,r){let n=gA(t,e,{encoding:"utf8",timeout:r,maxBuffer:16777216});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",...n.signal!==null?{signal:n.signal}:{},...n.error!==void 0?{error:n.error}:{}}}function Rg(t){Ag=t??kg}function Ng(t){Xi=t===null?vc:{...vc,...t}}function wA(t){return t==="~"?Tc():t.startsWith("~/")?wc(Tc(),t.slice(2)):t}function vA(t){let e=t.LMCTL_RATELIMIT_BIN;if(e!==void 0&&e!==""){let n=wA(e);if(Xi.exists(n))return n}let r=wc(Tc(),"repos","tools","lmratelimit","bin","lmratelimit");if(Xi.exists(r))return r;for(let n of(t.PATH??"").split(yA)){if(n==="")continue;let s=wc(n,"lmratelimit");if(Xi.exists(s))return s}return null}function Ig(t){return typeof t=="object"&&t!==null}function SA(t){let e;try{e=JSON.parse(t)}catch{return null}return Ig(e)?Array.isArray(e.readings)?e.readings.filter(Ig):typeof e.provider=="string"&&typeof e.status=="string"?[e]:null:null}function xg(t,e){let r=t.trim();return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Gi(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(c=>typeof c!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let c of e)if(!qi.includes(c))return{status:"error",error:`unknown provider: ${c} (valid targets: ${qi.join(", ")})`,readings:[]};let r=t.timeoutSeconds??EA;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=vA(n);if(s===null)return{status:"error",error:"lmratelimit binary not found (looked at LMCTL_RATELIMIT_BIN, ~/repos/tools/lmratelimit/bin/lmratelimit, and PATH).",readings:[]};let i=e.includes("all")?TA:e.length,o=Math.ceil(2*r*i*1e3);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let a=Ag(s,[...e,"--pretty","--timeout",String(r)],o);if(a.error!==void 0){let c=a.error.code==="ETIMEDOUT"?`timed out after ${Math.round(o/1e3)}s (--timeout ${r}s x ${i} provider(s))`:a.error.message;return{status:"error",error:`failed to run lmratelimit (${s}): ${c}`,readings:[]}}if(a.status!==0){let c=a.signal!==null&&a.signal!==void 0?`signal ${a.signal}`:`status ${a.status}`,d=xg(a.stderr,500);return{status:"error",error:`lmratelimit exited with ${c}${d!==""?`: ${d}`:""}`,readings:[]}}let l=SA(a.stdout);return l===null?{status:"error",error:`could not parse lmratelimit output as JSON: ${xg(a.stdout,300)}`,readings:[]}:{status:"ok",readings:l}}var qi,EA,TA,vc,Ag,Xi,Ji=k(()=>{"use strict";qi=["all","codex","agy","claude","kimi"],EA=15,TA=4;vc={exists:_A},Ag=kg,Xi=vc});import{readFileSync as bA}from"node:fs";import{createInterface as IA}from"node:readline";async function xA(t){let e=t.provider.trim().toLowerCase();return zr.includes(e)||Br().tools[e]?.agent!==void 0||!fr.includes(e)?!1:Zr().includes(e)}async function Sc(t,e){try{await C(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
2059
|
-
`)}}function
|
|
2060
|
-
`),null}}function
|
|
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=>wg(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?ls(e):as(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)=>cA(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)=>{if(e==null)return n;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o of s){if(i==null||typeof i!="object")return n;i=pt(i,o)}return i!==void 0?i:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("set",(e,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];(pt(i,a)==null||typeof pt(i,a)!="object")&&tr(i,a,{}),i=pt(i,a)}return s.length>0&&tr(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=>pt(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&pt(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&&pt(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=os(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 on,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>vg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let d=n.indexOf("}",l+1);if(d<0){o+=c,l+=1;continue}let u=n.slice(l+1,d);if(u==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(u)){let f=Number(u);o+=f<r.length?a(r[f]):`{${u}}`}else s&&/^[a-zA-Z0-9_]+$/.test(u)&&Object.hasOwn(s,u)?o+=a(s[u]):o+=`{${u}}`;l=d+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>os(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)=>hg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>hg(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 on?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,m=this.functionOriginModule.get(e);if(m&&m!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${m}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:gA(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}=mA(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new yc(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 qi(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 Je||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let h=typeof c.exitCode=="number"?c.exitCode:0;return{success:h===0,value:h,exitCode:h,diagnostics:i,output:n,errors:d}}let u=c instanceof M?c.line:1,f=c instanceof M?c.column:1,m=c instanceof M&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:m}],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 qi(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 Je||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let m=typeof l.exitCode=="number"?l.exitCode:0;return{success:m===0,value:m,exitCode:m,diagnostics:i,output:n,errors:c}}let d=l instanceof M?l.line:1,u=l instanceof M?l.column:1,f=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:f}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};gg=ge.basename(yg(import.meta.url));(gg==="lmscript.ts"||gg==="lmscript.js")&&process.argv[1]&&$.existsSync(process.argv[1])&&$.realpathSync(yg(import.meta.url))===$.realpathSync(ge.resolve(process.argv[1]))&&yA()});import{spawnSync as EA}from"node:child_process";import{existsSync as TA}from"node:fs";import{homedir as wc}from"node:os";import{delimiter as wA,join as vc}from"node:path";function kg(t,e,r){let n=EA(t,e,{encoding:"utf8",timeout:r,maxBuffer:16777216});return{status:n.status,stdout:typeof n.stdout=="string"?n.stdout:"",stderr:typeof n.stderr=="string"?n.stderr:"",...n.signal!==null?{signal:n.signal}:{},...n.error!==void 0?{error:n.error}:{}}}function Rg(t){Ag=t??kg}function Ng(t){Gi=t===null?Sc:{...Sc,...t}}function bA(t){return t==="~"?wc():t.startsWith("~/")?vc(wc(),t.slice(2)):t}function IA(t){let e=t.LMCTL_RATELIMIT_BIN;if(e!==void 0&&e!==""){let n=bA(e);if(Gi.exists(n))return n}let r=vc(wc(),"repos","tools","lmratelimit","bin","lmratelimit");if(Gi.exists(r))return r;for(let n of(t.PATH??"").split(wA)){if(n==="")continue;let s=vc(n,"lmratelimit");if(Gi.exists(s))return s}return null}function Ig(t){return typeof t=="object"&&t!==null}function xA(t){let e;try{e=JSON.parse(t)}catch{return null}return Ig(e)?Array.isArray(e.readings)?e.readings.filter(Ig):typeof e.provider=="string"&&typeof e.status=="string"?[e]:null:null}function xg(t,e){let r=t.trim();return r.length<=e?r:`${r.slice(0,e)}\u2026`}function Vi(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(c=>typeof c!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let c of e)if(!Ji.includes(c))return{status:"error",error:`unknown provider: ${c} (valid targets: ${Ji.join(", ")})`,readings:[]};let r=t.timeoutSeconds??vA;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=IA(n);if(s===null)return{status:"error",error:"lmratelimit binary not found (looked at LMCTL_RATELIMIT_BIN, ~/repos/tools/lmratelimit/bin/lmratelimit, and PATH).",readings:[]};let i=e.includes("all")?SA:e.length,o=Math.ceil(2*r*i*1e3);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let a=Ag(s,[...e,"--pretty","--timeout",String(r)],o);if(a.error!==void 0){let c=a.error.code==="ETIMEDOUT"?`timed out after ${Math.round(o/1e3)}s (--timeout ${r}s x ${i} provider(s))`:a.error.message;return{status:"error",error:`failed to run lmratelimit (${s}): ${c}`,readings:[]}}if(a.status!==0){let c=a.signal!==null&&a.signal!==void 0?`signal ${a.signal}`:`status ${a.status}`,d=xg(a.stderr,500);return{status:"error",error:`lmratelimit exited with ${c}${d!==""?`: ${d}`:""}`,readings:[]}}let l=xA(a.stdout);return l===null?{status:"error",error:`could not parse lmratelimit output as JSON: ${xg(a.stdout,300)}`,readings:[]}:{status:"ok",readings:l}}var Ji,vA,SA,Sc,Ag,Gi,Ki=k(()=>{"use strict";Ji=["all","codex","agy","claude","kimi"],vA=15,SA=4;Sc={exists:TA},Ag=kg,Gi=Sc});import{readFileSync as kA}from"node:fs";import{createInterface as AA}from"node:readline";async function RA(t){let e=t.provider.trim().toLowerCase();return Qr.includes(e)||Wr().tools[e]?.agent!==void 0||!fr.includes(e)?!1:en().includes(e)}async function bc(t,e){try{await C(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
2059
|
+
`)}}function NA(t,e){let r=rn(t,e);if(r.ok)return xt(r.identity);if(r.reason==="unset")return null;throw new Error(It("batch"))}async function LA(t,e){try{let{member:r}=e;return await C(t,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:r.teamfile,from_identity:`${r.teamfile}:batch`,target_teamfile:r.teamfile,target_alias:r.alias,root_teamfile:r.teamfile,cwd:r.sessiondir,command:`lmctl batch ${r.teamfile} ${r.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:r.provider,sessionid:r.sessionid,...r.model!==void 0?{model:r.model}:{}})}).id)}catch(r){return t.stderr.write(`warning: failed to start batch root invocation: ${r instanceof Error?r.message:String(r)}
|
|
2060
|
+
`),null}}function CA(t,e,r,n){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let s=Qe({path:fe(n?.LMCTL_DB)});try{s.finishTrackedInvocation(e,r)}finally{s.close()}}catch{}}async function Lg(t,e,r,n){if(!t.closed&&(t.closed=!0,t.kind!=="agent")){if(t.bundleSession)try{await t.bundleSession.close()}catch{}if(t.heartbeatTimer&&t.heartbeatTimer.stop(),t.heldLease&&await bc(e,t.heldLease),t.rootId!==null){let s=r==="done"?{status:"done",exit_code:0,result_summary:`batch completed ${t.promptCount}/${t.promptCount} prompts`}:{status:t.rootFinish.status??(r==="cancelled"?"cancelled":"error"),exit_code:1,error:n??t.rootFinish.error,result_summary:t.rootFinish.result_summary};try{await C(e,i=>{i.finishTrackedInvocation(t.rootId,s)})}catch(i){e.stderr.write(`warning: failed to finish batch root invocation: ${i instanceof Error?i.message:String(i)}
|
|
2061
2061
|
`)}}r==="done"&&e.stderr.write(`batch ${Me()}: completed ${t.promptCount}/${t.promptCount} prompts
|
|
2062
|
-
`)}}function
|
|
2062
|
+
`)}}function DA(t={}){let e=new rr;e.isAsyncMode=!0;let r=t.scriptArgs??[];if(e.setGlobal("args",[...r]),e.setGlobal("ARGV",[...r]),t.io){let n=t.io;e.registerFunction("print",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2063
2063
|
`),i},void 0,{description:"Prints formatted values to stdout",allowOverwrite:!0}),e.registerFunction("println",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2064
2064
|
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=os(s,i);return n.stdout.write(o+`
|
|
2065
|
-
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return ls(s,i,o)}return as(s)},{min:0,max:1},{description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",allowOverwrite:!0})}return e}function
|
|
2065
|
+
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return ls(s,i,o)}return as(s)},{min:0,max:1},{description:"Prompts operator on stdin/terminal, returning input string or null if closed/non-interactive",allowOverwrite:!0})}return e}function MA(t,e,r,n=process.env){t.registerFunction("lm_exit",(m=0)=>{let h=Math.floor(Number(m)),_=Number.isFinite(h)&&h>=0&&h<=255?h:1;throw new Je(_)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...m)=>{let h=m.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(h+(h.endsWith(`
|
|
2066
2066
|
`)?"":`
|
|
2067
|
-
`)),
|
|
2068
|
-
`),r.recordError(
|
|
2069
|
-
`);return!!
|
|
2070
|
-
`);try{if(v){let U=await C(e,q=>(
|
|
2071
|
-
`);try{let q={...
|
|
2072
|
-
`);let v=Ze(e,
|
|
2073
|
-
`);try{let
|
|
2074
|
-
`)}})}catch(
|
|
2067
|
+
`)),h},void 0,"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...m)=>{let h=m.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(`error: ${h}
|
|
2068
|
+
`),r.recordError(h),h},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(m,h=!1)=>{try{let _=kA(String(m),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2069
|
+
`);return!!h?[_.trim()].filter(p=>p.length>0):_.split(/\n\s*\n/u).map(p=>p.trim()).filter(Boolean)}catch(_){throw A(e,`batch: ${_ instanceof Error?_.message:String(_)}`),new Je(1)}};t.registerFunction("lm_read_prompts",(m,h=!1)=>s(m,h),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",m=>s(m,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",m=>{try{return ke(String(m)).members.map(_=>({alias:_.alias,provider:_.provider,model:_.model,sessionid:_.session,sessiondir:_.sessiondir}))}catch(h){throw new Error(`Failed to read teamfile '${m}': ${h?.message||String(h)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(m,h)=>{try{let _=ue(String(m),String(h),e.dal);return{alias:_.alias,provider:_.provider,model:_.model,sessionid:_.sessionid,sessiondir:_.sessiondir,isLead:_.isLead,teamfile:_.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(m,h,_,g={})=>{if(typeof m!="string"){if(!m||Array.isArray(m)||typeof m!="object"||typeof m.provider!="string"||!m.provider.trim())throw new Error("lm_batch_open: member map requires provider");let R=h??{};if(typeof R!="object"||Array.isArray(R)||_!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let N={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...m},sourceMember:m,options:{...R},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(N),N}if(typeof h!="string"||typeof _!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let p;try{p=ue(String(m),String(h),e.dal)}catch(R){return A(e,`batch: ${R?.message||String(R)}`),null}let y=Number(g?.promptCount??1),v=!!!g?.legacy&&y>1&&await RA(p),b={...e.env??n},T=await LA(e,{member:p,batchfile:String(_),promptCount:y,parentInvocationId:jt(b.LMCTL_INVOCATION_ID)});T!==null&&(b.LMCTL_INVOCATION_ID=String(T));let S,w,x,I=!1;e.stderr.write(`batch ${Me()}: starting ${y} prompt${y===1?"":"s"} -> ${p.alias} (teamfile=${m} input=${_})
|
|
2070
|
+
`);try{if(v){let U=await C(e,q=>(jr(q,p.teamfile,p.alias),at(q,p.teamfile,p.alias)));if(U.busy){let q=U.reason==="in-flight"?`${p.alias} is servicing ${U.inFlight.sender_alias} (${U.inFlight.sender_teamfile}) since ${U.inFlight.started_at} \u2014 wait and retry`:U.source==="terminal-lock"?hr(U.terminalLock):`${p.alias} is busy (interactive terminal); wait and retry`;return T!==null&&await C(e,Ce=>{Ce.finishTrackedInvocation(T,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${q}`),null}let re=await C(e,q=>NA(b,q)),ee=await C(e,q=>Mt(q,{receiver_teamfile:p.teamfile,receiver_alias:p.alias,sender_teamfile:re?.teamfile??p.teamfile,sender_alias:re?.alias??"operator",ttlMs:ot(b)}));if(!ee.acquired){let q=`${p.alias} is servicing ${ee.current.sender_alias} (${ee.current.sender_teamfile}) since ${ee.current.started_at} \u2014 wait and retry`;return T!==null&&await C(e,Ce=>{Ce.finishTrackedInvocation(T,{status:"busy",exit_code:1,error:q,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${q}`),null}S={row:ee.lease,leaseId:ee.leaseId};let xe=$r(q=>C(e,Ce=>Ce.heartbeatAgentInflight(S.row,S.leaseId,q)));x={stop:()=>clearInterval(xe)};let be=Ze(e,q=>`batch ${Me()}: opening provider session (${q}s elapsed)
|
|
2071
|
+
`);try{let q={...b};try{let Ce=await C(e,gt=>gt.getRootTeam(p.teamfile)?.name??null);Ce!==null&&(q.LMBEE_TEAM_NAME=Ce)}catch{}w=await zn({provider:p.provider,sessionId:p.sessionid,cwd:p.sessiondir,env:q,...p.model!==void 0?{model:p.model}:{},...p.effort!==void 0?{effort:p.effort}:{},alias:p.alias,isLead:p.isLead,permissionMode:"yolo",holdOpen:es(e,{teamfile:p.teamfile,alias:p.alias},q)}),I=!0}catch{x&&x.stop(),x=void 0,await bc(e,S),S=void 0,I=!1}finally{be.stop()}}let N={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(m),alias:String(h),batchfile:String(_),member:p,promptCount:y,useBundle:I,rootId:T,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:S,bundleSession:w,heartbeatTimer:x,closed:!1,env:b};return r.registerBatch(N),N}catch(R){if(x){try{x.stop()}catch{}x=void 0}if(S){try{await bc(e,S)}catch{}S=void 0}if(w){try{await w.close()}catch{}w=void 0}if(T!==null)try{await C(e,N=>{N.finishTrackedInvocation(T,{status:"error",exit_code:1,error:R?.message||String(R),result_summary:"0 prompts completed"})})}catch{}throw R}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),t.registerFunction("lm_batch_turn",async(m,h,_,g)=>{let p=typeof m=="string"?r.getBatch(m):m?.id?r.getBatch(m.id)??m:void 0;if(!p)throw new Error("Invalid or unmanaged batch handle");if(p.kind==="agent"){if(r.getBatch(p.id)!==p)throw new Error("Invalid or unmanaged batch handle");if(p.closed||p.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(p.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};p.inFlight=!0;try{let b=p.member.sessionid,T=await d(p.member,String(h),p.options);return p.member.sessionid&&p.sourceMember.provider===p.member.provider&&p.sourceMember.sessionid===b&&(p.sourceMember.sessionid=p.member.sessionid),T.status!=="ok"&&(p.failed=!0),{status:T.status,reply:T.reply.replace(/\n+$/u,""),error:T.error}}finally{p.inFlight=!1}}let y=Number(_),E=Number(g);e.stderr.write(`batch ${Me()}: prompt ${y}/${E} -> ${p.member.alias}
|
|
2072
|
+
`);let v=Ze(e,b=>`batch ${Me()}: prompt ${y}/${E} still running (${b}s elapsed)
|
|
2073
|
+
`);try{let b=await _r({teamfile:p.member.teamfile,alias:p.member.alias,prompt:String(h),expectedSession:{provider:p.member.provider,sessionid:p.member.sessionid},permissionMode:"yolo",env:{...p.env},messageType:"batch",...p.heldLease!==void 0?{heldLease:p.heldLease}:{},...p.bundleSession!==void 0?{bundleSession:p.bundleSession}:{},io:e,onEvent:S=>{v.poke(),S.kind==="warning"&&e.stderr.write(S.message)}}),T=b.replyText?String(b.replyText).replace(/\n+$/u,""):"";if(b.status!=="ok"){let S=b.status==="stalled"?"provider stalled":b.message,w=`batch: stopped at prompt ${y}/${E} (${y-1} completed): ${S}; later prompts were not sent`;return p.rootFinish={status:b.status==="busy"?"busy":"error",exit_code:1,error:w,result_summary:`${y-1}/${E} prompts completed`},A(e,w),{status:b.status,reply:T,error:w}}return{status:"ok",reply:T,error:null}}catch(b){let T=`batch: stopped at prompt ${y}/${E} (${y-1} completed): ${b instanceof Error?b.message:String(b)}; later prompts were not sent`;return p.rootFinish={status:"error",exit_code:1,error:T,result_summary:`${y-1}/${E} prompts completed`},A(e,T),{status:"error",reply:"",error:T}}finally{v.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(m,h="done",_)=>{let g=typeof m=="string"?r.getBatch(m):m?.id?r.getBatch(m.id)??m:void 0;return g?(await Lg(g,e,h==="done"?"done":h==="cancelled"?"cancelled":"error",_),!0):!1},{min:1,max:3},"Closes a batch session and cleans up resources"),t.registerFunction("lm_ratelimit_readings",async(m={})=>{try{if(!m||typeof m!="object"||Array.isArray(m))throw new Error("lm_ratelimit_readings: options must be a map");let h=m.providers??(m.provider===void 0?["all"]:[m.provider]);if(!Array.isArray(h)||h.some(g=>typeof g!="string"||!g||g.startsWith("-")))throw new Error("lm_ratelimit_readings: providers must be a list of provider names");let _=m.timeoutSeconds??15;if(typeof _!="number"||!Number.isFinite(_)||_<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return Vi({providers:h.length?h:["all"],timeoutSeconds:_,env:e.env??n,progress:g=>{e.stderr.write(`${g}
|
|
2074
|
+
`)}})}catch(h){return{status:"error",error:h instanceof Error?h.message:String(h),readings:[]}}},{min:0,max:1},"Reads live provider quota values without analytics or aggregation");let i=new WeakSet,o=new Set,a=new Set,l=new Map,c=async(m,h,_={},g=!1)=>{let p=(b,T="",S=null)=>({status:b,reply:T,error:S,message_id:null,team_chat_log_id:null}),y,E=!1,v;try{if(!m||typeof m!="object"||Array.isArray(m))throw new Error("lm_agent: member must be a map");for(let R of["provider","alias","model","effort","sessiondir","sessionid"]){let N=m[R];if(N!=null&&(typeof N!="string"||!N.trim()))throw new Error(`lm_agent: ${R} must be a nonempty string when supplied`)}if(!m.provider)throw new Error("lm_agent: provider is required");if(typeof h!="string")throw new Error("lm_agent: prompt must be a string");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_agent: options must be a map");let b=_.permissionMode??"yolo";if(b!=="yolo"&&b!=="plan")throw new Error("lm_agent: permissionMode must be yolo or plan");if(_.idleTimeoutMs!=null&&(typeof _.idleTimeoutMs!="number"||!Number.isFinite(_.idleTimeoutMs)||_.idleTimeoutMs<0))throw new Error("lm_agent: idleTimeoutMs must be a finite nonnegative number");let T=m.provider,S=m.sessiondir??process.cwd(),w=m.sessionid??"";if(y=w?JSON.stringify([T,w]):void 0,i.has(m)||y!==void 0&&(o.has(y)||!g&&a.has(y)))return p("busy","","lm_agent: session already has an active turn in this engine");i.add(m),y!==void 0&&o.add(y),E=!0,e.stderr.write(`agent ${Me()}: prompting ${m.alias??T}
|
|
2075
2075
|
`),v=Ze(e,R=>`agent ${Me()}: still running (${R}s elapsed)
|
|
2076
|
-
`);let x=w;if(!x&&["agy","pi","dsh"].includes(
|
|
2077
|
-
`);if(!R.success||!R.sessionId)throw new Error(R.error??"lm_agent: provider did not identify the seeded session");x=R.sessionId,m.sessionid=x,y=JSON.stringify([
|
|
2078
|
-
`);return x&&I.sessionId!==x?p("error","","lm_agent: provider changed session identity during resume"):(I.sessionId&&(m.sessionid=I.sessionId),I.status==="stalled"?p("stalled",I.text,"provider stalled"):I.sessionId?p("ok",I.text):p("error",I.text,"lm_agent: provider did not return a session ID"))}catch(
|
|
2079
|
-
`);let
|
|
2076
|
+
`);let x=w;if(!x&&["agy","pi","dsh"].includes(T)){if(b!=="yolo")throw new Error(`lm_agent: fresh ${T} sessions require yolo seed; supply sessionid for resume`);let R=await rc({provider:T,cwd:S,model:m.model,effort:m.effort});for(let N of R.warnings??[])e.stderr.write(`warning: ${N}
|
|
2077
|
+
`);if(!R.success||!R.sessionId)throw new Error(R.error??"lm_agent: provider did not identify the seeded session");x=R.sessionId,m.sessionid=x,y=JSON.stringify([T,x]),o.add(y)}let I=await pr({provider:T,cwd:S,sessionId:x,prompt:h,model:m.model,effort:m.effort,alias:m.alias,isLead:!1,permissionMode:b,timeoutMs:_.idleTimeoutMs,requireResume:!!x,env:{...e.env??n},onDelta:()=>v?.poke(),onProgress:()=>v?.poke()});for(let R of I.warnings??[])e.stderr.write(`warning: ${R}
|
|
2078
|
+
`);return x&&I.sessionId!==x?p("error","","lm_agent: provider changed session identity during resume"):(I.sessionId&&(m.sessionid=I.sessionId),I.status==="stalled"?p("stalled",I.text,"provider stalled"):I.sessionId?p("ok",I.text):p("error",I.text,"lm_agent: provider did not return a session ID"))}catch(b){return p("error","",b instanceof Error?b.message:String(b))}finally{v?.stop(),E&&(i.delete(m),y!==void 0&&o.delete(y))}},d=async(m,h,_={},g=!1)=>{let p=await c(m,h,_,g);if(m?.sessionid&&p.status!=="busy"){let y=JSON.stringify([m.provider,m.sessionid]),E=l.get(y)??{lines:[],options:{}};E.lines.push(`You: ${h}`),p.reply&&E.lines.push(`Agent: ${p.reply}`),p.error&&E.lines.push(`${p.status}: ${p.error}`),E.options={..._},l.set(y,E)}return p};t.registerFunction("lm_agent",d,{min:2,max:3},"Prompts an agent described by a map without a teamfile");let u=!1,f=async m=>{let h=m!==null&&typeof m=="object";if(u)throw new Error("prompt_human: another operator prompt is active");u=!0;let _,g;try{let p=e.stdin??process.stdin;if(!h)return await ls(m,p,e.stdout);let y={...m};if(Array.isArray(m)||typeof y.provider!="string"||!y.provider.trim()||typeof y.sessionid!="string"||!y.sessionid.trim())return{command:"error",args:["prompt_human: session map requires provider and sessionid; call lm_agent first"]};let E=JSON.stringify([y.provider,y.sessionid]);if(o.has(E))return{command:"busy",args:["Agent turn is still running"]};a.add(E),g=E;let v=p;if(v.destroyed||v.readableEnded)return{command:"eof",args:[]};_=AA({input:v,output:e.stdout,terminal:!!v.isTTY,crlfDelay:1/0});let b=_[Symbol.asyncIterator](),T=!1;_.on("SIGINT",()=>{T=!0,_?.close()}),e.stdout.write(`Session ${y.alias??y.provider} (${y.sessionid})
|
|
2079
|
+
`);let S=l.get(E);if(S)for(let w of S.lines)e.stdout.write(`${w}
|
|
2080
2080
|
`);else{let w=await Bt(zt()).getSession(y.sessionid,y.provider);if(!w)return{command:"error",args:["Could not load session history"]};for(let x of w.messages)(x.role==="user"||x.role==="assistant")&&e.stdout.write(`${x.role==="user"?"You":"Agent"}: ${x.content}
|
|
2081
2081
|
`)}for(e.stdout.write(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2082
|
-
`);;){e.stdout.write("You> ");let w=await
|
|
2082
|
+
`);;){e.stdout.write("You> ");let w=await b.next();if(T)return{command:"cancelled",args:[]};if(w.done)return{command:"eof",args:[]};let x=w.value.trim();if(!x)continue;if(/^\/exit(?:\s|$)/u.test(x)){let R=x.split(/\s+/u).slice(1);return{command:R.shift()??"exit",args:R}}let I=await d(y,w.value,S?.options??{},!0);if(I.reply&&e.stdout.write(`Agent: ${I.reply}
|
|
2083
2083
|
`),I.status!=="ok")return e.stdout.write(`${I.status}: ${I.error}
|
|
2084
|
-
`),{command:I.status,args:[I.error??"Agent turn failed"]}}}catch(p){if(!
|
|
2084
|
+
`),{command:I.status,args:[I.error??"Agent turn failed"]}}}catch(p){if(!h)throw p;return{command:"error",args:[p instanceof Error?p.message:String(p)]}}finally{_?.close(),g!==void 0&&a.delete(g),u=!1}};t.registerFunction("prompt_human",m=>{if(!t.isAsyncMode&&(m===null||typeof m!="object")){if(u)throw new Error("prompt_human: another operator prompt is active");return as(m)}return f(m)},{min:0,max:1},{description:"Prompts for a string, or hands an agent session to the operator and returns a decision map",allowOverwrite:!0}),t.registerFunctionDoc({name:"prompt_human",module:"core",category:"System & Process",signature:"prompt_human([question: string]): string|null; prompt_human(session: map): map",description:'Question form reads one line. In the lmctl engine, a session map opens an agent conversation showing script history. /exit retry a b returns {command: "retry", args: ["a", "b"]}; arguments are whitespace-separated. Bare /exit returns command "exit"; closed input returns "eof". Errors, stalls, busy sessions and Ctrl-C return "error", "stalled", "busy" and "cancelled" maps. All map results have args: string[].',example:'agent = { provider: "codex" }; lm_agent(agent, "Review this change"); decision = prompt_human(agent); if (decision.command == "retry") { lm_agent(agent, join(decision.args, " ")); }'}),t.registerFunction("lm_prompt",async(m,h,_,g={})=>{try{let p=await _r({teamfile:String(m),alias:String(h),prompt:String(_),permissionMode:g?.permissionMode??"yolo",idleTimeoutMs:g?.idleTimeoutMs,env:{...e.env??n},messageType:g?.messageType,io:e});return{status:p.status,reply:p.replyText??"",error:p.message??null,message_id:p.messageId??null,team_chat_log_id:p.teamChatLogId??null}}catch(p){return{status:"error",reply:"",error:p?.message||String(p),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}function FA(t,e,r=new kt,n=process.env){return t.registerModule($A,{io:e,registry:r,env:n})}function cs(t,e=[],r=new kt,n=process.env){let s=DA({scriptArgs:e,io:t,env:n});return FA(s,t,r,n),s}async function Cg(t,e,r={stdout:process.stdout,stderr:process.stderr},n=process.env,s){let i=new kt,o=d=>{for(let u of i.getOpenBatches()){if(u.kind==="agent"){u.closed=!0;continue}if(u.heartbeatTimer){try{u.heartbeatTimer.stop()}catch{}u.heartbeatTimer=void 0}if(u.heldLease){try{if(r.dal)r.dal.releaseAgentInflight(u.heldLease.row,u.heldLease.leaseId);else{let f=Qe({path:fe(n?.LMCTL_DB)});try{f.releaseAgentInflight(u.heldLease.row,u.heldLease.leaseId)}finally{f.close()}}}catch{}u.heldLease=void 0}u.rootId!==null&&CA(r,u.rootId,{status:"cancelled",signal:d,error:`batch interrupted by ${d}`},n)}process.exit(d==="SIGINT"?130:143)};process.once("SIGINT",o),process.once("SIGTERM",o);let a=!1,l,c=()=>{if(a)return;a=!0;let d=i.getErrors(),u=l?l.getRecordedErrors():[],f=[...d];for(let m of u)f.includes(m)||f.push(m);if(f.length>0){r.stderr.write(`
|
|
2085
2085
|
=== LMScript Error Summary (${f.length} error${f.length===1?"":"s"}) ===
|
|
2086
2086
|
`);for(let m=0;m<f.length;m++)r.stderr.write(` ${m+1}. ${f[m]}
|
|
2087
2087
|
`);r.stderr.write(`==========================================
|
|
@@ -2089,7 +2089,7 @@ fn clamp(val, low, high) {
|
|
|
2089
2089
|
`)?f:`${f}
|
|
2090
2090
|
`)}});if(c(),u.exitCode!==void 0)return u.exitCode;if(!u.success){for(let f of u.diagnostics){let m=f.file?`${f.file}:${f.line}:${f.column}`:`${f.line}:${f.column}`;r.stderr.write(`error:${m}: ${f.message}
|
|
2091
2091
|
`)}return 1}return i.hasErrors()||u.errors&&u.errors.length>0?1:0}catch(d){return c(),d instanceof Je||d?.name==="LMScriptExit"?d.exitCode:(r.stderr.write(`error: ${d instanceof Error?d.message:String(d)}
|
|
2092
|
-
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var kt,
|
|
2092
|
+
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var kt,OA,$A,Og=k(()=>{"use strict";Tc();Ui();Pe();Et();Ki();In();bt();Pi();he();Pt();rt();ze();Sn();Qn();nn();Zn();yn();Tc();kt=class{batchHandles=new Map;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}async forceCloseAll(e){for(let r of this.getOpenBatches())await Lg(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}};OA=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"Values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"Error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));$A={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:OA,register(t,e){MA(t,e.io,e.registry,e.env)}}});var Fg={};ae(Fg,{formatCategoryOverview:()=>xc,formatFunctionDoc:()=>Mg,formatModuleOverview:()=>$g,runScript:()=>UA});import{readFileSync as Dg}from"node:fs";import{resolve as PA}from"node:path";function Mg(t){let e="";if(e+=`Function: ${t.signature||t.name}
|
|
2093
2093
|
`,t.module&&(e+=`Module: ${t.module}
|
|
2094
2094
|
`),e+=`Category: ${t.category}
|
|
2095
2095
|
`,e+=`Description: ${t.description}
|
|
@@ -2107,24 +2107,24 @@ Example:
|
|
|
2107
2107
|
No functions registered in this module.
|
|
2108
2108
|
`,r;r+=`
|
|
2109
2109
|
Functions:
|
|
2110
|
-
`;let s=Array.from(new Set(n.map(o=>o.category))),i=[...
|
|
2110
|
+
`;let s=Array.from(new Set(n.map(o=>o.category))),i=[...Yi.filter(o=>s.some(a=>a.toLowerCase()===o.toLowerCase())),...s.filter(o=>!Yi.some(a=>a.toLowerCase()===o.toLowerCase()))];for(let o of i){let a=n.filter(l=>l.category.toLowerCase()===o.toLowerCase()).sort((l,c)=>l.name.localeCompare(c.name));if(a.length!==0){r+=`
|
|
2111
2111
|
${o}:
|
|
2112
2112
|
`;for(let l of a){let c=l.signature||l.name;r+=` ${c}
|
|
2113
2113
|
`,l.description&&(r+=` ${l.description}
|
|
2114
2114
|
`)}}}return r+=`
|
|
2115
2115
|
Use 'lmctl script help <function>' for parameter details, return types, and examples.
|
|
2116
|
-
`,r}function
|
|
2116
|
+
`,r}function xc(t){let e=Ic+`
|
|
2117
2117
|
Available Functions (by module):
|
|
2118
2118
|
`,n=[...t.getModules()].sort((s,i)=>s.name==="core"?-1:i.name==="core"?1:s.name==="lmctl"?-1:i.name==="lmctl"?1:s.name.localeCompare(i.name));for(let s of n){let i=t.getFunctionsByModule(s.name);if(i.length===0)continue;e+=`
|
|
2119
2119
|
Module '${s.name}'${s.description?` (${s.description})`:""}:
|
|
2120
|
-
`;let o=Array.from(new Set(i.map(l=>l.category))),a=[...
|
|
2120
|
+
`;let o=Array.from(new Set(i.map(l=>l.category))),a=[...Yi.filter(l=>o.some(c=>c.toLowerCase()===l.toLowerCase())),...o.filter(l=>!Yi.some(c=>c.toLowerCase()===l.toLowerCase()))];for(let l of a){let c=i.filter(d=>d.category.toLowerCase()===l.toLowerCase()).sort((d,u)=>d.name.localeCompare(u.name));if(c.length!==0){e+=`
|
|
2121
2121
|
${l}:
|
|
2122
2122
|
`;for(let d of c)e+=` ${d.signature||d.name}
|
|
2123
2123
|
`}}}return e+=`
|
|
2124
2124
|
Use 'lmctl script help <function>' for parameter details, return types, and examples.
|
|
2125
2125
|
Use 'lmctl script help <module>' to inspect a module.
|
|
2126
|
-
`,e}async function
|
|
2127
|
-
`)}return 2}return 0}return Cg(a,i,e,e.env,l)}var
|
|
2126
|
+
`,e}async function UA(t,e={stdout:process.stdout,stderr:process.stderr}){if(Gs(e),t.length===0)return A(e,Ic.trimEnd());if(t[0]==="help"){let c=cs(e,[],new kt,e.env);if(t.length===1)return e.stdout.write(xc(c)),0;let d=t[1],u=c.getModule(d);if(u)return e.stdout.write($g(c,u)),0;let f=c.getFunctionDoc(d);return f?(e.stdout.write(Mg(f)),0):A(e,`script: function '${d}' not found. Run 'lmctl script help' to see all available functions.`)}if(t[0]==="--help"||t[0]==="-h"){let c=cs(e,[],new kt,e.env);return e.stdout.write(xc(c)),0}let r,n=!1,s,i=[],o=0;for(;o<t.length;){let c=t[o];if(c==="-e"){if(o+1>=t.length)return A(e,"script: -e requires a code argument");r=t[o+1],o+=2,i.push(...t.slice(o));break}else if(c==="--check"||c==="--dry-run")n=!0,o++;else{if(c.startsWith("-")&&c!=="-")return A(e,`script: unknown flag: ${c}`);s=c,i.push(...t.slice(o+1));break}}let a,l=s&&s!=="-"?PA(s):void 0;if(r!==void 0)a=r;else if(s!==void 0)if(s==="-")try{e.stdin&&typeof e.stdin.on=="function"?a=await new Promise((c,d)=>{let u="";e.stdin.on("data",f=>{u+=f}),e.stdin.on("end",()=>c(u)),e.stdin.on("error",d)}):a=Dg(0,"utf8")}catch(c){return A(e,`script: failed to read standard input: ${c?.message||String(c)}`)}else try{a=Dg(s,"utf8")}catch(c){return A(e,`script: ${c?.message||String(c)}`)}else return A(e,Ic.trimEnd());if(n){let c=new kt,d=cs(e,i,c,e.env),{diagnostics:u}=d.scanAndCheck(a,{file:l});if(u.filter(m=>m.severity==="error").length>0){for(let m of u){let h=m.file?`${m.file}:${m.line}:${m.column}`:`${m.line}:${m.column}`;e.stderr.write(`error:${h}: ${m.message}
|
|
2127
|
+
`)}return 2}return 0}return Cg(a,i,e,e.env,l)}var Ic,Yi,Pg=k(()=>{"use strict";he();Og();Ic=`usage: lmctl script [flags] <scriptfile> [args...]
|
|
2128
2128
|
lmctl script [flags] -e '<code>' [args...]
|
|
2129
2129
|
lmctl script [flags] - [args...]
|
|
2130
2130
|
lmctl script help [module|function]
|
|
@@ -2139,12 +2139,12 @@ Flags:
|
|
|
2139
2139
|
-e <code> Execute inline script code
|
|
2140
2140
|
--check, --dry-run Scan and check script without executing host effects
|
|
2141
2141
|
-h, --help Show this help message and function listing
|
|
2142
|
-
`,
|
|
2142
|
+
`,Yi=["Language Constructs","lmctl Automation","Strings","Lists & Arrays","Maps & Key-Value","File I/O","JSON & Data","Math","System & Process"]});function Ug(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}function jg(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2143
2143
|
WHERE run_id = ?
|
|
2144
2144
|
AND acknowledged_at IS NULL
|
|
2145
2145
|
AND requires_user = 1
|
|
2146
|
-
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var
|
|
2147
|
-
WHERE a.id = ?`,e)[0];return n===void 0?null:
|
|
2146
|
+
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var kc=k(()=>{"use strict"});function Bg(t,e={}){return t.query("SELECT * FROM run ORDER BY id DESC LIMIT ?",e.limit??100)}function Wg(t,e){let n=t.query(`${jA}
|
|
2147
|
+
WHERE a.id = ?`,e)[0];return n===void 0?null:BA(n)}function BA(t){let{payload_json:e,...r}=t,n={...r,node_path:null,expected_response:null,transcript_tail:null,paused_at:null,created_run_inputs:null,workflow_version_id:null,workflow_step:null,escalation_tier:null,escalation_token:null,escalation_reason:null,declared_outcomes:null,agent_output:null};if(e==null)return n;let s;try{s=JSON.parse(e)}catch{return n}if(s===null||typeof s!="object")return n;let i=s;if(Array.isArray(i.node_path)&&i.node_path.every(o=>typeof o=="string")&&(n.node_path=i.node_path),i.expected_response!==null&&typeof i.expected_response=="object"){let o=i.expected_response;if(typeof o.kind=="string"){let a=Array.isArray(o.choices)&&o.choices.every(l=>typeof l=="string")?o.choices:null;n.expected_response={kind:o.kind,choices:a}}}if(Array.isArray(i.transcript_tail)&&i.transcript_tail.every(o=>typeof o=="string")&&(n.transcript_tail=i.transcript_tail),typeof i.paused_at=="string"&&(n.paused_at=i.paused_at),i.created_run_inputs!==null&&typeof i.created_run_inputs=="object"&&!Array.isArray(i.created_run_inputs)&&(n.created_run_inputs=i.created_run_inputs),typeof i.workflow_version_id=="number"?n.workflow_version_id=i.workflow_version_id:i.workflow_version_id===null&&(n.workflow_version_id=null),i.step!==null&&typeof i.step=="object"&&!Array.isArray(i.step)){let o=i.step;typeof o.id=="string"&&o.id.length>0&&(n.workflow_step={id:o.id,name:typeof o.name=="string"?o.name:null,type:typeof o.type=="string"?o.type:null})}return typeof i.tier=="string"&&(n.escalation_tier=i.tier),typeof i.token=="string"&&(n.escalation_token=i.token),typeof i.reason=="string"&&(n.escalation_reason=i.reason),Array.isArray(i.declared_outcomes)&&i.declared_outcomes.every(o=>typeof o=="string")&&(n.declared_outcomes=i.declared_outcomes),typeof i.agent_output=="string"&&(n.agent_output=i.agent_output),n}var jA,Ac=k(()=>{"use strict";jA=`SELECT a.id AS attention_id,
|
|
2148
2148
|
a.kind AS kind,
|
|
2149
2149
|
a.severity AS severity,
|
|
2150
2150
|
a.created_at AS created_at,
|
|
@@ -2166,28 +2166,28 @@ Flags:
|
|
|
2166
2166
|
ON isess.run_id = a.run_id
|
|
2167
2167
|
AND isess.id = (
|
|
2168
2168
|
SELECT MAX(id) FROM interactive_session WHERE run_id = a.run_id
|
|
2169
|
-
)`});var
|
|
2169
|
+
)`});var Nc={};ae(Nc,{parseIdleTimeoutMs:()=>Gg,resolvePromptInput:()=>qg,runChat:()=>Rc});import{readFileSync as WA,openSync as HA}from"node:fs";import{homedir as XA}from"node:os";import{join as qA}from"node:path";import{spawn as GA}from"node:child_process";function VA(t){return qA(XA(),".lmctl",`daemonize-${t}.log`)}function KA(t){let e=process.stdout.isTTY===!0,r=process.stderr.isTTY===!0;if(!e&&!r)return{stdio:["ignore","inherit","inherit"],logPath:null};let n=VA(t),s=HA(n,"a");return{stdio:["ignore",e?s:"inherit",r?s:"inherit"],logPath:n}}function YA(t,e){let{stdio:r,logPath:n}=KA(process.pid),s=GA(process.argv[0],[process.argv[1],"chat",...t],{detached:!0,stdio:r,env:{...process.env,[zi]:"1"}});return s.on("error",i=>{e.stderr.write(`error: --daemonize failed to spawn the detached child: ${i.message}
|
|
2170
2170
|
`)}),s.unref(),e.stdout.write(`${JSON.stringify({status:"detached",pid:s.pid??null,logPath:n})}
|
|
2171
|
-
`),0}async function
|
|
2172
|
-
`),t.length===0?2:0;if(t.includes("--daemonize")&&r[
|
|
2171
|
+
`),0}async function Rc(t,e={stdout:process.stdout,stderr:process.stderr}){let r=e.env??process.env;if(t.length===0||t[0]==="--help"||t[0]==="-h")return e.stdout.write(`${Hg}
|
|
2172
|
+
`),t.length===0?2:0;if(t.includes("--daemonize")&&r[zi]!=="1")return YA(t.filter(u=>u!=="--daemonize"),e);r[zi]==="1"&&(Gs(e),delete process.env[zi]);let n=zA(t);if(typeof n=="string")return e.stderr.write(`error: ${n}
|
|
2173
2173
|
${Hg}
|
|
2174
2174
|
`),2;if(n.promptFile!==void 0){let u=await qg(n.promptFile,e);if(typeof u!="string")return e.stderr.write(`error: ${u.error}
|
|
2175
2175
|
`),2;n.prompt=u}if(n.runFlag!==void 0){let u=Number.parseInt(n.runFlag,10);return!Number.isFinite(u)||u<=0||String(u)!==n.runFlag?(e.stderr.write(`error: invalid --run "${n.runFlag}" (expected a positive integer run id)
|
|
2176
2176
|
`),2):await C(e,async f=>{let m=f.getRun(u);if(m===null)return e.stderr.write(`error: run ${u}: not found
|
|
2177
|
-
`),1;if(m.terminal_state!==null&&m.terminal_state.length>0)return A(e,`run ${u}: already terminal (${m.terminal_state}); chat --run cannot resume a terminated run`);let
|
|
2178
|
-
`),1;if(
|
|
2179
|
-
`),2;let
|
|
2180
|
-
`),0):(e.stderr.write(`error: run ${u}: resumeEscalation failed (${
|
|
2181
|
-
`),1)}if(
|
|
2182
|
-
`),1;let
|
|
2183
|
-
`),0):(e.stderr.write(`error: run ${u}: resumeInteractive failed (${
|
|
2184
|
-
`),1)}return e.stderr.write(`error: run ${u}: pending attention kind "${
|
|
2185
|
-
`),1})}let s=st(
|
|
2177
|
+
`),1;if(m.terminal_state!==null&&m.terminal_state.length>0)return A(e,`run ${u}: already terminal (${m.terminal_state}); chat --run cannot resume a terminated run`);let h=jg(f,u);if(h===null)return e.stderr.write(`error: run ${u}: no pending operator-answerable attention (chat --run only resumes paused runs)
|
|
2178
|
+
`),1;if(h.kind==="workflow_escalation"){if(n.done)return e.stderr.write(`error: --done is not valid for workflow_escalation (the decision itself is terminal)
|
|
2179
|
+
`),2;let _=f.resumeEscalation(h.attention_id,n.prompt);return _.resumed===!0?(e.stdout.write(`run ${u}: escalation resumed (decision: ${n.prompt})
|
|
2180
|
+
`),0):(e.stderr.write(`error: run ${u}: resumeEscalation failed (${_.reason})
|
|
2181
|
+
`),1)}if(h.kind==="interactive_waiting_operator"){let _=Wg(f,h.attention_id);if(_===null||_.step_id===null)return e.stderr.write(`error: run ${u}: pending interactive_waiting_operator attention has no associated interactive step
|
|
2182
|
+
`),1;let g=f.resumeInteractive(_.step_id,n.prompt,n.done===!0);return g.resumed===!0?(e.stdout.write(`run ${u}: interactive resumed (step ${_.step_id}${n.done===!0?", done":""})
|
|
2183
|
+
`),0):(e.stderr.write(`error: run ${u}: resumeInteractive failed (${g.reason})
|
|
2184
|
+
`),1)}return e.stderr.write(`error: run ${u}: pending attention kind "${h.kind}" is not operator-answerable
|
|
2185
|
+
`),1})}let s=st(JA,{target:n.target,alias:n.alias,flags:{session:n.sessionFlag,provider:n.providerFlag}});if(s.mode==="error")return e.stderr.write(`error: ${s.message}
|
|
2186
2186
|
`),2;if(s.mode==="managed")return e.stderr.write(`error: chat managed mode requires --run <id>
|
|
2187
2187
|
`),2;let i;if(s.mode==="ai-team"){if(s.alias===void 0)return e.stderr.write(`error: chat: alias required (internal)
|
|
2188
2188
|
`),2;e.stderr.write(`${s.alias}: turn running; this can take minutes
|
|
2189
2189
|
`);let u=Ze(e,m=>`${s.alias}: turn still running (${m}s elapsed)
|
|
2190
|
-
`),f;try{f=await _r({teamfile:s.teamfile,alias:s.alias,prompt:n.prompt,permissionMode:n.permissionMode,...n.idleTimeoutMs!==void 0?{idleTimeoutMs:n.idleTimeoutMs}:{},...n.rootFlag!==void 0?{rootFlag:n.rootFlag}:{},env:r,io:e,onEvent:m=>{u.poke(),!(n.json===!0&&m.kind==="delta")&&
|
|
2190
|
+
`),f;try{f=await _r({teamfile:s.teamfile,alias:s.alias,prompt:n.prompt,permissionMode:n.permissionMode,...n.idleTimeoutMs!==void 0?{idleTimeoutMs:n.idleTimeoutMs}:{},...n.rootFlag!==void 0?{rootFlag:n.rootFlag}:{},env:r,io:e,onEvent:m=>{u.poke(),!(n.json===!0&&m.kind==="delta")&&eR(e,m,n.verbose===!0)},...n.json===!0?{onAccepted:m=>{u.poke(),e.stdout.write(`${JSON.stringify({status:"accepted",message_id:m})}
|
|
2191
2191
|
`)}}:{}})}finally{u.stop()}return n.json===!0?f.status==="busy"?(e.stdout.write(`${JSON.stringify({status:"busy",message:f.message,teamChatLogId:f.teamChatLogId})}
|
|
2192
2192
|
`),1):f.status==="error"?(e.stdout.write(`${JSON.stringify({status:"error",errorKind:f.errorKind,message:f.message,teamChatLogId:f.teamChatLogId,...f.messageId===null?{}:{message_id:f.messageId}})}
|
|
2193
2193
|
`),1):(e.stdout.write(`${JSON.stringify({status:f.status,replyText:f.replyText,teamChatLogId:f.teamChatLogId,...f.messageId===null?{}:{message_id:f.messageId},turn_finished:!0,note:Xg(s.alias)})}
|
|
@@ -2200,15 +2200,15 @@ ${Hg}
|
|
|
2200
2200
|
`)?"":`
|
|
2201
2201
|
`}`),e.stderr.write(`note: ${Xg(s.alias)}
|
|
2202
2202
|
`),f.status==="stalled"?1:0)}else{if(s.provider===void 0)return e.stderr.write(`error: chat raw mode (bare sessionid / --session) requires --provider <name>
|
|
2203
|
-
`),2;i={provider:s.provider,sessionId:s.sessionid,cwd:process.cwd()}}let o=!1,a=K(),l=0,c=0,d=0;try{let u={provider:i.provider,sessionId:i.sessionId,cwd:i.cwd,prompt:n.prompt,permissionMode:n.permissionMode,env:r,onDelta:
|
|
2203
|
+
`),2;i={provider:s.provider,sessionId:s.sessionid,cwd:process.cwd()}}let o=!1,a=K(),l=0,c=0,d=0;try{let u={provider:i.provider,sessionId:i.sessionId,cwd:i.cwd,prompt:n.prompt,permissionMode:n.permissionMode,env:r,onDelta:h=>{o=!0,a&&(l+=1,d=Buffer.byteLength(h,"utf8"),c+=d),e.stdout.write(h)},onProgress:h=>Jg(e,i.alias??"(raw)",h,n.verbose===!0)};i.model!==void 0&&(u.model=i.model),i.effort!==void 0&&(u.effort=i.effort),i.alias!==void 0&&(u.alias=i.alias),i.isLead!==void 0&&(u.isLead=i.isLead),n.idleTimeoutMs!==void 0&&(u.timeoutMs=n.idleTimeoutMs);let f=await pr(u);a&&_e(JSON.stringify({event:"chat_return",alias:i.alias??"(raw)",provider:i.provider,streamed:o,blockCount:l,streamedBytes:c,resultTextBytes:Buffer.byteLength(f.text,"utf8"),lastChunkBytes:d,tailPreview:ZA(f.text,200)}));let m=f.status==="stalled";return o?f.text.endsWith(`
|
|
2204
2204
|
`)||e.stdout.write(`
|
|
2205
2205
|
`):e.stdout.write(`${f.text}${f.text.endsWith(`
|
|
2206
2206
|
`)?"":`
|
|
2207
2207
|
`}`),f.status==="stalled"?1:0}catch(u){let f=u instanceof Error?u.message:String(u);return e.stderr.write(`error: ${f}
|
|
2208
|
-
`),1}}function Xg(t){return`${t}'s turn has finished and exited; resubmit \`lmctl prompt\` to continue (no persistent session is left running)`}function
|
|
2208
|
+
`),1}}function Xg(t){return`${t}'s turn has finished and exited; resubmit \`lmctl prompt\` to continue (no persistent session is left running)`}function zA(t){let e=[],r="yolo",n,s,i,o,a,l,c=!1,d=!1,u=!1;for(let g=0;g<t.length;g+=1){let p=t[g];if(p==="--permission-mode"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --permission-mode";if(y!=="plan"&&y!=="yolo")return`--permission-mode must be one of plan|yolo (got "${y}")`;r=y;continue}if(p==="--idle-timeout"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --idle-timeout";let E=Gg(y);if(typeof E=="string")return E;n=E;continue}if(p==="--session"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --session";s=y;continue}if(p==="--provider"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --provider";i=y;continue}if(p==="--from"||p.startsWith("--from="))return zh("chat");if(p.startsWith("I_am="))return`unknown argument: ${p}`;if(p==="--root"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --root";o=y;continue}if(p==="--prompt-file"){let y=t[++g];if(y===void 0||y!=="-"&&y.startsWith("--"))return"missing value for --prompt-file";a=y;continue}if(p==="--force"||p.startsWith("--force="))return"unknown option --force (a dead holder auto-reclaims; for a live holder use lmctl prompt)";if(p==="--json"){d=!0;continue}if(p==="--verbose"){u=!0;continue}if(p==="--run"){let y=t[++g];if(y===void 0||y.startsWith("--"))return"missing value for --run";l=y;continue}if(p==="--done"){c=!0;continue}if(p.startsWith("--"))return`unknown flag: ${p}`;e.push(p)}if(l!==void 0){if(s!==void 0)return"--run is mutually exclusive with --session";if(i!==void 0)return"--run is mutually exclusive with --provider";if(o!==void 0)return"--run is mutually exclusive with --root";if(a!==void 0&&e.length>0)return"--prompt-file is mutually exclusive with a positional answer; pass one or the other";if(a===void 0&&e.length===0)return"a prompt (answer) is required with --run";if(e.length>1)return`--run takes exactly one positional (the answer); got ${e.length}`;let g={prompt:a!==void 0?"":e[0],permissionMode:r,runFlag:l,done:c,json:d,verbose:u};return a!==void 0&&(g.promptFile=a),g}let f,m,h;if(a!==void 0){if(e.length===0){if(s===void 0)return"expected <teamfile>:<alias> --prompt-file <path> | <teamfile> <alias> --prompt-file <path> | --session <id> --prompt-file <path>"}else if(e.length===1)f=e[0];else if(e.length===2)f=e[0],m=e[1];else return"--prompt-file is mutually exclusive with a positional prompt; pass one or the other";h=""}else{if(e.length===0)return"a prompt is required";if(e.length===1){if(s===void 0)return'expected <teamfile>:<alias> "<prompt>" | <teamfile> <alias> "<prompt>" | <sessionid> "<prompt>" | --session <id> "<prompt>"';h=e[0]}else if(e.length===2)f=e[0],h=e[1];else if(e.length===3)f=e[0],m=e[1],h=e[2];else return`too many positionals (${e.length}); expected at most <teamfile> <alias> <prompt>`}if(c)return"--done requires --run";let _={prompt:h,permissionMode:r};return f!==void 0&&(_.target=f),m!==void 0&&(_.alias=m),n!==void 0&&(_.idleTimeoutMs=n),s!==void 0&&(_.sessionFlag=s),i!==void 0&&(_.providerFlag=i),o!==void 0&&(_.rootFlag=o),a!==void 0&&(_.promptFile=a),d&&(_.json=d),u&&(_.verbose=u),_}async function qg(t,e,r=process.stdin){let n;try{n=t==="-"?await QA(r):WA(t,"utf8")}catch(i){let o=i instanceof Error?i.message:String(i);return{error:`--prompt-file ${t}: ${o}`}}let s=n.endsWith(`\r
|
|
2209
2209
|
`)?n.slice(0,-2):n.endsWith(`
|
|
2210
|
-
`)?n.slice(0,-1):n;return s.length===0?{error:`--prompt-file ${t}: file is empty; a prompt is required`}:s}async function
|
|
2211
|
-
`)}function
|
|
2210
|
+
`)?n.slice(0,-1):n;return s.length===0?{error:`--prompt-file ${t}: file is empty; a prompt is required`}:s}async function QA(t){let e=[];for await(let r of t)e.push(typeof r=="string"?Buffer.from(r,"utf8"):r);return Buffer.concat(e).toString("utf8")}function Gg(t){if(t==="0")return 0;if(/^\d+$/.test(t)){let i=Number(t);return i>0&&i<1e3?`--idle-timeout ${t} means ${t}ms, not ${t}s \u2014 that's not enough time for any real provider call to make progress. Use an explicit unit, e.g. --idle-timeout ${t}s.`:i}let e=/^(\d+)([smhd])$/.exec(t);if(e===null)return`invalid --idle-timeout "${t}" (expected <n>(s|m|h|d), integer ms >= 1000, or 0)`;let r=Number(e[1]),n=e[2];return r*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Jg(t,e,r,n=!1){if(r.kind!=="tool_use"&&r.kind!=="tool_result"&&r.kind!=="api_retry")return;let s=r.kind==="tool_use"?`[${e}] tool_use ${r.tool??"tool"}${r.summary?`: ${r.summary}`:""}`:r.kind==="tool_result"?`[${e}] tool_result${r.status?` ${r.status}`:""}${r.summary?`: ${r.summary}`:""}`:`[${e}] api_retry${r.summary?`: ${r.summary}`:""}`;L({event:"chat_progress",alias:e,progress_kind:r.kind,line:s}),n&&t.stderr.write(`${s}
|
|
2211
|
+
`)}function ZA(t,e){return t.slice(-e)}function eR(t,e,r=!1){e.kind==="delta"?t.stdout.write(e.chunk):e.kind==="progress"?Jg(t,e.alias,e.event,r):t.stderr.write(e.message)}var JA,Hg,zi,Qi=k(()=>{"use strict";bt();he();Pe();Ui();nn();J();kc();Ac();he();JA={name:"chat",allowsBareTeamfile:!1,supportsRaw:!0},Hg=`usage: lmctl prompt <teamfile>:<alias> "<prompt>"
|
|
2212
2212
|
lmctl prompt <teamfile> <alias> "<prompt>"
|
|
2213
2213
|
lmctl prompt <sessionid> "<prompt>" --provider <name>
|
|
2214
2214
|
lmctl prompt --provider <name> --session <id> "<prompt>"
|
|
@@ -2260,31 +2260,31 @@ File input:
|
|
|
2260
2260
|
BUG-daemon-dies-without-setsid-detachment.md for the two incidents
|
|
2261
2261
|
this exists to stop recurring a third time.
|
|
2262
2262
|
|
|
2263
|
-
Send a prompt to a team member or raw provider session, or answer a paused run.`,
|
|
2264
|
-
`).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
|
|
2265
|
-
`}async function Yg(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(
|
|
2263
|
+
Send a prompt to a team member or raw provider session, or answer a paused run.`,zi="LMCTL_CHAT_DAEMONIZED"});var ds,OB,Lc=k(()=>{"use strict";ds=[{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}],OB=ds.length});import{spawn as tR}from"node:child_process";async function Kg(t,e,r){let n=nR.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 sR(n.name,s)}function sR(t,e){return t==="lmctl_chat"?iR(e):{status:"error",code:404,message:`unknown local tool: ${t}`}}function iR(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 K()&&_e(JSON.stringify({event:"mcp_chat_spawn",team:r,alias:n})),oR(s,process.cwd())}function oR(t,e){return new Promise(r=>{let n=!1,s,i=d=>{n||(n=!0,s!==void 0&&clearTimeout(s),r(d))},o=tR("lmctl",t,{cwd:e,env:process.env,stdio:["ignore","pipe","pipe"]}),a=aR(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){K()&&_e(JSON.stringify({event:"mcp_chat_payload",bytes:Buffer.byteLength(l,"utf8"),lines:l.split(`
|
|
2264
|
+
`).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 aR(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return Vg;let r=Number(e);return!Number.isFinite(r)||r<=0?Vg:r}function Cc(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:rR),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 rR,Vg,nR,Oc=k(()=>{"use strict";Lc();J();rR="http://127.0.0.1:8787",Vg=30*60*1e3,nR=new Map(ds.map(t=>[t.name,t]))});async function uR(t,e){let r=t.id===void 0,n=t.id??null;if(t.method==="exit")return r||e.io.write(Dc({jsonrpc:"2.0",id:n,result:null})),{kind:"exit"};if(t.method==="initialize")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{protocolVersion:lR,capabilities:{tools:{listChanged:!1}},serverInfo:{name:cR,version:dR}}}};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:ds.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 Kg(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 Dc(t){return`${JSON.stringify(t)}
|
|
2265
|
+
`}async function Yg(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(Dc({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 uR(l,t);c.kind==="response"?t.io.write(Dc(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(`
|
|
2266
2266
|
`);for(;u!==-1;){let f=n.slice(0,u);n=n.slice(u+1),a=a.then(()=>i(f)).then(()=>{s&&c(0)}),u=n.indexOf(`
|
|
2267
2267
|
`)}};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}
|
|
2268
|
-
`),a.finally(()=>c(1))})})}var
|
|
2269
|
-
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??
|
|
2268
|
+
`),a.finally(()=>c(1))})})}var lR,cR,dR,zg=k(()=>{"use strict";Lc();Oc();lR="2025-06-18",cR="lmctl",dR="0.0.1"});var Zg={};ae(Zg,{runMcp:()=>fR});async function fR(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(mR),0;if(t.length>0)return e.stderr.write(`usage: lmctl mcp
|
|
2269
|
+
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??pR(),i=1;try{let o=s===void 0?Cc({getConfig:()=>null},process.env):Cc(s,process.env);return i=await Yg({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 pR(){let t=fe(),e=3;for(let r=1;r<=e;r+=1)try{return Qe({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&&Qg(s))hR(50*r);else if(!Qg(s))break}}function Qg(t){return/SQLITE_BUSY|database is locked|database is busy/i.test(t)}function hR(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}var mR,e_=k(()=>{"use strict";Pt();Oc();zg();J();rt();mR=`usage: lmctl mcp
|
|
2270
2270
|
|
|
2271
2271
|
Start the stdio MCP bridge. The bridge resolves api.url and api.token from
|
|
2272
2272
|
local config, then uses stdin/stdout for JSON-RPC frames.
|
|
2273
|
-
`});function t_(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 r_=k(()=>{"use strict"});var m_={};ae(m_,{applyMaxBytes:()=>
|
|
2274
|
-
`),0;let r=ie(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=H(r,"--json"),s=B(r,"--since"),i=d_(s);if("error"in i)return A(e,i.error);let o=i.date,a=B(r,"--lines"),l=B(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 p=Number.parseInt(a,10);if(!Number.isFinite(p)||p<1||String(p)!==a)return A(e,`invalid --lines "${a}" (expected a positive integer)`);c={kind:"lines",lines:p}}else{let p=l===void 0?
|
|
2275
|
-
`),c={kind:"bytes",maxBytes:p}}let d=H(r,"--watch"),u=B(r,"--watch-interval"),f=u===void 0?
|
|
2276
|
-
`)}},
|
|
2277
|
-
`),
|
|
2278
|
-
`),
|
|
2279
|
-
`;return t.stdout.write(n.kind==="bytes"?
|
|
2273
|
+
`});function t_(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 r_=k(()=>{"use strict"});var m_={};ae(m_,{applyMaxBytes:()=>to,parseTailSince:()=>d_,renderMessage:()=>c_,runTail:()=>TR});async function TR(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${ER}
|
|
2274
|
+
`),0;let r=ie(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=H(r,"--json"),s=B(r,"--since"),i=d_(s);if("error"in i)return A(e,i.error);let o=i.date,a=B(r,"--lines"),l=B(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 p=Number.parseInt(a,10);if(!Number.isFinite(p)||p<1||String(p)!==a)return A(e,`invalid --lines "${a}" (expected a positive integer)`);c={kind:"lines",lines:p}}else{let p=l===void 0?_R:Number.parseInt(l,10);if(!Number.isFinite(p)||p<0||l!==void 0&&String(p)!==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
|
|
2275
|
+
`),c={kind:"bytes",maxBytes:p}}let d=H(r,"--watch"),u=B(r,"--watch-interval"),f=u===void 0?yR:Number.parseInt(u.replace(/s$/,""),10);if(!Number.isFinite(f)||f<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 m=B(r,"--run");if(m!==void 0){if(r.positionals.length>0)return A(e,"--run is mutually exclusive with positional [target] [alias]");if(B(r,"--session")!==void 0)return A(e,"--run is mutually exclusive with --session");if(B(r,"--provider")!==void 0)return A(e,"--run is mutually exclusive with --provider");let p=Number.parseInt(m,10);if(!Number.isFinite(p)||p<=0||String(p)!==m)return A(e,`invalid --run "${m}" (expected a positive integer run id)`);try{return await C(e,async y=>wR(e,y,p,c,d,f,o,n))}catch(y){return qe(e,y)}}let h=st(gR,{target:r.positionals[0],alias:r.positionals[1],flags:{session:B(r,"--session"),provider:B(r,"--provider")}});if(h.mode==="error")return A(e,h.message);if(h.mode==="managed")return A(e,"tail managed mode requires --run <id>");let _;if(h.mode==="ai-team")if(h.alias===void 0){let p;try{p=await C(e,v=>pe(h.teamfile,v))}catch(v){return A(e,`tail: ${v instanceof Error?v.message:String(v)}`)}let y;try{y=ke(p)}catch(v){return A(e,`tail: ${v instanceof Error?v.message:String(v)}`)}let E=Ct(y);if(E===void 0)return A(e,`tail: ${h.teamfile} has no Lead member; pass <tf>:<alias>`);try{let v=await C(e,b=>ue(h.teamfile,E.alias,b));_={provider:v.provider,sessionId:v.sessionid,cwd:v.sessiondir}}catch(v){return v instanceof se?A(e,v.message):qe(e,v)}}else try{let p=await C(e,y=>ue(h.teamfile,h.alias,y));_={provider:p.provider,sessionId:p.sessionid,cwd:p.sessiondir}}catch(p){return p instanceof se?A(e,p.message):qe(e,p)}else{let p=h.sessionid,y=h.provider;if(y===void 0){let E=await tn(p);if(E.length===0)return A(e,`tail: session "${p}" not found in any provider store`);if(E.length>1)return A(e,`tail: session "${p}" matches multiple providers (${E.join(", ")}); pass --provider`);y=E[0]}_={provider:y,sessionId:p}}let g=await n_(e,_.provider,_.sessionId,c,-1,o,n);return g===eo?1:d?await new Promise(p=>{let y=async()=>{try{let b=await n_(e,_.provider,_.sessionId,c,g,o,n);b!==eo&&(g=b)}catch(b){e.stderr.write(`tail: ${b instanceof Error?b.message:String(b)}
|
|
2276
|
+
`)}},E=setInterval(()=>{y()},f*1e3),v=()=>{clearInterval(E),p(0)};process.once("SIGINT",v),process.once("SIGTERM",v)}):0}async function n_(t,e,r,n,s,i,o){let a;try{a=await Ie(r,e)}catch(f){return t.stderr.write(`tail: failed to load session: ${f instanceof Error?f.message:String(f)}
|
|
2277
|
+
`),eo}if(a===null)return t.stderr.write(`tail: session not found: ${r} (provider=${e})
|
|
2278
|
+
`),eo;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 f=i.getTime(),m=l.length;for(let h=0;h<l.length;h+=1){let _=l[h].timestamp,g=_===void 0?NaN:(_ instanceof Date?_:new Date(_)).getTime();if(!Number.isNaN(g)&&g>=f){m=h;break}}c=Math.max(c,m)}let d=s<0&&c>0;if(c>=l.length)return o===!0&&s<0&&te(t,{schema_version:Zi,provider:e,sessionId:r,messages:[],truncated:d}),l.length-1;if(o===!0){let f=l.slice(c).map(h=>({role:h.role,content:h.content,model:h.model??null,timestamp:(h.timestamp instanceof Date?h.timestamp:new Date(h.timestamp)).toISOString()}));return te(t,{schema_version:Zi,provider:e,sessionId:r,messages:f,truncated:d}),l.length-1}let u="";for(let f=c;f<l.length;f+=1)u+=`${c_(l[f])}
|
|
2279
|
+
`;return t.stdout.write(n.kind==="bytes"?to(u,n.maxBytes):u),l.length-1}function c_(t){let e=u_(t.timestamp),r=e?`${e} ${t.role}`:t.role,s=(t.content??"").replace(/\r\n/g,`
|
|
2280
2280
|
`).replace(/\r/g,`
|
|
2281
2281
|
`).split(`
|
|
2282
2282
|
`),i=s[0]??"",o=s.slice(1);return o.length===0?`${r}: ${i}`:`${r}: ${i}
|
|
2283
2283
|
${o.map(a=>` ${a}`).join(`
|
|
2284
|
-
`)}`}function s_(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
|
|
2285
|
-
`).join("");t.stdout.write(n.kind==="bytes"?
|
|
2286
|
-
`).join("");t.stdout.write(n.kind==="bytes"?
|
|
2287
|
-
`)}},i*1e3),
|
|
2284
|
+
`)}`}function s_(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 wR(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(f=>f.timestamp_ms>=o.getTime()),d=n.kind==="lines"?c.slice(Math.max(0,c.length-n.lines)):c;if(a===!0)te(t,{schema_version:Zi,run_id:r,truncated:d.length<c.length,events:s_(d)});else{let f=d.map(m=>`${a_(m)}
|
|
2285
|
+
`).join("");t.stdout.write(n.kind==="bytes"?to(f,n.maxBytes):f)}let u=c.length>0?c[c.length-1].id:0;return s?await new Promise(f=>{let h=setInterval(()=>{try{let g=e.listSessionEvents(r,u);if(g.length===0)return;for(let y of g)u=y.id;if(a===!0){te(t,{schema_version:Zi,run_id:r,truncated:!1,events:s_(g)});return}let p=g.map(y=>`${a_(y)}
|
|
2286
|
+
`).join("");t.stdout.write(n.kind==="bytes"?to(p,n.maxBytes):p)}catch(g){t.stderr.write(`tail: ${g instanceof Error?g.message:String(g)}
|
|
2287
|
+
`)}},i*1e3),_=()=>{clearInterval(h),f(0)};process.once("SIGINT",_),process.once("SIGTERM",_)}):0}function to(t,e){if(e===0||Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.byteLength(i_,"utf8");if(n>=e)return o_(t,e);let s=e-n,i=o_(t,s);return`${i_}${i}`}function o_(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 a_(t){let e=u_(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 d_(t){return t_(t,"--since")}function u_(t){if(t===void 0)return;let e=(0,l_.formatLocalTimestamp)(t);return e==="unknown"?void 0:e}var l_,gR,_R,yR,Zi,ER,eo,i_,f_=k(()=>{"use strict";Qt();l_=_t(ct(),1);he();Pe();Et();Tt();r_();gR={name:"tail",allowsBareTeamfile:!0,supportsRaw:!0},_R=4096,yR=2,Zi=1,ER=`usage: lmctl tail [target] [alias]
|
|
2288
2288
|
lmctl tail --session <id> [--provider <name>]
|
|
2289
2289
|
lmctl tail --run <id>
|
|
2290
2290
|
[--lines N | --max-bytes N] [--since <duration|ISO8601>]
|
|
@@ -2311,8 +2311,8 @@ everything new by construction. --max-bytes has no JSON analog and is
|
|
|
2311
2311
|
ignored under --json (a stderr note is printed if you passed it
|
|
2312
2312
|
explicitly); --lines still applies. --watch --json emits one JSON
|
|
2313
2313
|
object per poll tick with something new (NDJSON) -- a tick with
|
|
2314
|
-
nothing new prints no line at all, same as text mode.`;
|
|
2315
|
-
`});var h_={};ae(h_,{runExport:()=>
|
|
2314
|
+
nothing new prints no line at all, same as text mode.`;eo=-2;i_=`\u2026 [truncated older output \u2014 raise with --max-bytes]
|
|
2315
|
+
`});var h_={};ae(h_,{runExport:()=>vR});async function vR(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(p_),0;let r=ie(t,[],["--prompt-only"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==2)return A(e,p_.trimEnd());let n;try{n=ue(r.positionals[0],r.positionals[1],e.dal)}catch(a){return a instanceof se?A(e,a.message):qe(e,a)}let s;try{s=await Ie(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=H(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}:
|
|
2316
2316
|
${a.content}`);return o.length>0&&e.stdout.write(`${o.join(`
|
|
2317
2317
|
|
|
2318
2318
|
`)}
|
|
@@ -2325,17 +2325,17 @@ messages. No timestamps, tool activity, or truncation.
|
|
|
2325
2325
|
context, one paragraph per prompt with a blank line between prompts.
|
|
2326
2326
|
Codex prompts require native prompt metadata or user_message events;
|
|
2327
2327
|
unclassified user-role records are omitted in this compact mode.
|
|
2328
|
-
`});import{mkdirSync as b_,readFileSync as TR,renameSync as wR,writeFileSync as vR,existsSync as I_}from"node:fs";import{homedir as SR}from"node:os";import{dirname as x_,join as eo,resolve as to}from"node:path";import{fileURLToPath as bR}from"node:url";function RR(){return eo(SR(),".lmctl","cache","lmprice")}function on(t,e){return eo(t,e)}function Er(t){try{return JSON.parse(TR(t,"utf-8"))}catch{return null}}function A_(t,e){let r=`${t}.tmp-${process.pid}`;vR(r,e),wR(r,t)}function Dc(t){return t===null||typeof t=="number"}function ro(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 Dc(s.input_per_1m_tokens)&&Dc(s.output_per_1m_tokens)&&Dc(s.input_cache_read_per_1m_tokens)})}function no(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"&&LR.has(i.evidence)});return r&&n}function CR(t){let e=Er(on(t,k_)),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=Er(on(t,NR));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 OR(t){let e=CR(t),r=Er(on(t,Mc)),n=Er(on(t,$c));return{catalog:ro(r)?r:null,aliases:no(n)?n:null,meta:e}}function DR(t,e){try{b_(t,{recursive:!0}),A_(on(t,k_),JSON.stringify(e))}catch{}}function y_(t,e,r){try{b_(t,{recursive:!0}),A_(on(t,e),JSON.stringify(r))}catch{}}function MR(t,e){let r=$R(t),n=r?[to(r,"data",e)]:[to(t,"..","..","data",e)];for(let s of n)if(I_(s))return s;return null}function $R(t){let e=to(t);for(;;){if(I_(to(e,"package.json")))return e;let r=x_(e);if(r===e)return null;e=r}}function E_(t,e,r){let n=r!==void 0?r:MR(t,e);return n===null?null:Er(n)}function FR(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return __;let e=Number(t);return!Number.isFinite(e)||e<0?__:e*1e3}function PR(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function T_(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(kR)});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(AR)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function so(t={}){return Object.keys(t).length===0?(w_??=v_(t),w_):v_(t)}async function v_(t){let e=x_(bR(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:PR();if(r!==null&&r!==""){let g=Er(eo(r,Mc)),h=Er(eo(r,$c));if(ro(g)&&no(h)){let _={catalog:g,aliases:h,source:"pinned",generatedAt:g.generated_at??null};return Fc=_.generatedAt,_}return S_(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??RR(),i=t.now??Date.now(),o=t.ttlMs??FR(),a=OR(s),l=(g,h)=>g!==null&&h.last_checked!==null&&i-Date.parse(h.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,f={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},m=!1;if(!l(c,a.meta.model_list)){let g=await T_(n,IR,c,a.meta.model_list.etag);g.kind==="match"?(f.model_list.last_checked=new Date(i).toISOString(),m=!0):g.kind==="payload"&&(f.model_list.last_checked=new Date(i).toISOString(),m=!0,ro(g.payload)&&(c=g.payload,g.etag!==null&&(f.model_list.etag=g.etag),y_(s,Mc,c),u=!0))}if(!l(d,a.meta.aliases)){let g=await T_(n,xR,d,a.meta.aliases.etag);g.kind==="match"?(f.aliases.last_checked=new Date(i).toISOString(),m=!0):g.kind==="payload"&&(f.aliases.last_checked=new Date(i).toISOString(),m=!0,no(g.payload)&&(d=g.payload,g.etag!==null&&(f.aliases.etag=g.etag),y_(s,$c,d),u=!0))}if((m||u)&&DR(s,f),c!==null||d!==null){let g={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return Fc=g.generatedAt,g}return S_(t,e)}function S_(t,e){let r=E_(e,"price-data.json",t.bundledPath),n=E_(e,"price-aliases.json",t.bundledAliasesPath),s=ro(r)?r:null,i=no(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Fc=o.generatedAt,o}function R_(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 IR,xR,kR,AR,__,Mc,$c,k_,NR,LR,Fc,w_,Pc=k(()=>{"use strict";IR="https://lmctl.com/dataset/model_list.json",xR="https://lmctl.com/dataset/aliases.json",kR=1e3,AR=1e4,__=6*60*60*1e3;Mc="model_list.json",$c="aliases.json",k_="meta.json",NR="model_list.meta.json";LR=new Set(["established","asserted","unresolved"]);Fc=null,w_=null});function an(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Tr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return an(r)}function L_(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(an(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function UR(t,e){let r=new Set,n=l=>{r.add(an(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 ln(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=>UR(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=L_(n);return s.some(o=>i.has(o))}}}function BR(t){let e=t.trim(),r=jR.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function io(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function qR(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 GR(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}${an(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!qR(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 JR(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 P_(t,e){return t.map(JR).sort((r,n)=>{let s=io(r.source)-io(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 Uc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function VR(t,e,r){let n=GR(t),s=P_(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 jc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=VR(t,e,r),s=n.offers.find(Uc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function KR(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function YR(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=Tr(i),a=r.records.filter(l=>Tr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:jc(a,o,Bc)}function U_(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 _=n.aliases.find(p=>h.includes(p.alias.toLowerCase()));if(_){if(_.evidence==="unresolved"||_.standard_slug===null)return{state:{kind:"unresolved",alias:_.alias},viaAlias:!0,pinRoute:null};let p=KR(n,_.standard_slug);return{state:YR(_,p,r),viaAlias:!0,pinRoute:p?.catalog_record_id?.toLowerCase()??null}}}let s=oo[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=an(i),c=r.records.filter(h=>h.source_model_id.toLowerCase()===i&&s.matchRow(h,[l]));if(c.length>0){let h=Tr(c[0]),_=r.records.filter(p=>s.matchRow(p,[h])&&Tr(p)===h);return a(jc(_.length>0?_:c,h,N_[t]??Bc))}let d=r.records.filter(h=>s.matchRow(h,o));if(d.length===0)return a({kind:"unknown",declared:e});let u=new Map;for(let h of d){let _=Tr(h),p=u.get(_);p?p.push(h):u.set(_,[h])}let f=N_[t]??Bc,m=null,g=null;for(let h of u.values()){let _=P_(h,f);(g===null||zR(_[0],g[0],f)<0)&&(m=h,g=_)}return a(jc(m,Tr(m[0]),f))}function ao(t,e,r,n){return U_(t,e,r,n).state}function j_(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=U_(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&&Uc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Uc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function B_(t,e){let r=oo[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Tr(s));return n.size}function zR(t,e,r){let n=io(t.source)-io(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 C_,O_,D_,M_,$_,F_,jR,WR,HR,XR,oo,N_,Bc,Wc=k(()=>{"use strict";C_=ln({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),O_=ln({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)(-|$)/}),D_=ln({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),M_=ln({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),$_=ln({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),F_=ln({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),jR=/\s*\(([^()]+)\)\s*$/;WR={"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"},HR=["gemini","google","vertex_ai-language-models","anthropic"],XR={normalize(t){let{model:e}=BR(t),r=WR[e.toLowerCase()];return r===void 0?[]:[an(r)]},isChatModel(){return!0},coversRecord(t){return/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=L_(t);return e.some(n=>r.has(n))}},oo={claude:C_,codex:O_,gemini:D_,agy:XR,kimi:M_,qwen:$_,hermes:F_},N_={claude:C_.firstPartyProviders,codex:O_.firstPartyProviders,gemini:D_.firstPartyProviders,agy:HR,kimi:M_.firstPartyProviders,qwen:$_.firstPartyProviders,hermes:F_.firstPartyProviders};Bc=[]});var W_={};ae(W_,{runCost:()=>rN});function ZR(t,e,r,n){let s=new Set,i=[];for(let o of e){let a=r===null?null:ao(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 rN(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${tN}
|
|
2329
|
-
`),0;let r=ie(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=H(r,"--json"),s=st(
|
|
2328
|
+
`});import{mkdirSync as b_,readFileSync as SR,renameSync as bR,writeFileSync as IR,existsSync as I_}from"node:fs";import{homedir as xR}from"node:os";import{dirname as x_,join as ro,resolve as no}from"node:path";import{fileURLToPath as kR}from"node:url";function CR(){return ro(xR(),".lmctl","cache","lmprice")}function an(t,e){return ro(t,e)}function Er(t){try{return JSON.parse(SR(t,"utf-8"))}catch{return null}}function A_(t,e){let r=`${t}.tmp-${process.pid}`;IR(r,e),bR(r,t)}function Mc(t){return t===null||typeof t=="number"}function so(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 Mc(s.input_per_1m_tokens)&&Mc(s.output_per_1m_tokens)&&Mc(s.input_cache_read_per_1m_tokens)})}function io(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"&&DR.has(i.evidence)});return r&&n}function MR(t){let e=Er(an(t,k_)),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=Er(an(t,OR));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 $R(t){let e=MR(t),r=Er(an(t,$c)),n=Er(an(t,Fc));return{catalog:so(r)?r:null,aliases:io(n)?n:null,meta:e}}function FR(t,e){try{b_(t,{recursive:!0}),A_(an(t,k_),JSON.stringify(e))}catch{}}function y_(t,e,r){try{b_(t,{recursive:!0}),A_(an(t,e),JSON.stringify(r))}catch{}}function PR(t,e){let r=UR(t),n=r?[no(r,"data",e)]:[no(t,"..","..","data",e)];for(let s of n)if(I_(s))return s;return null}function UR(t){let e=no(t);for(;;){if(I_(no(e,"package.json")))return e;let r=x_(e);if(r===e)return null;e=r}}function E_(t,e,r){let n=r!==void 0?r:PR(t,e);return n===null?null:Er(n)}function jR(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return __;let e=Number(t);return!Number.isFinite(e)||e<0?__:e*1e3}function BR(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function T_(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(NR)});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(LR)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function oo(t={}){return Object.keys(t).length===0?(w_??=v_(t),w_):v_(t)}async function v_(t){let e=x_(kR(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:BR();if(r!==null&&r!==""){let h=Er(ro(r,$c)),_=Er(ro(r,Fc));if(so(h)&&io(_)){let g={catalog:h,aliases:_,source:"pinned",generatedAt:h.generated_at??null};return Pc=g.generatedAt,g}return S_(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??CR(),i=t.now??Date.now(),o=t.ttlMs??jR(),a=$R(s),l=(h,_)=>h!==null&&_.last_checked!==null&&i-Date.parse(_.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,f={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},m=!1;if(!l(c,a.meta.model_list)){let h=await T_(n,AR,c,a.meta.model_list.etag);h.kind==="match"?(f.model_list.last_checked=new Date(i).toISOString(),m=!0):h.kind==="payload"&&(f.model_list.last_checked=new Date(i).toISOString(),m=!0,so(h.payload)&&(c=h.payload,h.etag!==null&&(f.model_list.etag=h.etag),y_(s,$c,c),u=!0))}if(!l(d,a.meta.aliases)){let h=await T_(n,RR,d,a.meta.aliases.etag);h.kind==="match"?(f.aliases.last_checked=new Date(i).toISOString(),m=!0):h.kind==="payload"&&(f.aliases.last_checked=new Date(i).toISOString(),m=!0,io(h.payload)&&(d=h.payload,h.etag!==null&&(f.aliases.etag=h.etag),y_(s,Fc,d),u=!0))}if((m||u)&&FR(s,f),c!==null||d!==null){let h={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return Pc=h.generatedAt,h}return S_(t,e)}function S_(t,e){let r=E_(e,"price-data.json",t.bundledPath),n=E_(e,"price-aliases.json",t.bundledAliasesPath),s=so(r)?r:null,i=io(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Pc=o.generatedAt,o}function R_(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 AR,RR,NR,LR,__,$c,Fc,k_,OR,DR,Pc,w_,Uc=k(()=>{"use strict";AR="https://lmctl.com/dataset/model_list.json",RR="https://lmctl.com/dataset/aliases.json",NR=1e3,LR=1e4,__=6*60*60*1e3;$c="model_list.json",Fc="aliases.json",k_="meta.json",OR="model_list.meta.json";DR=new Set(["established","asserted","unresolved"]);Pc=null,w_=null});function wr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Tr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return wr(r)}function L_(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(wr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function WR(t,e){let r=new Set,n=l=>{r.add(wr(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 ln(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=>WR(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=L_(n);return s.some(o=>i.has(o))}}}function XR(t){let e=t.trim(),r=HR.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function VR(t,e,r){let n=e.trim().toLowerCase(),s=wr(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 KR(t,e,r){let n=[];for(let[s,i]of Object.entries(us))s!==r&&VR(i,t,e)&&n.push(s);return n}function ao(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function YR(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 zR(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}${wr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!YR(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 QR(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 P_(t,e){return t.map(QR).sort((r,n)=>{let s=ao(r.source)-ao(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 jc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function ZR(t,e,r){let n=zR(t),s=P_(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 Bc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=ZR(t,e,r),s=n.offers.find(jc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function eN(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function tN(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=Tr(i),a=r.records.filter(l=>Tr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:Bc(a,o,Wc)}function U_(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let _=[e.trim().toLowerCase()];_.push(`${t.toLowerCase()}/${_[0]}`);let g=n.aliases.find(p=>_.includes(p.alias.toLowerCase()));if(g){if(g.evidence==="unresolved"||g.standard_slug===null)return{state:{kind:"unresolved",alias:g.alias},viaAlias:!0,pinRoute:null};let p=eN(n,g.standard_slug);return{state:tN(g,p,r),viaAlias:!0,pinRoute:p?.catalog_record_id?.toLowerCase()??null}}}let s=us[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=_=>({state:_,viaAlias:!1,pinRoute:null}),l=wr(i),c=r.records.filter(_=>_.source_model_id.toLowerCase()===i&&s.matchRow(_,[l]));if(c.length>0){let _=Tr(c[0]),g=r.records.filter(p=>s.matchRow(p,[_])&&Tr(p)===_);return a(Bc(g.length>0?g:c,_,N_[t]??Wc))}let d=r.records.filter(_=>s.matchRow(_,o));if(d.length===0){let _=KR(e,r,t);return _.length>0?a({kind:"wrong-provider",declared:e,otherProviders:_}):a({kind:"unknown",declared:e})}let u=new Map;for(let _ of d){let g=Tr(_),p=u.get(g);p?p.push(_):u.set(g,[_])}let f=N_[t]??Wc,m=null,h=null;for(let _ of u.values()){let g=P_(_,f);(h===null||rN(g[0],h[0],f)<0)&&(m=_,h=g)}return a(Bc(m,Tr(m[0]),f))}function lo(t,e,r,n){return U_(t,e,r,n).state}function j_(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=U_(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&&jc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(jc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function B_(t,e){let r=us[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Tr(s));return n.size}function rN(t,e,r){let n=ao(t.source)-ao(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 C_,O_,D_,M_,$_,F_,HR,qR,GR,JR,us,N_,Wc,Hc=k(()=>{"use strict";C_=ln({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),O_=ln({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)(-|$)/}),D_=ln({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),M_=ln({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),$_=ln({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),F_=ln({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),HR=/\s*\(([^()]+)\)\s*$/;qR={"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"},GR=["gemini","google","vertex_ai-language-models","anthropic"],JR={normalize(t){let{model:e}=XR(t),r=qR[e.toLowerCase()];return r===void 0?[]:[wr(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=L_(t);return e.some(n=>r.has(n))}},us={claude:C_,codex:O_,gemini:D_,agy:JR,kimi:M_,qwen:$_,hermes:F_},N_={claude:C_.firstPartyProviders,codex:O_.firstPartyProviders,gemini:D_.firstPartyProviders,agy:GR,kimi:M_.firstPartyProviders,qwen:$_.firstPartyProviders,hermes:F_.firstPartyProviders};Wc=[]});var W_={};ae(W_,{runCost:()=>aN});function sN(t,e,r,n){let s=new Set,i=[];for(let o of e){let a=r===null?null:lo(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 aN(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${oN}
|
|
2329
|
+
`),0;let r=ie(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=H(r,"--json"),s=st(nN,{target:r.positionals[0],alias:r.positionals[1],flags:{provider:B(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=>ue(s.teamfile,s.alias,R));i=I.provider,o=I.sessionid}catch(I){if(I instanceof se)return A(e,I.message);throw I}else if(o=s.sessionid,s.provider!==void 0)i=s.provider;else{let I=await tn(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 Ie(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},f=await oo(),m=sN(i,l,f.catalog,f.aliases),h=m.length>1,_="unavailable",g=null,p=null,y=null,E=null,v=!1,b=null,T=null;if(d!==null&&f.catalog!==null){let I=j_(i,d,f.catalog,f.aliases);if(_=I.state.kind,I.offer!==null)T=I.offer.pricing,g=I.offer.route,p=I.offer.source,y=I.offer.sourceModelId,E=I.provenance,v=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=T===null?null:{inputPer1m:T.input_per_1m_tokens,outputPer1m:T.output_per_1m_tokens,cachedInputPer1m:T.input_cache_read_per_1m_tokens},w=u.input===null||u.output===null?null:R_({input:u.input,output:u.output,cachedInput:u.cachedInput??0},T),x={schema_version:iN,provider:i,sessionId:o,model:d,modelsUsed:m,approximate:h,tokens:u,pricePerModel:S,costUsd:w,priceResolution:_,priceRoute:g,priceSource:p,priceSourceModelId:y,priceProvenance:E,priceEstimated:v,costUnavailableReason:b,priceDataSource:f.source,priceDataGeneratedAt:f.generatedAt};return n?(te(e,x),0):(e.stdout.write(`Session: ${o}
|
|
2330
2330
|
`),e.stdout.write(` Provider: ${i}
|
|
2331
2331
|
`),e.stdout.write(` Model: ${d??"(unknown)"}
|
|
2332
|
-
`),
|
|
2333
|
-
`),e.stdout.write(` Tokens: ${u.input==null?"n/a":(0,
|
|
2334
|
-
`),w===null?e.stdout.write(` Cost: n/a (${
|
|
2335
|
-
`):e.stdout.write(` Cost: ~$${w.toFixed(4)}${
|
|
2336
|
-
`),
|
|
2332
|
+
`),h&&e.stdout.write(` NOTE: this session used multiple models (${m.join(", ")}) -- cost below is approximate, priced at ${d}'s rate for the whole session.
|
|
2333
|
+
`),e.stdout.write(` Tokens: ${u.input==null?"n/a":(0,co.formatCount)(u.input)} in / ${u.output==null?"n/a":(0,co.formatCount)(u.output)} out`+(u.cachedInput!=null?` (cached: ${(0,co.formatCount)(u.cachedInput)})`:"")+`
|
|
2334
|
+
`),w===null?e.stdout.write(` Cost: n/a (${b??`no lmprice entry for "${d??"unknown"}"`})
|
|
2335
|
+
`):e.stdout.write(` Cost: ~$${w.toFixed(4)}${h?" (approximate)":""}${v?" (estimated rate)":""}
|
|
2336
|
+
`),g!==null&&e.stdout.write(` Price route: ${g}${v?" (manual/estimated row)":""}
|
|
2337
2337
|
`),e.stdout.write(` Price data: ${f.source}${f.generatedAt?` (generated ${f.generatedAt})`:""}
|
|
2338
|
-
`),0)}var
|
|
2338
|
+
`),0)}var co,nN,iN,oN,H_=k(()=>{"use strict";Qt();co=_t(ct(),1);Uc();Hc();he();Pe();nN={name:"cost",allowsBareTeamfile:!1,supportsRaw:!0};iN=1,oN=`usage: lmctl cost <target> [alias] [--json]
|
|
2339
2339
|
lmctl cost <sessionid> [--provider <name>]
|
|
2340
2340
|
|
|
2341
2341
|
Estimate a session's dollar cost: aggregate token usage x the model's
|
|
@@ -2358,64 +2358,69 @@ unavailable) and
|
|
|
2358
2358
|
\`priceDataGeneratedAt\` says how fresh it is -- the online check has a
|
|
2359
2359
|
strict short timeout and NEVER blocks or fails this command: any network
|
|
2360
2360
|
error degrades silently to the local cache, then the bundled built-in
|
|
2361
|
-
copy, in that order.`});var q_={};ae(q_,{runLs:()=>
|
|
2362
|
-
`),0;let r=ie(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=B(r,"--format"),s=H(r,"--json");if(H(r,"--runs")){for(let
|
|
2361
|
+
copy, in that order.`});var q_={};ae(q_,{runLs:()=>uN});import{resolve as Xc}from"node:path";function dN(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 uN(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${lN}
|
|
2362
|
+
`),0;let r=ie(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=B(r,"--format"),s=H(r,"--json");if(H(r,"--runs")){for(let g of["--provider","--sessiondir"])if(B(r,g)!==void 0)return A(e,`--runs is mutually exclusive with ${g}`);for(let g of["--recursive","--all"])if(H(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 m=B(r,"--limit"),h=cN;if(m!==void 0){let g=Number.parseInt(m,10);if(!Number.isFinite(g)||g<1||String(g)!==m)return A(e,`invalid --limit "${m}" (expected a positive integer)`);if(g>X_)return A(e,`--limit ${g} exceeds maximum (${X_})`);h=g}let _=n==="json"||s===!0?"json":"table";try{return await C(e,async g=>mN(e,g,h,_))}catch(g){return qe(e,g)}}let o=fN(n,s);if("error"in o)return A(e,o.error);let a=o.format,l=B(r,"--provider"),c=B(r,"--sessiondir"),d=H(r,"--recursive"),u=H(r,"--all"),f;try{f=await nc(l?{provider:l}:{})}catch(m){return A(e,`ls: discovery failed: ${m instanceof Error?m.message:String(m)}`)}if(!u){let m=c!==void 0?Xc(c):Xc(process.cwd());f=f.filter(h=>{let _=Xc(h.cwd);return d?_===m||_.startsWith(`${m}/`):_===m})}if(f=dN(f),a==="json")return te(e,f.map(m=>({provider:m.provider,sessionId:m.sessionId,cwd:m.cwd,messageCount:m.messageCount,modifiedAt:m.modifiedAt.toISOString(),...m.model!==void 0?{model:m.model}:{}}))),0;if(f.length===0){if(a==="table"){let m=u?"(all)":c??process.cwd(),h=d?"under":"in";e.stdout.write(`No native sessions found ${h} ${m}.
|
|
2363
2363
|
`)}return 0}if(a==="teamfile"){for(let m of f)e.stdout.write(`_MEMBER_ alias=- provider=${m.provider} sessionid=${m.sessionId} sessiondir=${m.cwd}
|
|
2364
|
-
`);return 0}return(0,Ne.printTable)(f.map(m=>[(0,Ne.escapeCell)(m.sessionId),(0,Ne.escapeCell)(m.provider),(0,Ne.escapeCell)(m.cwd.length>36?`\u2026${m.cwd.slice(-35)}`:m.cwd),(0,Ne.formatRelativeTime)(m.modifiedAt)]),{headers:["SESSION","PROVIDER","SESSIONDIR","MODIFIED"],stream:e.stdout}),0}async function
|
|
2365
|
-
`),0):((0,Ne.printTable)(s.map(i=>[(0,Ne.escapeCell)(i.id),(0,Ne.escapeCell)(i.workflow_id),(0,Ne.escapeCell)(i.team_id),(0,Ne.escapeCell)(i.current_state??""),(0,Ne.escapeCell)(i.terminal_state??""),(0,Ne.escapeCell)(i.started_at)]),{headers:["RUN_ID","WORKFLOW","TEAM","STATE","TERMINAL","STARTED"],stream:t.stdout}),0)}function
|
|
2364
|
+
`);return 0}return(0,Ne.printTable)(f.map(m=>[(0,Ne.escapeCell)(m.sessionId),(0,Ne.escapeCell)(m.provider),(0,Ne.escapeCell)(m.cwd.length>36?`\u2026${m.cwd.slice(-35)}`:m.cwd),(0,Ne.formatRelativeTime)(m.modifiedAt)]),{headers:["SESSION","PROVIDER","SESSIONDIR","MODIFIED"],stream:e.stdout}),0}async function mN(t,e,r,n){let s=Bg(e,{limit:r});return n==="json"?(te(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.
|
|
2365
|
+
`),0):((0,Ne.printTable)(s.map(i=>[(0,Ne.escapeCell)(i.id),(0,Ne.escapeCell)(i.workflow_id),(0,Ne.escapeCell)(i.team_id),(0,Ne.escapeCell)(i.current_state??""),(0,Ne.escapeCell)(i.terminal_state??""),(0,Ne.escapeCell)(i.started_at)]),{headers:["RUN_ID","WORKFLOW","TEAM","STATE","TERMINAL","STARTED"],stream:t.stdout}),0)}function fN(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 Ne,lN,cN,X_,G_=k(()=>{"use strict";Ne=_t(ct(),1);bt();he();Ac();lN=`usage: lmctl ls [--provider <name>] [--sessiondir <path>]
|
|
2366
2366
|
[--recursive] [--all] [--format table|teamfile|json] [--json]
|
|
2367
2367
|
lmctl ls --runs [--limit N] [--format table|json] [--json]
|
|
2368
2368
|
|
|
2369
|
-
List native provider sessions in scope, or list recent managed runs with --runs.`,sN=50,X_=500});import{spawnSync as Kc}from"node:child_process";import{existsSync as Y_,readFileSync as z_}from"node:fs";import{homedir as Q_}from"node:os";import{dirname as _W,resolve as Jc}from"node:path";function cn(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 mN(){let t=Kc("agy",["models"],{encoding:"utf-8",timeout:uN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function fN(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 pN(t){if(!t&&Xc)return Xc;let e=s=>(t||(Xc=s),s),r;try{r=(t??mN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?cn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:cn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=fN(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function gN(){let t=Kc("codex",["debug","models"],{encoding:"utf-8",timeout:hN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function _N(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 yN(t){if(!t&&qc)return qc;let e=s=>(t||(qc=s),s),r;try{r=(t??gN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?cn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:cn("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=_N(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 TN(t){let e=Kc("opencode",["models",t],{encoding:"utf-8",timeout:EN});return{status:e.status,stdout:e.stdout??"",error:e.error}}function wN(t,e){if(!e&&Gc.has(t))return Gc.get(t);let r=i=>(e||Gc.set(t,i),i),n;try{n=(e??TN)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?cn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:cn(`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 Yc(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&&dN.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=bN(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=wN(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=vN(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=pN(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||V_.includes(n.model))continue;J_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${us(J_)}. 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(V_)}. 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===K_&&r.push(`[${n.alias}] model="${K_}" 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=yN(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&&(Z_.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 ey(t,e={}){let r=t.filter(i=>i.model!==void 0&&Z_.has(i.provider.trim().toLowerCase()));if(r.length===0)return[];let n=e.snapshot??await so();if(n.catalog===null)return[];let s=[];for(let i of r){let o=i.provider.trim().toLowerCase(),a=i.model,l=ao(o,a,n.catalog,n.aliases);if(l.kind==="unknown"){let c=B_(n.catalog,o)??0;s.push(`[${i.alias}] model "${a}" is unknown to the lmprice catalog for provider "${o}" (${c} 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 ${o} accepts it.`)}else l.kind==="known-unpriced"&&s.push(`[${i.alias}] model "${a}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(o==="claude"&&(l.kind==="priced"||l.kind==="known-unpriced"||l.kind==="estimated")&&cN.test(a)){let c=a.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${i.alias}] model="${a}" 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="${c}" instead.`)}}return s}function vN(t){let e=process.env.KIMI_CODE_HOME||Jc(Q_(),".kimi-code"),r=t??Jc(e,"config.toml");if(!Y_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=z_(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=SN(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 SN(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 bN(t){let e=t??Jc(Q_(),".config","opencode","opencode.json");if(!Y_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(z_(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:IN(r)}}function IN(t){if(!Vc(t))return[];let e=co(t.provider)??co(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Vc(s))continue;let i=co(s.models)??co(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function co(t){return Vc(t)?t:null}function Vc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function us(t){return t.length>0?t.join(", "):"(none)"}var Z_,cN,dN,J_,V_,K_,uN,Xc,hN,qc,EN,Gc,ty=k(()=>{"use strict";Pc();Wc();Z_=new Set(Object.keys(oo).filter(t=>t!=="codex"&&t!=="kimi")),cN=/\d\.(?=\d)/,dN=new Set(["claude","codex","gemini","qwen","kimi","agy"]),J_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],V_=["deepseek-flash","deepseek-pro"],K_="gpt-5.3-codex-spark",uN=15e3;Xc=null;hN=5e3;qc=null;EN=5e3;Gc=new Map});import{homedir as xN}from"node:os";import{basename as kN}from"node:path";function ry(t,e){let r=new Set;return{text:t.replace(RN,(s,i)=>{let o=i.trim(),a=AN[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function ny(t){return{workdir:t.workdir,teamfile:t.teamfile,date:NN(t.date)}}function NN(t){return t.toISOString().slice(0,10)}var AN,RN,sy=k(()=>{"use strict";AN={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=kN(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>xN(),date:t=>t.date},RN=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var id={};ae(id,{GEMINI_PROVIDER_NOTICE:()=>dy,_setAgyModelsRunnerForTests:()=>FN,_setCatalogSnapshotForTests:()=>$N,_setCodexModelsRunnerForTests:()=>PN,_setLintOpenCodeConfigProbeForTests:()=>BN,_setLintSessiondirFsOpsForTests:()=>jN,_setTeamfileSeedForTests:()=>UN,buildRootTeamRegistrationRow:()=>hy,registerRootTeam:()=>gy,runLint:()=>Sr,runSeed:()=>br,sha256Text:()=>py,validateMemberSpec:()=>At});import{createHash as LN}from"node:crypto";import{accessSync as CN,constants as iy,existsSync as ON,readFileSync as ly,realpathSync as Zc,statSync as DN,writeFileSync as oy}from"node:fs";import{dirname as vr,resolve as cy}from"node:path";function $N(t){td=t??void 0}function fy(t){return ey(t,td!==void 0?{snapshot:td}:{})}function FN(t){nd=t??void 0}function PN(t){sd=t??void 0}function UN(t){uy=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(bt(),nc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function jN(t){wr=t===null?ed:{...ed,...t}}function BN(t){my=t??Fn}async function WN(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 my({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 HN(t,e){let r=vr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=cy(o);if(n.has(a))continue;let l=XN(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 XN(t){try{if(wr.existsSync(t)){if(!wr.statSync(t).isDirectory())return"ENOTDIR";wr.accessSync(t,iy.W_OK);return}let e=GN(t);if(e===void 0)return;if(!wr.statSync(e).isDirectory())return"ENOTDIR";wr.accessSync(e,iy.W_OK);return}catch(e){return JN(e)??"permission check failed"}}function qN(t){let e=cy(t);try{return Zc(e)}catch{return e}}function GN(t){let e=t;for(;;){try{if(wr.existsSync(e))return e}catch{return}let r=vr(e);if(r===e)return;e=r}}function JN(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 Sr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(MN),0;let r=ie(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2369
|
+
List native provider sessions in scope, or list recent managed runs with --runs.`,cN=50,X_=500});import{spawnSync as Yc}from"node:child_process";import{existsSync as Y_,readFileSync as z_}from"node:fs";import{homedir as Q_}from"node:os";import{dirname as vW,resolve as Vc}from"node:path";function cn(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 _N(){let t=Yc("agy",["models"],{encoding:"utf-8",timeout:gN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function yN(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 EN(t){if(!t&&qc)return qc;let e=s=>(t||(qc=s),s),r;try{r=(t??_N)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?cn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:cn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=yN(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function wN(){let t=Yc("codex",["debug","models"],{encoding:"utf-8",timeout:TN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function vN(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 SN(t){if(!t&&Gc)return Gc;let e=s=>(t||(Gc=s),s),r;try{r=(t??wN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?cn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:cn("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=vN(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 IN(t){let e=Yc("opencode",["models",t],{encoding:"utf-8",timeout:bN});return{status:e.status,stdout:e.stdout??"",error:e.error}}function xN(t,e){if(!e&&Jc.has(t))return Jc.get(t);let r=i=>(e||Jc.set(t,i),i),n;try{n=(e??IN)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?cn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:cn(`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 zc(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&&hN.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=RN(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=xN(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=kN(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: ${ms(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=EN(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: ${ms(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||V_.includes(n.model))continue;J_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${ms(J_)}. 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): ${ms(V_)}. 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===K_&&r.push(`[${n.alias}] model="${K_}" 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=SN(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: ${ms(i.models)}`);continue}n.model&&(Z_.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 ey(t,e={}){let r=t.filter(o=>o.model!==void 0&&Z_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await oo();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=lo(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=B_(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")&&pN.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 ty(t,e={}){return(await ey(t,e)).warnings}async function ry(t,e={}){return(await ey(t,e)).errors}function kN(t){let e=process.env.KIMI_CODE_HOME||Vc(Q_(),".kimi-code"),r=t??Vc(e,"config.toml");if(!Y_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=z_(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=AN(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 AN(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 RN(t){let e=t??Vc(Q_(),".config","opencode","opencode.json");if(!Y_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(z_(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:NN(r)}}function NN(t){if(!Kc(t))return[];let e=uo(t.provider)??uo(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Kc(s))continue;let i=uo(s.models)??uo(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function uo(t){return Kc(t)?t:null}function Kc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ms(t){return t.length>0?t.join(", "):"(none)"}var Z_,pN,hN,J_,V_,K_,gN,qc,TN,Gc,bN,Jc,ny=k(()=>{"use strict";Uc();Hc();Z_=new Set(Object.keys(us).filter(t=>t!=="codex"&&t!=="kimi")),pN=/\d\.(?=\d)/,hN=new Set(["claude","codex","gemini","qwen","kimi","agy"]),J_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],V_=["deepseek-flash","deepseek-pro"],K_="gpt-5.3-codex-spark",gN=15e3;qc=null;TN=5e3;Gc=null;bN=5e3;Jc=new Map});import{homedir as LN}from"node:os";import{basename as CN}from"node:path";function sy(t,e){let r=new Set;return{text:t.replace(DN,(s,i)=>{let o=i.trim(),a=ON[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function iy(t){return{workdir:t.workdir,teamfile:t.teamfile,date:MN(t.date)}}function MN(t){return t.toISOString().slice(0,10)}var ON,DN,oy=k(()=>{"use strict";ON={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=CN(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>LN(),date:t=>t.date},DN=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var id={};ae(id,{GEMINI_PROVIDER_NOTICE:()=>my,_setAgyModelsRunnerForTests:()=>WN,_setCatalogSnapshotForTests:()=>BN,_setCodexModelsRunnerForTests:()=>HN,_setLintOpenCodeConfigProbeForTests:()=>GN,_setLintSessiondirFsOpsForTests:()=>qN,_setTeamfileSeedForTests:()=>XN,buildRootTeamRegistrationRow:()=>yy,registerRootTeam:()=>Ey,runLint:()=>br,runSeed:()=>Ir,sha256Text:()=>_y,validateMemberSpec:()=>At});import{createHash as $N}from"node:crypto";import{accessSync as FN,constants as ay,existsSync as PN,readFileSync as dy,realpathSync as ed,statSync as UN,writeFileSync as ly}from"node:fs";import{dirname as Sr,resolve as uy}from"node:path";function BN(t){ps=t??void 0}function hy(t){return ty(t,ps!==void 0?{snapshot:ps}:{})}function gy(t){return ry(t,ps!==void 0?{snapshot:ps}:{})}function WN(t){nd=t??void 0}function HN(t){sd=t??void 0}function XN(t){fy=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(bt(),sc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function qN(t){vr=t===null?td:{...td,...t}}function GN(t){py=t??Fn}async function JN(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 py({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 VN(t,e){let r=Sr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=uy(o);if(n.has(a))continue;let l=KN(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 KN(t){try{if(vr.existsSync(t)){if(!vr.statSync(t).isDirectory())return"ENOTDIR";vr.accessSync(t,ay.W_OK);return}let e=zN(t);if(e===void 0)return;if(!vr.statSync(e).isDirectory())return"ENOTDIR";vr.accessSync(e,ay.W_OK);return}catch(e){return QN(e)??"permission check failed"}}function YN(t){let e=uy(t);try{return ed(e)}catch{return e}}function zN(t){let e=t;for(;;){try{if(vr.existsSync(e))return e}catch{return}let r=Sr(e);if(r===e)return;e=r}}function QN(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 br(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(jN),0;let r=ie(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2370
2370
|
`),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
|
|
2371
|
-
`),2;let n=r.positionals[0],s;try{s=await C(e,d=>pe(n,d))}catch(d){return dn(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=ke(s)}catch(d){return dn(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let o=
|
|
2372
|
-
`);let a=
|
|
2373
|
-
`);for(let d of i.members)rd([d],e),d.session!==void 0&&d.session.length<
|
|
2371
|
+
`),2;let n=r.positionals[0],s;try{s=await C(e,d=>pe(n,d))}catch(d){return dn(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let i;try{i=ke(s)}catch(d){return dn(e,`${n}: ${d instanceof Error?d.message:String(d)}`)}let o=ea(i,Sr(s));e.stderr.write(`notice: checking teamfile and models ...
|
|
2372
|
+
`);let a=zc(i.members,{agyModelsRunner:nd,codexModelsRunner:sd});a.push(...await hy(i.members)),o.push(...await gy(i.members));let l=dy(s,"utf8"),c=sy(l,iy({workdir:Sr(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(...Oa(i.members,Sr(s))),a.push(...VN(i.members,s)),a.push(...await JN(i.members,Sr(s),e.env));for(let d of o)e.stderr.write(`error: ${d.field}: ${d.message}
|
|
2373
|
+
`);for(let d of i.members)rd([d],e),d.session!==void 0&&d.session.length<fs&&a.push(`${d.alias}: sessionid is shorter than ${fs} chars; run lmctl seed to refresh it`);for(let d of a)e.stderr.write(`warning: ${d}
|
|
2374
2374
|
`);return e.stderr.write(`notice: ${o.length} error${o.length===1?"":"s"}, ${a.length} warning${a.length===1?"":"s"}
|
|
2375
2375
|
`),o.length>0?1:(e.stdout.write(`ok
|
|
2376
|
-
`),0)}async function
|
|
2377
|
-
`),l=
|
|
2378
|
-
`);return 1}try{
|
|
2379
|
-
`);for(let
|
|
2380
|
-
`);for(let
|
|
2381
|
-
`);for(let
|
|
2382
|
-
`);let d=
|
|
2383
|
-
`)
|
|
2384
|
-
`);
|
|
2385
|
-
`);let p=
|
|
2386
|
-
`)
|
|
2387
|
-
`),
|
|
2388
|
-
`)
|
|
2389
|
-
`)
|
|
2390
|
-
`),1
|
|
2391
|
-
`)
|
|
2392
|
-
`),
|
|
2393
|
-
`)}
|
|
2394
|
-
`)
|
|
2395
|
-
`)
|
|
2396
|
-
`)
|
|
2397
|
-
`)
|
|
2376
|
+
`),0)}async function Ir(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(Qc),0;let r=ie(t,[],[]);return r.error!==void 0?cy(e,r.error,Qc):r.positionals.length!==1?cy(e,"expected <teamfile.lmctl>",Qc):ZN(r.positionals[0],e)}async function ZN(t,e){let r;try{r=await C(e,g=>pe(t,g))}catch(g){return dn(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let n;try{n=ed(r)}catch(g){return dn(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let s=Sr(r),i;try{i=ke(r)}catch(g){return dn(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let a=dy(r,"utf8").split(`
|
|
2377
|
+
`),l=rL(a),c=ea(i,s);if(c.length>0){rd(i.members,e);for(let g of c)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2378
|
+
`);return 1}try{Or(e,i,r)}catch{}rd(i.members,e),e.stderr.write(`notice: checking teamfile and models ...
|
|
2379
|
+
`);for(let g of zc(i.members,{agyModelsRunner:nd,codexModelsRunner:sd}))e.stderr.write(`warning: ${g}
|
|
2380
|
+
`);for(let g of await hy(i.members))e.stderr.write(`warning: ${g}
|
|
2381
|
+
`);for(let g of Oa(i.members,s))e.stderr.write(`warning: ${g}
|
|
2382
|
+
`);let d=await gy(i.members);if(d.length>0){for(let g of d)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2383
|
+
`);return 1}let u=0,f=i.members.filter(g=>g.teamfile!==void 0?!1:g.session===void 0||g.session.length<fs);for(let g of f)if(!Ty(g.provider))return e.stderr.write(`error: ${g.alias}: invalid provider "${g.provider}"
|
|
2384
|
+
`),1;for(let g of i.members){if(g.teamfile!==void 0)continue;if(g.session!==void 0&&g.session.length>=fs){e.stderr.write(`warning: ${g.alias}: existing sessionid preserved; skipping
|
|
2385
|
+
`);continue}let p=g.sessiondir??s;e.stderr.write(`${g.alias}: launching ${g.provider} seed session; this can take several seconds
|
|
2386
|
+
`);let y=Ze(e,S=>`${g.alias}: still launching (${S}s elapsed)
|
|
2387
|
+
`),E;try{E=await fy({provider:g.provider,cwd:p,...g.model!==void 0?{model:g.model}:{},...g.effort!==void 0?{effort:g.effort}:{},...g.alias.toLowerCase()==="lead"?{prompt:eL(r,a.join(`
|
|
2388
|
+
`),i.members)}:{}})}finally{y.stop()}for(let S of E.warnings??[])e.stderr.write(`warning: ${g.alias}: ${S}
|
|
2389
|
+
`);if(E.error!==void 0||E.sessionId===void 0||E.sessionId.length<fs){let S=`provider did not report a sessionid; no new session was found for ${p} (possible provider workspace/cwd mismatch)`;return e.stderr.write(`error: ${g.alias}: seed failed${E.error!==void 0?`: ${E.error}`:`; ${S}`}
|
|
2390
|
+
`),1}let v=l.get(g.alias.toLowerCase());if(v===void 0)return e.stderr.write(`error: ${g.alias}: could not find matching _MEMBER_ line to update
|
|
2391
|
+
`),1;let b=YN(p),T=Zc(a[v],"sessionid",E.sessionId);if(T=Zc(T,"sessiondir",b),g.model===void 0){let S;try{S=(await Ie(E.sessionId,g.provider))?.model}catch{S=void 0}S!==void 0&&S.length>0?T=Zc(T,"model",S):e.stderr.write(`warning: ${g.alias}: seed could not determine which model ${g.provider} selected; model= left unset
|
|
2392
|
+
`)}a[v]=T,u+=1,ly(r,a.join(`
|
|
2393
|
+
`),"utf8"),e.stdout.write(`${g.alias}: seeded ${E.sessionId} provider=${g.provider} sessiondir=${b}
|
|
2394
|
+
`)}let m=a.join(`
|
|
2395
|
+
`),h=oL(m,ed(r));h!==m&&ly(r,h,"utf8"),u===0&&e.stdout.write(`no members needed seeding
|
|
2396
|
+
`);let _=new Date().toISOString();try{await C(e,g=>{Ey(g,{teamfilePath:n,name:i.name,rawText:h,now:_})})}catch(g){return dn(e,g instanceof Error?g.message:String(g))}return 0}function _y(t){return $N("sha256").update(t).digest("hex")}function yy(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:_y(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function Ey(t,e){let r=Cs(e.rawText,e.teamfilePath);na(t,e.teamfilePath,r);let n=yy(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(n),n}function eL(t,e,r){let n=r.filter(a=>a.alias.toLowerCase()!=="lead").map(a=>{let l=a.teamfile!==void 0?`teamfile=${a.teamfile}`:`provider=${a.provider}`;return`- ${a.alias}: ${l}`}),s=n.length>0?n.join(`
|
|
2397
|
+
`):"- (no non-Lead members)",i=r.find(a=>a.alias.toLowerCase()==="lead")?.provider??"",o=tL(i,t);return["lmctl seed initial connection only. Create or pin this provider session, then stop.","Do not inspect files, run commands, infer a task, delegate, edit, or begin work.","",`Teamfile path: ${t}`,"You are alias Lead for this AI-managed .lmctl team.","","Delegating work:",`- Blocking command shape: lmctl prompt "${t}" <alias> "your task here"`,"- SAFE INPUT \u2014 use for ANYTHING non-trivial. A prompt typed into the command line is expanded by YOUR shell first,"," so backticks, $(...), $VAR and quotes are executed or stripped out of the prompt before lmctl sees it."," If the text contains backticks, quotes, $, newlines, or ANY relayed/pasted/quoted content, do NOT put it in the command.",` Write it to a file with your file-writing tool (NOT echo/heredoc \u2014 those are shell too), then: lmctl prompt "${t}" <alias> --prompt-file <path>`,"- lmctl is foreground/background agnostic. Use your provider or host runtime for async command handling when it supports that.","- For delegation, run the lmctl prompt command above. If your runtime has a tracked background mode, it may wrap that same blocking command, but check the result with --json or lmctl status.","- Busy receiver ENQUEUES. lmctl prompt exits 0 for BOTH delivered and enqueued, so exit code alone CANNOT tell you an answer arrived.",'- lmctl prompt ... --json is machine-readable: status="ok" is a delivered answer (replyText); status="enqueued" (plus path="enqueued") means it was queued, and carries id/sender/receiver.',"- lmctl status shows your identity, members with busy/idle, pending outbound lanes, and why a receiver is busy. Run it when you are unsure whether a delegation landed.","- For arbitrary shell work, use your provider/runtime shell tools directly; lmctl does not execute shell commands.",o,"","Delegation is an ACTION, not a plan: to hand a member a task, run the lmctl prompt command above. lmctl exposes no delegation tool you should use \u2014 delegate with lmctl prompt.","","Team members:",s,"","If a member feels sluggish or starts drifting (degraded or off-track output):",` 1. Check ONE member's session: lmctl status "${t}" <alias> (size/state \u2014 informational).`," 2. Make sure important state is captured in durable-memory/ \u2014 update it if not.",` 3. Replace its session: edit the teamfile to delete that member's sessionid= field, then run lmctl seed "${t}" (mints a fresh session: drops conversation history, re-reads durable-memory/). To replace the Lead's own session, do it from a different member session or a plain operator shell.`,` Optional: lmctl tail "${t}" <alias> to inspect its recent prompts and answers while troubleshooting.`,"(These status/recovery steps are shell commands and file edits. For delegation, use lmctl prompt.)","","Full teamfile document at seed time:","```lmctl",e.trimEnd(),"```","","Remember this teamfile path. Do not ask the operator for it when asked to ping or delegate to members.","Reply exactly: ACK: teamfile context recorded."].join(`
|
|
2398
|
+
`)}function tL(t,e){let r=`lmctl prompt "${e}" <alias> "your task here"`;switch(t.toLowerCase()){case"claude":return`- Claude tip: run the blocking command (${r}) as background Bash (run_in_background: true); the runtime re-invokes you with the reply when it completes.`;case"copilot":return`- Copilot tip: run the blocking command (${r}) via bash async mode (mode:"async"); the runtime notifies you with output when it completes.`;case"agy":return`- Antigravity tip: run the blocking command (${r}) via run_command with WaitMsBeforeAsync: 0 (Background Tasks); agy wakes you with the output when it completes.`;case"qwen":return`- Qwen tip: run the blocking command (${r}) via the monitor tool; it notifies you on completion.`;case"codex":return"- Codex note: run lmctl prompt as the blocking delegation primitive; use Codex-native tool/background behavior when available.";case"gemini":return"- Gemini note: run lmctl prompt as the blocking delegation primitive; use Gemini-native tool/background behavior when available.";case"opencode":return"- OpenCode note: use the provider-native background/task surface when available; otherwise run one blocking lmctl prompt turn and wait.";case"kimi":return"- Kimi note: use Kimi native background tools when available; otherwise run one blocking lmctl prompt turn and wait.";default:return"- If your provider has native background completion, use it around the blocking command; otherwise run one blocking lmctl prompt turn at a time."}}function rL(t){let e=new Map;for(let r=0;r<t.length;r+=1){let n=t[r];if(!/^\s*_MEMBER_\s+\S/.test(n))continue;let s=sL(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function nL(t){return/^[A-Za-z][A-Za-z0-9_-]*$/u.test(t)}function sL(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function Zc(t,e,r){let n=`${e}=${iL(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(i,o)=>`${o}${n}`):`${t.trimEnd()} ${n}`}function iL(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function oL(t,e){let r=`#teamfile: ${e}`,n=t.indexOf(`
|
|
2398
2399
|
`),s=n>=0?t.slice(0,n):t,i=n>=0?t.slice(n+1):"";return s===r?t:s.startsWith("#teamfile:")?i.length>0?`${r}
|
|
2399
2400
|
${i}`:`${r}
|
|
2400
2401
|
`:t.length>0?`${r}
|
|
2401
2402
|
${t}`:`${r}
|
|
2402
|
-
`}function At(t){if(!
|
|
2403
|
-
`),1}function
|
|
2403
|
+
`}function At(t){if(!nL(t.alias))return`invalid alias "${t.alias}"`;if(!Ty(t.provider))return`invalid provider "${t.provider}"`}function Ty(t){return t==="claude"||t==="codex"||t==="gemini"||t==="copilot"||t==="opencode"||t==="lmplayer"||t==="qwen"||t==="agy"||t==="kimi"||t==="dsh"||t==="hermes"||t==="pi"||t==="ClaudeMock"}function dn(t,e){return t.stderr.write(`error: ${e}
|
|
2404
|
+
`),1}function cy(t,e,r){return t.stderr.write(`error: ${e}
|
|
2404
2405
|
${r}`),2}function rd(t,e){for(let r of t)r.teamfile!==void 0&&e.stderr.write(`warning: member "${r.alias}" uses deprecated member-level teamfile=; cross-team calls now work at runtime without _CONNECT_
|
|
2405
|
-
`),r.provider==="gemini"&&e.stderr.write(`${
|
|
2406
|
-
`)}var
|
|
2406
|
+
`),r.provider==="gemini"&&e.stderr.write(`${my.replace("%s",r.alias)}
|
|
2407
|
+
`)}var fs,jN,Qc,my,td,fy,vr,py,nd,sd,ps,nr=k(()=>{"use strict";Et();ny();Da();Xa();Qt();he();Tt();oy();Ps();fs=5,jN=`usage: lmctl lint <teamfile.lmctl>
|
|
2407
2408
|
|
|
2408
2409
|
Validate an lmctl teamfile and warn about stale or placeholder session ids.
|
|
2409
2410
|
For opencode members with model=, lint also asks the local ACP provider to
|
|
2410
2411
|
validate model= and effort= without sending a prompt.
|
|
2411
2412
|
|
|
2412
|
-
lint has
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2413
|
+
lint has three outcomes (operator ruling, 2026-09-29): ok, warning, or error.
|
|
2414
|
+
A warning means a model is not in the lmprice catalog at all -- genuinely
|
|
2415
|
+
unknown, not necessarily wrong (it may just be too new for lmprice to have
|
|
2416
|
+
published yet, or a typo); warnings are reported, never block, and there is
|
|
2417
|
+
no flag to promote one to a failing exit code (the old --strict has been
|
|
2418
|
+
removed entirely -- "no need to give users the choice with no obvious
|
|
2419
|
+
value"). An error means the declared model IS a real, recognized model,
|
|
2420
|
+
just not one that provider offers (it resolves cleanly under a DIFFERENT
|
|
2421
|
+
provider) -- a confirmed "this provider cannot run it," not a guess, so
|
|
2422
|
+
unlike a warning it DOES fail the exit code, the same as a malformed
|
|
2423
|
+
teamfile or an unparseable member line.
|
|
2419
2424
|
|
|
2420
2425
|
lint prints a "checking teamfile and models ..." note on stderr while the
|
|
2421
2426
|
checks run -- a pause there is a stale-lmprice-cache network fetch, not a
|
|
@@ -2425,7 +2430,7 @@ lint is a cheap pre-check that catches names which cannot possibly work --
|
|
|
2425
2430
|
it is NOT a guarantee that \`lmctl seed\` will succeed (operator, 2026-09-29).
|
|
2426
2431
|
A clean "ok" means nothing obviously wrong was found, not a working
|
|
2427
2432
|
configuration; only seed (or an actual dispatch) proves that.
|
|
2428
|
-
`,
|
|
2433
|
+
`,Qc=`usage: lmctl seed <teamfile.lmctl>
|
|
2429
2434
|
|
|
2430
2435
|
Seed missing or placeholder session ids in an lmctl teamfile by calling each
|
|
2431
2436
|
member's configured native provider. Also writes each seeded member's
|
|
@@ -2449,7 +2454,12 @@ While a member is being seeded, seed narrates its steps on stderr (checking,
|
|
|
2449
2454
|
then launching each provider seed session, with a "still launching"
|
|
2450
2455
|
heartbeat every 5s) -- a pause there means the provider CLI is still
|
|
2451
2456
|
running, not a stuck command.
|
|
2452
|
-
|
|
2457
|
+
|
|
2458
|
+
seed refuses to run when a declared model= is a confirmed wrong-provider
|
|
2459
|
+
model (a real model recognized under a DIFFERENT provider, per lint's
|
|
2460
|
+
error tier) -- rather than dispatch a real provider session that cannot
|
|
2461
|
+
possibly work, seed reports it as an error and seeds nothing.
|
|
2462
|
+
`,my='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',td={existsSync:PN,statSync:UN,accessSync:FN},fy=async t=>{let{seed:e}=await Promise.resolve().then(()=>(bt(),sc)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},vr=td,py=Fn});import*as wy from"node:child_process";function aL(t,e){try{let r=e(t,["--version"],{encoding:"utf-8",timeout:5e3});return r.status===0?{found:!0,version:(r.stdout??"").toString().trim().split(/\r?\n/,1)[0]?.trim()||void 0}:r.status===null?{found:!1,failureMode:"not installed"}:{found:!1,failureMode:"runs but failed"}}catch{return{found:!1,failureMode:"not installed"}}}function vy(t,e={}){let r=e.spawnSync===void 0&&process.env[lL]==="1",n=e.spawnSync??wy.spawnSync,s=new Set,i=[];for(let o of t){if(s.has(o))continue;s.add(o);let a=mo[o];if(!a){i.push({provider:o,binary:"<unknown>",found:!1,failureMode:"not installed"});continue}if(r){i.push({provider:o,binary:a,found:!0,version:"(skipped)"});continue}let l=aL(a,n);l.found?i.push({provider:o,binary:a,found:!0,version:l.version}):i.push({provider:o,binary:a,found:!1,failureMode:l.failureMode})}return i}var mo,lL,Sy=k(()=>{"use strict";mo={claude:"claude",codex:"codex",copilot:"copilot",gemini:"gemini",opencode:"opencode",lmplayer:"lmplayer",qwen:"qwen",agy:"agy",kimi:"kimi",dsh:"dsh",hermes:"hermes",pi:"pi"};lL="LMCTL_SKIP_BINARY_CHECK"});function Iy(t){return ad[t.trim().toLowerCase()]}function xy(t){let e=t.split(":");if(e.length<2)return{error:`invalid member spec "${t}" \u2014 expected Alias:provider[:model]`};let[r,n]=e,s=e.length>2?e.slice(2).join(":"):void 0;if(r===""||n==="")return{error:`invalid member spec "${t}" \u2014 expected Alias:provider[:model]`};let i=At({alias:r,provider:n});return i!==void 0?{error:i}:s!==void 0&&s===""?{error:`invalid member spec "${t}" \u2014 empty model`}:{spec:{alias:r,provider:n,...s!==void 0?{model:s}:{}}}}function by(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function cL(t){return[`_MEMBER_ provider=${t.provider} alias=${by(t.alias)}`,...t.model!==void 0?[`model=${by(t.model)}`]:[]].join(" ")}function po(t){let{teamName:e,members:r}=t,n=r.map(cL).join(`
|
|
2453
2463
|
`);return`# ${e}
|
|
2454
2464
|
#
|
|
2455
2465
|
# This is a starting point, not a finished teamfile -- edit alias/provider/model
|
|
@@ -2458,26 +2468,26 @@ running, not a stuck command.
|
|
|
2458
2468
|
# Format, and what lint/seed each do: https://lmctl.com/lmctl/docs/manuals/teamfile-format
|
|
2459
2469
|
|
|
2460
2470
|
${n}
|
|
2461
|
-
`}function
|
|
2462
|
-
`).map(e=>
|
|
2463
|
-
`)}function od(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function
|
|
2464
|
-
`)){if(!
|
|
2471
|
+
`}function Ay(t){return t.split(`
|
|
2472
|
+
`).map(e=>ky.test(e)?e.replace(/\s+sessionid=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessionid=(?:"[^"]*"|\S+)\s+/g,"$1 ").replace(/\s+sessiondir=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessiondir=(?:"[^"]*"|\S+)\s+/g,"$1 "):e).join(`
|
|
2473
|
+
`)}function od(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function ho(t){let e=[];for(let r of t.split(`
|
|
2474
|
+
`)){if(!ky.test(r))continue;let n=od(r,"alias"),s=od(r,"provider");if(n===void 0||s===void 0)continue;let i=od(r,"model");e.push({alias:n,provider:s,...i!==void 0&&i!==""?{model:i}:{}})}return e}var ad,fo,ky,ld=k(()=>{"use strict";nr();ad={1:["Lead"],lead:["Lead"],2:["Lead","Reviewer"],"lead-reviewer":["Lead","Reviewer"],3:["Lead","Coder","Reviewer"],"lead-coder-reviewer":["Lead","Coder","Reviewer"]},fo="1|2|3|lead|lead-reviewer|lead-coder-reviewer";ky=/^\s*_MEMBER_\s+\S/});import{mkdtempSync as dL,readFileSync as uL,rmSync as mL,writeFileSync as fL}from"node:fs";import{tmpdir as pL}from"node:os";import{spawnSync as hL}from"node:child_process";import{basename as go,extname as cd,join as dd,resolve as ud}from"node:path";import*as Ry from"node:readline";function gL(t){return e=>{let r=t.EDITOR??t.VISUAL??"vi";hL(r,[e],{stdio:"inherit"})}}async function Ny(t){let{io:e,cwd:r,env:n=process.env}=t,s=t.initial??{},i=Ry.createInterface({input:t.input,output:e.stdout,terminal:!1}),o=[],a=[];i.on("line",u=>{let f=a.shift();f!==void 0?f(u):o.push(u)});let l=!1;i.on("close",()=>{for(l=!0;a.length>0;)a.shift()("")});let c=async u=>{e.stdout.write(u);let f=o.shift();return f!==void 0?f.trim():l?"":new Promise(m=>a.push(h=>m(h.trim())))},d=()=>i.close();try{let u,f;if(s.output!==void 0)u=ud(r,s.output),f=go(u,cd(u));else{let p=ud(r,t.directory??"."),y=await c(`Directory [${p}]: `),E=y===""?p:ud(r,y),v=`${go(E)}.lmctl`,b=await c(`Teamfile name [${v}]: `),T=b===""?v:b,S=cd(T)?T:`${T}.lmctl`;u=dd(E,S),f=go(S,cd(S))}let m;if(s.members!==void 0&&s.members.length>0)m=s.members.map(p=>({...p,model:p.model??s.model}));else{let y=(t.checkProviders??(()=>vy(Object.keys(mo))))(),E=y.filter(x=>x.found).map(x=>x.provider),v=y.filter(x=>!x.found).map(x=>x.provider);e.stdout.write(`detected providers: ${E.length>0?E.join(", "):"(none)"}
|
|
2465
2475
|
`),v.length>0&&e.stdout.write(`not found: ${v.join(", ")}
|
|
2466
|
-
`);let
|
|
2467
|
-
`),d(),null;continue}if(At({alias:"Probe",provider:I})!==void 0){e.stdout.write(`unknown provider "${I}" (known: ${Object.keys(
|
|
2468
|
-
`),
|
|
2469
|
-
`);let x=(await c(`Pattern [${
|
|
2476
|
+
`);let b=s.provider??(E.length===1?E[0]:void 0),T=b;for(;T===void 0;){let x=await c(`Default provider${b!==void 0?` [${b}]`:""}: `),I=x===""?b:x;if(I===void 0){if(l)return e.stderr.write(`error: stdin closed (EOF) at the provider prompt and no default is available
|
|
2477
|
+
`),d(),null;continue}if(At({alias:"Probe",provider:I})!==void 0){e.stdout.write(`unknown provider "${I}" (known: ${Object.keys(mo).join(", ")})
|
|
2478
|
+
`),b=void 0;continue}T=I}let S=s.pattern??"3",w;for(;w===void 0;){e.stdout.write(`Patterns: 1) Lead 2) Lead+Reviewer 3) Lead+Coder+Reviewer c) custom
|
|
2479
|
+
`);let x=(await c(`Pattern [${S}]: `)).toLowerCase(),I=x===""?S:x;if(I==="c"||I==="custom"){w=[];let R=new Set;for(e.stdout.write(`Enter members; blank alias finishes. The first member must be Lead.
|
|
2470
2480
|
`);;){let N=await c(`Member ${w.length+1} alias: `);if(N===""){if(w.length===0){if(l)return e.stderr.write(`error: stdin closed (EOF) before any member alias was entered
|
|
2471
2481
|
`),d(),null;e.stdout.write(`at least one member is required
|
|
2472
|
-
`);continue}break}let U=At({alias:N,provider:
|
|
2482
|
+
`);continue}break}let U=At({alias:N,provider:T});if(U!==void 0){e.stdout.write(`${U}
|
|
2473
2483
|
`);continue}if(w.length===0&&N.toLowerCase()!=="lead"){e.stdout.write(`the first member must be Lead
|
|
2474
2484
|
`);continue}let re=N.toLowerCase();if(R.has(re)){e.stdout.write(`duplicate member alias "${N}"
|
|
2475
2485
|
`);continue}R.add(re),w.push(N)}}else w=ad[I],w===void 0&&e.stdout.write(`unknown pattern "${I}"
|
|
2476
|
-
`)}m=[];for(let x of w){let I=await c(`Provider for ${x} [${
|
|
2477
|
-
`),d(),null;let U=s.model,re=await c(`Model for ${x}${U!==void 0?` [${U}]`:" (blank to omit)"}: `),ee=re===""?U:re;m.push({alias:x,provider:R,...ee!==void 0?{model:ee}:{}})}}let
|
|
2486
|
+
`)}m=[];for(let x of w){let I=await c(`Provider for ${x} [${T}]: `),R=I===""?T:I,N=At({alias:x,provider:R});if(N!==void 0)return e.stdout.write(`error: ${N}
|
|
2487
|
+
`),d(),null;let U=s.model,re=await c(`Model for ${x}${U!==void 0?` [${U}]`:" (blank to omit)"}: `),ee=re===""?U:re;m.push({alias:x,provider:R,...ee!==void 0?{model:ee}:{}})}}let h=po({teamName:f,members:m}),_=t.editFile??gL(n),g=s.seed??!0;for(;;){e.stdout.write(`
|
|
2478
2488
|
--- ${u} ---
|
|
2479
|
-
${
|
|
2480
|
-
`);let p=(await c(`Write and seed? [${
|
|
2489
|
+
${h}---
|
|
2490
|
+
`);let p=(await c(`Write and seed? [${g?"Y/n":"y/N"}/e(dit)]: `)).toLowerCase();if(p==="e"||p==="edit"){let E=dL(dd(pL(),"lmctl-plan-edit-"));try{let v=dd(E,go(u));fL(v,h,"utf8"),_(v),h=uL(v,"utf8")}finally{mL(E,{recursive:!0,force:!0})}continue}if(p==="q"||p==="quit"||p==="abort")return d(),null;let y=p===""?g:p!=="n"&&p!=="no";return d(),{destPath:u,text:h,seed:y}}}catch(u){throw d(),u}}function Ly(t){return ho(t)}var Cy=k(()=>{"use strict";Sy();nr();ld()});import{existsSync as _L,mkdirSync as yL,readdirSync as EL,readFileSync as TL,writeFileSync as wL}from"node:fs";import{homedir as Dy}from"node:os";import{dirname as vL,join as xr}from"node:path";function yo(){return xr(Dy(),".lmctl","init.toml")}function md(t){let e=Oy[t]??Oy.claude;return{provider:t,model1:e[0],model2:e[1],model3:e[2]}}function My(t){let e=t.filter((o,a)=>t.indexOf(o)===a),r=e.length>0?e:["claude"],[n,s=n,i=n]=r;return{provider1:md(n),provider2:md(s),provider3:md(i)}}function hs(t){try{return _L(t)&&EL(t).length>0}catch{return!1}}function $y(){let t=Dy(),e=process.env.KIMI_CODE_HOME??xr(t,".kimi-code"),r=[];return hs(xr(t,".claude","projects"))&&r.push("claude"),(hs(xr(t,".codex","sessions"))||hs(xr(t,".code","sessions")))&&r.push("codex"),hs(xr(t,".gemini","antigravity-cli","conversations"))&&r.push("agy"),hs(xr(e,"sessions"))&&r.push("kimi"),r}function _o(t){return`"${t.replace(/"/g,'\\"')}"`}function Eo(t){let e=(r,n)=>[`[${r}]`,`provider = ${_o(n.provider)}`,`model1 = ${_o(n.model1)}`,`model2 = ${_o(n.model2)}`,`model3 = ${_o(n.model3)}`].join(`
|
|
2481
2491
|
`);return`# Generated by \`lmctl init\`. This is a STARTING POINT, not a fixed answer --
|
|
2482
2492
|
# edit any value below to change what \`lmctl plan\`/\`lmctl quickrun\` resolve to.
|
|
2483
2493
|
#
|
|
@@ -2495,37 +2505,37 @@ ${e("Provider1",t.provider1)}
|
|
|
2495
2505
|
${e("Provider2",t.provider2)}
|
|
2496
2506
|
|
|
2497
2507
|
${e("Provider3",t.provider3)}
|
|
2498
|
-
`}function
|
|
2499
|
-
`)){let l=a.trim();if(l===""||l.startsWith("#"))continue;if(l.startsWith("[")&&l.endsWith("]")){r=l.slice(1,-1).trim(),e[r]??={};continue}if(r===null)continue;let c=l.indexOf("=");if(c===-1)continue;let d=l.slice(0,c).trim(),u=
|
|
2508
|
+
`}function SL(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e}function bL(t){let e={},r=null;for(let a of t.split(`
|
|
2509
|
+
`)){let l=a.trim();if(l===""||l.startsWith("#"))continue;if(l.startsWith("[")&&l.endsWith("]")){r=l.slice(1,-1).trim(),e[r]??={};continue}if(r===null)continue;let c=l.indexOf("=");if(c===-1)continue;let d=l.slice(0,c).trim(),u=SL(l.slice(c+1));(d==="provider"||d==="model1"||d==="model2"||d==="model3")&&(e[r][d]=u)}let n=a=>{let l=e[a];return!l||!l.provider||!l.model1||!l.model2||!l.model3?null:{provider:l.provider,model1:l.model1,model2:l.model2,model3:l.model3}},s=n("Provider1"),i=n("Provider2"),o=n("Provider3");return!s||!i||!o?null:{provider1:s,provider2:i,provider3:o}}function un(t){let e=t??yo(),r;try{r=TL(e,"utf-8")}catch{return null}return bL(r)}function Fy(t,e){let r=e??yo();yL(vL(r),{recursive:!0}),wL(r,Eo(t),"utf-8")}function Py(t,e){let r={Provider1:e.provider1.provider,Provider2:e.provider2.provider,Provider3:e.provider3.provider,Model1:e.provider1.model1,Model2:e.provider2.model1,Model3:e.provider3.model1};return t.replace(/\$\{(Provider[123]|Model[123])\}/g,(n,s)=>r[s]??n)}var Oy,To=k(()=>{"use strict";Oy={claude:["claude-opus-5","claude-sonnet-5","claude-sonnet-5"],codex:["gpt-5.6-sol","gpt-5.5","gpt-6-astra"],agy:["Gemini 3.8 Flash (High)","Gemini 3.8 Flash (Medium)","Gemini 3.1 Pro (High)"],kimi:["kimi-code/k3","kimi-code/k3","kimi-code/k3"]}});var Gy={};ae(Gy,{readPlanSource:()=>mn,runPlan:()=>CL});import{existsSync as By,mkdirSync as IL,readdirSync as xL,readFileSync as Uy,statSync as kL,writeFileSync as AL}from"node:fs";import{basename as Wy,dirname as RL,extname as NL,join as Hy,resolve as pd}from"node:path";async function CL(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(LL),0;let n=[],s=[];for(let I=0;I<t.length;I+=1){let R=t[I];if(R==="--member"){let N=t[I+1];if(N===void 0||N.startsWith("--"))return e.stderr.write(`error: missing value for --member
|
|
2500
2510
|
`),2;n.push(N),I+=1;continue}s.push(R)}let i=ie(s,["--pattern","--provider","--model","--from","--output"],["--json","--stdout","--force","--seed","--no-seed","--wizard","--non-interactive","--no-interactive"]);if(i.error!==void 0)return e.stderr.write(`error: ${i.error}
|
|
2501
2511
|
`),e.stderr.write(`usage: lmctl plan [directory] [options]
|
|
2502
2512
|
`),2;if(i.positionals.length>1)return e.stderr.write(`usage: lmctl plan [directory] [options]
|
|
2503
|
-
`),2;let o=e.cwd??process.cwd(),a=i.positionals[0],l=B(i,"--pattern"),c=B(i,"--provider"),d=B(i,"--model"),u=B(i,"--from"),f=B(i,"--output"),m=H(i,"--json"),
|
|
2504
|
-
`),2;if(g
|
|
2505
|
-
`),2;if(
|
|
2506
|
-
`),2;if(y&&
|
|
2513
|
+
`),2;let o=e.cwd??process.cwd(),a=i.positionals[0],l=B(i,"--pattern"),c=B(i,"--provider"),d=B(i,"--model"),u=B(i,"--from"),f=B(i,"--output"),m=H(i,"--json"),h=H(i,"--stdout"),_=H(i,"--force"),g=H(i,"--seed"),p=H(i,"--no-seed"),y=H(i,"--wizard"),E=H(i,"--non-interactive")||H(i,"--no-interactive");if(m&&h)return e.stderr.write(`error: --json and --stdout are mutually exclusive
|
|
2514
|
+
`),2;if(h&&g)return e.stderr.write(`error: --seed requires a written teamfile; it cannot be combined with --stdout
|
|
2515
|
+
`),2;if(g&&p)return e.stderr.write(`error: --seed and --no-seed are mutually exclusive
|
|
2516
|
+
`),2;if(y&&h)return e.stderr.write(`error: --wizard cannot be combined with --stdout
|
|
2507
2517
|
`),2;if(y&&m)return e.stderr.write(`error: --wizard cannot be combined with --json
|
|
2508
|
-
`),2;let v=l!==void 0||c!==void 0||d!==void 0||u!==void 0||n.length>0,
|
|
2518
|
+
`),2;let v=l!==void 0||c!==void 0||d!==void 0||u!==void 0||n.length>0,b=e.stdin??process.stdin,T=r.stdinIsTTY??(e.stdin===void 0?process.stdin.isTTY===!0:b.isTTY===!0),S=y||!E&&!v&&!h&&!m&&T,w;if(S){if(u!==void 0)return e.stderr.write(`error: --from cannot be combined with --wizard
|
|
2509
2519
|
`),2;if(l!==void 0&&n.length>0)return e.stderr.write(`error: --pattern and --member are mutually exclusive
|
|
2510
|
-
`),2;let I=
|
|
2511
|
-
`)});if(I.error!==void 0)return 1;w=await
|
|
2512
|
-
`),2;let I=await
|
|
2520
|
+
`),2;let I=qy(n,d,R=>{e.stderr.write(`error: ${R}
|
|
2521
|
+
`)});if(I.error!==void 0)return 1;w=await OL(e,b,o,a,{provider:c,model:d,pattern:l,members:I.members,seed:!p,output:f},r)}else{if(!v)return e.stderr.write(`error: ${Xy}
|
|
2522
|
+
`),2;let I=await DL({pattern:l,provider:c,model:d,from:u,memberRaws:n,output:f,directory:a,cwd:o,seedFlag:g,deps:r},R=>{e.stderr.write(`error: ${R}
|
|
2513
2523
|
`)});if(typeof I=="number")return I;w=I}if(w===null)return e.stderr.write(`aborted
|
|
2514
|
-
`),1;if(
|
|
2515
|
-
`),1;
|
|
2516
|
-
`),r.asJson&&te(n,fd(e,!1,!1,t.members)),1;let a=!1;if(r.seed){let l=await
|
|
2524
|
+
`),1;if(h)return e.stdout.write(w.text),0;let x=w.destPath;return $L(w,x,{asJson:m,force:_,seed:w.seed},e)}async function OL(t,e,r,n,s,i){let o=await Ny({io:t,input:e,cwd:r,...n!==void 0?{directory:n}:{},initial:s,...i.checkProviders!==void 0?{checkProviders:i.checkProviders}:{},...i.editFile!==void 0?{editFile:i.editFile}:{},...t.env!==void 0?{env:t.env}:{}});return o===null?null:{text:o.text,destPath:o.destPath,members:Ly(o.text),seed:o.seed}}async function DL(t,e){let{pattern:r,provider:n,model:s,from:i,memberRaws:o,output:a,directory:l,cwd:c,seedFlag:d,deps:u}=t,f=[r!==void 0,o.length>0,i!==void 0].filter(Boolean).length;if(f===0)return e(Xy),2;if(f>1)return e("--pattern, --member and --from are mutually exclusive"),2;if(i!==void 0&&(n!==void 0||s!==void 0))return e("--from cannot be combined with --provider or --model (the source teamfile defines the roster)"),2;let m=ML(a,l,c);if(i!==void 0){let g;try{g=await mn(i,u.fetchFn??globalThis.fetch,c)}catch(E){return e(E instanceof Error?E.message:String(E)),1}let p=Ay(g),y=ho(p);return y.length===0?(e(`--from source "${i}" has no parseable _MEMBER_ lines`),1):{text:p,destPath:m,members:y,seed:d}}let h;if(o.length>0){let g=qy(o,s,e);if(g.error!==void 0)return 1;h=g.members}else{let g=Iy(r);if(g===void 0)return e(`invalid pattern "${r}" (expected ${fo})`),2;if(n!==void 0){let p=At({alias:"Lead",provider:n});if(p!==void 0)return e(p),1;h=g.map(y=>({alias:y,provider:n,...s!==void 0?{model:s}:{}}))}else{let p=un(u.initConfigPath);if(p===null)return e("missing --provider, and no ~/.lmctl/init.toml found. Run `lmctl init` first, or pass --provider explicitly."),2;let y=[p.provider1,p.provider2,p.provider3];h=g.map((E,v)=>{let b=y[v%y.length];return{alias:E,provider:b.provider,model:s??b.model1}})}}let _=Wy(m,NL(m));return{text:po({teamName:_,members:h}),destPath:m,members:h,seed:d}}function qy(t,e,r){if(t.length===0)return{members:void 0};let n=[],s=new Set;for(let i of t){let o=xy(i);if(o.error!==void 0)return r(o.error),{error:o.error};let a=o.spec,l=a.alias.toLowerCase();if(s.has(l))return r(`duplicate member alias "${a.alias}"`),{error:l};s.add(l),n.push({...a,model:a.model??e})}return n[0].alias.toLowerCase()!=="lead"?(r(`the first member must be Lead (got "${n[0].alias}")`),{error:"lead-not-first"}):{members:n}}function ML(t,e,r){if(t!==void 0)return pd(r,t);let n=pd(r,e??".");return Hy(n,`${Wy(n)}.lmctl`)}async function $L(t,e,r,n){if(By(e)&&!r.force)return n.stderr.write(`error: ${e} already exists (use --force to overwrite)
|
|
2525
|
+
`),1;IL(RL(e),{recursive:!0}),AL(e,t.text,"utf8");let s=r.asJson?{...n,stdout:{write:()=>{}}}:n;if(!(await br([e],s)===0))return r.seed&&n.stderr.write(`error: refusing to seed \u2014 lint failed
|
|
2526
|
+
`),r.asJson&&te(n,fd(e,!1,!1,t.members)),1;let a=!1;if(r.seed){let l=await Ir([e],s);return a=l===0,r.asJson&&te(n,fd(e,!0,a,t.members)),l}return r.asJson?(te(n,fd(e,!0,!1,t.members)),0):(n.stdout.write(`Created ${e}
|
|
2517
2527
|
`),n.stdout.write(`This is a starting point, not a finished teamfile -- edit it freely.
|
|
2518
2528
|
`),n.stdout.write(`Only _MEMBER_ lines are parsed; everything else is free-form.
|
|
2519
2529
|
`),n.stdout.write(`Format, and what lint/seed each do: https://lmctl.com/lmctl/docs/manuals/teamfile-format
|
|
2520
2530
|
`),n.stdout.write(`After editing, run: lmctl lint ${e}
|
|
2521
2531
|
`),n.stdout.write(`Then run: lmctl seed ${e}
|
|
2522
|
-
`),0)}function fd(t,e,r,n){return{path:t,linted:e,seeded:r,members:n.map(s=>({alias:s.alias,provider:s.provider,...s.model!==void 0?{model:s.model}:{}}))}}async function mn(t,e,r){if(/^http:\/\//i.test(t))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(t))return
|
|
2532
|
+
`),0)}function fd(t,e,r,n){return{path:t,linted:e,seeded:r,members:n.map(s=>({alias:s.alias,provider:s.provider,...s.model!==void 0?{model:s.model}:{}}))}}async function mn(t,e,r){if(/^http:\/\//i.test(t))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(t))return PL(t,e);let n=pd(r,t);if(!By(n))throw new Error(`source not found: ${t}`);if(!kL(n).isDirectory())return Uy(n,"utf8");let i=xL(n).filter(o=>o.endsWith(".lmctl"));if(i.length===0)throw new Error(`no .lmctl files in source directory: ${t}`);if(i.length>1)throw new Error(`multiple .lmctl files in source directory: ${t}; specify the source file explicitly`);return Uy(Hy(n,i[0]),"utf8")}async function PL(t,e){let r=new URL(t);for(let n=0;;n+=1){if(r.protocol!=="https:")throw new Error("HTTPS redirects must remain https://");let s=await e(r.href,{redirect:"manual"});if(s.url!==""&&new URL(s.url).protocol!=="https:")throw new Error("HTTPS redirects must remain https://");if(!FL.has(s.status)){if(!s.ok)throw new Error(`HTTP ${s.status}`);return await s.text()}if(n>=jy)throw new Error(`too many HTTPS redirects (maximum ${jy})`);let i=s.headers.get("location");if(i===null)throw new Error(`HTTP ${s.status} redirect missing Location header`);r=new URL(i,r)}}var LL,Xy,FL,jy,wo=k(()=>{"use strict";he();Cy();nr();To();ld();LL=`usage: lmctl plan [directory] [options]
|
|
2523
2533
|
|
|
2524
2534
|
Generate an lmctl teamfile. With no config flags and a TTY, an interactive
|
|
2525
2535
|
wizard runs; with flags, everything is non-interactive.
|
|
2526
2536
|
|
|
2527
2537
|
Member selection (pick exactly one):
|
|
2528
|
-
--pattern <${
|
|
2538
|
+
--pattern <${fo}> Member set: 1=Lead, 2=Lead+Reviewer, 3=Lead+Coder+Reviewer
|
|
2529
2539
|
--member <Alias:provider[:model]> Explicit member (repeatable; first must be Lead)
|
|
2530
2540
|
--from <file|dir|url> Template mode: copy a teamfile, stripping session ids
|
|
2531
2541
|
|
|
@@ -2551,18 +2561,18 @@ Examples:
|
|
|
2551
2561
|
lmctl plan ./backend --member Lead:claude --member Reviewer:codex:o3
|
|
2552
2562
|
lmctl plan ./backend-v2 --from https://example.com/backend.lmctl
|
|
2553
2563
|
lmctl plan ./backend --pattern 3 --provider claude --seed
|
|
2554
|
-
`,
|
|
2555
|
-
one of: --pattern <${
|
|
2556
|
-
plus: --provider <name> (required with --pattern)`;
|
|
2557
|
-
`),2;let i=r.configPath??
|
|
2564
|
+
`,Xy=`missing required flags for non-interactive plan:
|
|
2565
|
+
one of: --pattern <${fo}>, --member <Alias:provider[:model]>, or --from <file|dir|url>
|
|
2566
|
+
plus: --provider <name> (required with --pattern)`;FL=new Set([301,302,303,307,308]),jy=10});var Jy={};ae(Jy,{runInit:()=>jL});async function jL(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(UL),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}
|
|
2567
|
+
`),2;let i=r.configPath??yo(),o=un(i);if(o!==null&&!n)return e.stdout.write(`${i} already exists:
|
|
2558
2568
|
|
|
2559
|
-
`),e.stdout.write(
|
|
2569
|
+
`),e.stdout.write(Eo(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??$y)(),l=My(a);return Fy(l,i),e.stdout.write(`Wrote ${i}
|
|
2560
2570
|
|
|
2561
|
-
`),e.stdout.write(
|
|
2571
|
+
`),e.stdout.write(Eo(l)),e.stdout.write(`
|
|
2562
2572
|
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.
|
|
2563
2573
|
`),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.
|
|
2564
2574
|
`):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.
|
|
2565
|
-
`),0}var
|
|
2575
|
+
`),0}var UL,Vy=k(()=>{"use strict";To();UL=`usage: lmctl init [--force]
|
|
2566
2576
|
|
|
2567
2577
|
Writes ~/.lmctl/init.toml: three provider slots (Provider1/2/3), each
|
|
2568
2578
|
resolved to a provider and a starting model, detected from which provider
|
|
@@ -2580,16 +2590,16 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2580
2590
|
|
|
2581
2591
|
--force Overwrite ~/.lmctl/init.toml if it already exists
|
|
2582
2592
|
-h, --help display help for command
|
|
2583
|
-
`});import{execFileSync as
|
|
2584
|
-
`),we({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=
|
|
2585
|
-
`),t.stdout.write(`${
|
|
2593
|
+
`});import{execFileSync as BL}from"node:child_process";import{resolve as Ky}from"node:path";function WL(t){return t.filter(e=>e.state!=="retired")}function Yy(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=BL("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=Ky(s),o=e.listProjects().find(a=>Ky(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 zy(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 Qy(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=WL(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 Zy=k(()=>{"use strict";he()});var rE={};ae(rE,{SIZE_WARN_EST_TOKENS:()=>gs,estimateTokens:()=>tE,runTerminal:()=>hd});import{spawn as HL}from"node:child_process";import{statSync as XL}from"node:fs";async function hd(t,e){if(t.includes("--help")||t.includes("-h"))return QL(e);let r=ie(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return A(e,r.error);let n=B(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"?H(r,o):B(r,o)!==void 0)return A(e,`--run is mutually exclusive with ${o}`);try{return await C(e,async o=>{let a=B(r,"--alias"),l=Ug(o,s,a);return"err"in l?A(e,l.err):gd(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 qe(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?H(r,l):B(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=st(qL,{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=>GL(e,a.teamfile,a.alias,l,H(r,"--json")))}try{return await C(e,async s=>{let i=KL(e,s,r);if(typeof i=="number")return i;let o=B(r,"--alias");return H(r,"--size")?zL(e,s,i,o,H(r,"--json")):YL(e,s,i,o)})}catch(s){return qe(e,s)}}async function GL(t,e,r,n,s){let i;try{i=ue(e,r,n)}catch(f){return f instanceof se?A(t,f.message):qe(t,f)}let o=Mt(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:ot()});if(!o.acquired){let f=o.current.holder_pid,m=f===null?null:Re(f)?"live":"dead",h=`${i.alias} is busy/held by ${o.current.sender_alias} (${o.current.sender_teamfile}) since ${o.current.started_at} `+(f===null?"(holder_pid=unavailable)":`(holder_pid=${f}, ${m})`);return s?(te(t,{status:"error",errorKind:"busy",message:h,holder_pid:f,holder_liveness:m}),1):A(t,h)}let a=Vh({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,d=null,u=[];try{n.setTerminalLock(a),c=JL(n,i),c!==null&&(process.env.LMCTL_INVOCATION_ID=String(c));let f=n.getRootTeam(i.teamfile)?.name??null;f!==null&&(process.env.LMBEE_TEAM_NAME=f),l=setInterval(()=>{try{let m=new Date().toISOString(),h=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,m);h&&n.heartbeatAgentInflight(o.lease,o.leaseId,m),!h&&l!==null&&(clearInterval(l),l=null)}catch{}},Kh()),l.unref?.();try{Or(t,ke(i.teamfile),i.teamfile)}catch{}return d=await gd(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},m=>{u.push(`${m.provider} terminal ignored model=${m.model}: ${m.reason}`)}),d}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),VL(n,c,d,u)}}function JL(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:jt(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 VL(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 gd(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!Fi(n))return A(t,`no resume incantation for provider "${n}"`);if(!jh.test(s))return A(t,"refusing to resume: malformed sessionid");let a=ac(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}
|
|
2594
|
+
`),we({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=HL(l,c,{stdio:"inherit",cwd:i,env:Ee(process.env,i,s,"terminal")});u.on("error",f=>{d(A(t,`failed to launch ${l}: ${f.message}`))}),u.on("exit",f=>d(f??0))})}function KL(t,e,r){let n=B(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?A(t,`team not found: ${n}`):o}let s=Yy(t,e,B(r,"--project"));return typeof s=="number"?s:zy(t,e,s,void 0)}async function YL(t,e,r,n){let s=Qy(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>)`):gd(t,{provider:pa(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function tE(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=XL(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 zL(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=pa(a),d=a.model??null,u=null;Fi(c)&&(u=await Ie(l,c));let f=tE(u),m=f.est>gs;o.push({alias:a.alias,provider:c,sessionid:l,messages:f.messages,bytes:f.bytes,est_tokens:f.est,estimate:!0,over_guide:m,model:d,resume_incantation:m?Bh(c,l,d!==null?{model:d}:{}):null})}if(s)return te(t,{estimate:!0,legend:eE,guide_tokens:gs,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
2595
|
+
`),t.stdout.write(`${eE}
|
|
2586
2596
|
`);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)
|
|
2587
2597
|
`),a.over_guide&&t.stdout.write(` \u26A0 ${a.alias}: estimated ~${a.est_tokens} tokens \u2014 ESTIMATE only, exceeds the 200K guide.
|
|
2588
2598
|
Nothing was changed automatically. If you choose to compact, open the
|
|
2589
2599
|
session yourself:
|
|
2590
2600
|
${a.resume_incantation??"(no resume incantation for provider "+a.provider+")"}
|
|
2591
2601
|
(or: lmctl terminal --team ${r.name} --alias ${a.alias})
|
|
2592
|
-
`)}return 0}function
|
|
2602
|
+
`)}return 0}function QL(t){return t.stdout.write(`usage: lmctl terminal <teamfile>:<alias> [--json]
|
|
2593
2603
|
lmctl terminal <teamfile> <alias> [--json]
|
|
2594
2604
|
lmctl terminal --run <id> [--alias A]
|
|
2595
2605
|
lmctl terminal [--project P] [--team T] [--alias A] [--size] [--json]
|
|
@@ -2618,16 +2628,16 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2618
2628
|
exact provider count: the messages path slightly
|
|
2619
2629
|
under-counts code-dense text; the byte fallback
|
|
2620
2630
|
over-counts (JSONL overhead \u2192 safe over-warn); CJK is
|
|
2621
|
-
denser (under-warns). At >${
|
|
2631
|
+
denser (under-warns). At >${gs} est
|
|
2622
2632
|
tokens it surfaces the resume incantation so YOU can
|
|
2623
2633
|
open & self-compact. Nothing is ever changed
|
|
2624
|
-
automatically; ${
|
|
2625
|
-
`),0}var
|
|
2626
|
-
`),2;let o=i[0],a=r.cwd??process.cwd(),l=r.fetchFn??fetch,c=un(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 mn(o,l,a)}catch(
|
|
2627
|
-
`),1}let u=
|
|
2628
|
-
`),await
|
|
2634
|
+
automatically; ${gs} is a guide, not a gate.
|
|
2635
|
+
`),0}var qL,gs,eE,_d=k(()=>{"use strict";Pt();Qt();he();Zy();Pe();Et();dt();Ps();ze();yn();Qn();kc();J();or();qL={name:"terminal",allowsBareTeamfile:!1,supportsRaw:!1},gs=2e5,eE="est = rough local heuristic (~4 chars/token), NOT an exact provider token count \u2014 open the session to verify before acting."});var sE={};ae(sE,{runQuickrun:()=>oC});import{existsSync as ZL,mkdirSync as eC,writeFileSync as tC}from"node:fs";import{basename as rC,dirname as nC,join as nE}from"node:path";function iC(t){let e=rC(t),r=nE(t,`${e}.lmctl`),n=2;for(;ZL(r);)r=nE(t,`${e}${n}.lmctl`),n+=1;return r}async function oC(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>
|
|
2636
|
+
`),2;let o=i[0],a=r.cwd??process.cwd(),l=r.fetchFn??fetch,c=un(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 mn(o,l,a)}catch(g){return e.stderr.write(`error: could not fetch ${o}: ${g instanceof Error?g.message:String(g)}
|
|
2637
|
+
`),1}let u=Py(d,c),f=iC(a);if(eC(nC(f),{recursive:!0}),tC(f,u,"utf8"),e.stdout.write(`Wrote ${f}
|
|
2638
|
+
`),await br([f],e)!==0)return e.stderr.write(`error: ${f} failed lint after substitution -- check the values in ~/.lmctl/init.toml.
|
|
2629
2639
|
`),1;if(n)return e.stdout.write(`Edit ${f} if needed, then run: lmctl seed ${f}
|
|
2630
|
-
`),0;let
|
|
2640
|
+
`),0;let h=await Ir([f],e);return h!==0?h:s?0:(r.openTerminal??hd)([f,"Lead"],e)}var sC,iE=k(()=>{"use strict";To();wo();nr();_d();sC=`usage: lmctl quickrun <url-or-path>
|
|
2631
2641
|
|
|
2632
2642
|
Fetches a .lmctl teamfile template (any https:// URL or local file/dir
|
|
2633
2643
|
path -- lmctl.com publishes example templates, but this is not restricted
|
|
@@ -2644,13 +2654,13 @@ taken, so quickrun never overwrites an existing teamfile.
|
|
|
2644
2654
|
--no-seed Write the resolved teamfile but do not seed or open it
|
|
2645
2655
|
--no-terminal Seed, but do not open the Lead's terminal afterward
|
|
2646
2656
|
-h, --help display help for command
|
|
2647
|
-
`});var
|
|
2648
|
-
`),2;let o=r.cwd??process.cwd(),a=r.fetchFn??fetch,l=`${
|
|
2649
|
-
`),1}let d=
|
|
2650
|
-
`),await
|
|
2651
|
-
`),1;let f=await
|
|
2657
|
+
`});var aE={};ae(aE,{runHello:()=>dC});import{writeFileSync as aC}from"node:fs";import{join as lC}from"node:path";async function dC(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(cC),0;let n,s,i=[];for(let h=0;h<t.length;h+=1){let _=t[h];if(_==="-p"||_==="--prompt"){s=t[h+1],h+=1;continue}i.push(_)}if(i.length===1&&(n=i[0]),n===void 0||s===void 0)return e.stderr.write(`usage: lmctl hello <provider> -p "<prompt>"
|
|
2658
|
+
`),2;let o=r.cwd??process.cwd(),a=r.fetchFn??fetch,l=`${oE}/${n}.lmctl`,c;try{c=await mn(l,a,o)}catch(h){return e.stderr.write(`error: could not fetch ${l}: ${h instanceof Error?h.message:String(h)}
|
|
2659
|
+
`),1}let d=lC(o,`${n}_hello.lmctl`);if(aC(d,c,"utf8"),e.stdout.write(`Wrote ${d}
|
|
2660
|
+
`),await br([d],e)!==0)return e.stderr.write(`error: ${d} failed lint -- lmctl.com's ${n}.lmctl example may be out of date.
|
|
2661
|
+
`),1;let f=await Ir([d],e);return f!==0?f:(r.sendPrompt??Rc)([d,"Lead",s],e)}var oE,cC,lE=k(()=>{"use strict";wo();nr();Qi();oE="https://lmctl.com/helloexample",cC=`usage: lmctl hello <provider> -p "<prompt>"
|
|
2652
2662
|
|
|
2653
|
-
Downloads ${
|
|
2663
|
+
Downloads ${oE}/<provider>.lmctl, saves it as
|
|
2654
2664
|
<provider>_hello.lmctl in the current directory, seeds it, sends your
|
|
2655
2665
|
prompt to the Lead, and prints the answer -- the one-command proof that a
|
|
2656
2666
|
provider works at all.
|
|
@@ -2660,10 +2670,10 @@ provider works at all.
|
|
|
2660
2670
|
|
|
2661
2671
|
Example:
|
|
2662
2672
|
lmctl hello claude -p "hi"
|
|
2663
|
-
`});import{execFileSync as yd}from"node:child_process";import{dirname as
|
|
2673
|
+
`});import{execFileSync as yd}from"node:child_process";import{dirname as cE,resolve as uC}from"node:path";function dE(t){return(0,Ed.formatCount)(t)}async function Td(t,e){return C(t,r=>{let n=r.query(`SELECT config_warnings FROM tracked_invocation
|
|
2664
2674
|
WHERE target_teamfile = ? AND target_alias = ? AND config_warnings IS NOT NULL
|
|
2665
|
-
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 wd(t,e,r,n){let s=pe(t,e);if(r.has(s))return[];r.add(s);let i=We(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(...wd(
|
|
2666
|
-
`)}catch{}}async function
|
|
2675
|
+
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 wd(t,e,r,n){let s=pe(t,e);if(r.has(s))return[];r.add(s);let i=We(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(...wd(uC(cE(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 vd(t,e){try{let r=await C(t,n=>e.map(s=>{let i=at(n,s.teamfile,s.alias);return[vo(s.teamfile,s.alias),mC(i)]}));return new Map(r)}catch{return new Map}}function vo(t,e){return`${t}\0${e.toLowerCase()}`}function mC(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}:So(t.reclaimable===void 0?null:{source:t.reclaimable.source,holderPid:t.reclaimable.holder_pid,holderHost:t.reclaimable.holder_host,reason:t.reclaimable.reason})}function So(t=null){return{state:"idle",reason:null,inFlight:null,terminalLock:null,terminalInvocation:null,reclaimable:t}}function bo(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 Sd(t){return t.resets_at!==null?t.resets_at:t.timezone!==null?`${t.reset_time} (${t.timezone})`:t.reset_time}function Ve(t){return t==null?"unknown":(0,Ed.formatCount)(t)}function uE(t){return t==="n/a"?t:Ve(t)}function mE(t,e,r=String){return t!==void 0?r(t):e?"n/a":"unknown"}function bd(t){let e=cE(t),r;try{yd("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=yd("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:fC(e)}}function fC(t){let e;try{e=yd("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 Id(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 xd(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 Ed,fE=k(()=>{"use strict";Ed=_t(ct(),1);ze();he();Tt()});function kd(t){for(let e=t.length-1;e>=0;e-=1){let r=t[e],n=pC.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:hC(r.timestamp,s,i,o,a),reset_time:l,timezone:a,detected_at:r.timestamp.toISOString()}}return null}function hC(t,e,r,n,s){if(!Number.isFinite(t.getTime())||e<1||e>12||r<0||r>59)return null;let i=gC(e,n);try{let o=_C(t,s),a=pE(o.year,o.month,o.day,i,r,s);if(a.getTime()<=t.getTime()){let l=wC(o,1);a=pE(l.year,l.month,l.day,i,r,s)}return a.toISOString()}catch{return null}}function gC(t,e){return e==="am"?t===12?0:t:t===12?12:t+12}function _C(t,e){let r=hE(e,!1).formatToParts(t);return{year:Rt(r,"year"),month:Rt(r,"month"),day:Rt(r,"day")}}function pE(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=yC(new Date(o),i);o=Date.UTC(t,e-1,r,n,s,0,0)-l}return new Date(o)}function yC(t,e){let r=hE(e,!0).formatToParts(t);return Date.UTC(Rt(r,"year"),Rt(r,"month")-1,Rt(r,"day"),Rt(r,"hour"),Rt(r,"minute"),Rt(r,"second"),0)-t.getTime()}function hE(t,e){let r=e?TC:EC,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 Rt(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 wC(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 pC,EC,TC,gE=k(()=>{"use strict";pC=/you['\u2019]ve hit your session limit\s*(?:\u00b7|-|:)?\s*resets\s+([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;EC=new Map,TC=new Map});var RE={};ae(RE,{appendIntent:()=>Ad,formatAge:()=>_s,formatDuration:()=>ko,resolveIntentLogPath:()=>vE,runStatus:()=>CC,shortIdentity:()=>ht});import{appendFileSync as vC,existsSync as SC,mkdirSync as bC}from"node:fs";import{homedir as IC}from"node:os";import{basename as xC,dirname as wE,isAbsolute as kC,join as AC,resolve as RC}from"node:path";function vE(){return process.env.LMCTL_INTENT_LOG??AC(IC(),".lmctl","recent-intents.log")}function Ad(t){try{let e=vE();bC(wE(e),{recursive:!0});let r=JSON.stringify({ts:t.ts??new Date().toISOString(),cwd:t.cwd??process.cwd(),verb:t.verb,args:[...t.args]});vC(e,`${r}
|
|
2676
|
+
`)}catch{}}async function CC(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(NC),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=ie(t,["--since"],["--json","--details"]);if(n.error!==void 0)return A(e,n.error);let s=H(n,"--json"),i=H(n,"--details");if(n.positionals.length>0){let a=await DC(e,n.positionals,{json:s,details:i,since:B(n,"--since")});return a===0&&Ad({verb:"status",args:t}),a}if(i)return A(e,"--details only applies with a teamfile argument (lmctl status <teamfile> --details)");let o=tO(B(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=>EE(c,a));te(e,{schema_version:Dd,...l})}else{let l=await C(e,async c=>JC(await EE(c,a),{sinceIso:o.iso}));e.stdout.write(l)}return Ad({verb:"status",args:t}),0}catch(a){return A(e,a instanceof Error?a.message:String(a))}}async function DC(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=st(OC,{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 rO(t,n.teamfile,r.json,r.details):await lO(t,n.teamfile,n.alias,r.json)}catch(s){return s instanceof se?A(t,s.message):A(t,`status: ${s instanceof Error?s.message:String(s)}`)}}async function EE(t,e){let r=uc(e,t);if(!r.ok){if(r.reason==="not-found")throw new Error(It("status"));return await $C(t)}return await MC(t,r.identity)}async function MC(t,e){let r=xt(e),n=t.getRootTeam(r.teamfile);if(n===null)throw new Error(It("status"));let s=We(n.teamfile_path,t),i=Nd(xo(t,{from:r.value})),o=Nd(xo(t,{target_teamfile:r.teamfile,target_alias:r.alias})),a=jC([...Rd(t,{from:r.value}),...Rd(t,{target_teamfile:r.teamfile,target_alias:r.alias})]);return{scope:"self",identity:r.value,...SE(),team:{name:s.name,teamfile:n.teamfile_path},members:s.members.map(l=>PC(t,n.teamfile_path,l)),activity:{from_me:i.map(l=>Ld(l)),to_me:o.map(l=>Ld(l))},transcript_harvest:await bE(a)}}function SE(){let t=null;try{t=rf(Wr())}catch{}return{db_path:fe(),site_name:t}}async function $C(t){let e=t.listRootTeams();return{scope:"db",identity:null,...SE(),teams:e.map(r=>FC(t,r)),activity:Nd(xo(t)).map(r=>Ld(r)),transcript_harvest:await bE(Rd(t))}}function FC(t,e){if(!SC(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=We(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 PC(t,e,r){let n=r.teamfile===void 0?null:pe(kC(r.teamfile)?r.teamfile:RC(wE(e),r.teamfile),t),s=at(t,e,r.alias),i=s.busy&&s.reason==="in-flight"?UC(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 UC(t,e,r,n){let s=n.sender_alias==="operator"?"operator":`${n.sender_teamfile}:${n.sender_alias}`,o=t.db.prepare(`
|
|
2667
2677
|
SELECT * FROM tracked_invocation
|
|
2668
2678
|
WHERE kind = 'chat'
|
|
2669
2679
|
AND status = 'running'
|
|
@@ -2673,27 +2683,27 @@ Example:
|
|
|
2673
2683
|
AND holder_pid IS ?
|
|
2674
2684
|
ORDER BY started_at DESC, id DESC
|
|
2675
2685
|
LIMIT 5
|
|
2676
|
-
`).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:
|
|
2686
|
+
`).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 xo(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(`
|
|
2677
2687
|
SELECT * FROM tracked_invocation
|
|
2678
2688
|
${s}
|
|
2679
2689
|
ORDER BY started_at DESC, id DESC
|
|
2680
|
-
`).all(...n)}function Rd(t,e={}){return
|
|
2690
|
+
`).all(...n)}function Rd(t,e={}){return xo(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&$t(n)==="dead")}function jC(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 Nd(t){return t.filter(e=>$t(e)!=="dead")}async function bE(t){let e=[];for(let r of t)e.push(await BC(r));return e}async function BC(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 kr(r,"missing-target",null,null);if(t.request_payload===null||t.request_payload.length===0)return kr(r,"missing-request-payload",null,null);let n=WC(t.meta);if(n.provider===null||n.sessionid===null)return kr(r,"missing-session-metadata",n.provider,n.sessionid);if(!HC(n.provider))return kr(r,"unsupported-provider",n.provider,n.sessionid);let s;try{s=await Ie(n.sessionid,n.provider)}catch{return kr(r,"read-error",n.provider,n.sessionid)}if(s===null)return kr(r,"session-not-found",n.provider,n.sessionid);let i=XC(t.request_payload,s.messages);return i.state!=="completed"?kr(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:AE(i.result),assistant_timestamp:i.assistantTimestamp,matched_user_index:i.userIndex}}function kr(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 WC(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 HC(t){return["claude","codex","gemini","copilot","opencode","lmplayer","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"].includes(t)}function XC(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(`
|
|
2681
2691
|
|
|
2682
|
-
`),assistantTimestamp:
|
|
2683
|
-
`)}function
|
|
2684
|
-
`)}function
|
|
2685
|
-
`)}u.detailLoaded=m!==null,u.messageCount=m?.messageCount??null,u.observedModel=m?.model??"(unknown)",u.lastContext=m?.lastInputTokens??null,u.totalInputTokens=m?.totalInputTokens??null,u.totalOutputTokens=m?.totalOutputTokens??null,m?.totalCachedInputTokens!==void 0&&(u.totalCachedInputTokens=m.totalCachedInputTokens),u.sessionLimit=m===null?null:kd(m.messages),o!==null&&(u.activitySinceLastCommit={messageCount:m===null?null:Id(m,o.since),tokens:null},u.cumulativeTokens=m===null?null:xd(m)??"n/a"),m?.messageCount===void 0?c=void 0:c!==void 0&&(c+=m.messageCount)}l.push(u)}return r?(te(t,{schema_version:Dd,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(
|
|
2692
|
+
`),assistantTimestamp:qC(s[s.length-1]?.timestamp)}}function qC(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function GC(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 Ld(t){let e=GC(t.config_warnings);return{id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:$t(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:TE(t.result_summary),error:TE(t.error),...e!==void 0?{config_warnings:e}:{}}}function JC(t,e){return t.scope==="self"?KC(t,e):YC(t,e)}function VC(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 KC(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"?VC(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:"),xE(r,t.transcript_harvest,"self"),r.push(""),r.push("activity from me:"),Cd(r,Od(t.activity.from_me,e.sinceIso),"from-me"),r.push(""),r.push("activity to me:"),Cd(r,Od(t.activity.to_me,e.sinceIso),"to-me"),r.push(""),r.push(IE(t)),r.join(`
|
|
2693
|
+
`)}function YC(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:"),xE(r,t.transcript_harvest,"db"),r.push(""),r.push("recent activity:"),Cd(r,Od(t.activity,e.sinceIso),"db"),r.push(""),r.push(IE(t)),r.join(`
|
|
2694
|
+
`)}function IE(t){return hn(t.db_path)}function Cd(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Io))zC(t,n,r);kE(t,e.length,Io,"older")}function xE(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Io)){let s=r==="db"?` from ${ht(n.from_identity)} -> ${ht(n.target)}`:` -> ${ht(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}`)}kE(t,e.length,Io,"more transcript harvest rows")}function Od(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 zC(t,e,r){let n=ZC(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?"":` "${AE(i)}"`;if(t.push(` #${e.id} ${QC(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 QC(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function ZC(t,e){if(e==="from-me")return t.target===null?"":` -> ${ht(t.target)}`;if(e==="to-me")return` from ${ht(t.from_identity)}`;let r=t.target===null?"":` -> ${ht(t.target)}`;return` from ${ht(t.from_identity)}${r}`}function kE(t,e,r,n){let s=e-r;s>0&&t.push(` (+${s} ${n} -- use --json)`)}function TE(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function AE(t){let e=t.replace(/\s+/g," ").trim();return e.length<=_E?e:`${e.slice(0,_E-3)}...`}function eO(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=yE?e:`${e.slice(0,yE-3)}...`}function ko(t){return(0,Le.formatDuration)(t)}function _s(t){return(0,Le.formatRelativeTime)(t)}function ht(t){if(t==="operator")return t;try{let e=xt(t);return`${xC(e.teamfile)}:${e.alias}`}catch{return t}}function tO(t){if(t===void 0)return{iso:new Date(Date.now()-LC).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 rO(t,e,r,n){let s=await C(t,d=>{let u=pe(e,d),f=We(u,d);if(f.parseErrors.length>0)throw new Error(f.parseErrors.join("; "));return{teamfile:u,teamName:f.name,targets:wd(u,d,new Set,[])}}),i=bd(s.teamfile),o=i.kind==="repo"?i:null,a=await vd(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(vo(d.teamfile,d.alias))??So(),probed:!1,detailLoaded:!1},f=await Td(t,{teamfile:d.teamfile,alias:d.alias});if(f!==void 0&&(u.configWarnings=f),n&&d.sessionid!==null){u.probed=!0;let m=null;try{m=await Ie(d.sessionid,d.provider)}catch(h){t.stderr.write(`warning: failed to load session "${d.sessionid}" for ${d.reportPath} (${d.provider}): ${h instanceof Error?h.message:String(h)}
|
|
2695
|
+
`)}u.detailLoaded=m!==null,u.messageCount=m?.messageCount??null,u.observedModel=m?.model??"(unknown)",u.lastContext=m?.lastInputTokens??null,u.totalInputTokens=m?.totalInputTokens??null,u.totalOutputTokens=m?.totalOutputTokens??null,m?.totalCachedInputTokens!==void 0&&(u.totalCachedInputTokens=m.totalCachedInputTokens),u.sessionLimit=m===null?null:kd(m.messages),o!==null&&(u.activitySinceLastCommit={messageCount:m===null?null:Id(m,o.since),tokens:null},u.cumulativeTokens=m===null?null:xd(m)??"n/a"),m?.messageCount===void 0?c=void 0:c!==void 0&&(c+=m.messageCount)}l.push(u)}return r?(te(t,{schema_version:Dd,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(iO(s.teamName,s.teamfile,i,l,n,c)),0)}function nO(t){return t.sessionid??"(not seeded)"}function sO(t){return t.sessionid===null?"not seeded":bo(t.liveness)}function iO(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 _ of r.commits)o.push(` ${_.ref}: ${_.timestamp.toISOString()}`);o.push(` Uncommitted: ${Ve(r.working.uncommittedTracked)} changed (tracked), ${Ve(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 _ of n){let g=_.declaredModel===null?"":` model=${_.declaredModel}`;if(_.sessionid===null?o.push(` ${_.reportPath}: not seeded provider=${_.provider}${g} (run: lmctl seed "${_.teamfile}")`):o.push(` ${_.reportPath}: ${bo(_.liveness)} provider=${_.provider}${g} session=${_.sessionid}`),_.configWarnings!==void 0)for(let p of _.configWarnings)o.push(` config not applied: ${p}`)}return o.push(""),o.push("session detail (observed model, messages, tokens, limits) not probed -- use --details"),`${o.join(`
|
|
2686
2696
|
`)}
|
|
2687
|
-
`}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((
|
|
2688
|
-
`);if(o.push(
|
|
2697
|
+
`}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((_,g)=>g>=5?"right":"left"),d=!1,u=n.filter(_=>_.sessionLimit!=null),f=[];for(let _ of n){let g=mE(_.lastContext??void 0,_.detailLoaded,dE);(g==="n/a"||_.cumulativeTokens==="n/a")&&(d=!0);let p=[(0,Le.escapeCell)(nO(_)),(0,Le.escapeCell)(_.reportPath),(0,Le.escapeCell)(_.provider),(0,Le.escapeCell)(_.observedModel??"(unknown)"),sO(_),Ve(_.messageCount),g];a!==null&&p.push(Ve(_.activitySinceLastCommit?.messageCount),Ve(_.activitySinceLastCommit?.tokens),uE(_.cumulativeTokens)),f.push(p)}let m=["TOTAL","","","","",Ve(i)];a!==null&&m.push("",Ve(oO(n)),Ve(null),Ve(aO(n))),f.push(m);let h=(0,Le.formatTable)(f,{headers:l,align:c,margin:2}).split(`
|
|
2698
|
+
`);if(o.push(h[0]),n.forEach((_,g)=>{if(o.push(h[g+1]),_.configWarnings!==void 0)for(let p of _.configWarnings)o.push(` config not applied: ${p}`)}),o.push(h[h.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.
|
|
2689
2699
|
Right after a compaction the last completed turn IS the summarisation request, which carried the
|
|
2690
2700
|
full pre-compaction prompt \u2014 so this reads the OLD large number while the live context is already
|
|
2691
|
-
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
|
|
2701
|
+
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 _ of u)o.push(` ${_.reportPath}: LIMITED resets_at=${Sd(_.sessionLimit)}`)}return`${o.join(`
|
|
2692
2702
|
`)}
|
|
2693
|
-
`}function
|
|
2703
|
+
`}function oO(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 aO(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 lO(t,e,r,n){let s=await C(t,h=>ue(e,r,h)),i;try{i=await Ie(s.sessionid,s.provider)}catch(h){return A(t,`status: failed to load session: ${h instanceof Error?h.message:String(h)}`)}if(i===null)return A(t,`status: session not found: ${s.sessionid} (provider=${s.provider})`);let o=kd(i.messages),l=(await vd(t,[{teamfile:s.teamfile,alias:s.alias}])).get(vo(s.teamfile,s.alias))??So(),c=await Td(t,{teamfile:s.teamfile,alias:s.alias}),d=bd(s.teamfile),u=d.kind==="repo"?d:null,f={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:Id(i,u.since),tokens:null},cumulativeTokens:xd(i)}:{},createdAt:i.createdAt.toISOString(),modifiedAt:i.modifiedAt.toISOString()};if(n)return te(t,{schema_version:Dd,scope:"member",...f}),0;let m=[];if(m.push(`Session: ${i.sessionId}`),m.push(` Provider: ${i.provider}`),m.push(` Alias: ${s.alias}`),m.push(` Liveness: ${bo(l)}`),m.push(` CWD: ${i.cwd}`),m.push(` Messages: ${Ve(i.messageCount)}`),m.push(` Model (declared): ${s.model??"(none)"}`),m.push(` Model (observed): ${i.model??"(unknown)"}`),c!==void 0)for(let h of c)m.push(` Config NOT applied: ${h}`);if(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)m.push(" Tokens: n/a");else{let h=` Tokens: ${(0,Le.formatCount)(i.totalInputTokens)} in / ${(0,Le.formatCount)(i.totalOutputTokens)} out`;f.totalCachedInputTokens!==void 0&&(h+=` (cached: ${(0,Le.formatCount)(f.totalCachedInputTokens)})`),m.push(h)}return(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)&&m.push(" n/a = this provider does not expose a context/token total; absence is not a health signal."),m.push(` lastContext = prompt size of the LAST COMPLETED turn; it LAGS BY ONE TURN. Right after a
|
|
2694
2704
|
compaction it still reports the pre-compaction size (the summarisation request itself).`),o!==null&&m.push(` SessionLimit: LIMITED resets_at=${Sd(o)}`),m.push(` Created: ${f.createdAt}`),m.push(` Modified: ${f.modifiedAt}`),t.stdout.write(`${m.join(`
|
|
2695
2705
|
`)}
|
|
2696
|
-
`),0}var Le,
|
|
2706
|
+
`),0}var Le,NC,Dd,Io,LC,_E,yE,OC,Md=k(()=>{"use strict";Le=_t(ct(),1);ze();he();Zn();rt();nn();Tt();Pe();fE();In();Qt();gE();NC=`usage: lmctl status [--json] [--since <duration|ISO8601>]
|
|
2697
2707
|
lmctl status <teamfile> [--details] [--json]
|
|
2698
2708
|
lmctl status <teamfile> <alias> [--json]
|
|
2699
2709
|
|
|
@@ -2712,28 +2722,28 @@ With a teamfile and an alias: single-member deep view (session detail, token
|
|
|
2712
2722
|
breakdown, liveness with terminal-lock/in-flight holder info).
|
|
2713
2723
|
|
|
2714
2724
|
--json emits { schema_version: 2, scope: 'self'|'db'|'team'|'member', ... }.
|
|
2715
|
-
`,Dd=2,
|
|
2716
|
-
`,1)[0];return e.length<=
|
|
2725
|
+
`,Dd=2,Io=5,LC=24*60*60*1e3,_E=72,yE=80;OC={name:"status",allowsBareTeamfile:!0,supportsRaw:!1}});var $E={};ae($E,{_setRunningWatchMaxTicksForTests:()=>uO,runRunning:()=>vO});function uO(t){jd=t??void 0}function fO(t){let e=t.split(`
|
|
2726
|
+
`,1)[0];return e.length<=LE?e:`${e.slice(0,LE)}\u2026`}function Ao(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function Fd(t,e){let r=t.target_teamfile,n=t.target_alias;if(r===null||n===null)return $d;let s=e.get(r);if(s===void 0){try{s=ke(r)}catch{s=null}e.set(r,s)}return s===null?$d:Ns(s,n)?.model??$d}function Bd(t){return t.target!==null?ht(t.target):t.from_identity}function CE(t){return[(0,Ke.escapeCell)(Bd(t)),t.kind,"running",t.holder_liveness,(0,Ke.escapeCell)(t.model),_s(t.started_at)]}function OE(t){return[(0,Ke.escapeCell)(Bd(t)),t.kind,"DEAD","",(0,Ke.escapeCell)(t.model),`stale ${_s(t.started_at)}, holder process confirmed dead`]}function DE(t){let e=`ran ${ko(t.ran_ms)}, idle ${_s(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,Ke.escapeCell)(fO(t.error))}`),[(0,Ke.escapeCell)(Bd(t)),t.kind,t.status,"",(0,Ke.escapeCell)(t.model),e]}function Pd(t){return t.filter(e=>e!=="").join(" ")}function ME(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 hO(t){let{roots:e,childrenByParent:r}=ME(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 gO(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}=ME(n),o=a=>({...a,children:(i.get(a.id)??[]).map(o)});return s.map(o)}function _O(t){if(t===void 0)return{windowMs:cO};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 Ud(t,e){return!(e.teamfile!==void 0&&t.target_teamfile!==e.teamfile||e.member!==void 0&&(t.target_alias??"").toLowerCase()!==e.member)}function yO(t,e,r={}){let n=Date.now(),s=t.listAllRunningTrackedInvocations().filter(m=>Ud(m,e)),i=new Map,o=[],a=[];for(let m of s){let h=$t(m),_=n-new Date(m.started_at).getTime(),g={id:m.id,kind:m.kind,origin:m.origin,from_identity:m.from_identity,target:Ao(m),model:Fd(m,i),started_at:m.started_at,parent_invocation_id:m.parent_invocation_id};if(h==="dead"){if(ga(t,m)!==null)continue;a.push({...g,stale_for_ms:_})}else o.push({...g,running_for_ms:_,holder_liveness:h??"unknown"})}let l=new Set(s.map(Ao).filter(m=>m!==null)),c=new Date(n-e.idleWindowMs).toISOString(),d=t.listRecentlyFinishedTrackedInvocations(c).filter(m=>Ud(m,e)),u=new Set,f=[];for(let m of d){let h=Ao(m);h===null||l.has(h)||u.has(h)||(u.add(h),f.push({id:m.id,kind:m.kind,origin:m.origin,from_identity:m.from_identity,target:h,model:Fd(m,i),status:m.status,started_at:m.started_at,ended_at:m.ended_at,idle_ms:n-new Date(m.ended_at).getTime(),ran_ms:new Date(m.ended_at).getTime()-new Date(m.started_at).getTime(),error:m.error,parent_invocation_id:m.parent_invocation_id}))}if(r.tree===!0){let m=new Set([...o.map(_=>_.id),...a.map(_=>_.id),...f.map(_=>_.id)]),h=[...m];for(;h.length>0;){let _=t.listFinishedTrackedInvocationChildren(h,c).filter(g=>!m.has(g.id)&&Ud(g,e));if(_.length===0)break;h=[];for(let g of _){m.add(g.id),h.push(g.id);let p=Ao(g);f.push({id:g.id,kind:g.kind,origin:g.origin,from_identity:g.from_identity,target:p,model:Fd(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:f}}function EO(t,e){return e?{schema_version:NE,tree:gO(t.running,t.dead,t.idle)}:{schema_version:NE,...t}}function TO(t){let e=[...t.running.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Pd(CE(n))})),...t.dead.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Pd(OE(n))})),...t.idle.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:Pd(DE(n))}))],r=hO(e);return`${r.length>0?r.join(`
|
|
2717
2727
|
`):" none"}
|
|
2718
|
-
`}function
|
|
2728
|
+
`}function wO(t,e){let r=[{title:`Running (${t.running.length}):`,rows:t.running.map(CE)},{title:`Dead (reclaimable) (${t.dead.length}):`,rows:t.dead.map(OE)},{title:`Idle, finished in the last ${ko(e)} (${t.idle.length}):`,rows:t.idle.map(DE)}],n=["MEMBER","KIND","STATE","LIVENESS","MODEL","TIMING"],s=(0,Ke.measureColumns)([{rows:[],headers:n},...r.map(a=>a.rows)],{max:pO}),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,Ke.renderGrid)(a.rows,{widths:s,margin:2,...c?{headers:n}:{}}))}),`${o.join(`
|
|
2719
2729
|
`)}
|
|
2720
|
-
`}async function
|
|
2721
|
-
`),0;let r=ie(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=H(r,"--json"),s=H(r,"--tree"),i=H(r,"--watch"),o=B(r,"--team"),a=B(r,"--member"),l=
|
|
2722
|
-
`):te(e,
|
|
2723
|
-
`)}finally{
|
|
2724
|
-
`),
|
|
2725
|
-
${
|
|
2726
|
-
`),2}async function
|
|
2727
|
-
`),0;let r=ie(t,["--timeout"],["--json"]);if(r.error!==void 0)return Hd(e,r.error);let n=H(r,"--json");for(let
|
|
2728
|
-
`)});if(a.status==="error"){let
|
|
2729
|
-
Set LMCTL_RATELIMIT_BIN=<path> to point at the lmratelimit CLI.`:a.error;return e.stderr.write(`error: ${
|
|
2730
|
+
`}async function vO(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${mO}
|
|
2731
|
+
`),0;let r=ie(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=H(r,"--json"),s=H(r,"--tree"),i=H(r,"--watch"),o=B(r,"--team"),a=B(r,"--member"),l=_O(B(r,"--since"));if("error"in l)return A(e,l.error);let c=B(r,"--watch-interval"),d=c===void 0?dO: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,f=>{let m={...o!==void 0?{teamfile:pe(o,f)}:{},...a!==void 0?{member:a.toLowerCase()}:{},idleWindowMs:l.windowMs},h=yO(f,m,{tree:s});if(n){let _=EO(h,s);return i?e.stdout.write(`${JSON.stringify(_)}
|
|
2732
|
+
`):te(e,_),0}return e.stdout.write(s?TO(h):wO(h,l.windowMs)),0});return i?await new Promise(f=>{let m=0,h=!1,_=y=>{clearInterval(y),f(0)},g=async y=>{if(!h){h=!0;try{await u()}catch(E){e.stderr.write(`running: ${E instanceof Error?E.message:String(E)}
|
|
2733
|
+
`)}finally{h=!1}m+=1,jd!==void 0&&m>=jd&&_(y)}},p=setInterval(()=>{g(p)},d*1e3);g(p),process.once("SIGINT",()=>_(p)),process.once("SIGTERM",()=>_(p))}):u()}var Ke,cO,NE,dO,jd,mO,LE,$d,pO,FE=k(()=>{"use strict";Ke=_t(ct(),1);ze();Sn();Et();he();Md();Tt();cO=24*60*60*1e3,NE=3,dO=2;mO=["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(`
|
|
2734
|
+
`),LE=120;$d="default";pO=[26,void 0,void 0,void 0,24,void 0]});var jE={};ae(jE,{_setRatelimitFsDepsForTests:()=>Ng,_setRatelimitRunnerForTests:()=>Rg,runRatelimit:()=>RO});function Wd(t){return typeof t=="object"&&t!==null}function bO(t){return(0,Te.formatPercent)(typeof t=="number"?t:null)}function IO(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,Te.escapeCell)(r)}function kO(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,Te.formatDuration)(i,{maxUnit:"d",style:"compact"})}`:r=`${(0,Te.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,Te.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,Te.formatPercent)(d)}`}else{let d=n*s,u=d>0?(1-c)/c*d:0,f=Math.max(0,i-u);o=`needing -${(0,Te.formatDuration)(f,{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=[IO(t,e),`${(0,Te.formatBar)(typeof e.used_fraction=="number"?e.used_fraction:null)} ${bO(e.used_fraction)}`,r];return o!==""&&l.push(o),a.length>0&&l.push(a.join(" ")),l}function AO(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,Te.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"&&SO.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(Wd).map(u=>kO(l,u)):[],d=[];if(Wd(t.credits)){let u=t.credits,f=[];typeof u.has_credits=="boolean"&&f.push(`has_credits=${u.has_credits}`),u.unlimited===!0&&f.push("unlimited"),u.balance!==void 0&&u.balance!==null&&f.push(`balance=${String(u.balance)}`),d.push(` credits: ${f.length>0?f.join(" "):"present"}`)}if(Wd(t.spend_control)){let u=t.spend_control,f=` spend control: reached=${u.reached===!0}`;u.individual_limit!==void 0&&u.individual_limit!==null&&(f+=` individual_limit=${String(u.individual_limit)}`),d.push(f)}return{head:a,bucketRows:c,footers:d}}function Hd(t,e){return t.stderr.write(`error: ${e}
|
|
2735
|
+
${UE}
|
|
2736
|
+
`),2}async function RO(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${UE}
|
|
2737
|
+
`),0;let r=ie(t,["--timeout"],["--json"]);if(r.error!==void 0)return Hd(e,r.error);let n=H(r,"--json");for(let _ of r.positionals)if(!PE.includes(_))return Hd(e,`unknown provider: ${_} (valid targets: ${PE.join(", ")})`);let s=r.positionals.length>0?r.positionals:["all"],i=15,o=B(r,"--timeout");if(o!==void 0){let _=Number(o);if(!Number.isFinite(_)||_<=0)return Hd(e,`invalid --timeout "${o}" (expected a positive number of seconds)`);i=_}let a=Vi({targets:s,timeoutSeconds:i,env:e.env??process.env,progress:_=>e.stderr.write(`${_}
|
|
2738
|
+
`)});if(a.status==="error"){let _=a.error.startsWith("lmratelimit binary not found")?`${a.error}
|
|
2739
|
+
Set LMCTL_RATELIMIT_BIN=<path> to point at the lmratelimit CLI.`:a.error;return e.stderr.write(`error: ${_}
|
|
2730
2740
|
`),1}let l=a.readings;if(n)return te(e,{readings:l}),0;if(l.length===0)return e.stdout.write(`rate-limit: no readings returned.
|
|
2731
|
-
`),0;let c=["LIMIT","USED","RESET TIME","OVERSTOCK"],d=["left","left","left"],u=l.map(
|
|
2741
|
+
`),0;let c=["LIMIT","USED","RESET TIME","OVERSTOCK"],d=["left","left","left"],u=l.map(AO),f=(0,Te.measureColumns)([{rows:[],headers:c},...u.map(_=>_.bucketRows)]),m=!1,h=[];for(let _ of u){if(h.length>0&&h.push(""),h.push(_.head),_.bucketRows.length>0){let g=!m;m=!0,h.push((0,Te.renderGrid)(_.bucketRows,{widths:f,margin:2,align:d,...g?{headers:c}:{}}))}h.push(..._.footers)}return e.stdout.write(`${h.join(`
|
|
2732
2742
|
`)}
|
|
2733
|
-
`),0}var Te
|
|
2734
|
-
`),
|
|
2735
|
-
`,"utf8"),
|
|
2736
|
-
`)}catch{}}
|
|
2743
|
+
`),0}var Te,UE,SO,PE,xO,BE=k(()=>{"use strict";Te=_t(ct(),1);he();Ki();Ki();UE=["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(`
|
|
2744
|
+
`),SO=new Set(["agy_not_found","credentials_missing"]),PE=Ji;xO={five_hour:5*36e5,daily:864e5,weekly:7*864e5,monthly:30*864e5}});rt();import{pathToFileURL as NO}from"node:url";import{execFileSync as sT}from"node:child_process";import{existsSync as iT,readFileSync as oT}from"node:fs";import{join as Zd}from"node:path";import{fileURLToPath as aT}from"node:url";function eu(){return aT(new URL("../..",import.meta.url))}function Do(t=eu()){try{let e=JSON.parse(oT(Zd(t,"package.json"),"utf8"));if(typeof e.version=="string")return e.version}catch{}return"0.0.0"}function Oo(t,e){try{return sT("git",e,{cwd:t,stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim()}catch{return}}function Mo(t=eu()){let e=Do(t);if(!iT(Zd(t,".git")))return e;let r=Oo(t,["rev-parse","--short","HEAD"]);if(r===void 0)return e;let n=Oo(t,["describe","--tags","--exact-match","HEAD"]),s=Oo(t,["status","--porcelain"]),i=s!==void 0&&s.length>0;return n===`v${e}`&&!i?e:`${e}+${r}${i?".dirty":""}`}J();import{mkdirSync as TT,readFileSync as wT,renameSync as vT,writeFileSync as ST}from"node:fs";import{homedir as bT}from"node:os";import{dirname as IT,join as xT}from"node:path";function cu(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function yT(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function ET(t,e){return!yT(t)||cu(t)?null:`${e} must use https://: ${t}`}async function du(t,e){let r=ET(t,e.description);if(r!==null||!cu(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 lu(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 lu(t,e.description,n,a)}}finally{clearTimeout(i)}}function lu(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 kT="https://registry.npmjs.org/@lmctl-ai/lmctl/latest",AT=60*60*1e3,RT=1500;function NT(){let t=process.env.HOME??bT();return xT(t,".lmctl",".update-check.json")}function LT(t){return t.isTTY===!0}function CT(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 Fo(t,e){return!!(process.env.LMCTL_NO_UPDATE_NOTIFIER==="1"||!LT(e.stderr)||t.includes("--json")||t.includes("--help")||t.includes("-h")||t[0]==="help"||t[0]==="mcp")}function OT(t,e){try{let r=JSON.parse(wT(t,"utf8"));if(typeof r.checkedAt=="number"&&Number.isFinite(r.checkedAt)&&typeof r.latest=="string"&&e-r.checkedAt<AT)return r.latest}catch{}return null}function DT(t,e){TT(IT(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;ST(r,`${JSON.stringify(e)}
|
|
2745
|
+
`,"utf8"),vT(r,t)}async function MT(){let t=await du(kT,{description:"lmctl npm metadata",timeoutMs:RT}),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 uu(t,e=[],r={}){try{if(Fo(e,t))return;let n=r.now?.()??Date.now(),s=r.cachePath??NT();if(OT(s,n)!==null)return;let o=await(r.fetchLatest??MT)();try{DT(s,{checkedAt:n,latest:o})}catch{return}let a=r.currentVersion?.()??Do();CT(o,a)>0&&t.stderr.write(`update available: ${a} \u2192 ${o} run: npm i -g @lmctl-ai/lmctl@latest
|
|
2746
|
+
`)}catch{}}Uo();As();var fn=`usage: lmctl [--db PATH] [--debug] <command> [args]
|
|
2737
2747
|
`,Xd=`${fn}
|
|
2738
2748
|
Onboarding:
|
|
2739
2749
|
init Detect your provider CLIs and write ~/.lmctl/init.toml (run this first).
|
|
@@ -2769,9 +2779,9 @@ Global flags:
|
|
|
2769
2779
|
write full stack + cause chain and context to that file.
|
|
2770
2780
|
|
|
2771
2781
|
Run 'lmctl help <command>' for command-specific help.
|
|
2772
|
-
`,
|
|
2782
|
+
`,WE=new Set(["init","quickrun","hello","prompt","chat","batch","script","mcp","terminal","tail","export","cost","ls","lint","seed","plan","status","running","ratelimit","db"]);function HE(t,e){return t.stderr.write(`error: ${e}
|
|
2773
2783
|
${fn}Run 'lmctl help' for usage.
|
|
2774
|
-
`),2}function
|
|
2784
|
+
`),2}function qE(t,e){return e==="send"?(t.stderr.write(`error: unknown command: send (use lmctl prompt)
|
|
2775
2785
|
${fn}Run 'lmctl help' for usage.
|
|
2776
2786
|
`),1):e==="recv"?(t.stderr.write(`error: unknown command: recv
|
|
2777
2787
|
${fn}Run 'lmctl help' for usage.
|
|
@@ -2779,23 +2789,23 @@ ${fn}Run 'lmctl help' for usage.
|
|
|
2779
2789
|
${fn}Run 'lmctl help' for usage.
|
|
2780
2790
|
`),1):(t.stderr.write(`error: unknown command: ${e}
|
|
2781
2791
|
${fn}Run 'lmctl help' for usage.
|
|
2782
|
-
`),1)}async function
|
|
2783
|
-
`),0;if(s==="--help"||s==="-h"||s===void 0)return e.stdout.write(Xd),0;if(s==="help"){let[l,...c]=r.slice(1);return l===void 0||l==="--help"||l==="-h"?(e.stdout.write(Xd),0):
|
|
2792
|
+
`),1)}async function LO(t,e={stdout:process.stdout,stderr:process.stderr}){let r=iu();try{return await CO(t,e)}finally{ou(r)}}async function CO(t,e={stdout:process.stdout,stderr:process.stderr}){let r=[],n;for(let l=0;l<t.length;l+=1){let c=t[l];if(c==="--db"){let d=t[++l];if(d===void 0||d.startsWith("--"))return HE(e,"missing value for --db");n=d;continue}if(c==="--debug"){su();continue}if(c==="--allow-schema-skew"){process.env.LMCTL_ALLOW_SCHEMA_SKEW="1";continue}r.push(c)}if(n!==void 0){let l=r[0];if(vs()&&l!==void 0&&Ss(l))return HE(e,"--db cannot be combined with an infra command (lmctl and lmauto use separate databases)");process.env.LMCTL_DB=n}let s=r[0];if(s==="--version"||s==="-v"||s==="-V")return e.stdout.write(`lmctl ${Mo()}
|
|
2793
|
+
`),0;if(s==="--help"||s==="-h"||s===void 0)return e.stdout.write(Xd),0;if(s==="help"){let[l,...c]=r.slice(1);return l===void 0||l==="--help"||l==="-h"?(e.stdout.write(Xd),0):WE.has(l)?XE(l,[...c,"--help"],e):qE(e,l)}Co(fe(),e.stderr);let[i,...o]=r;if(i===void 0)return e.stdout.write(Xd),0;let a=Date.now();qd(i,o,{phase:"start",started_at:new Date(a).toISOString()});try{let l=await XE(i,o,e);return qd(i,o,{phase:"finish",outcome:l===0?"ok":"error",exit_code:l,duration_ms:Date.now()-a}),WE.has(i)&&!Fo(r,e)&&await uu(e,r),l}catch(l){let c=l instanceof Error?l:new Error(String(l));return qd(i,o,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-a,error_class:c.name,error_message:c.message,error_stack:c.stack??null,causes:DO(c)}),OO(l,i,o,e)}}function qd(t,e,r){we({event:t,record_kind:"cli_action",command:t,argv:e,cwd:process.cwd(),db_path:fe(),lmctl_version:Mo(),node_version:process.version,...r})}function OO(t,e,r,n){let s=t instanceof Error?t:new Error(String(t));return s instanceof Lt&&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)}
|
|
2784
2794
|
`),1):(n.stderr.write(`error: ${s.message}
|
|
2785
2795
|
`),au()?(n.stderr.write(`(debug details written to ~/.lmctl/debug-*.log)
|
|
2786
2796
|
`),1):(n.stderr.write(`(re-run with --debug for the full stack trace and context in ~/.lmctl/debug-*.log)
|
|
2787
|
-
`),1))}function
|
|
2788
|
-
`);let{runChat:n}=await Promise.resolve().then(()=>(
|
|
2797
|
+
`),1))}function DO(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 XE(t,e,r){switch(t){case"batch":{let{runBatch:n}=await Promise.resolve().then(()=>(cg(),lg));return n(e,r)}case"script":{let{runScript:n}=await Promise.resolve().then(()=>(Pg(),Fg));return n(e,r)}case"prompt":{let{runChat:n}=await Promise.resolve().then(()=>(Qi(),Nc));return n(e,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)
|
|
2798
|
+
`);let{runChat:n}=await Promise.resolve().then(()=>(Qi(),Nc));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(e_(),Zg));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(f_(),m_));return n(e,r)}case"export":{let{runExport:n}=await Promise.resolve().then(()=>(g_(),h_));return n(e,r)}case"cost":{let{runCost:n}=await Promise.resolve().then(()=>(H_(),W_));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(G_(),q_));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>(nr(),id));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>(nr(),id));return n(e,r)}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(wo(),Gy));return n(e,r)}case"init":{let{runInit:n}=await Promise.resolve().then(()=>(Vy(),Jy));return n(e,r)}case"quickrun":{let{runQuickrun:n}=await Promise.resolve().then(()=>(iE(),sE));return n(e,r)}case"hello":{let{runHello:n}=await Promise.resolve().then(()=>(lE(),aE));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(_d(),rE));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Md(),RE));return n(e,r)}case"running":{let{runRunning:n}=await Promise.resolve().then(()=>(FE(),$E));return n(e,r)}case"ratelimit":{let{runRatelimit:n}=await Promise.resolve().then(()=>(BE(),jE));return n(e,r)}case"db":return MO(e,r);default:if(vs()&&Ss(t)){let{runInfraCommand:n}=await Promise.resolve().then(()=>(Uo(),fu));return n(t,e,r)}return qE(r,t)}}async function MO(t,e){let[r,...n]=t;return r==="--help"||r==="-h"||r==="help"?(e.stdout.write(`usage: lmctl db <subcommand>
|
|
2789
2799
|
|
|
2790
2800
|
backfill-events Replay the legacy tables into the event-log
|
|
2791
2801
|
(with --db <copy>) substrate and rebuild projections. Idempotent;
|
|
2792
2802
|
run against a COPY of the DB, never the live file.
|
|
2793
2803
|
downgrade --to <version> --confirm Documented stub (restore from backup).
|
|
2794
|
-
`),0):r==="backfill-events"
|
|
2804
|
+
`),0):r==="backfill-events"?$O(n,e):r==="downgrade"?(e.stderr.write(`not yet implemented; restore from backup, or run lmctl migrate (forward-migrates ok)
|
|
2795
2805
|
`),1):(e.stderr.write(`usage: lmctl db <subcommand> (backfill-events | downgrade)
|
|
2796
|
-
`),1)}async function
|
|
2806
|
+
`),1)}async function $O(t,e){let{resolveDbPath:r}=await Promise.resolve().then(()=>(rt(),Qd)),n=r();if(!((process.env.LMCTL_DB??"").length>0)&&!t.includes("--allow-live"))return e.stderr.write(`refusing to backfill the default live DB.
|
|
2797
2807
|
resolved target: ${n}
|
|
2798
2808
|
run against a COPY: cp <state.db> copy.db && lmctl --db copy.db db backfill-events
|
|
2799
2809
|
(or pass --allow-live to target the resolved DB deliberately).
|
|
2800
|
-
`),1;let{migrate:i}=await Promise.resolve().then(()=>(
|
|
2801
|
-
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===
|
|
2810
|
+
`),1;let{migrate:i}=await Promise.resolve().then(()=>(As(),Su)),{backfillEventLog:o}=await Promise.resolve().then(()=>(Jo(),hu)),a=i({dbPath:n});try{let l=o(a);return e.stdout.write(`${JSON.stringify(l,null,2)}
|
|
2811
|
+
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===NO(process.argv[1]).href){let t=await LO(process.argv.slice(2));process.exitCode=t}export{WE as COMMANDS,LO as runCli};
|