@lmctl-ai/lmctl 0.2.44 → 0.2.46
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/build-info.json +1 -1
- package/dist/cli/index.js +418 -419
- package/dist/cli/script.js +199 -200
- package/package.json +1 -1
package/dist/cli/script.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}catch{}}function
|
|
3
|
-
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function
|
|
1
|
+
var Q_=Object.create;var po=Object.defineProperty;var Z_=Object.getOwnPropertyDescriptor;var ey=Object.getOwnPropertyNames;var ty=Object.getPrototypeOf,ry=Object.prototype.hasOwnProperty;var L=(t,e)=>()=>(t&&(e=t(t=0)),e);var ny=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Wc=(t,e)=>{for(var r in e)po(t,r,{get:e[r],enumerable:!0})},sy=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ey(e))!ry.call(t,s)&&s!==r&&po(t,s,{get:()=>e[s],enumerable:!(n=Z_(e,s))||n.enumerable});return t};var Xc=(t,e,r)=>(r=t!=null?Q_(ty(t)):{},sy(e||!t||!t.__esModule?po(r,"default",{value:t,enumerable:!0}):r,t));import{readFileSync as dd,appendFileSync as yy,mkdirSync as Ey,existsSync as cR,readdirSync as dR,unlinkSync as uR}from"node:fs";import{join as cs,dirname as Ty}from"node:path";import{homedir as wy}from"node:os";function vo(){return cs(wy(),".lmctl")}function ae(){if(ud||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-cd>=Sy&&(ld=Iy(),cd=t),ld}function vy(){let t=new Date,e=t.getTimezoneOffset(),r=e<=0?"+":"-",n=String(Math.floor(Math.abs(e)/60)).padStart(2,"0"),s=String(Math.abs(e)%60).padStart(2,"0");return new Date(t.getTime()-e*6e4).toISOString().replace("Z",`${r}${n}:${s}`)}function Se(t,e){if(e?.verbose){if(!ud)return}else if(!e?.always&&!ae())return;try{by();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};yy(ls,JSON.stringify(r)+`
|
|
2
|
+
`)}catch{}}function by(){if(!ls){let e=vy().slice(0,13).replace("T","-");ls=cs(vo(),`debug-${e}.log`)}Ey(Ty(ls),{recursive:!0})}function Le(...t){Se({event:"legacy",msg:t.join(" ")})}function ge(...t){Se({event:"legacy",msg:t.join(" ")},{verbose:!0})}function D(t){Se(t,{always:!0})}function Iy(){return xy()||ky()}function xy(){try{let t=dd(cs(vo(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
3
|
+
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function ky(){try{let t=dd(cs(vo(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var ud,ld,cd,Sy,ls,re=L(()=>{"use strict";ud=!1,ld=!1,cd=0,Sy=5e3;ls=null});import{existsSync as Py}from"node:fs";import{createRequire as $y}from"node:module";function Uy(){return xo===null&&(xo=$y(import.meta.url)("node:sqlite").DatabaseSync),xo}function Hy(t){let e=By[t];if(e!==void 0)return e;let r=jy[t&255];return r!==void 0?r:`SQLITE_UNKNOWN_${t}`}function Ht(t){throw t&&typeof t=="object"&&"errcode"in t&&typeof t.errcode=="number"&&(t.code=Hy(t.errcode)),t}function Wy(t){return t instanceof Error&&/cannot rollback - no transaction is active/i.test(t.message)}function Xy(t){return t instanceof Error&&/no such savepoint:/i.test(t.message)}function ko(t){return t.length===1&&qy(t[0])?[t[0]]:t}function qy(t){if(!Ro(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Ro(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var xo,jy,By,Ao,mr,No,gs=L(()=>{"use strict";xo=null;jy={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",23:"SQLITE_AUTH",25:"SQLITE_RANGE",26:"SQLITE_NOTADB"},By={275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE",261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB"};Ao=class{name;handle;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!Py(e))throw new Error("unable to open database file");this.name=e;try{this.handle=new(Uy())(e,{readOnly:r.readonly===!0})}catch(n){Ht(n)}this.exec("PRAGMA busy_timeout = 5000"),this.exec(`PRAGMA foreign_keys = ${r.foreignKeys===!0?"ON":"OFF"}`)}prepare(e){try{return new No(this.handle.prepare(e))}catch(r){Ht(r)}}exec(e){try{this.handle.exec(e)}catch(r){Ht(r)}}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}if(r?.simple===!0){let s=this.prepare(n).get();return s===void 0?void 0:Object.values(s)[0]}return this.prepare(n).all()}transaction(e){let r=(...n)=>this.runTransaction("BEGIN",e,n);return r.immediate=(...n)=>this.runTransaction("BEGIN IMMEDIATE",e,n),r}get inTransaction(){return this.handle.isTransaction}close(){try{this.handle.close()}catch(e){Ht(e)}}runTransaction(e,r,n){if(!this.inTransaction){this.exec(e);try{let i=r(...n);return this.exec("COMMIT"),i}catch(i){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(o){if(!Wy(o))throw o}throw i}}let s=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${s}`);try{let i=r(...n);return this.exec(`RELEASE ${s}`),i}catch(i){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${s}`),this.exec(`RELEASE ${s}`)}catch(o){if(!Xy(o))throw o}throw i}}};mr=Ao,No=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){try{let r=this.handle.get(...ko(e));return this.normalizeRow(r)}catch(r){Ht(r)}}all(...e){try{return this.handle.all(...ko(e)).map(r=>this.normalizeRow(r))}catch(r){Ht(r)}}run(...e){try{let r=this.handle.run(...ko(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){Ht(r)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Ro(e)?Object.values(e):Ro(e)?{...e}:e}}});import{createHash as Gy}from"node:crypto";function Jy(t,e,r){return Gy("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function Ae(t,e,r){let n=Jy(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)
|
|
4
4
|
VALUES (?, ?, ?, ?, ?)
|
|
5
|
-
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
|
|
5
|
+
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 _s=L(()=>{"use strict"});import{createHash as Vy}from"node:crypto";function Wt(t,e){return t==null?null:{teamfile:t,alias:e??""}}function Ky(t,e,r){return`lease_${Vy("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function ys(t,e,r,n){r.forEach((s,i)=>{Ae(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 Yy(t){let e=`msg_tcl_${t.id}`,r=Wt(t.sender_teamfile,t.sender_alias),n=Wt(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:Z.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:Z.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 zy(t){let e=`msg_mbx_${t.id}`,r=Wt(t.sender_teamfile,t.sender_alias),n=Wt(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:Z.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:Z.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:Z.RESPONSE_DELIVERED,ts:t.delivered_at,payload:{...i,message_type:"response",receipt:t.receipt}}),{streamId:e,events:o}}return o.push({event_type:Z.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:Z.ENQUEUE,ts:t.created_at,payload:{...i,message_type:"request"}}),t.waited_at!==null&&o.push({event_type:Z.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:Z.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:Z.DELIVERED,ts:t.delivered_at,payload:{...i,receipt:t.receipt}}),{streamId:e,events:o}}function Qy(t){let e=`inv_${t.id}`,r=Wt(t.target_teamfile,t.target_alias),n={table:"tracked_invocation",id:t.id},s=[{event_type:Z.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:Z.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:Z.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 Zy(t){let e=Ky(t.receiver_teamfile,t.receiver_alias,t.started_at),r=Wt(t.receiver_teamfile,t.receiver_alias),n=Wt(t.sender_teamfile,t.sender_alias);return{streamId:e,events:[{event_type:Z.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 Es(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Td(t){let e={appended:0,skipped:0},r={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};t.transaction(()=>{if(Es(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}=Yy(i);ys(t,a,l,e),r.team_chat_log+=e.appended+e.skipped-o}if(Es(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}=zy(i);ys(t,a,l,e),r.agent_mailbox+=e.appended+e.skipped-o}if(Es(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}=Qy(i);ys(t,a,l,e),r.tracked_invocation+=e.appended+e.skipped-o}if(Es(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}=Zy(i);ys(t,a,l,e),r.agent_inflight+=e.appended+e.skipped-o}eE(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 eE(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);tE(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 tE(t,e,r,n,s){switch(n){case Z.ENQUEUE:case Z.RESPONSE_ENQUEUE:{let i=n===Z.RESPONSE_ENQUEUE;t.prepare(`INSERT INTO message_pending
|
|
6
6
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
7
7
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
8
8
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
@@ -26,7 +26,7 @@ var ry=Object.create;var ho=Object.defineProperty;var ny=Object.getOwnPropertyDe
|
|
|
26
26
|
cwd, command, request_message_id, request_payload, holder_pid, holder_host, status, started_at, last_seq)
|
|
27
27
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)
|
|
28
28
|
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 Z.INVOCATION_FINISH:t.prepare(`UPDATE invocation_state SET status=?, ended_at=?, result_summary=?, error=?, last_seq=?
|
|
29
|
-
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case Z.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 Z,
|
|
29
|
+
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case Z.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 Z,wd=L(()=>{"use strict";_s();Z={CREATE:"CREATE",ENQUEUE:"ENQUEUE",DELIVER_CLAIM:"DELIVER_CLAIM",DELIVER_CLAIM_RELEASE:"DELIVER_CLAIM_RELEASE",DELIVERED:"DELIVERED",HANDLED:"HANDLED",WAIT_REGISTER:"WAIT_REGISTER",RESPONSE_CREATE:"RESPONSE_CREATE",RESPONSE_ENQUEUE:"RESPONSE_ENQUEUE",RESPONSE_DELIVERED:"RESPONSE_DELIVERED",INFLIGHT_TAKE:"INFLIGHT_TAKE",INFLIGHT_RELEASE:"INFLIGHT_RELEASE",INFLIGHT_RECLAIM:"INFLIGHT_RECLAIM",TERMINAL_LOCK_TAKE:"TERMINAL_LOCK_TAKE",TERMINAL_LOCK_RELEASE:"TERMINAL_LOCK_RELEASE",TERMINAL_LOCK_EXPIRE:"TERMINAL_LOCK_EXPIRE",INVOCATION_START:"INVOCATION_START",INVOCATION_FINISH:"INVOCATION_FINISH",INVOCATION_NOTIFY_CLAIM:"INVOCATION_NOTIFY_CLAIM"}});import{existsSync as rE,mkdirSync as nE,readFileSync as bd}from"node:fs";import{randomUUID as sE}from"node:crypto";import{homedir as iE}from"node:os";import{dirname as Id,join as oE,resolve as xd}from"node:path";import{fileURLToPath as aE,pathToFileURL as lE}from"node:url";function Ts(t){t.dbPath!==":memory:"&&nE(Id(t.dbPath),{recursive:!0});let e=new mr(t.dbPath);try{e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=Nd(e),n=t.buildVersionForTests??St;if(r===0)e.exec(bd(Ad,"utf8")),e.pragma(`user_version = ${St}`);else if(r>n){let s=fE(e,r);if(pE={dbVersion:r,buildVersion:n},s>n&&!t.allowSchemaSkew)throw e.close(),new on(t.dbPath,r,n);return mE(t.dbPath,r,n),e}return dE(e,r),uE(e),e}catch(r){try{e.close()}catch{}throw r}}function dE(t,e){let r=e;if(r<2&&r!==0&&(t.exec(`
|
|
30
30
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
31
31
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
32
32
|
team_name TEXT NOT NULL,
|
|
@@ -565,7 +565,7 @@ var ry=Object.create;var ho=Object.defineProperty;var ny=Object.getOwnPropertyDe
|
|
|
565
565
|
ON agent_mailbox(sender_teamfile, sender_alias, created_at);
|
|
566
566
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_created
|
|
567
567
|
ON agent_mailbox(created_at);
|
|
568
|
-
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(We(t,"team_chat_log")?
|
|
568
|
+
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(We(t,"team_chat_log")?Sd(t):t.exec(`
|
|
569
569
|
CREATE TABLE IF NOT EXISTS team_chat_log (
|
|
570
570
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
571
571
|
root_teamfile TEXT NOT NULL,
|
|
@@ -584,7 +584,7 @@ var ry=Object.create;var ho=Object.defineProperty;var ny=Object.getOwnPropertyDe
|
|
|
584
584
|
`),t.exec(`
|
|
585
585
|
CREATE INDEX IF NOT EXISTS idx_team_chat_log_root_time
|
|
586
586
|
ON team_chat_log(root_teamfile, created_at);
|
|
587
|
-
`),t.pragma("user_version = 46"),r=46),r>=46&&We(t,"team_chat_log")&&!z(t,"team_chat_log").has("origin")&&
|
|
587
|
+
`),t.pragma("user_version = 46"),r=46),r>=46&&We(t,"team_chat_log")&&!z(t,"team_chat_log").has("origin")&&Sd(t),r<47&&r!==0){if(wt(t,"tracked_invocation"),We(t,"agent_mailbox")){let s=z(t,"agent_mailbox");s.has("delivered_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivered_at TEXT;"),s.has("receipt")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN receipt TEXT;")}let n=z(t,"tracked_invocation");n.has("notified_by")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_by TEXT;"),n.has("notified_at")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_at TEXT;"),t.pragma("user_version = 47"),r=47}if(r<48&&r!==0){if(We(t,"agent_mailbox")){let n=z(t,"agent_mailbox");n.has("delivering_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivering_at TEXT;"),n.has("delivery_holder_pid")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_pid INTEGER;"),n.has("delivery_holder_host")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_host TEXT;"),n.has("waited_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_at TEXT;"),n.has("waited_by")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_by TEXT;"),t.exec(`
|
|
588
588
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_sender_delivery_wait
|
|
589
589
|
ON agent_mailbox(sender_teamfile, sender_alias, delivered_at, waited_at, id);
|
|
590
590
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_lane_delivery
|
|
@@ -747,7 +747,7 @@ var ry=Object.create;var ho=Object.defineProperty;var ny=Object.getOwnPropertyDe
|
|
|
747
747
|
ON tracked_invocation(scope_teamfile, status, started_at);
|
|
748
748
|
CREATE INDEX IF NOT EXISTS idx_tracked_invocation_status_ended
|
|
749
749
|
ON tracked_invocation(status, ended_at);
|
|
750
|
-
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(We(t,"agent_mailbox")&&
|
|
750
|
+
`),t.pragma("user_version = 56"),r=56),r<57&&r!==0&&(We(t,"agent_mailbox")&&Td(t),t.exec("DROP TABLE IF EXISTS agent_mailbox;"),t.pragma("user_version = 57"),r=57),r<58&&r!==0&&(wt(t,"tracked_invocation"),z(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(`
|
|
751
751
|
CREATE TABLE IF NOT EXISTS state_ledger_identity (
|
|
752
752
|
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
753
753
|
instance_id TEXT NOT NULL,
|
|
@@ -836,7 +836,7 @@ CREATE TABLE IF NOT EXISTS prompt_task_reassignments(
|
|
|
836
836
|
);
|
|
837
837
|
|
|
838
838
|
CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_reassignments(prompt_id);
|
|
839
|
-
`),t.exec("INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '61')"),t.pragma("user_version = 62"),r=62),
|
|
839
|
+
`),t.exec("INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '61')"),t.pragma("user_version = 62"),r=62),rE(cE)}function uE(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(sE(),new Date().toISOString())}function z(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function We(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function wt(t,e){if(!We(t,e)&&(t.exec(bd(Ad,"utf8")),!We(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function Sd(t){let e=z(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
840
840
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
841
841
|
CREATE TABLE team_chat_log_v46 (
|
|
842
842
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -865,10 +865,10 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
865
865
|
FROM team_chat_log;
|
|
866
866
|
DROP TABLE team_chat_log;
|
|
867
867
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
868
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function
|
|
868
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function Nd(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function fE(t,e){try{if(!We(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 mE(t,e,r=St){vd||(vd=!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
|
|
869
869
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:r,mode:"best_effort"}})}
|
|
870
|
-
`))}function
|
|
871
|
-
`)}finally{t.close()}}});function
|
|
870
|
+
`))}function hE(){return process.env.LMCTL_DB??oE(iE(),".lmctl","state.db")}var kd,Ad,cE,St,on,vd,pE,Rd=L(()=>{"use strict";gs();wd();kd=Id(aE(import.meta.url)),Ad=xd(kd,"schema.sql"),cE=xd(kd,"migrations"),St=62,on=class extends Error{dbPath;dbVersion;buildVersion;constructor(e,r,n=St){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}};vd=!1;pE=null;if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===lE(process.argv[1]).href){let t=Ts({dbPath:process.argv[2]??hE()});try{process.stdout.write(`migrated user_version=${Nd(t)}
|
|
871
|
+
`)}finally{t.close()}}});function Ld(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(`
|
|
872
872
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
873
873
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
874
874
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
@@ -1004,7 +1004,7 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1004
1004
|
AND sender_teamfile = ?
|
|
1005
1005
|
AND sender_alias = ?
|
|
1006
1006
|
AND active_count > 1
|
|
1007
|
-
`),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}var
|
|
1007
|
+
`),clearAgentInflightOlderThan:t.prepare("DELETE FROM agent_inflight WHERE started_at < ?")}}var Cd=L(()=>{"use strict"});function Dd(t){return{insertTrackedInvocation:t.prepare(`
|
|
1008
1008
|
INSERT INTO tracked_invocation (
|
|
1009
1009
|
kind, origin, scope_teamfile, from_identity, target_teamfile, target_alias,
|
|
1010
1010
|
root_teamfile, cwd, command, status, started_at, holder_pid, holder_host,
|
|
@@ -1084,37 +1084,37 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1084
1084
|
AND holder_host IS ?
|
|
1085
1085
|
AND started_at = ?
|
|
1086
1086
|
AND last_heartbeat_at IS ?
|
|
1087
|
-
`)}}function Pe(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(
|
|
1088
|
-
...[truncated]`});function
|
|
1087
|
+
`)}}function Pe(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(Od,"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")}${Od}`}var Od,Md=L(()=>{"use strict";Od=`
|
|
1088
|
+
...[truncated]`});function cn(t,e){return JSON.stringify([t,e])}function Fd(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 an,ln,Pd=L(()=>{"use strict";an="terminal_lock",ln="member"});function ve(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 Xt=L(()=>{"use strict"});import{hostname as pr}from"node:os";function ws(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??gE);return r.unref?.(),r}function hr(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(!vs(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 jd(t){return t.status!=="running"?null:t.holder_host===pr()&&t.holder_pid!==null&&t.holder_pid>0?ve(t.holder_pid)?"live":"dead":"unknown"}function Ss(t,e,r){let n,s=t.getTerminalLock(e,r);if(s!==null){if(_E(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===pr()?"dead-pid":"stale"}}let i=yE(t,e,r);if(i!==null){if(EE(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===pr())?"dead-pid":"stale"}}let o=t.getAgentInflight(e,r);if(o!==null){let a=new Date(Date.now()-gr()).toISOString();if(!vs(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:pr(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function _E(t){if(t.holder_host===pr())return ve(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=wE():!1}function yE(t,e,r){return t.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1089
1089
|
FROM tracked_invocation
|
|
1090
1090
|
WHERE target_teamfile = ?
|
|
1091
1091
|
AND target_alias = ?
|
|
1092
1092
|
AND status = 'running'
|
|
1093
1093
|
AND launch_source = 'terminal'
|
|
1094
1094
|
ORDER BY started_at DESC, id DESC
|
|
1095
|
-
LIMIT 1`,e,r)[0]??null}function
|
|
1095
|
+
LIMIT 1`,e,r)[0]??null}function EE(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===pr())?ve(t.holder_pid):TE(t)}function TE(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=gr():!1}function vs(t,e){return t.holder_pid===null?t.started_at<e:!ve(t.holder_pid)}function gr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return $d;let r=Number(e);return!Number.isFinite(r)||r<=0?$d:r}function wE(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return Ud;let r=Number(e);return!Number.isFinite(r)||r<=0?Ud:r}var $d,Ud,gE,qt=L(()=>{"use strict";Xt();$d=8*60*60*1e3,Ud=12e4,gE=3e4});import{randomUUID as SE}from"node:crypto";import{hostname as vE}from"node:os";function vt(t,e){return{teamfile:t,alias:e}}function Bd(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 Lo(t,e){return t===null?null:vt(t,e??"")}function lt(t){return`msg_tcl_${t}`}function Gt(t){return`inv_${t}`}function _r(t,e,r){return t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1096
1096
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1097
1097
|
terminal_invocation_id, currently_handling_message_id,
|
|
1098
1098
|
currently_handling_since, last_seq
|
|
1099
1099
|
FROM agent_state
|
|
1100
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function
|
|
1100
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function IE(t,e,r){if(e===null||r===null)return null;let n=t.prepare(`SELECT currently_handling_message_id, currently_handling_since
|
|
1101
1101
|
FROM agent_state
|
|
1102
|
-
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>
|
|
1102
|
+
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>bE?null:n.currently_handling_message_id}function xE(t,e,r){let n=IE(t,e,r);return n===null?{}:{causation:{request_message_id:n}}}function Co(t,e,r,n,s=new Date().toISOString()){t.prepare(`INSERT INTO agent_state
|
|
1103
1103
|
(receiver_teamfile, receiver_alias, currently_handling_message_id,
|
|
1104
1104
|
currently_handling_since, last_seq)
|
|
1105
1105
|
VALUES (?, ?, ?, ?, 0)
|
|
1106
1106
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
1107
1107
|
currently_handling_message_id = excluded.currently_handling_message_id,
|
|
1108
|
-
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function
|
|
1108
|
+
currently_handling_since = excluded.currently_handling_since`).run(e,r,n,s)}function Oo(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1109
1109
|
SET currently_handling_message_id = NULL,
|
|
1110
1110
|
currently_handling_since = NULL
|
|
1111
1111
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1112
|
-
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function
|
|
1112
|
+
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function kE(t,e){let r=e??new Date(Date.now()-gr()).toISOString();return vs({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function AE(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!ve(t.holder_pid)?"dead-pid":"stale"}function NE(t){return{sender:Lo(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function yr(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function Do(t,e,r){let n=lt(e),s=Lo(r.sender_teamfile,r.sender_alias),i=Bd(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 Ae(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,...xE(t,r.sender_teamfile,r.sender_alias)}},()=>{Co(t,r.receiver_teamfile,r.receiver_alias,n,r.created_at)}),n}function bs(t,e,r){let n=lt(e),s={message_id:n,message_type:"request",sender:Lo(r.sender_teamfile,r.sender_alias),receiver:Bd(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 Ae(t,{stream_id:n,event_type:"HANDLED",observedLastSeq:1,ts:r.created_at,payload:{...s,outcome:r.status,receipt:r.response,error:r.error_detail,truncated:r.truncated===1}},()=>{Oo(t,r.receiver_teamfile,r.receiver_alias,n)}),n}function RE(t){return{sender:vt(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at}}function Hd(t,e,r,n){let s=t.prepare(`UPDATE agent_state
|
|
1113
1113
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1114
1114
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1115
1115
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1116
1116
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1117
|
-
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);yr(s.changes,n)}function
|
|
1117
|
+
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);yr(s.changes,n)}function Wd(t,e,r,n,s=null,i=!1){let o=vE();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=_r(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||kE(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let u=AE(a,n,i),f=NE(a),p=a.lease_id;Ae(t,{stream_id:p,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:vt(e.receiver_teamfile,e.receiver_alias),reason:u,previous_holder:f}},_=>Hd(t,a,_,"INFLIGHT_RECLAIM")),a=_r(t,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${SE()}`;return Ae(t,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:vt(e.receiver_teamfile,e.receiver_alias),sender:vt(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
|
|
1118
1118
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1119
1119
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1120
1120
|
last_heartbeat_at, last_seq)
|
|
@@ -1123,18 +1123,18 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1123
1123
|
holder_pid = ?, holder_host = ?, started_at = ?,
|
|
1124
1124
|
last_heartbeat_at = ?, last_seq = ?
|
|
1125
1125
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1126
|
-
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);yr(u.changes,"INFLIGHT_TAKE")}),c}function
|
|
1126
|
+
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);yr(u.changes,"INFLIGHT_TAKE")}),c}function Xd(t,e,r,n){return t.prepare(`UPDATE agent_state
|
|
1127
1127
|
SET last_heartbeat_at = ?
|
|
1128
1128
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1129
1129
|
AND lease_id = ?
|
|
1130
1130
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1131
|
-
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
|
|
1131
|
+
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 dn(t,e,r,n){let s=_r(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||Ae(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:vt(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:RE(e)}:{lease_id:s.lease_id}}},i=>Hd(t,s,i,r))}function qd(t,e){let r=_r(t,e.teamfile,e.alias),n=r?.last_seq??0;Ae(t,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:vt(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
|
|
1132
1132
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1133
1133
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1134
1134
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1135
|
-
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);yr(i.changes,"TERMINAL_LOCK_TAKE")})}function
|
|
1135
|
+
AND terminal_lock_id IS NULL AND last_seq = ?`).run(e.lock_id,s,e.teamfile,e.alias,r.last_seq);yr(i.changes,"TERMINAL_LOCK_TAKE")})}function Mo(t,e,r=!1){let n=_r(t,e.teamfile,e.alias);n===null||n.terminal_lock_id!==e.lock_id||Ae(t,{stream_id:e.lock_id,event_type:r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE",observedLastSeq:n.last_seq,payload:{receiver:vt(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 = ?
|
|
1136
1136
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1137
|
-
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);yr(i.changes,r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function
|
|
1137
|
+
AND terminal_lock_id = ? AND last_seq = ?`).run(s,e.teamfile,e.alias,e.lock_id,n.last_seq);yr(i.changes,r?"TERMINAL_LOCK_EXPIRE":"TERMINAL_LOCK_RELEASE")})}function Gd(t,e,r){let n=_r(t,r.targetTeamfile,r.targetAlias);if(n===null){t.prepare(`INSERT INTO agent_state
|
|
1138
1138
|
(receiver_teamfile, receiver_alias, terminal_invocation_id,
|
|
1139
1139
|
terminal_invocation_pid, terminal_invocation_host,
|
|
1140
1140
|
terminal_invocation_heartbeat_at, last_seq)
|
|
@@ -1143,24 +1143,24 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1143
1143
|
terminal_invocation_host = ?,
|
|
1144
1144
|
terminal_invocation_heartbeat_at = ?, last_seq = ?
|
|
1145
1145
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1146
|
-
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);yr(s.changes,"terminal INVOCATION_START")}function
|
|
1146
|
+
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);yr(s.changes,"terminal INVOCATION_START")}function Jd(t,e,r){return t.prepare(`UPDATE agent_state
|
|
1147
1147
|
SET terminal_invocation_heartbeat_at = ?
|
|
1148
|
-
WHERE terminal_invocation_id = ?`).run(r,e).changes===1}function
|
|
1148
|
+
WHERE terminal_invocation_id = ?`).run(r,e).changes===1}function Vd(t,e,r){let n=t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, terminal_lock_id,
|
|
1149
1149
|
terminal_invocation_id, last_seq
|
|
1150
1150
|
FROM agent_state WHERE terminal_invocation_id = ?`).get(r);if(n===void 0)return;let s=t.prepare(`UPDATE agent_state
|
|
1151
1151
|
SET terminal_invocation_id = NULL, terminal_invocation_pid = NULL,
|
|
1152
1152
|
terminal_invocation_host = NULL,
|
|
1153
1153
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1154
1154
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1155
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);yr(s.changes,"terminal INVOCATION_FINISH")}var
|
|
1155
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);yr(s.changes,"terminal INVOCATION_FINISH")}var bE,Is=L(()=>{"use strict";_s();qt();Xt();bE=60*60*1e3});function Kd(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function Fo(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function Yd(t,e){let r=Gt(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;Ae(t,{stream_id:r,event_type:LE,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
|
|
1156
1156
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1157
1157
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1158
1158
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1159
|
-
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),
|
|
1159
|
+
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),Fo(e)&&Gd(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function xs(t,e){let r=Gt(e.id),n=Kd(t,r);return n===null?!1:(Ae(t,{stream_id:r,event_type:CE,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
|
|
1160
1160
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1161
|
-
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}`);
|
|
1161
|
+
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}`);Fo(e)&&Vd(t,s,r)}),!0)}function zd(t,e,r,n){let s=Gt(e.id),i=Kd(t,s);return i===null?!1:(Ae(t,{stream_id:s,event_type:OE,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:r,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(r,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function Qd(t,e,r){let n=Gt(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),Fo(e)&&Jd(t,n,r)}function Zd(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,Gt(e))}function eu(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,Gt(e))}var LE,CE,OE,tu=L(()=>{"use strict";_s();Is();LE="INVOCATION_START",CE="INVOCATION_FINISH",OE="INVOCATION_NOTIFY_CLAIM"});var DE,ME,F0,ru,nu,su,iu=L(()=>{"use strict";DE="other",ME=["not_enough_information","dont_know","other_work"],F0=new Set([DE,...ME]),ru="@abort",nu="invalid_decision",su="workflow_escalation"});import{randomUUID as ou}from"node:crypto";import{existsSync as uu,mkdirSync as FE,renameSync as PE,rmdirSync as $E}from"node:fs";import{hostname as Po}from"node:os";function $o(t){return t.provider_resolved??t.provider}function j(){return new Date().toISOString()}function UE(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!uu(t))return e;let r;try{r=new mr(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 jE(t){if(t===":memory:"||!uu(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{PE(n,`${e}${r}`)}catch{}}return e}function au(t,e){let r=e instanceof Error?e.message:String(e);try{let n=UE(t),s=jE(t),i=new ks(Ts({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${St} (${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}.
|
|
1162
1162
|
`:`
|
|
1163
|
-
`)),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
|
|
1163
|
+
`)),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 lu(t,e){let r;try{return r=Ts({dbPath:t,allowSchemaSkew:e}),{dal:new ks(r)}}catch(n){if(n instanceof on)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 XE(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function qE(t){if(t===":memory:")return!0;try{return FE(`${t}${fu}`),!0}catch{return!1}}function GE(t){if(t!==":memory:")try{$E(`${t}${fu}`)}catch{}}function Jt(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<BE;n+=1)if(r=lu(t.path,e),r.dal!==void 0)return r.dal;if(r.dbVersion!==void 0&&r.dbVersion>St){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${St}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<HE;n+=1){if(qE(t.path))try{return au(t.path,r.cause)}finally{GE(t.path)}XE(WE);let s=lu(t.path,e);if(s.dal!==void 0)return s.dal}return au(t.path,r.cause)}function cu(t,e,r){let n=du(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 du(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 du(t){let e=JE(t),r=e===null?null:VE(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))As(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function JE(t){try{let e=JSON.parse(t);return As(e)?e:null}catch{return null}}function VE(t,e){let r=t[e];return As(r)?r:null}function As(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function KE(t){try{let e=JSON.parse(t);return!As(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 YE(t,e){return t===null?!0:t.holder_host===Po()?!ve(t.holder_pid):t.last_heartbeat<e}function zE(t){return{getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
1164
1164
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
1165
1165
|
VALUES (?, ?, ?, ?, ?)
|
|
1166
1166
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1567,132 +1567,132 @@ CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_r
|
|
|
1567
1567
|
response = NULL
|
|
1568
1568
|
WHERE id = ?
|
|
1569
1569
|
AND status = 'running'
|
|
1570
|
-
`),...Md(t),...Cd(t)}}function rT(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var qE,mu,GE,JE,Rs,Er=L(()=>{"use strict";Es();Ld();Od();Fd();$d();Xt();As();ru();ou();qE=3,mu=".recovery.lock",GE=20,JE=50;Rs=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=tT(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let _=this.getJob(a.id);return{claimed:!1,reason:_?.locked_until!==null&&_?.locked_until!==void 0&&_.locked_until>=i?"locked":"not_claimable",job_id:r,status:_?.status??a.status,locked_by:_?.locked_by??a.locked_by,locked_until:_?.locked_until??a.locked_until}}let p=this.getJob(a.id);return p===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:p}}),this.resumeRunTxn=e.transaction((r,n,s)=>rT("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!==iu)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!==nu&&!a.includes(n))return{resumed:!1,reason:su};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=Xd(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){du(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,j()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,j());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){du(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,j());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,j())}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,j());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,j()),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,j(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(j(),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,j());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,j());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,j(),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,j());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",j());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,j());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=j(),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,j(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,j(),e)??null}closeIssue(e,r,n){let s=j(),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,j(),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,j(),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=j();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,j(),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,j(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=au(),s=j();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=j(),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,j())}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??j(),e.dedupe_key??null,e.concurrency_key??null,j());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=j(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=j(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=j(),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:j();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,j()),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,j()),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??j(),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,j());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=j(),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,j(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(j(),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 Mo(this.db,n,e),ks(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 Mo(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}`);ks(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{Oo(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>Do(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??j(),n=e.holder_host??$o(),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,Pe(e.command),r,e.holder_pid??null,n,s,Pe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return zd(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(`
|
|
1570
|
+
`),...Dd(t),...Ld(t)}}function QE(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var BE,fu,HE,WE,ks,Er=L(()=>{"use strict";gs();Rd();Cd();Md();Pd();Xt();Is();tu();iu();BE=3,fu=".recovery.lock",HE=20,WE=50;ks=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=zE(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let _=this.getJob(a.id);return{claimed:!1,reason:_?.locked_until!==null&&_?.locked_until!==void 0&&_.locked_until>=i?"locked":"not_claimable",job_id:r,status:_?.status??a.status,locked_by:_?.locked_by??a.locked_by,locked_until:_?.locked_until??a.locked_until}}let p=this.getJob(a.id);return p===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:p}}),this.resumeRunTxn=e.transaction((r,n,s)=>QE("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!==su)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!==ru&&!a.includes(n))return{resumed:!1,reason:nu};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=Wd(this.db,o,s,l,n.stale_before??null,n.force===!0);a={acquired:!0,current:o,lease_id:c}}else a={acquired:!1,current:this.getAgentInflight(r.receiver_teamfile,r.receiver_alias)??(()=>{throw new Error("agent_inflight conflict row disappeared during acquire")})()};return this.db.exec("COMMIT"),a}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}}close(){this.db.close()}query(e,...r){let n=e.trim().toLowerCase();if(!n.startsWith("select")&&!n.startsWith("with")&&!n.startsWith("pragma"))throw new Error("Dal.query only allows read-only SELECT/WITH/PRAGMA statements");return this.db.prepare(e).all(...r)}insertWorkflow(e){cu(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,j()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,j());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){cu(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,j());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,j())}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,j());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,j()),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,j(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(j(),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,j());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,j());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,j(),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,j());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",j());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,j());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=j(),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,j(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,j(),e)??null}closeIssue(e,r,n){let s=j(),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,j(),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,j(),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=j();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,j(),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,j(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=ou(),s=j();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=j(),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,j())}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??j(),e.dedupe_key??null,e.concurrency_key??null,j());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=j(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=j(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=j(),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:j();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,j()),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,j()),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??j(),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,j());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=j(),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,j(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(j(),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 Do(this.db,n,e),bs(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 Do(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}`);bs(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{Co(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>Oo(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??j(),n=e.holder_host??Po(),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,Pe(e.command),r,e.holder_pid??null,n,s,Pe(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Yd(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(`
|
|
1571
1571
|
SELECT * FROM tracked_invocation
|
|
1572
1572
|
WHERE parent_invocation_id IN (${n})
|
|
1573
1573
|
AND ended_at IS NOT NULL
|
|
1574
1574
|
AND ended_at >= ?
|
|
1575
1575
|
ORDER BY started_at ASC, id ASC
|
|
1576
|
-
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??j();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Pe(r.result_summary),Pe(r.error),r.team_chat_log_id??null,Pe(r.meta),Pe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return
|
|
1577
|
-
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&&mn(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&&(mn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(dn,fn(e,r),un);return n===void 0?null:Pd(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Fo(this.db,n,!0),this.stmts.upsertRuntimeState.run(dn,fn(e.teamfile,e.alias),un,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Gd(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(dn,fn(e,r),un,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(dn,fn(e,r),un);return i.changes===1&&Fo(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:ZE(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=j()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!eT(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:au(),holder_pid:process.pid,holder_host:$o(),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,j(),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,j())}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,j());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,j(),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??j(),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,j());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,j()).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,j()),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,j());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(j(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=j();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??j());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,j())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,j())}}});var Ho=ay(be=>{"use strict";function Tr(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 hu(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left", "right", or "decimal" per column');return t.map(e=>{if(e!=="left"&&e!=="right"&&e!=="decimal")throw new TypeError('align entries must be "left", "right", or "decimal"');return e})}function ct(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 jo(t,e,r){let n=" ".repeat(Math.max(0,e-ct(t)));return r?n+t:t+n}function gu(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 nT(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 sT(t,e,r="\u2026"){if(ct(t)<=e)return t;let n=ct(r)>e?"\u2026":r,s=ct(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=ct(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function iT(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 _u(t){let e=/^(?:[+-]?\$?|\$[+-]?)(?:\d+|\d{1,3}(?:,\d{3})+|(?=\.))(?:\.(\d+))?$/.exec(t);return!e||!/\d/.test(t)?null:{places:e[1]?.length??0}}function oT(t){if(t!==void 0){if(!Array.isArray(t)||t.some(e=>!Number.isInteger(e)||e<0))throw new TypeError("decimalPlaces must be an array of nonnegative integers");return t}}function yu(t){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let e=[];for(let r of t){let n=gu(r);n.headers!==void 0&&Tr(n.headers);for(let s of n.rows.map(Tr))s.forEach((i,o)=>{e[o]=Math.max(e[o]??0,_u(i)?.places??0)})}return e}be.measureDecimalPlaces=yu;function Eu(t,e,r){let n=oT(r)??[],s=e.includes("decimal")?yu(t):[];return Array.from({length:Math.max(n.length,s.length)},(i,o)=>Math.max(n[o]??0,s[o]??0))}function Tu(t,e){let r=_u(t);if(!r)return null;let n=r.places?r.places+1:0,s=e?e+1:0;return t+" ".repeat(Math.max(0,s-n))}function wu(t,{max:e,align:r,decimalPlaces:n}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let s=iT(e),i=hu(r),o=Eu(t,i,n),a=[],l=(c,d)=>{a[c]=Math.max(a[c]??0,d)};for(let c of t){let d=gu(c);d.headers!==void 0&&Tr(d.headers).forEach((u,f)=>{l(f,ct(u))});for(let u of d.rows.map(Tr))u.forEach((f,p)=>{let _=i[p]==="decimal"?Tu(f,o[p]??0)??f:f;l(p,ct(_))})}return a.map((c,d)=>{let u=s[d];return u===void 0?c:Math.min(c,u)})}be.measureColumns=wu;function aT(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 Su(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l,decimalPlaces:c}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let d=aT(o),u=hu(n),f=nT(l),p=Eu([t],u,c),_=e??wu([{rows:t,headers:r}],{max:a,align:u,decimalPlaces:p}),E=t.map(Tr);r!==void 0&&E.unshift(Tr(r));let m=E.map((h,T)=>{let g=h.length-1;for(;g>=0&&h[g]==="";)g--;return h.slice(0,g+1).map((y,v)=>{let b=_[v]||0,I=s&&b>0&&(v!==g||i)?sT(y,b,f):y;if(u[v]==="decimal"){let A=r!==void 0&&T===0?null:Tu(y,p[v]??0),S=jo(A!==null&&ct(A)<=b?A:I,b,!0);return v===g&&A!==null?S.trimEnd():S}return u[v]==="right"?jo(I,b,!0):v===g?I:jo(I,b,!1)}).join(" ")}).join(`
|
|
1576
|
+
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??j();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Pe(r.result_summary),Pe(r.error),r.team_chat_log_id??null,Pe(r.meta),Pe(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return xs(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??j();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Pe(n.result_summary),Pe(n.error),n.team_chat_log_id??null,Pe(n.meta),Pe(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 xs(this.db,o),o})()}heartbeatTrackedInvocation(e,r=j()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Qd(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(Zd(this.db,e,r),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,e).changes!==1?null:(eu(this.db,e,lt(r)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,r,n){return this.db.transaction(()=>{let s=j();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Pe(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 xs(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||bs(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:j()})}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=j()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return zd(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=j()){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:Xd(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&&dn(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&&dn(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
|
|
1577
|
+
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&&dn(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&&(dn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(an,cn(e,r),ln);return n===void 0?null:Fd(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Mo(this.db,n,!0),this.stmts.upsertRuntimeState.run(an,cn(e.teamfile,e.alias),ln,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&qd(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(an,cn(e,r),ln,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(an,cn(e,r),ln);return i.changes===1&&Mo(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:KE(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=j()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!YE(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:ou(),holder_pid:process.pid,holder_host:Po(),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,j(),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,j())}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,j());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,j(),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??j(),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,j());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,j()).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,j()),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,j());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(j(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=j();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??j());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,j())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,j())}}});var Bo=ny(be=>{"use strict";function Tr(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 pu(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left", "right", or "decimal" per column');return t.map(e=>{if(e!=="left"&&e!=="right"&&e!=="decimal")throw new TypeError('align entries must be "left", "right", or "decimal"');return e})}function ct(t){let e=0;for(let r of t){let n=r.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){e+=2;continue}e+=1}}return e}function Uo(t,e,r){let n=" ".repeat(Math.max(0,e-ct(t)));return r?n+t:t+n}function hu(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 ZE(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 eT(t,e,r="\u2026"){if(ct(t)<=e)return t;let n=ct(r)>e?"\u2026":r,s=ct(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=ct(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function tT(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 gu(t){let e=/^(?:[+-]?\$?|\$[+-]?)(?:\d+|\d{1,3}(?:,\d{3})+|(?=\.))(?:\.(\d+))?$/.exec(t);return!e||!/\d/.test(t)?null:{places:e[1]?.length??0}}function rT(t){if(t!==void 0){if(!Array.isArray(t)||t.some(e=>!Number.isInteger(e)||e<0))throw new TypeError("decimalPlaces must be an array of nonnegative integers");return t}}function _u(t){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let e=[];for(let r of t){let n=hu(r);n.headers!==void 0&&Tr(n.headers);for(let s of n.rows.map(Tr))s.forEach((i,o)=>{e[o]=Math.max(e[o]??0,gu(i)?.places??0)})}return e}be.measureDecimalPlaces=_u;function yu(t,e,r){let n=rT(r)??[],s=e.includes("decimal")?_u(t):[];return Array.from({length:Math.max(n.length,s.length)},(i,o)=>Math.max(n[o]??0,s[o]??0))}function Eu(t,e){let r=gu(t);if(!r)return null;let n=r.places?r.places+1:0,s=e?e+1:0;return t+" ".repeat(Math.max(0,s-n))}function Tu(t,{max:e,align:r,decimalPlaces:n}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let s=tT(e),i=pu(r),o=yu(t,i,n),a=[],l=(c,d)=>{a[c]=Math.max(a[c]??0,d)};for(let c of t){let d=hu(c);d.headers!==void 0&&Tr(d.headers).forEach((u,f)=>{l(f,ct(u))});for(let u of d.rows.map(Tr))u.forEach((f,p)=>{let _=i[p]==="decimal"?Eu(f,o[p]??0)??f:f;l(p,ct(_))})}return a.map((c,d)=>{let u=s[d];return u===void 0?c:Math.min(c,u)})}be.measureColumns=Tu;function nT(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 wu(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l,decimalPlaces:c}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let d=nT(o),u=pu(n),f=ZE(l),p=yu([t],u,c),_=e??Tu([{rows:t,headers:r}],{max:a,align:u,decimalPlaces:p}),E=t.map(Tr);r!==void 0&&E.unshift(Tr(r));let m=E.map((h,T)=>{let g=h.length-1;for(;g>=0&&h[g]==="";)g--;return h.slice(0,g+1).map((y,S)=>{let I=_[S]||0,b=s&&I>0&&(S!==g||i)?eT(y,I,f):y;if(u[S]==="decimal"){let k=r!==void 0&&T===0?null:Eu(y,p[S]??0),v=Uo(k!==null&&ct(k)<=I?k:b,I,!0);return S===g&&k!==null?v.trimEnd():v}return u[S]==="right"?Uo(b,I,!0):S===g?b:Uo(b,I,!1)}).join(" ")}).join(`
|
|
1578
1578
|
`);return m===""||d===""?m:`${d}${m.split(`
|
|
1579
1579
|
`).join(`
|
|
1580
|
-
${d}`)}`}be.renderGrid=
|
|
1581
|
-
`)}be.formatTable=
|
|
1582
|
-
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}be.escapeCell=
|
|
1580
|
+
${d}`)}`}be.renderGrid=wu;function Su(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l}={}){return wu(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l})}function sT(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l,stream:c=process.stdout}={}){let d=Su(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,decimalPlaces:l});d&&c.write(`${d}
|
|
1581
|
+
`)}be.formatTable=Su;be.printTable=sT;function mu(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function iT(t,{now:e=Date.now()}={}){let r=mu(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=mu(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":""}`}be.formatRelativeTime=iT;function oT(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`}be.formatCount=oT;var jo=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function aT(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=jo.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=jo.slice(n).filter(([u])=>u!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,d=!1;for(let[u,f]of a){let p=Math.floor(c/f);if(c-=p*f,p>0&&!d){let _=u==="d"||u==="w"?`${p}${u}`:`${ze(p)}${u}`;l.push({text:_,zero:!1}),d=!0}else d&&l.push({text:`${ze(p)}${u}`,zero:p===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(u=>u.text).join("")}let i=s,o=[];for(let[a,l]of jo.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(" ")}be.formatDuration=aT;function vu(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function ze(t){return String(t).padStart(2,"0")}function bu(t){let e=vu(t);return Number.isNaN(e.getTime())?"unknown":`${ze(e.getHours())}:${ze(e.getMinutes())}:${ze(e.getSeconds())}`}be.formatClock=bu;function lT(t){let e=vu(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${ze(e.getMonth()+1)}-${ze(e.getDate())}`} ${bu(e)}`}be.formatLocalTimestamp=lT;function cT(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}be.formatPercent=cT;function dT(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)||ct(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)}`}be.formatBar=dT;function uT(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=`${ze(n)}:${ze(s)}:${ze(e)}`;return r>0?`${r}d ${i}`:i}be.formatTimer=uT;function fT(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
1582
|
+
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}be.escapeCell=fT});import{homedir as mT}from"node:os";import{join as Iu}from"node:path";function gT(){let t=process.env.LMCTL_HOME;return t!==void 0&&t.length>0?t:Iu(mT(),pT)}function _T(){return Iu(gT(),hT)}function dt(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:_T()}function xu(t){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}var pT,hT,un=L(()=>{"use strict";pT=".lmctl",hT="state.db"});function bt(t){return(t.env??process.env).LMCTL_NON_INTERACTIVE==="1"}async function G(t,e){if(t.dal!==void 0)return e(t.dal);let r=Jt({path:dt()});try{return await e(r)}finally{r.close()}}function Ho(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 It(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function Vt(t,e){return t.flags[e]===!0}function Wo(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1583
1583
|
`)}function K(t,e){return t.stderr.write(`error: ${e}
|
|
1584
|
-
`),1}function xt(){return(0,
|
|
1585
|
-
`),2}function Sr(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var
|
|
1586
|
-
`);if(e[0]!=="---")throw new Qe("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 Qe(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!
|
|
1587
|
-
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=
|
|
1588
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(
|
|
1589
|
-
allowed keys: ${
|
|
1590
|
-
`)}){let n=Ze(t,
|
|
1591
|
-
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=
|
|
1592
|
-
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??
|
|
1593
|
-
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(
|
|
1584
|
+
`),1}function xt(){return(0,ku.formatClock)()}function wr(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 Ns(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1585
|
+
`),2}function Sr(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}var ku,Kt=L(()=>{"use strict";Er();ku=Xc(Bo(),1);un()});function ut(t){return t!=="gemini"}function Ls(t){if(!ut(t))throw new Error(kt)}var kt,vr=L(()=>{"use strict";kt="Standalone Gemini CLI support is disabled; use provider=agy with an Agy-supported Gemini model."});function Ru(t){if(t.length===0||!t.startsWith("---"))throw new Qe("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
1586
|
+
`);if(e[0]!=="---")throw new Qe("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 Qe(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!yT.has(c))throw new Qe(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Cs.join(", ")}`);r[c]=d}if(n===-1)throw new Qe("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Cs)if(r[o]===void 0)throw new Qe(`missing required frontmatter key "${o}" \u2014 required: ${Cs.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 Cs,yT,Qe,Lu=L(()=>{"use strict";Cs=["title","description","members"],yT=new Set(Cs),Qe=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as ET,writeFileSync as uL,renameSync as fL,existsSync as Ou}from"node:fs";import{basename as TT,resolve as br,dirname as Xo}from"node:path";function ST(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 vT(t){return/^\s*_MEMBER_\s+\S/.test(t)}function bT(t){return/^\s*_SESSION_\s+\S/.test(t)}function IT(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function Os(t){return/\.(?:lmctl|lmc)$/i.test(t)}function fn(t){return TT(t).replace(/\.(?:lmctl|lmc)$/i,"")}function Xe(t){let e=ET(t,"utf-8"),r=Xo(br(t)),n=Go(e,fn(t),{baseDir:r,sourcePath:br(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=br(r,s.sessiondir));return n}function Go(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
1587
|
+
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=Ru(i)}catch(l){if(l instanceof Qe)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
1588
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(bT(c))throw new Error(`line ${d}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(IT(c)||!vT(c))continue;let u=ST(c);for(let p of Object.keys(u))if(!Cu.includes(p))throw new Error(`line ${d}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
1589
|
+
allowed keys: ${Cu.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 Jo(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()===qo.toLowerCase());n.length>1&&r.push({field:qo,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?br(e,i.teamfile):br(i.teamfile);if(!Ou(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Xe(a),c=Ds(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 wT.has(i.provider)?ut(i.provider)||r.push({field:i.alias,message:kt}):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 Ds(t){return t.members.find(e=>e.alias.toLowerCase()===qo.toLowerCase())}function Vo(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=br(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),!Ou(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Xe(i),l=Ds(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return Vo(l,Xo(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||Xo(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function Du(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var qo,wT,Cu,ft=L(()=>{"use strict";vr();Lu();qo="Lead",wT=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","miniplayer","muse","ClaudeMock"]);Cu=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as xT}from"node:crypto";import{existsSync as Mu,readFileSync as Fu,realpathSync as kT}from"node:fs";import{dirname as AT,resolve as Pu}from"node:path";function Ze(t,e){let r=Pu(t);if(Mu(r))return kT(r);if(e!==void 0){let n=RT(t,r,e);if(n!==null)return n}return r}function Fs(t,e){let r=AT(e),n=Go(t,fn(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Pu(r,s.sessiondir));return n}function Ps(t,e,r=n=>{process.stderr.write(`warning: ${n}
|
|
1590
|
+
`)}){let n=Ze(t,NT(e)?e:void 0);if(Mu(n)){let i=Fu(n,"utf8"),o=Fs(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&<(o)&&OT(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 NT(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function RT(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function LT(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=Ko)}function Yo(t,e,r){let n=Ze(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=Ko);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=Ze(i.teamfile_path),o===n)continue;a=Fu(o,"utf8")}catch(c){if(CT(c))continue;throw c}let l=Fs(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)>=Ko);if(d!==void 0)throw new Ms(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${d.alias} both use sessionid "${c.session}"`)}}}function CT(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function OT(t,e,r,n,s){try{Yo(t,e,r)}catch(o){if(!(o instanceof Ms))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:xT("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var Ko,Ms,mn=L(()=>{"use strict";ft();Ko=5,Ms=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{randomUUID as DT}from"node:crypto";import{closeSync as MT,openSync as FT,readFileSync as Uu,statSync as PT,unlinkSync as zo,writeFileSync as $T}from"node:fs";function ju(t,e){return`${t}.seed-${e.toLowerCase()}.lock`}function Bu(t){let e;try{e=JSON.parse(Uu(t,"utf8"))}catch(n){return n.code==="ENOENT"?!1:$u(t)}let r=typeof e=="object"&&e!==null&&"pid"in e?e.pid:void 0;if(typeof r!="number"||!Number.isInteger(r)||r<=0)return $u(t);try{return process.kill(r,0),!0}catch(n){return n.code!=="ESRCH"}}function $u(t){try{return Date.now()-PT(t).mtimeMs<3e5}catch{return!1}}function Qo(t,e){return Bu(ju(t,e))}function Hu(t,e){let r=ju(t,e),n=JSON.stringify({pid:process.pid,token:DT()});for(let s=0;s<2;s+=1)try{let i=FT(r,"wx");try{$T(i,n)}catch(o){throw zo(r),o}finally{MT(i)}return()=>{try{Uu(r,"utf8")===n&&zo(r)}catch(o){if(o.code!=="ENOENT")throw o}}}catch(i){if(i.code!=="EEXIST")throw i;if(Bu(r))throw new Error(`${e}: seed already in progress; wait for it to finish`);try{zo(r)}catch(o){if(o.code!=="ENOENT")throw o}}throw new Error(`${e}: could not acquire seed marker`)}var Zo=L(()=>{"use strict"});import{existsSync as UT}from"node:fs";import{dirname as Wu}from"node:path";function WT(t){return jT.test(t)||BT.test(t)||HT.test(t)}function Xu(t){return $s.test(t)}function Us(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!Os(r)||!$s.test(n)?null:{teamfile:r,alias:n}}function mt(t,e,r){if(!Os(t))throw new ye(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl or .lmc extension).`);if(!Xu(e))throw new ye(`lmctl: "${e}" is not a valid alias (must match ${$s.source}).`);let n=Ze(t,r);if(r===void 0&&!UT(n))throw new ye(`lmctl: teamfile not found: ${t}`);let s;try{s=Ps(n,r)}catch(o){throw new ye(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new ye(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=Du(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new ye(`lmctl: alias "${e}" not found in ${t}.
|
|
1591
|
+
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=Vo(i,Wu(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(Qo(n,i.alias))throw new ye(`lmctl: alias "${i.alias}" is being seeded. Wait for the seed to finish, then retry this prompt.`);if(i.session===void 0)throw s.members.some(o=>Qo(n,o.alias))?new ye(`lmctl: alias "${i.alias}" has no session ID yet, and a seed is currently in progress for this team. Wait for the seed to finish, then retry this prompt.`):new ye(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
1592
|
+
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Wu(n),isLead:Ds(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function qu(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=Us(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(Os(r))return n!==void 0?Xu(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${$s.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
1593
|
+
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(WT(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.
|
|
1594
1594
|
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}".
|
|
1595
1595
|
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.
|
|
1596
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ye,
|
|
1597
|
-
`,"utf8"),$e.renameSync(r,t)}catch(n){try{$e.unlinkSync(r)}catch{}throw n}}function
|
|
1598
|
-
`)),M({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Ju(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function aw(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=zu(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=lw(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Bs&&c[1]!==Hs)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=Qu(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=dw(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===Bs&&ef(i.command,i.args)&&n.add(s),s===Hs&&tf(i.command,i.args)&&n.add(s);return n}function lw(t,e){if(t.startsWith("mcp_servers"))return Ws(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Ws(t);return r===null?null:[...e,...r]}function zu(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Ws(e[1])}function cw(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 Ws(r)}function Ws(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 Qu(t){let e=Zu(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 dw(t){let e=Zu(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=>Qu(s.trim()));return n.some(s=>s===null)?null:n}function Zu(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 uw(t){return kr(t)?t.type==="stdio"&&typeof t.command=="string"&&ef(t.command,t.args):!1}function fw(t){return!kr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&nf(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"&&rf(t.command[0],[t.command[1],t.command[2]])}function mw(t){return kr(t)?t.type==="stdio"&&tf(t.command,t.args):!1}function pw(t){return!kr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&sf(t.command[0])&&t.command[1]==="mcp"}function ef(t,e){return nf(t)&&of(e)||rf(t,e)}function tf(t,e){return sf(t)&&of(e)}function rf(t,e){return hw(t)&&Array.isArray(e)&&e.length===2&&gw(e[0])&&e[1]==="mcp"}function nf(t){return typeof t=="string"&&ra(t)==="lmctl"}function sf(t){return typeof t=="string"&&ra(t)==="lmctl0"}function hw(t){if(typeof t!="string")return!1;let e=ra(t).toLowerCase();return e==="node"||e==="node.exe"}function gw(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 ra(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function of(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function kr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Bs,Hs,tw,$e,ta,Xs=L(()=>{"use strict";re();Bs="lmctl",Hs="lmctl0",tw={existsSync:VT,mkdirSync:KT,readFileSync:YT,writeFileSync:ZT,renameSync:zT,unlinkSync:QT},$e=tw});import{basename as _w}from"node:path";function ff(t,e){let r=new Date(e.now.getTime()-Rt()).toISOString(),n=hf(t,r).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=ww(e.sender,n),i=Sw(e.sender,n);i!==null&&i.teamfile===e.root&&!uf(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>uf(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,_)=>_-p)[0]??null,d=c!==null&&e.now.getTime()-c<yw,u=na(e.sender,n).length;return{stop:l.length>=1&&d&&u>=Ew,chain:vw(a)}}function mf(t,e){let r=new Date(e.now.getTime()-Rt()).toISOString(),n=hf(t,r),s=na(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 Rt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return df;let r=Number(e);return!Number.isFinite(r)||r<=0?df:r}function pf(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function Tw(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 hf(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(Tw).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function ww(t,e,r={}){let n=new Map;for(let a of e)n.set(zt(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([zt(t)]);for(let a=0;a<64;a+=1){let l=n.get(zt(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=zt(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function na(t,e){let r=zt(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=zt(l.sender),d=zt(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 Sw(t,e){let r=na(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function uf(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function zt(t){return`${t.teamfile}\0${t.alias}`}function vw(t){return t.map(e=>`${_w(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var yw,Ew,df,qs=L(()=>{"use strict";yw=6e4,Ew=2,df=8*60*60*1e3});function Js(t,e,r){return ut(t)&&e.tools[t]?.agent===void 0&&r.includes(t)}async function pt(t,e,r,n,s){if(t.provider!==e)throw new Error(`bundle session provider mismatch: session serves "${t.provider}", turn targets "${e}"`);if(t.sessionId!==r)throw new Rr(`session identity mismatch: expected "${r}", got "${t.sessionId}"`);let i=await t.sendTurn(n,s);if(i.sessionId!==r)throw new Rr(`session identity mismatch: expected "${r}", got "${i.sessionId}"`);return{...i,...i.text===""&&i.sawActivity===!1?{status:"empty"}:{}}}async function Vs(t,e){Ds(t.name);let r=e.requireResume??!0;if(r&&!e.sessionId.trim())throw new Error("conversation requires an existing session ID");let n=e.userConfig?.tools[t.name]?.agent!==void 0,s=e.execution!=="per-turn"&&t.openSession!==void 0&&!n;if(e.execution==="persistent"&&!s)throw new Error(`provider "${t.name}" does not support persistent sessions with this configuration`);let i=s?await t.openSession(e):void 0,o=!r&&e.sessionId==="";if(i&&(i.provider!==t.name||typeof i.sessionId!="string"||!i.sessionId.trim()||!o&&i.sessionId!==e.sessionId))throw await i.close(),new Error(`session identity mismatch opening ${t.name}: expected "${e.sessionId}", got "${i.sessionId}" (${i.provider})`);let a=i?.sessionId??e.sessionId,l=0,c=!1,d,u;return{provider:t.name,sessionId:a,execution:s?"persistent":"per-turn",transport:n?"custom":t.protocol?.transport??"unknown",cancellation:n?"unknown":s?t.protocol?.persistentCancellation??"unknown":t.protocol?.perTurnCancellation??"unknown",get completedTurns(){return l},async sendTurn(f,p={}){if(c)throw new Error("conversation is closed");if(d)throw new Error("conversation already has an active turn");if(p.signal?.aborted)throw new Error("Aborted");let _=new AbortController;d=_;let E=()=>_.abort();p.signal?.addEventListener("abort",E,{once:!0});try{let m=i?await pt(i,t.name,a,f,{...p,signal:_.signal}):await t.sendTurn(f,{...e,...p,signal:_.signal,requireResume:r,timeoutMs:e.timeoutMs??0});if(_.signal.aborted)throw new Error("Aborted");if(r&&m.sessionId!==e.sessionId)throw c=!0,new Rr(`session identity mismatch: expected "${e.sessionId}", got "${m.sessionId}"`);return m.status!=="empty"&&m.status!=="stalled"&&l++,m}catch(m){throw _.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),m instanceof Rr&&(c=!0,await i?.close()),m}finally{p.signal?.removeEventListener("abort",E),d=void 0}},close(){return u||(c=!0,d?.abort(),u=i?i.close():Promise.resolve()),u}}}var Rr,Lr=L(()=>{"use strict";vr();Rr=class extends Error{}});import{realpathSync as Iw}from"node:fs";import{resolve as xw}from"node:path";function sa(t){let e=xw(t);try{return Iw(e)}catch{return e}}var gf=L(()=>{"use strict"});import{platform as _f}from"node:os";function Lt(t){let e=new yn;for(let r of t)e.registerAdapter(r);return e}var yn,ia=L(()=>{"use strict";gf();yn=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=sa(e.workspace);i=i.filter(a=>sa(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=_f()==="darwin"||_f()==="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{readFileSync as kw,writeFileSync as iC,mkdirSync as oC}from"node:fs";import{join as Aw,dirname as lC}from"node:path";import{homedir as Nw}from"node:os";function Lw(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Cw(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=Lw(t.slice(e+1).trim());return r?{key:r,value:n}:null}function Ow(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Ks(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function Dw(){return Aw(Nw(),".lmctl","config.toml")}function Ef(t){let e=t??Dw(),r;try{r=kw(e,"utf-8")}catch{return{tools:{}}}return Mw(r)}function yf(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 Mw(t){let e={},r={},n=t.split(`
|
|
1599
|
-
`),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=
|
|
1600
|
-
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let d=
|
|
1601
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function H(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ue(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var V,pe=L(()=>{"use strict";V=
|
|
1596
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ye,jT,BT,HT,$s,Yt=L(()=>{"use strict";ft();ft();mn();Zo();ye=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},jT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,BT=/^ses_[A-Za-z0-9_-]+$/,HT=/^session_[A-Za-z0-9_-]+$/,$s=/^[A-Za-z][A-Za-z0-9_-]*$/});import{existsSync as XT,mkdirSync as qT,readFileSync as GT,renameSync as JT,unlinkSync as VT,writeFileSync as KT}from"node:fs";import{homedir as Ju}from"node:os";import{dirname as pn,join as Ie,resolve as YT}from"node:path";function xr(t,e,r){let n=pn(YT(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())et(Ie(o,".mcp.json"),"mcpServers",[At(),Nt()]),a.has("opencode")&&et(Ie(o,".opencode","opencode.json"),"mcp",[Vu(),Ku()]),a.has("kimi")&&et(Ie(o,".kimi-code","mcp.json"),"mcpServers",[At(),Nt()]);for(let o of s)tw(o)}function QT(t=ea??Ju()){return Ie(t,".copilot","mcp-config.json")}function ZT(t,e){$e.mkdirSync(pn(t),{recursive:!0});let r=Ie(pn(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{$e.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
1597
|
+
`,"utf8"),$e.renameSync(r,t)}catch(n){try{$e.unlinkSync(r)}catch{}throw n}}function ew(t,e){$e.mkdirSync(pn(t),{recursive:!0});let r=Ie(pn(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{$e.writeFileSync(r,e,"utf8"),$e.renameSync(r,t)}catch(n){try{$e.unlinkSync(r)}catch{}throw n}}function et(t,e,r){try{if(!$e.existsSync(t))return;let n=JSON.parse($e.readFileSync(t,"utf8"));if(!Ir(n)||!Ir(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,ZT(t,n),D({event:"mcp_cleanup",path:t,removed:i})}catch{}}function At(){return{name:Bs,shouldRemove:cw}}function Vu(){return{name:Bs,shouldRemove:dw}}function Nt(){return{name:js,shouldRemove:aw}}function Ku(){return{name:js,shouldRemove:lw}}function tw(t){let e=ea??Ju();switch(t){case"copilot":et(QT(e),"mcpServers",[At(),Nt()]);return;case"claude":et(Ie(e,".claude.json"),"mcpServers",[At(),Nt()]);return;case"gemini":et(Ie(e,".gemini","settings.json"),"mcpServers",[At(),Nt()]);return;case"qwen":et(Ie(e,".qwen","settings.json"),"mcpServers",[At(),Nt()]);return;case"agy":et(Ie(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[At(),Nt()]);return;case"opencode":et(Ie(e,".config","opencode","opencode.json"),"mcp",[Vu(),Ku()]);return;case"kimi":et(Ie(ea===void 0?process.env.KIMI_CODE_HOME??Ie(e,".kimi-code"):Ie(e,".kimi-code"),"mcp.json"),"mcpServers",[At(),Nt()]);return;case"codex":rw(Ie(e,".codex","config.toml"));return;default:return}}function rw(t){try{if(!$e.existsSync(t))return;let e=$e.readFileSync(t,"utf8"),r=nw(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=Yu(l);if(c===null)return;if(c!==void 0){if(Gu(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=iw(l);if(d===null)return;if(d!==void 0&&Gu(d,r)){i.add(d[1]);continue}s.push(l)}if(i.size===0)return;ew(t,s.join(`
|
|
1598
|
+
`)),D({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function Gu(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function nw(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=Yu(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=sw(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==js&&c[1]!==Bs)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=zu(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=ow(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===js&&Zu(i.command,i.args)&&n.add(s),s===Bs&&ef(i.command,i.args)&&n.add(s);return n}function sw(t,e){if(t.startsWith("mcp_servers"))return Hs(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=Hs(t);return r===null?null:[...e,...r]}function Yu(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:Hs(e[1])}function iw(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 Hs(r)}function Hs(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 zu(t){let e=Qu(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 ow(t){let e=Qu(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=>zu(s.trim()));return n.some(s=>s===null)?null:n}function Qu(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 aw(t){return Ir(t)?t.type==="stdio"&&typeof t.command=="string"&&Zu(t.command,t.args):!1}function lw(t){return!Ir(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&rf(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"&&tf(t.command[0],[t.command[1],t.command[2]])}function cw(t){return Ir(t)?t.type==="stdio"&&ef(t.command,t.args):!1}function dw(t){return!Ir(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&nf(t.command[0])&&t.command[1]==="mcp"}function Zu(t,e){return rf(t)&&sf(e)||tf(t,e)}function ef(t,e){return nf(t)&&sf(e)}function tf(t,e){return uw(t)&&Array.isArray(e)&&e.length===2&&fw(e[0])&&e[1]==="mcp"}function rf(t){return typeof t=="string"&&ta(t)==="lmctl"}function nf(t){return typeof t=="string"&&ta(t)==="lmctl0"}function uw(t){if(typeof t!="string")return!1;let e=ta(t).toLowerCase();return e==="node"||e==="node.exe"}function fw(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 ta(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function sf(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Ir(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var js,Bs,zT,$e,ea,Ws=L(()=>{"use strict";re();js="lmctl",Bs="lmctl0",zT={existsSync:XT,mkdirSync:qT,readFileSync:GT,writeFileSync:KT,renameSync:JT,unlinkSync:VT},$e=zT});import{basename as mw}from"node:path";function lf(t,e){let r=new Date(e.now.getTime()-Rt()).toISOString(),n=uf(t,r).filter(p=>!p.sender.teamfile.startsWith("prompt:")),s=_w(e.sender,n),i=yw(e.sender,n);i!==null&&i.teamfile===e.root&&!af(s[0],i)&&s.unshift({...i,at:null});let o={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,o],l=s.filter(p=>af(p,o)),c=l.map(p=>p.at).filter(p=>p!==null).sort((p,_)=>_-p)[0]??null,d=c!==null&&e.now.getTime()-c<pw,u=ra(e.sender,n).length;return{stop:l.length>=1&&d&&u>=hw,chain:Ew(a)}}function cf(t,e){let r=new Date(e.now.getTime()-Rt()).toISOString(),n=uf(t,r),s=ra(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 Rt(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return of;let r=Number(e);return!Number.isFinite(r)||r<=0?of:r}function df(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function gw(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 uf(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(gw).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function _w(t,e,r={}){let n=new Map;for(let a of e)n.set(zt(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([zt(t)]);for(let a=0;a<64;a+=1){let l=n.get(zt(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=zt(l.sender);if(o.has(d))break;s.unshift(c),o.add(d),i=l.sender}return s}function ra(t,e){let r=zt(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=zt(l.sender),d=zt(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 yw(t,e){let r=ra(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function af(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function zt(t){return`${t.teamfile}\0${t.alias}`}function Ew(t){return t.map(e=>`${mw(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var pw,hw,of,Xs=L(()=>{"use strict";pw=6e4,hw=2,of=8*60*60*1e3});function Gs(t,e,r){return ut(t)&&e.tools[t]?.agent===void 0&&r.includes(t)}async function pt(t,e,r,n,s){if(t.provider!==e)throw new Error(`bundle session provider mismatch: session serves "${t.provider}", turn targets "${e}"`);if(t.sessionId!==r)throw new kr(`session identity mismatch: expected "${r}", got "${t.sessionId}"`);let i=await t.sendTurn(n,s);if(i.sessionId!==r)throw new kr(`session identity mismatch: expected "${r}", got "${i.sessionId}"`);return{...i,...i.text===""&&i.sawActivity===!1?{status:"empty"}:{}}}async function Js(t,e){Ls(t.name);let r=e.requireResume??!0;if(r&&!e.sessionId.trim())throw new Error("conversation requires an existing session ID");let n=e.userConfig?.tools[t.name]?.agent!==void 0,s=e.execution!=="per-turn"&&t.openSession!==void 0&&!n;if(e.execution==="persistent"&&!s)throw new Error(`provider "${t.name}" does not support persistent sessions with this configuration`);let i=s?await t.openSession(e):void 0,o=!r&&e.sessionId==="";if(i&&(i.provider!==t.name||typeof i.sessionId!="string"||!i.sessionId.trim()||!o&&i.sessionId!==e.sessionId))throw await i.close(),new Error(`session identity mismatch opening ${t.name}: expected "${e.sessionId}", got "${i.sessionId}" (${i.provider})`);let a=i?.sessionId??e.sessionId,l=0,c=!1,d,u;return{provider:t.name,sessionId:a,execution:s?"persistent":"per-turn",transport:n?"custom":t.protocol?.transport??"unknown",cancellation:n?"unknown":s?t.protocol?.persistentCancellation??"unknown":t.protocol?.perTurnCancellation??"unknown",get completedTurns(){return l},async sendTurn(f,p={}){if(c)throw new Error("conversation is closed");if(d)throw new Error("conversation already has an active turn");if(p.signal?.aborted)throw new Error("Aborted");let _=new AbortController;d=_;let E=()=>_.abort();p.signal?.addEventListener("abort",E,{once:!0});try{let m=i?await pt(i,t.name,a,f,{...p,signal:_.signal}):await t.sendTurn(f,{...e,...p,signal:_.signal,requireResume:r,timeoutMs:e.timeoutMs??0});if(_.signal.aborted)throw new Error("Aborted");if(r&&m.sessionId!==e.sessionId)throw c=!0,new kr(`session identity mismatch: expected "${e.sessionId}", got "${m.sessionId}"`);return m.status!=="empty"&&m.status!=="stalled"&&l++,m}catch(m){throw _.signal.aborted&&i&&t.protocol?.persistentCancellation==="session"&&(c=!0),m instanceof kr&&(c=!0,await i?.close()),m}finally{p.signal?.removeEventListener("abort",E),d=void 0}},close(){return u||(c=!0,d?.abort(),u=i?i.close():Promise.resolve()),u}}}var kr,Ar=L(()=>{"use strict";vr();kr=class extends Error{}});import{realpathSync as ww}from"node:fs";import{resolve as Sw}from"node:path";function na(t){let e=Sw(t);try{return ww(e)}catch{return e}}var ff=L(()=>{"use strict"});import{platform as mf}from"node:os";function Lt(t){let e=new hn;for(let r of t)e.registerAdapter(r);return e}var hn,sa=L(()=>{"use strict";ff();hn=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=na(e.workspace);i=i.filter(a=>na(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=mf()==="darwin"||mf()==="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{readFileSync as vw,writeFileSync as zL,mkdirSync as QL}from"node:fs";import{join as bw,dirname as eC}from"node:path";import{homedir as Iw}from"node:os";function kw(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Aw(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=kw(t.slice(e+1).trim());return r?{key:r,value:n}:null}function Nw(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function Vs(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function Rw(){return bw(Iw(),".lmctl","config.toml")}function hf(t){let e=t??Rw(),r;try{r=vw(e,"utf-8")}catch{return{tools:{}}}return Lw(r)}function pf(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 Lw(t){let e={},r={},n=t.split(`
|
|
1599
|
+
`),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=pf(i.min);f!==null&&(u.min=f)}if(i.max!==void 0){let f=pf(i.max);f!==null&&(u.max=f)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=u):r.global=u}i={}}for(let u of n){let f=u.trim();if(!f||f.startsWith("#"))continue;let p=Nw(f);if(p!==null){if(o=!0,l(),p.startsWith("tool.")){let E=".profile.",m=p.indexOf(E);m!==-1?s={kind:"tool",tool:p.slice(5,m),profile:p.slice(m+E.length)}:s={kind:"tool",tool:p.slice(5),profile:null}}else p==="compact"?s={kind:"compact",provider:null}:p.startsWith("compact.")?s={kind:"compact",provider:p.slice(8)}:s={kind:"none"};continue}let _=Aw(f);_&&s.kind!=="none"?i[_.key]=_.value:_&&!o&&(a[_.key]=_.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let d=a.site_name;return d!==void 0&&d.length>0&&(c.site_name=d),c}function Cw(t,e,r){if(!r)return"";let n=t.tools[e]??ia[e],s=n?.profiles?.[r]?.flags??ia[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 gf(t,e){return!!t.tools[e]}function _f(t,e,r,n,s){let i=t.tools[e]??ia[e],o;if(i?.agent){let l=Vs(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=xw[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(Vs).join(" ");o=`printf '%s\\n' ${Vs(n)} | ${d}`}else o=c.map(Vs).join(" ")}let a=Cw(t,e,s);return a&&(o+=" "+a),o}var ia,xw,oa=L(()=>{"use strict";ia={muse:{start:"muse",resume:"muse resume {{session_id}} --yolo",profiles:{default:{description:"Default profile",flags:""}}},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:""}}}},xw={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 yf(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 Ef=L(()=>{"use strict"});var Ow,Y,Ks,Ee=L(()=>{"use strict";Ow="ACK: waiting for explicit lmctl task.",Y=`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: ${Ow}`,Ks=`send this exact lmctl seed instruction: "${Y}"`});import{existsSync as Dw}from"node:fs";function Tf(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&&!Dw(e);if(!r&&!n)return t;D({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 Nr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function Fw(t,e){return e===void 0||e.length===0?t:{...t??process.env,[aa]:e}}function ue(t,e,r,n="chat"){return{...Fw(Nr(t,e),r),[Mw]:n}}var aa,Mw,qe=L(()=>{"use strict";re();aa="LMCTL_SELF_SESSIONID",Mw="LMCTL_LAUNCH_SOURCE"});function gn(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var la=L(()=>{"use strict"});import{spawn as wf}from"node:child_process";import{mkdirSync as Pw}from"node:fs";var Rr,ee,Te=L(()=>{"use strict";oa();Ef();Ee();qe();la();Rr=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},ee=class t{name;capabilities;injection;protocol;provider;binary;seedArgs;seedTimeoutMs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.protocol=e.protocol,this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedTimeoutMs=e.seedTimeoutMs??6e4,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===Y?r:n)}turnOptsFor(e){return e}seed(e,r){return Pw(e,{recursive:!0}),new Promise(n=>{let s;try{s=wf(this.binary,this.seedArgsFor(r),{cwd:e,env:Nr(void 0,e),stdio:["pipe","pipe","pipe"],timeout:this.seedTimeoutMs})}catch(l){return n({success:!1,error:l instanceof Error?l.message:String(l)})}let i="",o="";s.stdout?.on("data",l=>{i+=l.toString()}),s.stderr?.on("data",l=>{o+=l.toString()});let a=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1600
|
+
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let d=gn(o).trim(),u=gn(i).trim();n({success:!1,error:(d||u).slice(0,500)||(c?`terminated by ${c}`:`exit code ${l}`)})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:Ks,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&&gf(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,r,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),d(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},d=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let u={...n,binary:this.binary,signal:s.signal,onDelta:_=>{a+=_,c(),n.onDelta?.(_)},onProgress:_=>{_.kind!=="api_retry"&&c(),n.onProgress?.(_)}},f=this.transportFn(r,u).then(_=>(d(),{..._,status:_.status??"ok"})).catch(_=>{throw d(),o==="external"?new Rr("Turn cancelled","external"):_}),p=new Promise(_=>{l=_});return Promise.race([f,p])}runOneShotAgent(e,r,n){let s=_f(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=r.timeoutMs!==void 0&&r.timeoutMs<=0?0:yf(r.env),c=wf(s,{shell:!0,cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,f=l>0?setTimeout(()=>{u=!0,c.kill()},l):void 0,p="",_="";if(c.stdout?.on("data",E=>{let m=E.toString();p+=m,r.onDelta?.(m)}),c.stderr?.on("data",E=>{_+=E.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",E=>{if(d)return;d=!0,clearTimeout(f);let m=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):E===0||E===null?o({text:p.trim(),sessionId:r.sessionId,durationMs:m}):a(new Error(_.trim().slice(0,200)||`Agent command exited with code ${E}`))}),c.on("error",E=>{d||(d=!0,clearTimeout(f),a(E))})})}}});function Ys(t,e=!0){let r={input_uncached:null,input_cached:null,input_cache_write:null,output:null};if(!e||!t.length||new Set(t.map(n=>n.response_id)).size!==t.length)return r;for(let n of Object.keys(r)){let s=t.map(o=>o.tokens[n]);if(s.some(o=>o===null||!Number.isSafeInteger(o)||o<0))continue;let i=s.reduce((o,a)=>o+a,0);Number.isSafeInteger(i)&&(r[n]=i)}return r}var ca=L(()=>{"use strict"});import{createReadStream as Sf}from"node:fs";import{createInterface as vf}from"node:readline";import{stat as $w}from"node:fs/promises";import{homedir as Uw}from"node:os";function bf(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*oe(t,e){let r=Sf(t,{encoding:"utf-8"}),n=vf({input:r,crlfDelay:1/0});try{for await(let s of n){let i=s.trim();if(!i)continue;let o=bf(i);o!==void 0?yield o:e?.()}}finally{r.destroy()}}async function Oe(t,e){let r=[],n=Sf(t,{encoding:"utf-8"}),s=vf({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=bf(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 $w(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function ne(t){return t.replace(/\\n/g,`
|
|
1601
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function H(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ue(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var V,pe=L(()=>{"use strict";V=Uw()});import{readdir as jw}from"node:fs/promises";import{join as _n,resolve as Bw}from"node:path";function da(t){return Bw(t||process.env.XDG_DATA_HOME||_n(V,".local","share"))}function Hw(t,e,r,n){let s=n?.input_uncached_tokens,i=n?.cache_read_tokens??n?.input_cache_read_tokens,o=n?.cache_write_tokens??n?.input_cache_write_tokens;return{response_id:t,timestamp:e.toISOString(),model:typeof r=="string"&&r.length>0?r:null,tokens:{input_uncached:typeof s=="number"?s:null,input_cached:typeof i=="number"?i:null,input_cache_write:typeof o=="number"?o:null,output:typeof n?.output_tokens=="number"?n.output_tokens:null},files_read:null,files_written:null}}function Ww(t,e){let r,n,s,i,o,a=[],l=new Map,c=new Map,d=new Set,u,f,p=()=>{f="partial"},_=h=>{if(typeof h!="string"||h.length===0){p();return}let T=l.get(h);return T||(T={id:h,turn:{id:h,status:"unknown"},responseIds:[]},l.set(h,T)),T},E=h=>{if(h.retained_frame&&Array.isArray(h.children)){for(let b of h.children)try{if(typeof b?.record_json!="string")throw new Error("missing record_json");E(JSON.parse(b.record_json))}catch{p()}return}if(h.stream?.kind!=="session"||h.stream?.id!==t)return;if(h.schema_version!==1){p();return}if(h.payload_type?.startsWith("runtime.session")&&h.payload_schema_version!==1){p();return}let T=h.payload?.source_run_record_id;for(let b of[h.id,T])if(!(typeof b!="string"||b.length===0)&&d.has(b))return;for(let b of[h.id,T])typeof b=="string"&&b.length>0&&d.add(b);let g=typeof h.recorded_at=="number"&&Number.isFinite(h.recorded_at)?new Date(h.recorded_at/1e3):void 0;if(h.recorded_at!==void 0&&(!g||!Number.isFinite(g.getTime()))){p();return}g&&Number.isFinite(g.getTime())&&((!s||g<s)&&(s=g),(!i||g>i)&&(i=g));let y=h.payload;if(h.payload_type==="runtime.session.metadata"&&(typeof y?.record?.workspace_root=="string"&&(r=y.record.workspace_root),typeof y?.record?.model_id=="string"&&(n=y.record.model_id)),h.payload_type!=="runtime.session"||y?.kind!=="run")return;let S=y.event,I=_(y.run_id);if(!S||!g||!I){S||p();return}if(S.kind==="started"&&typeof S.prompt=="string")a.push({role:"user",content:S.prompt,timestamp:g}),I.turn.startedAt=g,I.turn.prompt=S.prompt,I.turn.status="in_progress",o="in_progress";else if(S.kind==="assistant_message_committed"&&typeof S.text=="string")a.push({role:"assistant",content:S.text,timestamp:g});else if(S.kind==="terminal")I.turn.completedAt=g,I.turn.status=S.terminal==="completed"?"complete":"aborted",o=I.turn.status;else if(S.kind==="model_completed"){typeof S.model=="string"&&S.model.length>0&&(n=S.model,I.turn.model=S.model);let b=typeof T=="string"&&T.length>0?T:typeof h.id=="string"&&h.id.length>0?h.id:void 0;if(!b)p();else{I.responseIds.push(b);let x={};if(S.usage&&typeof S.usage=="object")for(let O of["input_tokens","output_tokens","cached_tokens","reasoning_tokens","input_uncached_tokens","cache_read_tokens","input_cache_read_tokens","cache_write_tokens","input_cache_write_tokens"]){let M=S.usage[O];typeof M=="number"&&Number.isSafeInteger(M)&&M>=0&&(x[O]=M)}Object.keys(x).length>0&&(I.turn.rawUsage=[...I.turn.rawUsage??[],{responseId:b,values:x}]),c.set(b,Hw(b,g,S.model,x))}if(!S.usage)return;let k={},v=S.usage.input_uncached_tokens,w=S.usage.cache_read_tokens??S.usage.input_cache_read_tokens,N=S.usage.cache_write_tokens??S.usage.input_cache_write_tokens,A=S.usage.output_tokens,R=S.usage.reasoning_tokens;typeof v=="number"&&Number.isSafeInteger(v)&&v>=0&&(k.inputTokens=v),typeof w=="number"&&Number.isSafeInteger(w)&&w>=0&&(k.cachedInputTokens=w),typeof N=="number"&&Number.isSafeInteger(N)&&N>=0&&(k.cacheWriteInputTokens=N),typeof A=="number"&&Number.isSafeInteger(A)&&A>=0&&(k.outputTokens=A),typeof R=="number"&&Number.isSafeInteger(R)&&R>=0&&(k.reasoningOutputTokens=R),u=k}};return{visit:E,finish:()=>{if(!r||!s||!i)return null;let h=a.filter(S=>S.role==="user").map(S=>S.content),T=[...l.values()].map(S=>({...S.turn,...S.responseIds.length>0?{responseIds:[...S.responseIds]}:{}})),g=[...c.values()],y=Ys(g,f!=="partial");return{provider:"muse",sessionId:t,filePath:e,cwd:r,createdAt:s,modifiedAt:i,model:n,messages:a,messageCount:a.length,firstUserMessage:h[0],lastUserMessage:h.at(-1),userPrompts:h,turnStatus:o,totalInputTokens:y.input_uncached??void 0,totalCachedInputTokens:y.input_cached??void 0,totalCacheWriteInputTokens:y.input_cache_write??void 0,totalOutputTokens:y.output??void 0,lastTokenUsage:u,turns:T,responses:g,...f?{captureStatus:f}:{}}},markPartial:p}}async function xf(t,e){let r=Ww(t,e);for await(let n of oe(e,r.markPartial))r.visit(n);return r.finish()}var If,zs,kf=L(()=>{"use strict";ca();pe();If=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;zs=class{name="muse";dataHome;constructor(e={}){this.dataHome=da(e.museDataHome)}get root(){return _n(this.dataHome,"muse","sessions")}getWatchPaths(){return[{directory:this.root,filePattern:/session\.jsonl$/}]}async files(e=this.root,r=0){let n;try{n=await jw(e,{withFileTypes:!0})}catch{return[]}let s=[];for(let i of n)i.isFile()&&i.name==="session.jsonl"?s.push(_n(e,i.name)):i.isDirectory()&&r<4&&s.push(...await this.files(_n(e,i.name),r+1));return s}async resolveSessionPath(e){return If.test(e)?(await this.files()).find(r=>r.endsWith(_n(e,"session.jsonl")))??null:null}async loadSession(e){let r=await this.resolveSessionPath(e);return r?xf(e,r):null}async discoverSessions(){let e=[];for(let r of await this.files())try{let n=r.split(/[\\/]/).at(-2);if(!If.test(n))continue;let s=await xf(n,r);s&&e.push(s)}catch{}return e}async deleteSession(){return!1}}});function Tn(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new En(t,r,e)}var Ct,se,yn,Qs,En,Qt=L(()=>{"use strict";Ct=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},se=class extends Ct{},yn=class extends Ct{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Qs=class extends Ct{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},En=class extends Ct{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import{createInterface as Xw}from"node:readline";function Ot(t,e){let r=e.protocol??"acp",n=Xw({input:t.stdout}),s=new Map,i=(a,l={},c)=>new Promise((d,u)=>{let f=qw++;s.set(f,{resolve:d,reject:u,onResponse:c});let p=JSON.stringify({jsonrpc:"2.0",id:f,method:a,params:l});Se({event:`${r}_send`,direction:"SEND",provider:e.provider,method:a,id:f,params:l}),t.stdin?.write(`${p}
|
|
1602
1602
|
`)}),o=(a,l={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:a,params:l})}
|
|
1603
|
-
`)};return n.on("line",a=>{let l=u=>{if(!e.onProtocolError)return;let f=a.slice(0,512);
|
|
1604
|
-
`);return}e.onNotification?.(c)}),{sendRpc:i,sendNotification:o,close(a=new se(`${r.toUpperCase()} RPC channel closed`)){n.close();for(let l of s.values())l.reject(a);s.clear()}}}var
|
|
1605
|
-
`),sessionId:_,durationMs:typeof R.durationMs=="number"?R.durationMs:Date.now()-w.started,stopReason:R.terminal,...X.some($=>$.truncated)?{warnings:["Muse reported a truncated response; inspect the native transcript for complete content"]}:{}})},T=Ot(n,{provider:"muse",protocol:"msp",onProtocolError:m,onNotification:w=>{if(p=Date.now(),w.method==="view/gap"||w.method==="session/closed"){w.params?.sessionId===_&&!a&&m(new Error(`Muse ${w.method}: session must be reopened`));return}let N=s;N&&(N.id?h(N,w):N.events.push(w))}}),g=async(w,N,R=In())=>(await T.sendRpc(w,{...N,commandId:R})).result,y=w=>{!w.id||w.interruptSent||s!==w||(w.interruptSent=!0,g("turn/interrupt",{sessionId:_,turnId:w.id}).catch(N=>{s===w&&m(N instanceof Error?N:new Error(String(N)))}))},v=w=>{!w.id||w.unqueueSent||s!==w||(w.unqueueSent=!0,g("turn/unqueue",{sessionId:_,turnId:w.id}).catch(N=>{let R=N instanceof Error?N.message:String(N);/already started|not queued|launch boundary|turn is running/i.test(R)?(w.queued=!1,y(w)):s===w&&m(N instanceof Error?N:new Error(R))}))},b=w=>{w.queued?v(w):y(w)};n.on("error",w=>m(new Error(`Unable to start Muse: ${w.message}`)));let I=()=>{a||d||i||c||(c=!0,te(n,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(w=>m(w instanceof Error?w:new Error(String(w)))))};n.stdin.on("error",I),n.stdout.on("end",I),n.on("exit",()=>{d=!0}),n.on("close",(w,N)=>{d=!0,a?T.close(new Error("Muse session closed")):m(new Error(`Muse exited (${N??w}) after ${u} completed prompt(s)${f?`: ${f.trim()}`:""}`)),s&&E(s,new Error("Muse session closed"))});let A=()=>{if(o)return o;a=!0;let w=!!s;return s&&(s.cancelled=!0,b(s)),o=(async()=>{d||(await new Promise(N=>tt(l?t.holdOpen:void 0,{isAborted:()=>w,hasChildExited:()=>d,isTurnInFlight:()=>!!s,lastEventAtMs:()=>p,closeStdin:()=>{n.stdin.end(),N()},label:"muse"})),await te(n,{stdinEnd:!1,softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{})),s&&E(s,new Error("Muse session closed")),T.close(new Error("Muse session closed"))})(),o},S=()=>{m(new Error("Aborted")),A()};t.signal?.addEventListener("abort",S,{once:!0});try{if(t.signal?.aborted)throw new Error("Aborted");let w=(await T.sendRpc("initialize",{clientInfo:{name:"lmctl",version:"1"}})).result;if(w?.schema?.version!==1)throw new Error("Muse MSP schema version is unsupported");if(t.expectedHome&&(typeof w.museHome!="string"||await ri(w.museHome)!==await ri(t.expectedHome)))throw new Error("Muse data home does not match the configured session reader");if(w.sessionDurability!==void 0&&w.sessionDurability!=="durable")throw new Error("Muse did not provide durable sessions");T.sendNotification("initialized");let N=e?"denyUnmatched":"allowAll",k=(t.create?await g("session/start",{sessionId:_,workspaceRoot:t.cwd,approvalMode:N,...t.model?{modelId:t.model}:{}}):await g("session/resume",{sessionId:_,excludeItems:!0}))?.session;if(k?.sessionId!==_)throw new Error(`Muse did not return requested session "${_}"`);if(typeof k.workspaceRoot!="string"||await ri(k.workspaceRoot)!==await ri(t.cwd))throw new Error("Muse session belongs to a different working directory");if(k.activeTurnId||k.status!=="idle")throw new Error(`Muse session is not idle (${String(k.status)})`);if((await g("session/setApprovalMode",{sessionId:_,mode:N}))?.effectiveMode?.mode!==N)throw new Error("Muse did not apply the requested approval mode");if(!t.create&&t.model&&k.modelId!==t.model&&(await g("session/setModel",{sessionId:_,model:{modelId:t.model,...k.providerId?{providerId:k.providerId}:{}}}))?.status!=="accepted")throw new Error("Muse did not accept the requested model");l=!0}catch(w){throw await A(),i??w}finally{t.signal?.removeEventListener("abort",S)}return{provider:"muse",sessionId:_,get completedTurns(){return u},close:A,async sendTurn(w,N={}){if(s?.cancelled&&await s.drain,i)throw i;if(a)throw new Error("Muse session is closed");if(s)throw new Error("Muse already has an active turn");if(N.signal?.aborted)throw new Error("Aborted");return new Promise((R,k)=>{let x,O=new Promise($=>{x=$}),D={commandId:In(),events:[],items:new Map,opts:N,started:Date.now(),cancelled:!1,interruptSent:!1,unqueueSent:!1,queued:!1,settled:!1,resolve:R,reject:k,drain:O,drained:x,cleanup:()=>{}};s=D;let X=()=>{D.cancelled=!0,D.settled=!0,k(new Error("Aborted")),b(D)};D.cleanup=()=>N.signal?.removeEventListener("abort",X),N.signal?.addEventListener("abort",X,{once:!0}),g("turn/start",{sessionId:_,input:[{type:"text",text:w}],...t.effort?{reasoningEffort:t.effort}:{}},D.commandId).then($=>{if(s===D){if($?.commandId!==D.commandId||$.status!=="accepted"||!["started","queued"].includes($.disposition)||typeof $.turnId!="string"||$.turnId.length===0){m(new Error("Muse did not admit a fresh turn; refusing ambiguous dispatch"));return}D.id=$.turnId,D.queued=$.disposition==="queued",D.cancelled&&b(D);for(let ie of D.events)s===D&&h(D,ie);D.events=[]}},$=>{s===D&&E(D,$ instanceof Error?$:new Error(String($)))})})}}}var Df=L(()=>{"use strict";Te();fa();Dr();qe();bn();rt()});import{join as ga}from"node:path";import{mkdir as cS}from"node:fs/promises";function _a(t={}){let e=ua(t.museDataHome),r=s=>({...s??process.env,XDG_DATA_HOME:e}),n=async(s,i)=>{if(i.bundleSession)return pt(i.bundleSession,"muse",i.sessionId,s,i);let o=i.sessionId||In(),a=await ni({...i,sessionId:o,create:i.sessionId==="",env:r(i.env),expectedHome:ga(e,"muse")});try{return await a.sendTurn(s,i)}finally{await a.close()}};return new class extends ee{constructor(){super({provider:new Qs({museDataHome:e}),protocol:{transport:"muse-msp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"muse",seedArgs:[],startTemplate:"muse",resumeTemplate:"muse resume {{session_id}}",transport:n})}openSession(s){return ni({...s,env:r(s.env),expectedHome:ga(e,"muse")})}async seed(s,i){await cS(s,{recursive:!0});let o=In(),a;try{if(a=await ni({sessionId:o,cwd:s,create:!0,env:r(),expectedHome:ga(e,"muse"),model:i?.model,effort:i?.effort}),await a.sendTurn(i?.prompt??Y),await a.close(),!await this.load(o))throw new Error("Muse seed did not persist a readable native session");return{success:!0,sessionId:o}}catch(l){return{success:!1,error:`Muse seed failed: ${l instanceof Error?l.message:String(l)}`}}finally{await a?.close()}}}}var ya=L(()=>{"use strict";Te();Lf();Df();Lr();Ee()});function ht(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}var Mf=L(()=>{"use strict"});import{readFile as Ff,readdir as dS,rm as uS,stat as Pf}from"node:fs/promises";import{basename as gO,join as xn,resolve as fS}from"node:path";function Ta(t){return fS(t||process.env.MINIPLAYER_HOME||xn(process.env.XDG_DATA_HOME||xn(V,".local","share"),"miniplayer"))}function si(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function Ea(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function $f(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Uf(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function jf(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return null}}function Bf(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},r={};for(let[l,c]of Object.entries(e))ht(c)!==null&&(r[l]=c);let n=ht(e.inputTokens),s=ht(e.cachedInputTokens),i=ht(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=ht(e.outputTokens),a=null;return t.usageConvention==="input-includes-cache"&&n!==null&&s!==null&&s<=n&&(a=n-s),t.usageConvention==="input-excludes-cache"&&n!==null&&i!==null&&(a=n+i),t.usageConvention==="synthetic"&&n===0&&s===0&&i===0&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:r,pricingFacts:ht(e.reasoningTokens)===null?null:{reasoning_output_tokens:ht(e.reasoningTokens)}}}function pS(t,e,r){if(!t||typeof t!="object")return null;let n=t;if(![1,2].includes(n.version)||n.id!==e||typeof n.cwd!="string")return null;let s=_=>{if(typeof _!="string")return;let E=new Date(_);return Number.isFinite(E.getTime())?E:void 0},i=s(n.createdAt),o=s(n.updatedAt);if(!i||!o)return null;let a=[],l=[],c=[],d=n.version===1,u="complete";if(n.version===1){if(!Array.isArray(n.messages))return null;for(let _ of n.messages){if(!_||!["user","assistant"].includes(_.role)||typeof _.content!="string")return null;a.push({role:_.role,content:_.content,timestamp:s(_.timestamp)??o})}}else{if(!Array.isArray(n.turns))return null;let _=new Set,E=new Set;for(let m of n.turns){if(!m||typeof m.responseId!="string"||!m.responseId||typeof m.input?.text!="string")return null;if(_.has(m.responseId)){d=!0;continue}_.add(m.responseId);let h=s(m.startedAt),T=s(m.completedAt??m.endedAt);if(!h)return null;let g=typeof m.model=="string"?m.model:void 0;["complete","running","failed","aborted"].includes(m.status)||(d=!0);let y=m.status==="complete"?"complete":m.status==="running"?"in_progress":m.status==="failed"?"failed":m.status==="aborted"?"aborted":"unknown";u=y==="failed"||y==="unknown"?"aborted":y,(y!=="complete"||m.partial===!0)&&(d=!0);let v=Array.isArray(m.modelResponses),b=v?m.modelResponses:[],I=[];l.push({id:m.responseId,startedAt:h,completedAt:T,model:g,prompt:m.input.text,status:y,responseIds:I}),a.push({role:"user",timestamp:h,content:m.input.text});let A=Array.isArray(m.toolEvents)&&m.toolEvents.length>0;if(!v&&!A){let k=m.usage??{},x=Bf({...m,usage:k});Object.keys(x.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:m.responseId,values:x.rawUsage}]),I.push(m.responseId),c.push({response_id:m.responseId,timestamp:(T??h).toISOString(),model:g??null,model_provider:typeof m.provider=="string"?m.provider:null,tokens:x.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(m.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:m.responseId,ref:null,bytes:Buffer.byteLength(m.input.text,"utf8"),basis:"input_text"}],pricing_facts:x.pricingFacts}),y!=="complete"&&!m.usage&&(d=!0),typeof m.output?.text=="string"&&a.push({role:"assistant",timestamp:T??h,content:m.output.text,model:g});continue}let S=new Map,w=new Map,N=new Set,R=[];for(let k of b){if(!k||typeof k!="object"||typeof k.responseId!="string"||!k.responseId){d=!0;continue}if(I.includes(k.responseId)){d=!0;continue}let x=k,O=R.length;R.push({response:x,index:O,filesRead:[],filesWritten:[],io:[]}),I.push(k.responseId),E.has(k.responseId)&&(d=!0),E.add(k.responseId),x.toolCalls!==void 0&&!Array.isArray(x.toolCalls)&&(d=!0,R[O].io.push({direction:"read",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:k.responseId,ref:null,bytes:null,basis:"unknown"}));for(let D of Array.isArray(x.toolCalls)?x.toolCalls:[]){let X=$f(D),$=Ea(D);if(X)S.set(X,O),w.set(X,$);else{d=!0;let ie=$==="list_directory"||$==="read_file"||$==="webget"||$==="shell"||$==="tool",B=$==="write_file"||$==="shell"||$==="tool";ie&&R[O].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),B&&R[O].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}I.length===0&&b.length>0&&(d=!0);for(let k of Array.isArray(m.toolEvents)?m.toolEvents:[]){let x=k&&typeof k=="object"?k:{},O=$f(x),D=O?S.get(O):void 0,X=Ea(x),$=Uf(x.result),ie=x.status==="failed"||x.error!==void 0;if(x.type==="tool_call"?a.push({role:"tool_use",timestamp:s(x?.timestamp)??h,content:si(x?.input??x?.args),toolName:X,toolInput:si(x?.input??x?.args),toolInputData:Uf(x?.input??x?.args)??void 0,...O?{toolCallId:O}:{}}):a.push({role:"tool_result",timestamp:s(x?.timestamp)??T??h,content:si(ie?x?.error:x?.result),toolName:X,...O?{toolCallId:O}:{}}),D===void 0){d=!0;continue}let B=R[D];(x.type==="tool_result"||ie||x.result!==void 0)&&N.add(O);let J=$?.path,P=ht($?.bytesRead??$?.bytesWritten);x.type!=="tool_call"&&(X==="read_file"&&!ie&&typeof J=="string"&&P!==null?B.filesRead.push({path:J,bytes:P}):X==="write_file"&&!ie&&typeof J=="string"&&P!==null?B.filesWritten.push({path:J,bytes:P}):X==="webget"&&!ie&&P!==null?B.io.push({direction:"read",kind:"web",id:O,ref:jf($?.finalUrl??$?.url),bytes:P,basis:"certified_counter"}):X==="shell"||ie?(X!=="write_file"&&B.io.push({direction:"read",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}),(X==="shell"||X==="write_file")&&B.io.push({direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"})):X==="list_directory"||X==="read_file"||X==="webget"?B.io.push({direction:"read",kind:X==="webget"?"web":"unattributed",id:O,ref:X==="webget"?jf($?.finalUrl??$?.url):null,bytes:null,basis:"unknown"}):X==="write_file"?B.io.push({direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}):B.io.push({direction:"read",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}))}for(let[k,x]of w)if(!N.has(k)){let O=R[S.get(k)],D=x==="list_directory"||x==="read_file"||x==="webget"||x==="shell",X=x==="write_file"||x==="shell";D&&O.io.push({direction:"read",kind:"unattributed",id:k,ref:null,bytes:null,basis:"unknown"}),X&&O.io.push({direction:"write",kind:"unattributed",id:k,ref:null,bytes:null,basis:"unknown"}),d=!0}for(let k of R){let x=k.response,O=Bf(x),D=s(x.completedAt??x.startedAt)??T??h;new Set((Array.isArray(x.toolCalls)?x.toolCalls:[]).map(B=>Ea(B))).has("shell")&&!k.io.some(B=>B.kind==="unattributed"&&B.direction==="read")&&k.io.push({direction:"read",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"}),k.index===0&&k.io.unshift({direction:"read",kind:"prompt",id:m.responseId,ref:null,bytes:Buffer.byteLength(m.input.text,"utf8"),basis:"input_text"});let $=k.io.some(B=>B.direction==="read"&&B.bytes===null),ie=k.io.some(B=>B.direction==="write"&&B.bytes===null);if(c.push({response_id:x.responseId,timestamp:D.toISOString(),model:typeof x.model=="string"?x.model:null,model_provider:typeof x.provider=="string"?x.provider:typeof m.provider=="string"?m.provider:null,tokens:O.tokens,files_read:$?null:k.filesRead,files_written:ie?null:k.filesWritten,read_bytes:$?null:k.filesRead.reduce((B,J)=>B+(J.bytes??0),0)+k.io.filter(B=>B.direction==="read").reduce((B,J)=>B+(J.bytes??0),0),write_bytes:ie?null:k.filesWritten.reduce((B,J)=>B+(J.bytes??0),0)+k.io.filter(B=>B.direction==="write").reduce((B,J)=>B+(J.bytes??0),0),external_io:k.io,pricing_facts:O.pricingFacts}),Object.keys(O.rawUsage).length){let B=l.at(-1);B.rawUsage=[...B.rawUsage??[],{responseId:x.responseId,values:O.rawUsage}]}}l.at(-1).responseIds=I,I.length!==b.length&&(d=!0),typeof m.output?.text=="string"&&a.push({role:"assistant",timestamp:T??h,content:m.output.text,model:g})}}let f=a.filter(_=>_.role==="user").map(_=>_.content),p=zs(c,!d);return{provider:"miniplayer",sessionId:e,cwd:n.cwd,filePath:r,createdAt:i,modifiedAt:o,model:typeof n.model=="string"?n.model:void 0,messages:a,messageCount:a.length,userPrompts:f,firstUserMessage:f[0],lastUserMessage:f.at(-1),turns:l,responses:c,turnStatus:u,...d?{captureStatus:"partial"}:{},totalInputTokens:p.input_uncached??void 0,totalCachedInputTokens:p.input_cached??void 0,totalCacheWriteInputTokens:p.input_cache_write??void 0,totalOutputTokens:p.output??void 0}}var mS,ii,Hf=L(()=>{"use strict";da();pe();Mf();mS=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;ii=class{name="miniplayer";home;constructor(e={}){this.home=Ta(e.miniplayerHome)}getWatchPaths(){return[{directory:xn(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await dS(xn(this.home,"sessions"))}catch{return[]}return(await Promise.all(e.filter(n=>n.endsWith(".json")).map(n=>this.loadSession(n.slice(0,-5))))).filter(n=>n!==null)}async resolveSessionPath(e){if(!mS.test(e))return null;let r=xn(this.home,"sessions",`${e}.json`);try{return(await Pf(r)).isFile()?r:null}catch{return null}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;try{let n=pS(JSON.parse(await Ff(r,"utf8")),e,r);if(!n)return null;let s="complete";try{let i=JSON.parse(await Ff(`${r}.lock`,"utf8"));if(Number.isInteger(i.pid)&&i.pid>0)try{process.kill(i.pid,0),s="in_progress"}catch{s="aborted"}}catch{}return{...n,...s!=="complete"?{turnStatus:s}:{}}}catch{return null}}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{throw await Pf(`${r}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(n){if(n.code!=="ENOENT")throw n}return await uS(r),!0}}});function Wf(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let r=0;r<t.length;r++)r===0?e.push(t[r]):e.push(`
|
|
1603
|
+
`)};return n.on("line",a=>{let l=u=>{if(!e.onProtocolError)return;let f=a.slice(0,512);D({event:`${r}_protocol_error`,provider:e.provider,reason:u,raw_preview:f,truncated:a.length>512}),e.onProtocolError(new Error(`${r.toUpperCase()} ${u}: ${JSON.stringify(f)}${a.length>512?" (truncated)":""}`))},c;try{c=JSON.parse(a)}catch{l("returned malformed JSON");return}if(!c||typeof c!="object"||Array.isArray(c)){l("returned an invalid message");return}if(Se({event:`${r}_recv`,direction:"RECV",provider:e.provider,id:typeof c.id=="number"?c.id:void 0,method:typeof c.method=="string"?c.method:void 0,preview:JSON.stringify(c).slice(0,300)}),e.onEvent?.(c),typeof c.method!="string"&&typeof c.id=="number"&&s.has(c.id)){let u=s.get(c.id);s.delete(c.id);try{u.onResponse?.(c)}catch(f){u.reject(f instanceof Error?f:new Error(String(f)));return}if(c.error){let f=c.error,p=typeof f?.message=="string"&&f.message.length>0?f.message:JSON.stringify(c.error);u.reject(Tn(`${r.toUpperCase()} RPC error: ${p}`,f))}else u.resolve(c);return}let d=c.method;if(!d){l("returned an uncorrelated response");return}if(typeof c.id=="number"||typeof c.id=="string"){D({event:`${r}_unhandled_request`,provider:e.provider,method:d,id:c.id,params:c.params});let u=JSON.stringify({jsonrpc:"2.0",id:c.id,error:{code:-32601,message:`Method not found: ${d} (lmctl does not implement server-side ${r.toUpperCase()} methods)`}});Se({event:`${r}_send`,direction:"SEND",provider:e.provider,replyTo:c.id,error:"method not found"}),t.stdin?.write(`${u}
|
|
1604
|
+
`);return}e.onNotification?.(c)}),{sendRpc:i,sendNotification:o,close(a=new se(`${r.toUpperCase()} RPC channel closed`)){n.close();for(let l of s.values())l.reject(a);s.clear()}}}var qw,ua=L(()=>{"use strict";re();Qt();qw=1});import*as ma from"node:child_process";function Jw(t){if(typeof ma.spawnSync=="function")try{ma.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function Af(t){return t.exitCode!==null||t.signalCode!==null}function fa(t,e){return Af(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 te(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??Jw;if(Af(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await fa(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 fa(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await fa(t,Gw)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var Gw,Lr=L(()=>{"use strict";Gw=1e3});async function ei(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(pa),e),n.unref?.(),r!==void 0&&(s=()=>i(pa),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function tt(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();Qw(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function Qw(t,e,r,n){let s=t.pollMs??Vw,i=t.maxHoldMs??Zs,o=t.settleMs??Kw,a=t.backgroundGraceMs??Yw,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 ei(t.hasOutstandingWork(),u,e.signal)}catch{return d("check-error")}if(f===pa)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 E=a-(Date.now()-r);await new Promise(m=>setTimeout(m,Math.max(0,Math.min(s,zw,E))).unref?.());continue}if(!l||o<=0)return d("cleared");c===null&&(c=Date.now(),ge(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let _=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-_>=o)return d("cleared")}if(l||(l=!0,t.onHold?.(),ge(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-r>=i)return D({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-r}),d("max-hold");let p=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(_=>setTimeout(_,p).unref?.())}}var Vw,Zs,Kw,Yw,zw,pa,wn=L(()=>{"use strict";re();Vw=2e3,Zs=8*60*60*1e3,Kw=5e3,Yw=1e3,zw=50,pa=Symbol("check-timed-out")});function Nf(t){ae()&&Se({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Dt(t,e){let r=eS[t];if(r)return r[e]??r.yolo}function rS(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 he(t,e,r="yolo"){if(tS.has(t)){Nf(`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":t==="muse"?"MSP approval mode plus fixed host sandbox/write/shell posture":t==="miniplayer"?"native tools always granted; no permission mode":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?Dt(t,"plan"):Zw[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 D({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new se(s)}if(!rS(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 D({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new se(i)}Nf(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var Zw,eS,tS,rt=L(()=>{"use strict";Qt();re();Zw={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},eS={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"]}};tS=new Set(["codex","opencode","kimi","dsh","hermes","pi","miniplayer","muse"])});import{spawn as nS}from"node:child_process";import{randomBytes as sS}from"node:crypto";import{realpath as ti}from"node:fs/promises";function Sn(){let t=sS(16);t.writeUIntBE(Date.now(),0,6),t[6]=t[6]&15|112,t[8]=t[8]&63|128;let e=t.toString("hex");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}async function ri(t){if(t.signal?.aborted)throw new Error("Aborted");if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t.sessionId))throw new Error("Muse requires a native session UUID");let e=t.permissionMode==="plan",r=["serve",...e?["--disable-write","--disable-shell"]:["--disable-sandbox","--trust-workspace"],...t.model?["--model",t.model]:[]];he("muse",r,t.permissionMode??"yolo");let n=nS(t.progPath??"muse",r,{cwd:t.cwd,env:ue(t.env,t.cwd,t.sessionId),stdio:["pipe","pipe","pipe"]}),s,i,o,a=!1,l=!1,c=!1,d=!1,u=0,f="",p=Date.now(),_=t.sessionId;n.stderr.setEncoding("utf8"),n.stderr.on("data",w=>{f=(f+w).slice(-32768)});let E=(w,N,A)=>{s===w&&(s=void 0,w.cleanup(),w.drained(),w.settled||(w.settled=!0,N?w.reject(N):(u++,w.resolve(A))))},m=w=>{i||(i=w,s&&E(s,i),T.close(i),!d&&!a&&te(n,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{}))},h=(w,N)=>{let A=N.params;if(!A||A.sessionId!==_)return;let R=N.method;if(R==="view/gap"||R==="session/closed"){m(new Error(`Muse ${R}: the conversation cannot continue without reopening`));return}if(R==="turn/unqueued"&&A.turnId===w.id){E(w,new Rr("Muse queued turn cancelled","external"));return}R==="turn/started"&&A.turnId===w.id&&(w.queued=!1);let x=A.item,O=A.turnId??x?.turnId;if(O&&O!==w.id)return;w.opts.onEvent?.(N);let M={kind:"other",raw:N};if(["item/started","item/updated","item/completed"].includes(R)&&x?.turnId===w.id&&typeof x.itemId=="string"){let $=w.items.get(x.itemId);if($&&typeof x.revision=="number"&&x.revision<=$.revision)return;w.items.set(x.itemId,{...x}),(x.kind==="toolCall"||x.kind==="userShell")&&R!=="item/updated"?M={kind:R==="item/completed"?"tool_result":"tool_use",id:x.itemId,tool:x.tool??x.kind,summary:x.failureReason??x.fallbackText,...R==="item/completed"?{status:x.status==="completed"?"ok":"error"}:{},...x.durationMs!==void 0?{elapsedMs:x.durationMs}:{},raw:N}:x.kind==="reasoning"?M={kind:"thinking",raw:N}:x.kind==="agentMessage"&&(M={kind:"text",raw:N})}else if(R==="item/delta"&&typeof A.itemId=="string"&&typeof A.delta=="string"){let $=w.items.get(A.itemId);if(!$)return;$.kind==="agentMessage"&&(A.field===void 0||A.field==="text")?($.text=($.text??"")+A.delta,w.cancelled||w.opts.onDelta?.(A.delta),M={kind:"text",raw:N}):$.kind==="reasoning"&&(M={kind:"thinking",raw:N})}if(w.cancelled||w.opts.onProgress?.(M),R!=="turn/completed"||A.turnId!==w.id)return;if(!["completed","failed","cancelled"].includes(A.terminal)){m(new Error(`Muse returned an unknown turn terminal: ${String(A.terminal)}`));return}if(w.cancelled||A.terminal==="cancelled"){E(w,new Rr("Muse turn cancelled",w.cancelled?"external":"provider"));return}if(A.terminal!=="completed"){E(w,new Error(A.error?.message??A.reason??`Muse turn ended with ${String(A.terminal)}`));return}let X=[...w.items.values()].filter($=>$.kind==="agentMessage");E(w,void 0,{text:X.map($=>typeof $.text=="string"?$.text:"").join(`
|
|
1605
|
+
`),sessionId:_,durationMs:typeof A.durationMs=="number"?A.durationMs:Date.now()-w.started,stopReason:A.terminal,...X.some($=>$.truncated)?{warnings:["Muse reported a truncated response; inspect the native transcript for complete content"]}:{}})},T=Ot(n,{provider:"muse",protocol:"msp",onProtocolError:m,onNotification:w=>{if(p=Date.now(),w.method==="view/gap"||w.method==="session/closed"){w.params?.sessionId===_&&!a&&m(new Error(`Muse ${w.method}: session must be reopened`));return}let N=s;N&&(N.id?h(N,w):N.events.push(w))}}),g=async(w,N,A=Sn())=>(await T.sendRpc(w,{...N,commandId:A})).result,y=w=>{!w.id||w.interruptSent||s!==w||(w.interruptSent=!0,g("turn/interrupt",{sessionId:_,turnId:w.id}).catch(N=>{s===w&&m(N instanceof Error?N:new Error(String(N)))}))},S=w=>{!w.id||w.unqueueSent||s!==w||(w.unqueueSent=!0,g("turn/unqueue",{sessionId:_,turnId:w.id}).catch(N=>{let A=N instanceof Error?N.message:String(N);/already started|not queued|launch boundary|turn is running/i.test(A)?(w.queued=!1,y(w)):s===w&&m(N instanceof Error?N:new Error(A))}))},I=w=>{w.queued?S(w):y(w)};n.on("error",w=>m(new Error(`Unable to start Muse: ${w.message}`)));let b=()=>{a||d||i||c||(c=!0,te(n,{softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(w=>m(w instanceof Error?w:new Error(String(w)))))};n.stdin.on("error",b),n.stdout.on("end",b),n.on("exit",()=>{d=!0}),n.on("close",(w,N)=>{d=!0,a?T.close(new Error("Muse session closed")):m(new Error(`Muse exited (${N??w}) after ${u} completed prompt(s)${f?`: ${f.trim()}`:""}`)),s&&E(s,new Error("Muse session closed"))});let k=()=>{if(o)return o;a=!0;let w=!!s;return s&&(s.cancelled=!0,I(s)),o=(async()=>{d||(await new Promise(N=>tt(l?t.holdOpen:void 0,{isAborted:()=>w,hasChildExited:()=>d,isTurnInFlight:()=>!!s,lastEventAtMs:()=>p,closeStdin:()=>{n.stdin.end(),N()},label:"muse"})),await te(n,{stdinEnd:!1,softDelayMs:t.closeTimeoutMs??2e3,killDelayMs:t.closeTimeoutMs??2e3}).catch(()=>{})),s&&E(s,new Error("Muse session closed")),T.close(new Error("Muse session closed"))})(),o},v=()=>{m(new Error("Aborted")),k()};t.signal?.addEventListener("abort",v,{once:!0});try{if(t.signal?.aborted)throw new Error("Aborted");let w=(await T.sendRpc("initialize",{clientInfo:{name:"lmctl",version:"1"}})).result;if(w?.schema?.version!==1)throw new Error("Muse MSP schema version is unsupported");if(t.expectedHome&&(typeof w.museHome!="string"||await ti(w.museHome)!==await ti(t.expectedHome)))throw new Error("Muse data home does not match the configured session reader");if(w.sessionDurability!==void 0&&w.sessionDurability!=="durable")throw new Error("Muse did not provide durable sessions");T.sendNotification("initialized");let N=e?"denyUnmatched":"allowAll",R=(t.create?await g("session/start",{sessionId:_,workspaceRoot:t.cwd,approvalMode:N,...t.model?{modelId:t.model}:{}}):await g("session/resume",{sessionId:_,excludeItems:!0}))?.session;if(R?.sessionId!==_)throw new Error(`Muse did not return requested session "${_}"`);if(typeof R.workspaceRoot!="string"||await ti(R.workspaceRoot)!==await ti(t.cwd))throw new Error("Muse session belongs to a different working directory");if(R.activeTurnId||R.status!=="idle")throw new Error(`Muse session is not idle (${String(R.status)})`);if((await g("session/setApprovalMode",{sessionId:_,mode:N}))?.effectiveMode?.mode!==N)throw new Error("Muse did not apply the requested approval mode");if(!t.create&&t.model&&R.modelId!==t.model&&(await g("session/setModel",{sessionId:_,model:{modelId:t.model,...R.providerId?{providerId:R.providerId}:{}}}))?.status!=="accepted")throw new Error("Muse did not accept the requested model");l=!0}catch(w){throw await k(),i??w}finally{t.signal?.removeEventListener("abort",v)}return{provider:"muse",sessionId:_,get completedTurns(){return u},close:k,async sendTurn(w,N={}){if(s?.cancelled&&await s.drain,i)throw i;if(a)throw new Error("Muse session is closed");if(s)throw new Error("Muse already has an active turn");if(N.signal?.aborted)throw new Error("Aborted");return new Promise((A,R)=>{let x,O=new Promise($=>{x=$}),M={commandId:Sn(),events:[],items:new Map,opts:N,started:Date.now(),cancelled:!1,interruptSent:!1,unqueueSent:!1,queued:!1,settled:!1,resolve:A,reject:R,drain:O,drained:x,cleanup:()=>{}};s=M;let X=()=>{M.cancelled=!0,M.settled=!0,R(new Error("Aborted")),I(M)};M.cleanup=()=>N.signal?.removeEventListener("abort",X),N.signal?.addEventListener("abort",X,{once:!0}),g("turn/start",{sessionId:_,input:[{type:"text",text:w}],...t.effort?{reasoningEffort:t.effort}:{}},M.commandId).then($=>{if(s===M){if($?.commandId!==M.commandId||$.status!=="accepted"||!["started","queued"].includes($.disposition)||typeof $.turnId!="string"||$.turnId.length===0){m(new Error("Muse did not admit a fresh turn; refusing ambiguous dispatch"));return}M.id=$.turnId,M.queued=$.disposition==="queued",M.cancelled&&I(M);for(let ie of M.events)s===M&&h(M,ie);M.events=[]}},$=>{s===M&&E(M,$ instanceof Error?$:new Error(String($)))})})}}}var Rf=L(()=>{"use strict";Te();ua();Lr();qe();wn();rt()});import{join as ha}from"node:path";import{mkdir as iS}from"node:fs/promises";function ga(t={}){let e=da(t.museDataHome),r=s=>({...s??process.env,XDG_DATA_HOME:e}),n=async(s,i)=>{if(i.bundleSession)return pt(i.bundleSession,"muse",i.sessionId,s,i);let o=i.sessionId||Sn(),a=await ri({...i,sessionId:o,create:i.sessionId==="",env:r(i.env),expectedHome:ha(e,"muse")});try{return await a.sendTurn(s,i)}finally{await a.close()}};return new class extends ee{constructor(){super({provider:new zs({museDataHome:e}),protocol:{transport:"muse-msp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"muse",seedArgs:[],startTemplate:"muse",resumeTemplate:"muse resume {{session_id}}",transport:n})}openSession(s){return ri({...s,env:r(s.env),expectedHome:ha(e,"muse")})}async seed(s,i){await iS(s,{recursive:!0});let o=Sn(),a;try{if(a=await ri({sessionId:o,cwd:s,create:!0,env:r(),expectedHome:ha(e,"muse"),model:i?.model,effort:i?.effort}),await a.sendTurn(i?.prompt??Y),await a.close(),!await this.load(o))throw new Error("Muse seed did not persist a readable native session");return{success:!0,sessionId:o}}catch(l){return{success:!1,error:`Muse seed failed: ${l instanceof Error?l.message:String(l)}`}}finally{await a?.close()}}}}var _a=L(()=>{"use strict";Te();kf();Rf();Ar();Ee()});function ht(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:null}var Lf=L(()=>{"use strict"});import{readFile as Cf,readdir as oS,rm as aS,stat as Of}from"node:fs/promises";import{basename as lO,join as vn,resolve as lS}from"node:path";function Ea(t){return lS(t||process.env.MINIPLAYER_HOME||vn(process.env.XDG_DATA_HOME||vn(V,".local","share"),"miniplayer"))}function ni(t){if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function ya(t){return!t||typeof t!="object"?"tool":typeof t.toolName=="string"?t.toolName:typeof t.name=="string"?t.name:"tool"}function Df(t){if(!t||typeof t!="object")return null;let e=t.toolCallId??t.id;return typeof e=="string"&&e.length>0?e:null}function Mf(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ff(t){if(typeof t!="string")return null;try{let e=new URL(t);return e.username="",e.password="",e.search="",e.hash="",e.toString()}catch{return null}}function Pf(t){let e=t.usage&&typeof t.usage=="object"&&!Array.isArray(t.usage)?t.usage:{},r={};for(let[l,c]of Object.entries(e))ht(c)!==null&&(r[l]=c);let n=ht(e.inputTokens),s=ht(e.cachedInputTokens),i=ht(t.cacheWriteInputTokens??e.cacheWriteInputTokens),o=ht(e.outputTokens),a=null;return t.usageConvention==="input-includes-cache"&&n!==null&&s!==null&&s<=n&&(a=n-s),t.usageConvention==="input-excludes-cache"&&n!==null&&i!==null&&(a=n+i),t.usageConvention==="synthetic"&&n===0&&s===0&&i===0&&o===0&&(a=0),{tokens:{input_uncached:a,input_cached:s,input_cache_write:i,output:o},rawUsage:r,pricingFacts:ht(e.reasoningTokens)===null?null:{reasoning_output_tokens:ht(e.reasoningTokens)}}}function dS(t,e,r){if(!t||typeof t!="object")return null;let n=t;if(![1,2].includes(n.version)||n.id!==e||typeof n.cwd!="string")return null;let s=_=>{if(typeof _!="string")return;let E=new Date(_);return Number.isFinite(E.getTime())?E:void 0},i=s(n.createdAt),o=s(n.updatedAt);if(!i||!o)return null;let a=[],l=[],c=[],d=n.version===1,u="complete";if(n.version===1){if(!Array.isArray(n.messages))return null;for(let _ of n.messages){if(!_||!["user","assistant"].includes(_.role)||typeof _.content!="string")return null;a.push({role:_.role,content:_.content,timestamp:s(_.timestamp)??o})}}else{if(!Array.isArray(n.turns))return null;let _=new Set,E=new Set;for(let m of n.turns){if(!m||typeof m.responseId!="string"||!m.responseId||typeof m.input?.text!="string")return null;if(_.has(m.responseId)){d=!0;continue}_.add(m.responseId);let h=s(m.startedAt),T=s(m.completedAt??m.endedAt);if(!h)return null;let g=typeof m.model=="string"?m.model:void 0;["complete","running","failed","aborted"].includes(m.status)||(d=!0);let y=m.status==="complete"?"complete":m.status==="running"?"in_progress":m.status==="failed"?"failed":m.status==="aborted"?"aborted":"unknown";u=y==="failed"||y==="unknown"?"aborted":y,(y!=="complete"||m.partial===!0)&&(d=!0);let S=Array.isArray(m.modelResponses),I=S?m.modelResponses:[],b=[];l.push({id:m.responseId,startedAt:h,completedAt:T,model:g,prompt:m.input.text,status:y,responseIds:b}),a.push({role:"user",timestamp:h,content:m.input.text});let k=Array.isArray(m.toolEvents)&&m.toolEvents.length>0;if(!S&&!k){let R=m.usage??{},x=Pf({...m,usage:R});Object.keys(x.rawUsage).length&&(l.at(-1).rawUsage=[{responseId:m.responseId,values:x.rawUsage}]),b.push(m.responseId),c.push({response_id:m.responseId,timestamp:(T??h).toISOString(),model:g??null,model_provider:typeof m.provider=="string"?m.provider:null,tokens:x.tokens,files_read:[],files_written:[],read_bytes:Buffer.byteLength(m.input.text,"utf8"),write_bytes:0,external_io:[{direction:"read",kind:"prompt",id:m.responseId,ref:null,bytes:Buffer.byteLength(m.input.text,"utf8"),basis:"input_text"}],pricing_facts:x.pricingFacts}),y!=="complete"&&!m.usage&&(d=!0),typeof m.output?.text=="string"&&a.push({role:"assistant",timestamp:T??h,content:m.output.text,model:g});continue}let v=new Map,w=new Map,N=new Set,A=[];for(let R of I){if(!R||typeof R!="object"||typeof R.responseId!="string"||!R.responseId){d=!0;continue}if(b.includes(R.responseId)){d=!0;continue}let x=R,O=A.length;A.push({response:x,index:O,filesRead:[],filesWritten:[],io:[]}),b.push(R.responseId),E.has(R.responseId)&&(d=!0),E.add(R.responseId),x.toolCalls!==void 0&&!Array.isArray(x.toolCalls)&&(d=!0,A[O].io.push({direction:"read",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:R.responseId,ref:null,bytes:null,basis:"unknown"}));for(let M of Array.isArray(x.toolCalls)?x.toolCalls:[]){let X=Df(M),$=ya(M);if(X)v.set(X,O),w.set(X,$);else{d=!0;let ie=$==="list_directory"||$==="read_file"||$==="webget"||$==="shell"||$==="tool",B=$==="write_file"||$==="shell"||$==="tool";ie&&A[O].io.push({direction:"read",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"}),B&&A[O].io.push({direction:"write",kind:"unattributed",id:null,ref:null,bytes:null,basis:"unknown"})}}}b.length===0&&I.length>0&&(d=!0);for(let R of Array.isArray(m.toolEvents)?m.toolEvents:[]){let x=R&&typeof R=="object"?R:{},O=Df(x),M=O?v.get(O):void 0,X=ya(x),$=Mf(x.result),ie=x.status==="failed"||x.error!==void 0;if(x.type==="tool_call"?a.push({role:"tool_use",timestamp:s(x?.timestamp)??h,content:ni(x?.input??x?.args),toolName:X,toolInput:ni(x?.input??x?.args),toolInputData:Mf(x?.input??x?.args)??void 0,...O?{toolCallId:O}:{}}):a.push({role:"tool_result",timestamp:s(x?.timestamp)??T??h,content:ni(ie?x?.error:x?.result),toolName:X,...O?{toolCallId:O}:{}}),M===void 0){d=!0;continue}let B=A[M];(x.type==="tool_result"||ie||x.result!==void 0)&&N.add(O);let J=$?.path,P=ht($?.bytesRead??$?.bytesWritten);x.type!=="tool_call"&&(X==="read_file"&&!ie&&typeof J=="string"&&P!==null?B.filesRead.push({path:J,bytes:P}):X==="write_file"&&!ie&&typeof J=="string"&&P!==null?B.filesWritten.push({path:J,bytes:P}):X==="webget"&&!ie&&P!==null?B.io.push({direction:"read",kind:"web",id:O,ref:Ff($?.finalUrl??$?.url),bytes:P,basis:"certified_counter"}):X==="shell"||ie?(X!=="write_file"&&B.io.push({direction:"read",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}),(X==="shell"||X==="write_file")&&B.io.push({direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"})):X==="list_directory"||X==="read_file"||X==="webget"?B.io.push({direction:"read",kind:X==="webget"?"web":"unattributed",id:O,ref:X==="webget"?Ff($?.finalUrl??$?.url):null,bytes:null,basis:"unknown"}):X==="write_file"?B.io.push({direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}):B.io.push({direction:"read",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:O,ref:null,bytes:null,basis:"unknown"}))}for(let[R,x]of w)if(!N.has(R)){let O=A[v.get(R)],M=x==="list_directory"||x==="read_file"||x==="webget"||x==="shell",X=x==="write_file"||x==="shell";M&&O.io.push({direction:"read",kind:"unattributed",id:R,ref:null,bytes:null,basis:"unknown"}),X&&O.io.push({direction:"write",kind:"unattributed",id:R,ref:null,bytes:null,basis:"unknown"}),d=!0}for(let R of A){let x=R.response,O=Pf(x),M=s(x.completedAt??x.startedAt)??T??h;new Set((Array.isArray(x.toolCalls)?x.toolCalls:[]).map(B=>ya(B))).has("shell")&&!R.io.some(B=>B.kind==="unattributed"&&B.direction==="read")&&R.io.push({direction:"read",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"},{direction:"write",kind:"unattributed",id:x.responseId,ref:null,bytes:null,basis:"unknown"}),R.index===0&&R.io.unshift({direction:"read",kind:"prompt",id:m.responseId,ref:null,bytes:Buffer.byteLength(m.input.text,"utf8"),basis:"input_text"});let $=R.io.some(B=>B.direction==="read"&&B.bytes===null),ie=R.io.some(B=>B.direction==="write"&&B.bytes===null);if(c.push({response_id:x.responseId,timestamp:M.toISOString(),model:typeof x.model=="string"?x.model:null,model_provider:typeof x.provider=="string"?x.provider:typeof m.provider=="string"?m.provider:null,tokens:O.tokens,files_read:$?null:R.filesRead,files_written:ie?null:R.filesWritten,read_bytes:$?null:R.filesRead.reduce((B,J)=>B+(J.bytes??0),0)+R.io.filter(B=>B.direction==="read").reduce((B,J)=>B+(J.bytes??0),0),write_bytes:ie?null:R.filesWritten.reduce((B,J)=>B+(J.bytes??0),0)+R.io.filter(B=>B.direction==="write").reduce((B,J)=>B+(J.bytes??0),0),external_io:R.io,pricing_facts:O.pricingFacts}),Object.keys(O.rawUsage).length){let B=l.at(-1);B.rawUsage=[...B.rawUsage??[],{responseId:x.responseId,values:O.rawUsage}]}}l.at(-1).responseIds=b,b.length!==I.length&&(d=!0),typeof m.output?.text=="string"&&a.push({role:"assistant",timestamp:T??h,content:m.output.text,model:g})}}let f=a.filter(_=>_.role==="user").map(_=>_.content),p=Ys(c,!d);return{provider:"miniplayer",sessionId:e,cwd:n.cwd,filePath:r,createdAt:i,modifiedAt:o,model:typeof n.model=="string"?n.model:void 0,messages:a,messageCount:a.length,userPrompts:f,firstUserMessage:f[0],lastUserMessage:f.at(-1),turns:l,responses:c,turnStatus:u,...d?{captureStatus:"partial"}:{},totalInputTokens:p.input_uncached??void 0,totalCachedInputTokens:p.input_cached??void 0,totalCacheWriteInputTokens:p.input_cache_write??void 0,totalOutputTokens:p.output??void 0}}var cS,si,$f=L(()=>{"use strict";ca();pe();Lf();cS=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;si=class{name="miniplayer";home;constructor(e={}){this.home=Ea(e.miniplayerHome)}getWatchPaths(){return[{directory:vn(this.home,"sessions"),filePattern:/\.json$/}]}async discoverSessions(){let e;try{e=await oS(vn(this.home,"sessions"))}catch{return[]}return(await Promise.all(e.filter(n=>n.endsWith(".json")).map(n=>this.loadSession(n.slice(0,-5))))).filter(n=>n!==null)}async resolveSessionPath(e){if(!cS.test(e))return null;let r=vn(this.home,"sessions",`${e}.json`);try{return(await Of(r)).isFile()?r:null}catch{return null}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;try{let n=dS(JSON.parse(await Cf(r,"utf8")),e,r);if(!n)return null;let s="complete";try{let i=JSON.parse(await Cf(`${r}.lock`,"utf8"));if(Number.isInteger(i.pid)&&i.pid>0)try{process.kill(i.pid,0),s="in_progress"}catch{s="aborted"}}catch{}return{...n,...s!=="complete"?{turnStatus:s}:{}}}catch{return null}}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{throw await Of(`${r}.lock`),new Error("Cannot delete a locked miniplayer session")}catch(n){if(n.code!=="ENOENT")throw n}return await aS(r),!0}}});function Uf(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(`
|
|
1606
1606
|
|
|
1607
1607
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1608
1608
|
|
|
1609
|
-
`+t[r]);return e.join("")}function
|
|
1609
|
+
`+t[r]);return e.join("")}function ii(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=jf(e),i=Uf(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 jf(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(_=>typeof _=="string").join("; "):void 0,p=typeof a.subtype=="string"?a.subtype:"unknown";o=f&&f.length>0?f:`result subtype=${p} (no error detail provided)`}}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s,isError:i,errorMessage:o}}var Ta=L(()=>{"use strict"});import{spawn as Hf}from"node:child_process";import{existsSync as Wf}from"node:fs";import{join as oi}from"node:path";import{readdir as uS}from"node:fs/promises";function Xf(){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 qf(){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 Gf(t){let r=t.message?.content;return Array.isArray(r)?r.some(n=>n?.type==="tool_use"):!1}function mS(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1610
1610
|
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:
|
|
1611
1611
|
${e}
|
|
1612
1612
|
|
|
1613
|
-
${r}`:r}function
|
|
1614
|
-
`);u=Q.pop()||"";for(let
|
|
1615
|
-
`),ge(`stream-json: prompt sent (${t.length} chars)`)})}function
|
|
1616
|
-
`);P=W.pop()||"";for(let fe of W)
|
|
1617
|
-
`),ge(`stream-json bundle: prompt sent (${F.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(F=>{tt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),F()},label:e})}):i.stdin?.end(),!a.exited)){let F=t.closeTimeoutMs??2e3;await Promise.race([
|
|
1613
|
+
${r}`:r}function Jf(t){let e=t.tool||"claude",r=t.binaryPath||fS[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=Dt(e,s)??pS[e]??["--dangerously-skip-permissions"];if(n.push(...i),he(e,n,s),t.cwd&&!Wf(t.cwd))throw D({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new se(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=ue(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?Tf(o):o}}function Vf(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Jf(e))}catch(P){return n(P instanceof Error?P:new Error(String(P)))}let c=Hf(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",P=>{ge(`stream-json: stdin pipe error, ignored (exit handler reports): ${P.message}`)});let d=!1;if(e.signal){if(e.signal.aborted)return d=!0,D({event:"transport_abort",provider:i,phase:"pre_spawn"}),te(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,D({event:"transport_abort",provider:i}),te(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let u="",f=!1,p=!1,_=0,E=!1,m="",h="",T,g,y=null,S=null,I=!1,b=!1,k=Xf(),v=qf();function w(){T!==void 0&&(clearTimeout(T),T=void 0)}function N(){g!==void 0&&(clearTimeout(g),g=void 0)}let A=null;function R(){return f||d||X.sawResult()}function x(P){return P==="text_done"?k:v}async function O(P){if(P==="text_done"?T=void 0:g=void 0,R()||y!==null)return;A??=Date.now();let Q=x(P);if(e.holdOpen){let Vr=(e.holdOpen.maxHoldMs??Zs)-(Date.now()-A),fo=Vr>0?await ei(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),Vr,e.signal):!1;if(R()||(P==="text_done"?T!==void 0:g!==void 0))return;if(fo===!0){D({event:"transport_stall_grace_deferred",provider:i,grace_kind:P,grace_ms:Q,reason:"outstanding_dispatched_work"}),M(P);return}}S=P,y=P==="text_done"?`${i} finished responding but never emitted its closing result event (${Q}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${Q}ms of silence)`,D({event:"transport_stall_grace_fired",provider:i,grace_kind:P,grace_ms:Q}),te(c).catch(()=>{})}function M(P){let Q=setTimeout(()=>{O(P)},x(P));Q.unref?.(),P==="text_done"?(w(),T=Q):(N(),g=Q)}let X=ii({onEvent:P=>{_=Date.now(),E=P.type!=="result",P.type==="system"&&P.subtype==="init"&&(h=P.session_id||h),P.type==="assistant"?(I=!Gf(P),b=I&&P.message?.stop_reason==="pause_turn"):(P.type==="result"||P.type==="user")&&(I=!1,b=!1),w(),i==="claude"&&I&&!b&&!X.sawResult()&&M("text_done"),N(),i==="claude"&&!X.sawResult()&&M("tool_use_silence"),e.onEvent?.(P)},onText:P=>{m+=P,e.onText?.(P)}});function $(){p||(p=!0,tt(e.holdOpen,{isAborted:()=>d,hasChildExited:()=>f,isTurnInFlight:()=>E,lastEventAtMs:()=>_,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function ie(P){let Q=X.sawResult();X.processLine(P),!Q&&X.sawResult()&&$()}c.stdout?.on("data",P=>{u+=P.toString();let Q=u.split(`
|
|
1614
|
+
`);u=Q.pop()||"";for(let Zn of Q)ie(Zn)});let B="";c.stderr?.on("data",P=>{B+=P.toString()}),c.on("error",P=>{D({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:P.message}),n(new se(`Failed to spawn ${o}: ${P.message}`,{cause:P}))}),c.on("exit",P=>{if(f=!0,w(),N(),d)return;u.trim()&&ie(u);let Q=X.finalize();Q?.isError?(D({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:Q.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${Q.errorMessage??"unknown error"}`))):Q?(ge(`stream-json: result ${Q.result.slice(0,80)}${Q.result.length>80?"...":""} (${Q.durationMs}ms)`),r({result:Q.result,sessionId:Q.sessionId,durationMs:Q.durationMs,numTurns:Q.numTurns,exitCode:P})):y!==null&&S==="text_done"&&m.trim().length>0?(D({event:"transport_stall_finalized",provider:i,reason:y,text_len:m.length}),r({result:m,sessionId:h||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:P,warnings:[y]})):y!==null&&S==="tool_use_silence"?(D({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:P,stderr_tail:B.slice(0,500)}),n(new Error(`${y} \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})`:"")))):(D({event:"transport_error",provider:i,error_class:"Error",reason:y!==null?"provider_stalled_no_content":"provider_no_result",exit_code:P,stderr_tail:B.slice(0,500)}),n(new Error(y!==null?`${y} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):mS({tool:i,exitCode:P,stderr:B}))))});let J=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(J+`
|
|
1615
|
+
`),ge(`stream-json: prompt sent (${t.length} chars)`)})}function hS(t){return t==="qwen"?[oi(V,".qwen","projects")]:[oi(V,".claude","projects")]}async function Bf(t,e,r){let n=r??hS(t),s=null;for(let a of n){let l;try{l=await uS(a)}catch{continue}for(let c of l){for(let d of[oi(a,c,`${e}.jsonl`),oi(a,c,"chats",`${e}.jsonl`)])if(Wf(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 Oe(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 Kf(t){let{tool:e,binary:r,args:n,spawnEnv:s}=Jf(t),i=Hf(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",F=>{ge(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${F.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",F=>{d+=F.toString()});let u="",f="",p=!1,_=!1,E=null,m=null,h=null,T,g,y=Xf(),S=qf(),I=null,b=[],k=()=>a.exited?Promise.resolve():new Promise(F=>{b.push(F)}),v=()=>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 w(){T!==void 0&&(clearTimeout(T),T=void 0)}function N(){g!==void 0&&(clearTimeout(g),g=void 0)}function A(){return a.exited||I===null||I.aborted||I.processor.sawResult()}function R(F){return F==="text_done"?y:S}async function x(F){if(F==="text_done"?T=void 0:g=void 0,A()||E!==null)return;h??=Date.now();let W=R(F);if(t.holdOpen){let dr=(t.holdOpen.maxHoldMs??Zs)-(Date.now()-h),es=dr>0?await ei(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),dr,void 0):!1;if(A()||(F==="text_done"?T!==void 0:g!==void 0))return;if(es===!0){D({event:"transport_stall_grace_deferred",provider:e,grace_kind:F,grace_ms:W,reason:"outstanding_dispatched_work"}),O(F);return}}m=F,E=F==="text_done"?`${e} finished responding but never emitted its closing result event (${W}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${W}ms of silence)`,D({event:"transport_stall_grace_fired",provider:e,grace_kind:F,grace_ms:W}),te(i).catch(()=>{})}function O(F){let W=setTimeout(()=>{x(F)},R(F));W.unref?.(),F==="text_done"?(w(),T=W):(N(),g=W)}let M=!1,X,$,ie=new Promise((F,W)=>{X=F,$=W});ie.catch(()=>{});let B=setTimeout(()=>{M||(M=!0,$(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);B.unref?.();function J(F){M||(M=!0,clearTimeout(B),F?$(F):X())}let P="";function Q(F){if(a.lastEventAtMs=Date.now(),F.type==="system"&&F.subtype==="init"){if(f=F.session_id||f,t.sessionId&&typeof F.session_id=="string"&&F.session_id.length>0&&F.session_id!==t.sessionId){let fe=new Error(`stream-json bundle: provider resumed a different session (init reported "${F.session_id}", expected "${t.sessionId}")`);J(fe),te(i).catch(()=>{});return}J()}let W=I?.processor.sawResult()??!0;F.type==="assistant"?(p=!Gf(F),_=p&&F.message?.stop_reason==="pause_turn"):(F.type==="result"||F.type==="user")&&(p=!1,_=!1),w(),e==="claude"&&a.turnActive&&p&&!_&&!W&&O("text_done"),N(),e==="claude"&&a.turnActive&&!W&&O("tool_use_silence")}function Zn(){let F=I;if(F===null)return;let W=F.processor.finalize();if(W!==null){if(I=null,a.turnActive=!1,w(),N(),W.isError){D({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:W.errorMessage}),F.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${W.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=W.sessionId||l,ge(`stream-json bundle: result ${W.result.slice(0,80)}${W.result.length>80?"...":""} (${W.durationMs}ms)`),F.resolve({result:W.result,sessionId:W.sessionId||l,durationMs:W.durationMs,numTurns:W.numTurns})}}function Vr(F){if(!F.trim())return;let W;try{W=JSON.parse(F)}catch{return}Q(W);let fe=I;if(fe!==null){let dr=fe.processor.sawResult();fe.processor.processLine(F),fe.onEventForward?.(W),!dr&&fe.processor.sawResult()&&Zn()}}i.stdout?.on("data",F=>{P+=F.toString();let W=P.split(`
|
|
1616
|
+
`);P=W.pop()||"";for(let fe of W)Vr(fe)}),i.on("error",F=>{if(c=new se(`Failed to spawn ${r}: ${F.message}`,{cause:F}),D({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:F.message}),J(c),I!==null){let W=I;I=null,a.turnActive=!1,W.reject(c)}}),i.on("exit",F=>{a.exited=!0,a.exitCode=F,w(),N(),P.trim()&&Vr(P),J(a.exited&&!M?new Error(`stream-json bundle: ${e} exited (code ${String(F)}) before its init event`):void 0);let W=I;W!==null&&(I=null,a.turnActive=!1,W.aborted||(E!==null&&m==="text_done"&&u.trim().length>0?(D({event:"transport_stall_finalized",provider:e,reason:E,text_len:u.length}),W.resolve({result:u,sessionId:f||t.sessionId||"",durationMs:Date.now()-W.startMs,numTurns:1,warnings:[E]})):E!==null&&m==="tool_use_silence"?(D({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:F,stderr_tail:d.slice(0,500)}),W.reject(new Error(`${E} \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})`:"")))):(D({event:"transport_error",provider:e,error_class:"Error",reason:E!==null?"provider_stalled_no_content":"provider_no_result",exit_code:F,stderr_tail:d.slice(0,500)}),W.reject(v()))));for(let fe of b.splice(0))fe()});try{t.sessionId&&await Bf(e,t.sessionId,t.sessionFileRoots),await ie}catch(F){let W=c??(F instanceof Error?F:new Error(String(F))),fe=t.closeTimeoutMs??2e3;throw await te(i,{softDelayMs:Math.min(1e3,fe),killDelayMs:Math.min(1e3,fe)}).catch(()=>{}),W}let fo=F=>new Promise(W=>{setTimeout(W,F).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(F,W={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw v();if(I!==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 fe=()=>(a.closed=!0,te(i).catch(()=>{}),new Error("Aborted"));if(W.signal?.aborted)throw fe();if(t.sessionId&&(await Bf(e,t.sessionId,t.sessionFileRoots),a.exited))throw v();if(W.signal?.aborted)throw fe();return u="",p=!1,_=!1,E=null,m=null,h=null,new Promise((dr,es)=>{let mo={processor:ii({onText:Hc=>{u+=Hc,W.onText?.(Hc)}}),resolve:dr,reject:es,startMs:Date.now(),aborted:!1,onEventForward:W.onEvent};I=mo,a.turnActive=!0;let Y_=()=>{mo.aborted=!0,D({event:"transport_abort",provider:e}),a.closed=!0,te(i).catch(()=>{}),I===mo&&(I=null,a.turnActive=!1),es(new Error("Aborted"))};W.signal?.addEventListener("abort",Y_,{once:!0});let z_=JSON.stringify({type:"user",message:{role:"user",content:F}});i.stdin?.write(`${z_}
|
|
1617
|
+
`),ge(`stream-json bundle: prompt sent (${F.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(F=>{tt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),F()},label:e})}):i.stdin?.end(),!a.exited)){let F=t.closeTimeoutMs??2e3;await Promise.race([k(),fo(F)]),a.exited||await te(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,F),killDelayMs:Math.min(1e3,F)}).catch(()=>{})}})()),a.closing}}}var fS,pS,wa=L(()=>{"use strict";Qt();Lr();rt();re();wn();qe();Ta();pe();Ta();fS={claude:"claude",qwen:"qwen"};pS={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function ai(t={}){return[]}var Sa=L(()=>{"use strict"});function va(t){return t==="plan"?"read-only":"danger-full-access"}function Yf(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function li(){return{agentItems:new Map,resultText:""}}function Cr(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 ci(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function zf(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 di(){return{pendingCodexError:null}}function ui(t,e){let r=zf(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function fi(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 ba=L(()=>{"use strict"});import{spawn as Qf}from"node:child_process";import{createInterface as Zf}from"node:readline";import{existsSync as gS,readFileSync as _S}from"node:fs";import{fileURLToPath as yS}from"node:url";function em(){return Yf(ES)}function Mt(t,e){ge(`[codex:${t}] ${JSON.stringify(e)}`)}function TS(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1618
1618
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1619
1619
|
${e}
|
|
1620
1620
|
|
|
1621
|
-
${r}`:r}function
|
|
1622
|
-
`)})}function y(b
|
|
1623
|
-
`)}c.on("line",
|
|
1624
|
-
`),
|
|
1625
|
-
`)})}function _(
|
|
1626
|
-
`)}let E=[],m=()=>o.exited?Promise.resolve():new Promise(
|
|
1627
|
-
`),
|
|
1628
|
-
`),
|
|
1629
|
-
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function
|
|
1630
|
-
`,"utf-8"),!0}let s;try{s=JSON.parse(
|
|
1631
|
-
`,"utf-8"),i}var
|
|
1621
|
+
${r}`:r}function tm(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?ai():[];r.push(...s),ae()&&Le(JSON.stringify({event:"codex_mcp_inject",alias:t.alias??null,isLead:n,injected:s.length>0}));let i=t.permissionMode??"yolo",o=va(i);if(he("codex",r,i),t.cwd&&!gS(t.cwd))throw D({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`}),new se(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:e,codexArgs:r,sandbox:o,permissionMode:i,spawnEnv:ue(t.env,t.cwd,t.threadId)}}function rm(t,e){return new Promise((r,n)=>{let s,i,o;try{({binary:s,codexArgs:i,sandbox:o}=tm(e))}catch(I){return n(I instanceof Error?I:new Error(String(I)))}let a=Qf(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:ue(e.env,e.cwd,e.threadId)}),l=!1;if(e.signal){if(e.signal.aborted)return l=!0,D({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),te(a).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{l=!0,D({event:"transport_abort",provider:"codex"}),te(a).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let c=Zf({input:a.stdout}),d=new Map,u=1,f=e.threadId||"",p="",_=!1,E=!1,m=Date.now(),h=li(),T=di();function g(I,b={}){return new Promise((k,v)=>{let w=u++;d.set(w,{resolve:k,reject:v});let N=JSON.stringify({jsonrpc:"2.0",id:w,method:I,params:b});a.stdin?.write(N+`
|
|
1622
|
+
`)})}function y(I,b={}){let k=JSON.stringify({jsonrpc:"2.0",method:I,params:b});a.stdin?.write(k+`
|
|
1623
|
+
`)}c.on("line",I=>{let b;try{b=JSON.parse(I)}catch{return}if(typeof b.id=="number"&&d.has(b.id)){let w=d.get(b.id);if(d.delete(b.id),b.error){let N=b.error,A=typeof N?.message=="string"&&N.message.length>0?N.message:JSON.stringify(b.error);w.reject(Tn(`codex app-server error: ${A}`,N))}else w.resolve(b);e.onEvent?.(b);return}let k=b.method;if(!k){e.onEvent?.(b);return}if(k==="thread/started"){let N=b.params?.thread;N?.id&&(f=N.id)}let v=ae()?w=>{Mt("item.text/buffer-mismatch",{itemId:w.itemId,threadId:w.threadId??null,turnId:w.turnId??null,expectedFromItemText:w.expectedFromItemText,gotFromBuffer:w.gotFromBuffer,expectedLen:w.expectedFromItemText.length,gotLen:w.gotFromBuffer.length})}:void 0;if(k==="turn/started"){let w=b.params,N=w?.turn;N?.id&&(p=N.id),Cr(b,h,e.onDelta,v),ae()&&Mt("turn/started",{params:w??null})}if(ae()&&(k==="item/started"||k==="item/completed")){let w=b.params;w?.item?.type==="agentMessage"&&Mt(k,{params:w??null})}if(k==="item/started"||k==="item/agentMessage/delta"||k==="item/completed"){if(k==="item/agentMessage/delta"){let w=b.params;ae()&&Mt("agentMessage/delta",{params:w??null})}Cr(b,h,e.onDelta,v)}if(k==="turn/completed"){let w=b.params;if(ae())for(let[A,R]of h.agentItems.entries())R.buffer&&Mt("turn/completed/unflushed-item",{itemId:A,phase:R.phase,bufferLen:R.buffer.length});ci(h),ae()&&Mt("turn/completed",{params:w??null});let N=fi(b,T);N.shouldReject?(ae()&&Mt("turn/completed/terminal-reject",{message:N.turnError.message}),E=!0,_=!0,a.stdin?.end(),n(N.turnError)):(_=!0,a.stdin?.end())}if(k==="error"){let w=ui(b,T);if(ae()){let N=b.params,A=N?.error,R=typeof A?.message=="string"?A.message:"(no message)";Mt(w.willRetry?"error/retry":"error/terminal-deferred",{message:R,willRetry:w.willRetry,params:N??null})}}e.onEvent?.(b)});let S="";a.stderr?.on("data",I=>{S+=I.toString()}),a.on("error",I=>{D({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:I.message}),n(new se(`Failed to spawn codex app-server: ${I.message}`,{cause:I}))}),a.on("exit",I=>{if(!l&&!E){if(_){r({result:h.resultText,threadId:f,turnId:p,durationMs:Date.now()-m,exitCode:I});return}if(T.pendingCodexError){n(T.pendingCodexError);return}D({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:I,stderr_tail:S.slice(0,500)}),n(new Error(TS({exitCode:I,stderr:S})))}}),(async()=>{try{if(await g("initialize",em()),y("initialized",{}),e.threadId)try{let I=g("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),b,k=new Promise((v,w)=>{b=setTimeout(()=>w(new Error("resume timeout")),3e4)});try{let w=(await Promise.race([I,k])).result?.thread?.id;if(e.requireResume&&w!==e.threadId)throw new Error(`thread/resume did not return the requested thread "${e.threadId}" (got "${w??"unknown"}")`)}finally{clearTimeout(b)}f=e.threadId}catch(I){if(e.requireResume)throw I;process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1624
|
+
`),D({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:I instanceof Error?I.message:String(I)});let k=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;k?.id&&(f=k.id)}else{let b=(await g("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;b?.id&&(f=b.id)}await g("turn/start",{threadId:f,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(I){te(a).catch(()=>{}),n(I instanceof Error?I:new Error(String(I)))}})()})}async function nm(t){let{binary:e,codexArgs:r,sandbox:n}=tm(t),s=Qf(e,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:ue(t.env,t.cwd,t.threadId)}),i=Date.now(),o={exited:!1,exitCode:null,completedTurns:0,closed:!1,closing:null},a=t.threadId||"",l=null,c="";s.stderr?.on("data",v=>{c+=v.toString()});let d=Zf({input:s.stdout}),u=new Map,f=1;function p(v,w={}){return new Promise((N,A)=>{let R=f++;u.set(R,{resolve:N,reject:A});let x=JSON.stringify({jsonrpc:"2.0",id:R,method:v,params:w});s.stdin?.write(x+`
|
|
1625
|
+
`)})}function _(v,w={}){let N=JSON.stringify({jsonrpc:"2.0",method:v,params:w});s.stdin?.write(N+`
|
|
1626
|
+
`)}let E=[],m=()=>o.exited?Promise.resolve():new Promise(v=>{E.push(v)}),h=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),T=null,g=null,y,S,I=v=>{v.turnId&&p("turn/interrupt",{threadId:a,turnId:v.turnId}).catch(()=>{})};function b(v){let w=T;w===null||w.settled||(w.settled=!0,T=null,v&&w.reject(v))}d.on("line",v=>{let w;try{w=JSON.parse(v)}catch{return}if(typeof w.id=="number"&&u.has(w.id)){let O=u.get(w.id);if(u.delete(w.id),w.error){let M=w.error,X=typeof M?.message=="string"&&M.message.length>0?M.message:JSON.stringify(w.error);O.reject(Tn(`codex app-server error: ${X}`,M))}else O.resolve(w);T?.onEvent?.(w);return}let N=w.method;if(!N){T?.onEvent?.(w);return}if(N==="thread/started"){let M=w.params?.thread;M?.id&&(a=M.id)}let A=w.params,R=A?.turnId??A?.turn?.id;if(g&&(N==="turn/started"&&!g.turnId&&R&&(g.turnId=R,I(g)),N==="turn/completed"&&R===g.turnId&&(g=null,S?.()),N.startsWith("turn/")||N.startsWith("item/")||N==="error"))return;let x=T;if(!(R&&x?.turnId&&R!==x.turnId)){if(N==="turn/started"&&x!==null){let M=w.params?.turn;M?.id&&(x.turnId=M.id),Cr(w,x.agentState,x.onDelta,void 0)}if(x!==null&&(N==="item/started"||N==="item/agentMessage/delta"||N==="item/completed")&&Cr(w,x.agentState,x.onDelta,void 0),N==="turn/completed"&&x!==null&&!x.settled){ci(x.agentState);let O=fi(w,x.turnState);x.settled=!0,T=null,O.shouldReject?x.reject(O.turnError):(o.completedTurns+=1,x.resolve({text:x.agentState.resultText,sessionId:a,turnId:x.turnId,durationMs:Date.now()-x.startMs}))}N==="error"&&x!==null&&ui(w,x.turnState),x?.onEvent?.(w)}}),s.on("error",v=>{l=new se(`Failed to spawn codex app-server: ${v.message}`,{cause:v}),D({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:v.message});for(let w of u.values())w.reject(l);u.clear(),b(l)}),s.on("exit",v=>{o.exited=!0,S?.(),o.exitCode=v;let w=h();for(let A of u.values())A.reject(w);u.clear();let N=T;N!==null&&!N.settled&&(N.settled=!0,T=null,N.turnState.pendingCodexError?N.reject(N.turnState.pendingCodexError):(D({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:v,stderr_tail:c.slice(0,500)}),N.reject(w)));for(let A of E.splice(0))A()});try{if(await p("initialize",em()),_("initialized",{}),t.threadId){let v;try{v=await p("thread/resume",{threadId:t.threadId,sandbox:n,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(N){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${N instanceof Error?N.message:String(N)} (the thread/start fallback is disabled in bundle mode)`)}let w=v.result?.thread;if(w?.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${w?.id??"unknown"}"`);a=t.threadId}else{let w=(await p("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:n,...t.model?{model:t.model}:{}})).result?.thread;w?.id&&(a=w.id)}}catch(v){let w=l??(v instanceof Error?v:new Error(String(v))),N=t.closeTimeoutMs??2e3;throw await te(s,{softDelayMs:Math.min(1e3,N),killDelayMs:Math.min(1e3,N)}).catch(()=>{}),w}let k=v=>new Promise(w=>{setTimeout(w,v).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(v,w={}){if(y&&await y,o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw h();if(T!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(w.signal?.aborted)throw new Error("Aborted");return new Promise((N,A)=>{let R={agentState:li(),turnState:di(),resolve:N,reject:A,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};T=R;let x=()=>{R.settled||(R.settled=!0,T=null,g=R,y=new Promise(O=>{S=O}),I(R),w.signal?.removeEventListener("abort",x),A(new Error("Aborted")))};w.signal?.addEventListener("abort",x,{once:!0}),p("turn/start",{threadId:a,input:[{type:"text",text:v}],...t.model?{model:t.model}:{}}).catch(O=>{if(R.settled){g===R&&(g=null,S?.());return}R.settled=!0,T=null,w.signal?.removeEventListener("abort",x),A(o.exited?h():O instanceof Error?O:new Error(String(O)))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,S?.(),!o.exited&&(t.holdOpen!==void 0?await new Promise(v=>{tt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>T!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),v()},label:"codex"})}):s.stdin?.end(),!o.exited)){let v=t.closeTimeoutMs??2e3;await Promise.race([m(),k(v)]),o.exited||await te(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{})}})()),o.closing}}}var ES,sm=L(()=>{"use strict";re();re();Qt();Lr();wn();rt();Sa();re();qe();ba();ba();ES=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(_S(yS(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function mi(t){let e=[...t.matchAll(wS)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return im(t.slice(n).trimStart())}return im(xS(t.replace(SS,"")))}function xS(t){let e=vS.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(bS)];if(n.length<2)return t;let s=n[0],i=(s.index??0)+s[0].length;return r.slice(i).trimStart()}function im(t){let e=[...t.matchAll(IS)];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 am(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function pi(t={}){let e="",r="",n="",s=!1,i=!1,o=!1,a=t.isolateResult??(t.tool==="gemini"?mi:void 0),l=()=>({result:a?a(r):r,sessionId:e,stopReason:n,sawActivity:o});return{setSessionId(c){e=c},beginTurn(){r="",n="",s=!1,i=!0,o=!1},completeTurn(c){return n=am(c),s=!0,i=!1,l()},cancelTurn(){r="",n="",i=!1},processMessage(c){if(c.method!=="session/update")return!1;let u=c.params?.update,f=u?.sessionUpdate;if(typeof f!="string"||(i&&kS.has(f)&&(o=!0),f!=="agent_message_chunk"))return!1;let p=u?.content,_=typeof p?.text=="string"?p.text:"";return _&&i&&(r+=_,t.onDelta?.(_)),!0},finalize(){return s?l():null}}}var om,wS,SS,vS,bS,IS,kS,bn=L(()=>{"use strict";om="(?:png|jpe?g|webp|heic|pdf)",wS=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${om}\\s*`,"gi"),SS=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${om}\\s*`,"i"),vS=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,bS=/^STANCE:\s+\S+\s*$/gim,IS=/\[Thought:\s*true\]\s*/gi;kS=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"])});var Ia=L(()=>{"use strict";ua()});var hi,lm=L(()=>{"use strict";hi={name:"miniplayer",binary:"miniplayer",baseArgs:["acp"],argv:t=>{if(t.permissionMode==="plan")throw new Error("miniplayer has no plan mode; its native tools always have full permissions");return["acp",...t.model?["-m",t.model]:[]]}}});import{readFileSync as AS,readdirSync as cm}from"node:fs";import{join as gi}from"node:path";function dm(t,e){let r=e.GEMINI_DIR??process.env.GEMINI_DIR??gi(V,".gemini"),n=gi(r,"tmp"),s;try{s=cm(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=gi(n,a,"chats"),c;try{c=cm(l)}catch{continue}for(let d of c){if(!d.endsWith(".json"))continue;let u;try{u=AS(gi(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 In,um=L(()=>{"use strict";bn();pe();rt();In={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(t){let e=[...In.baseArgs];if(t.permissionMode==="plan"){let r=Dt("gemini","plan"),n=Dt("gemini","yolo");e=e.filter(s=>!(n??[]).includes(s)),r&&e.push(...r)}return t.model&&e.push("--model",t.model),e},isolateResult:mi,sessionIdentity:{verifyLoadedSession:t=>{dm(t.requestedSessionId,t.env)},recheckSession:t=>{dm(t.requestedSessionId,t.env)}}}});import{existsSync as NS,readFileSync as RS}from"node:fs";import{join as xa}from"node:path";function fm(t,e){let r=e.COPILOT_HOME??process.env.COPILOT_HOME??xa(V,".copilot"),n=xa(r,"session-state",t),s=xa(n,"workspace.yaml");if(!NS(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=RS(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 xn,mm=L(()=>{"use strict";re();pe();xn={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(t){return t.permissionMode==="plan"&&(process.stderr.write(`[acp] copilot has no plan-mode flag in --acp mode; --permission-mode plan is not honored (running yolo). See src/providers/yolo-contract.ts.
|
|
1627
|
+
`),D({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),t.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${t.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1628
|
+
`),D({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...xn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{fm(t.requestedSessionId,t.env)},recheckSession:t=>{fm(t.requestedSessionId,t.env)}}}});import{existsSync as gm,mkdirSync as LS,readFileSync as _m,writeFileSync as pm}from"node:fs";import{join as kn,resolve as CS}from"node:path";function ym(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 ka(t,e,r={existsSync:gm,readFileSync:_m}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=CS(e,s.sessiondir??e);for(let o of OS(i)){let a=DS(o,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(ym(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 OS(t){return[kn(t,".opencode","opencode.jsonc"),kn(t,"opencode.jsonc"),kn(t,"opencode.json")]}function DS(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(MS(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function MS(t){let e="",r=!1,n="",s=!1;for(let i=0;i<t.length;i+=1){let o=t[i],a=t[i+1];if(r){e+=o,s?s=!1:o==="\\"?s=!0:o===n&&(r=!1,n="");continue}if(o==='"'||o==="'"){r=!0,n=o,e+=o;continue}if(o==="/"&&a==="/"){for(;i<t.length&&t[i]!==`
|
|
1629
|
+
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function Em(t,e={}){let r=kn(t,".opencode"),n=kn(r,"opencode.json");if(!gm(n)){LS(r,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return pm(n,o+`
|
|
1630
|
+
`,"utf-8"),!0}let s;try{s=JSON.parse(_m(n,"utf-8"))}catch{return console.log(hm.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(hm.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),ym(s.permission)||D({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&&pm(n,JSON.stringify(s,null,2)+`
|
|
1631
|
+
`,"utf-8"),i}var hm,Aa=L(()=>{"use strict";re();hm={yellow:t=>t}});import{existsSync as Ra,readdirSync as FS,statSync as Tm}from"node:fs";import{join as Ft}from"node:path";import{createRequire as PS}from"node:module";function La(){return Na===null&&(Na=PS(import.meta.url)("node:sqlite").DatabaseSync),Na}function wm(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Sm(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 vm(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 bm(){let t=process.env.XDG_DATA_HOME||Ft(V,".local","share"),e=process.env.XDG_CONFIG_HOME||Ft(V,".config");return[Ft(t,"opencode","opencode.db"),Ft(e,"opencode","opencode.db")]}function $S(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let t=process.env.XDG_DATA_HOME||Ft(V,".local","share"),e=Ft(t,"lmplayer"),r=Ft(e,"opencode-local.db"),n=[r];try{let s=FS(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>Ft(e,i)).filter(i=>i!==r).sort((i,o)=>{try{return Tm(o).mtimeMs-Tm(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function US(t){return t==="lmplayer"?$S():bm()}function Ca(t,e){let r=e?.dbPath!==void 0?[e.dbPath]:bm();for(let n of r){if(!Ra(n))continue;let s=new(La())(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 Na,Or,_i=L(()=>{"use strict";pe();re();Na=null;Or=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=US(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>Ra(e))}openDb(e){if(!Ra(e))return null;let r=new(La())(e,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),r}async discoverSessions(){let e=[];for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1632
1632
|
s.time_created, s.time_updated
|
|
1633
1633
|
FROM session s
|
|
1634
1634
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",d=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1635
|
-
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,p,_,E=
|
|
1636
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,f,p=
|
|
1637
|
-
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(
|
|
1635
|
+
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,p,_,E=wm(),m=[];for(let T of d){let g;try{g=JSON.parse(T.data)}catch{continue}_||(_=g.model?.modelID||g.modelID),(g.role==="user"||g.role==="assistant")&&u++,g.role==="user"&&m.push(T.id),g.role==="assistant"&&Sm(E,g.tokens)}let h=[...m.length>0?[m[0]]:[],...m.length>1?[m[m.length-1]]:[]];for(let T of h){let g=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(T),y=this.extractText(g);y&&(f||(f=H(y,80)),p=H(y,80))}e.push({provider:this.name,sessionId:a.id,slug:a.slug,cwd:c,createdAt:new Date(a.time_created),modifiedAt:new Date(a.time_updated),model:_,startCommand:this.startCommand,firstUserMessage:f,lastUserMessage:p,messageCount:u,filePath:r,...vm(E)})}}catch(s){D({event:"opencode_discover_sessions_failed",provider:this.name,db_path:r,error_message:s instanceof Error?s.message:String(s)})}finally{n.close()}}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=this.findSessionRow(n,e);if(!s)continue;return this.buildSessionDetail(n,s,r)}catch{}finally{n.close()}}return null}buildSessionDetail(e,r,n){let s=e.prepare("SELECT id, worktree, name FROM project WHERE id = ?").get(r.project_id),i=r.directory||s?.worktree||"(unknown)",o=e.prepare(`SELECT id, session_id, time_created, time_updated, data
|
|
1636
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=[],c=0,d,u,f,p=wm();for(let _ of o){let E;try{E=JSON.parse(_.data)}catch{continue}d||(d=E.model?.modelID||E.modelID);let m=E.model?.modelID||E.modelID,h=new Date(E.time?.created||_.time_created),T=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_.id);if(E.role==="user"){let g=this.extractText(T),y=this.extractText(T,!0);y&&l.push(y),g&&(u||(u=H(g,80)),f=H(g,80)),a.push({role:"user",timestamp:h,content:g||"(empty)"}),c++}else if(E.role==="assistant"){Sm(p,E.tokens);for(let g of T){let y;try{y=JSON.parse(g.data)}catch{continue}y.type==="text"&&y.text?a.push({role:"assistant",timestamp:h,content:y.text,model:m}):y.type==="reasoning"&&y.text?a.push({role:"thinking",timestamp:h,content:y.text}):y.type==="tool"&&y.tool&&(a.push({role:"tool_use",timestamp:h,content:`${y.tool}`,toolName:y.tool,toolCallId:y.callID,toolInput:y.state?.input?JSON.stringify(y.state.input):void 0,toolInputData:Ue(y.state?.input)}),y.state&&(y.state.status==="completed"||y.state.status==="error"||y.state.output!==void 0||y.state.error!==void 0)&&a.push({role:"tool_result",timestamp:h,content:y.state.error??y.state.output??"",toolCallId:y.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,...vm(p),messages:a,userPrompts:l}}extractText(e,r=!1){let n=[];for(let s of e){let i;try{i=JSON.parse(s.data)}catch{continue}r&&(i.synthetic===!0||i.ignored===!0)||i.type==="text"&&i.text&&n.push(i.text)}return n.join(`
|
|
1637
|
+
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(La())(r,{open:!0});try{let s=this.findSessionRow(n,e);if(!s)continue;return n.prepare("DELETE FROM session WHERE id = ?").run(s.id).changes>0}catch{}finally{n.close()}}return!1}findSessionRow(e,r){let n=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1638
1638
|
s.time_created, s.time_updated
|
|
1639
1639
|
FROM session s WHERE s.id = ?`).get(r);if(n)return n;let s=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1640
1640
|
s.time_created, s.time_updated
|
|
1641
1641
|
FROM session s
|
|
1642
1642
|
WHERE s.id LIKE ?
|
|
1643
1643
|
ORDER BY s.time_updated DESC
|
|
1644
|
-
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function
|
|
1645
|
-
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var
|
|
1644
|
+
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function An(t){return{id:t.id,onFailure:"non-fatal",applies:e=>t.value(e)!==void 0,run:async e=>{await e.sendRpc("session/set_config_option",{sessionId:e.sessionId,configId:t.configId,value:t.value(e)})},describeFailure:(e,r)=>{let n=t.value(e),s=r instanceof Error?r.message:String(r);return{event:"acp_config_option_failed",fields:{config_id:t.configId,value:n,error_message:s},stderrLine:`[acp] set_config_option(${t.configId}=${n}) failed: ${s}
|
|
1645
|
+
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var Oa=L(()=>{"use strict"});import{spawn as jS}from"node:child_process";import{resolve as Im}from"node:path";function yi(t){let e;try{e=jS(t.binaryPath??Zt.binary,[...Zt.baseArgs],{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:ue(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=Ot(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}te(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 Zt,Da=L(()=>{"use strict";re();Aa();_i();bn();qe();Lr();Ia();Oa();Zt={name:"opencode",binary:"opencode",baseArgs:["acp"],argv:()=>[...Zt.baseArgs],preSpawn(t){try{Em(t.cwd)}catch(e){D({event:"opencode_config_install_failed",cwd:t.cwd,error_message:e instanceof Error?e.message:String(e)})}},sessionSetup:[An({id:"model",provider:"opencode",configId:"model",value:t=>t.model}),An({id:"effort",provider:"opencode",configId:"effort",value:t=>t.effort})],probe:yi,sessionIdentity:{verifyLoadedSession:t=>{let e=Ca(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(Im(e.directory)!==Im(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(Ca(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 BS}from"node:fs";import{readdir as HS}from"node:fs/promises";import{join as Ma,resolve as WS}from"node:path";function km(t){let e=XS.exec(t);return e?e[0]:null}function qS(t){if(!t.includes("notifications/initialized"))return t;let e=t.split(/\r?\n/),r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s.includes("Error handling notification")&&s.includes("notifications/initialized")){let i=[s],o=n;for(;o+1<e.length&&i.length<8&&(o++,i.push(e[o]),e[o].trim()!=="}"););let a=i.join(`
|
|
1646
1646
|
`);if(/\bcode:\s*-32601\b/.test(a)&&/Method not found[^]*notifications\/initialized/.test(a)){n=o;continue}}r.push(s)}return r.join(`
|
|
1647
|
-
`)}async function
|
|
1648
|
-
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function
|
|
1647
|
+
`)}async function xm(t,e){let r=WS(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??Ma(V,".kimi-code")),n=Ma(r,"sessions"),s;try{s=await HS(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()&&BS(Ma(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 XS,Fa,Nn,Pa=L(()=>{"use strict";re();pe();Oa();XS=/runtime\s+\S+\s+does not exist in workspace\s+\S+/;Fa=t=>t.permissionMode==="plan"?"plan":"auto";Nn={name:"kimi",binary:"kimi",baseArgs:["acp"],argv:()=>[...Nn.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:Fa(t)})},describeFailure:(t,e)=>{let r=Fa(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=${Fa(t)}) ok`},An({id:"model",provider:"kimi",configId:"model",value:t=>t.model})],onExitFinalization(t){let e=km(t.result);e!==null&&D({event:"kimi_runtime_dead",provider:"kimi",session_id:t.sessionId,matched_text:e})},filterExpectedStderr:qS,sessionIdentity:{verifyLoadedSession:async t=>{await xm(t.requestedSessionId,t.env)},recheckSession:async t=>{await xm(t.requestedSessionId,t.env)}}}});var Rn,Am=L(()=>{"use strict";Rn={name:"hermes",binary:"hermes",baseArgs:["acp"],argv(t){if(t.permissionMode==="plan")throw new Error('provider "hermes" does not support --permission-mode plan');return[...Rn.baseArgs]},preSpawn(t){t.permissionMode==="yolo"&&(t.env.HERMES_YOLO_MODE="1")},modeVocabulary:{known:["default","accept_edits","dont_ask"],selectable:["accept_edits","dont_ask"]},sessionSetup:[{id:"session-mode",onFailure:"fail-closed",applies:t=>t.acpMode!==void 0,run:async t=>{await t.sendRpc("session/set_mode",{sessionId:t.sessionId,modeId:t.acpMode})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_session_mode_failed",fields:{mode_id:t.acpMode,error_message:r},message:`Cannot set hermes ACP session mode to ${String(t.acpMode)}: ${r}`}},successLog:t=>`acp: set_mode(modeId=${String(t.acpMode)}) ok`},{id:"model",onFailure:"fail-closed",applies:t=>{if(t.model===void 0)return!1;let e=t.response.result?.models?.currentModelId;return t.model!==e},run:async t=>{await t.sendRpc("session/set_model",{sessionId:t.sessionId,modelId:t.model})},describeFailure:(t,e)=>{let r=e instanceof Error?e.message:String(e);return{event:"acp_config_option_failed",fields:{config_id:"model",value:t.model,error_message:r},stderrLine:`[acp] set_model(modelId=${String(t.model)}) failed: ${r}
|
|
1648
|
+
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function Ln(t){return GS[t]}var GS,JS,Nm=L(()=>{"use strict";lm();um();mm();Da();Pa();Am();GS={miniplayer:hi,gemini:In,copilot:xn,opencode:Zt,kimi:Nn,hermes:Rn};JS={miniplayer:{binary:hi.binary,args:hi.baseArgs},gemini:{binary:In.binary,args:In.baseArgs},copilot:{binary:xn.binary,args:xn.baseArgs},opencode:{binary:Zt.binary,args:Zt.baseArgs},kimi:{binary:Nn.binary,args:Nn.baseArgs},hermes:{binary:Rn.binary,args:Rn.baseArgs}}});import{spawn as Rm}from"node:child_process";import{existsSync as VS}from"node:fs";function Lm(t,e){let r=Ln(t)?.modeVocabulary;if(!r)throw new se(`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 se(`provider "${t}" has no ACP mode "${e}" (known: ${r.known.join(", ")}).`);if(!r.selectable.includes(e))throw new se(`provider "${t}" ACP mode "${e}" is not selectable by lmctl (selectable: ${r.selectable.join(", ")}).`)}function KS(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1649
1649
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1650
1650
|
${e}
|
|
1651
1651
|
|
|
1652
|
-
${r}`:r}function
|
|
1653
|
-
`),M({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:u instanceof Error?u.message:String(u)});let f=await e("session/new",{cwd:n.cwd,mcpServers:[]});return a=gt(f),s.setSessionId(a),{sessionId:a,sessionResponse:f}}let d=gt(c);if(n.requireResume&&d!==""&&d!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${d}"`);if(i){let u=gt(c);if(u!==""&&u!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${u}"`);if(u===""){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(c)}a=n.sessionId}else a=gt(c,n.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:n.cwd,mcpServers:[]});a=gt(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function jm(t,e){let r=Dn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{Mm(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:A=>{o.push(A)}}},l,c,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=$m(r,e,a))}catch(A){return s(A instanceof Error?A:new Error(String(A)))}let u=Dm(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),p=!1,_=!1,E=0,m=!1,h=!1;if(e.signal){if(e.signal.aborted)return p=!0,M({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),te(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,M({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),te(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let T=e.sessionId||"",g=hi({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(T);let y=Ot(u,{provider:e.tool,onEvent:A=>{E=Date.now(),Fm(A)&&(h=!0),e.onEvent?.(A)},onNotification:A=>{E=Date.now(),g.processMessage(A)}}),{sendRpc:v,sendNotification:b}=y,I="";u.stderr?.on("data",A=>{I+=A.toString()}),u.on("error",A=>{y.close(A),M({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:A.message,elapsed_ms:Date.now()-f}),s(new se(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${A.message}`,{cause:A}))}),u.on("exit",A=>{if(_=!0,y.close(new se(`ACP process exited with code ${String(A)}`)),p)return;let S=g.finalize();if(S!==null)r.onExitFinalization?.({...a,sessionId:S.sessionId,result:S.result,stopReason:S.stopReason,exitCode:A}),n({result:S.result,sessionId:S.sessionId,durationMs:Date.now()-f,stopReason:S.stopReason,exitCode:A,sawActivity:S.sawActivity,...o.length>0?{warnings:o}:{}});else{let w=ev(e.tool,I);M({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:A,stderr_tail:w.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(ZS({tool:e.tool,exitCode:A,stderr:w})))}}),(async()=>{try{let A=await Um({sendRpc:v,sendNotification:b,opts:e,outputProcessor:g});T=A.sessionId;let S=A.sessionResponse;await Pm(r,a,{sessionId:T,response:S},v),g.beginTurn(),m=!0,ge(`acp: prompt sent (${t.length} chars)`);let w;if(await v("session/prompt",{sessionId:T,prompt:[{type:"text",text:t}]},N=>{N.error?g.cancelTurn():w=g.completeTurn(N)}),!w)throw new Error("ACP prompt completed without a result boundary");m=!1,ge(`acp: result received (${w.result.length} chars, stopReason=${w.stopReason})`),tt(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>_,isTurnInFlight:()=>m,lastEventAtMs:()=>E,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>h})}catch(A){te(u).catch(()=>{}),s(A instanceof Error?A:new Error(String(A)))}})()})}async function Bm(t){let e=Dn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&Mm(t.tool,t.acpMode);let r=t.permissionMode??"yolo",n=[],s=!0,i={permissionMode:r,...t.model!==void 0?{model:t.model}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.acpMode!==void 0?{acpMode:t.acpMode}:{},purpose:"chat",warnings:{push:S=>{n.push(S)}}},{binary:o,spawnArgs:a,spawnEnv:l}=$m(e,t,i),c=Dm(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,p=t.sessionId||"",_=null,E="";c.stderr?.on("data",S=>{E+=S.toString()});let m,h,T=hi({tool:t.tool,onDelta:S=>m?.(S),...e.isolateResult?{isolateResult:e.isolateResult}:{}});T.setSessionId(p);let g=Ot(c,{provider:t.tool,onEvent:S=>{u.lastEventAtMs=Date.now(),Fm(S)&&(u.backgroundJobLaunched=!0),h?.(S)},onNotification:S=>{u.lastEventAtMs=Date.now(),T.processMessage(S)}}),y=()=>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(S=>{v.push(S)}),I=null;c.on("error",S=>{_=new se(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${S.message}`,{cause:S}),M({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:S.message,elapsed_ms:Date.now()-d}),g.close(S)}),c.on("exit",S=>{if(u.exited=!0,u.exitCode=S,g.close(new se(`ACP process exited with code ${String(S)}`)),!u.telemetryFired){u.telemetryFired=!0;let w=T.finalize();w!==null&&e.onExitFinalization?.({...i,sessionId:w.sessionId,result:w.result,stopReason:w.stopReason,exitCode:S})}if(I!==null){let w=I;I=null,w(y())}for(let w of v.splice(0))w()});try{let S=await Um({sendRpc:g.sendRpc,sendNotification:g.sendNotification,opts:t,outputProcessor:T,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async w=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:w,cwd:t.cwd,env:l})});p=S.sessionId,await Pm(e,i,{sessionId:S.sessionId,response:S.sessionResponse},g.sendRpc)}catch(S){let w=_??(S instanceof Error?S:new Error(String(S)));throw te(c).catch(()=>{}),w}let A=S=>new Promise(w=>{setTimeout(w,S).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return u.completedTurns},async sendTurn(S,w={}){if(f&&await f,u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw y();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(w.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:p,cwd:t.cwd,env:l}),u.exited)throw y();if(w.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,m=w.onDelta,h=w.onEvent;let N=Date.now();try{T.beginTurn(),ge(`acp: bundle prompt sent (${S.length} chars)`);let R,k=!1;if(await new Promise((O,D)=>{I=D;let X,$=()=>{k=!0,f=Promise.resolve().then(()=>X).catch(()=>{}),T.cancelTurn(),g.sendNotification("session/cancel",{sessionId:p}),D(new Error("Aborted"))},ie=w.signal;ie?.addEventListener("abort",$,{once:!0}),X=g.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:S}]},B=>{k||(B.error?T.cancelTurn():R=T.completeTurn(B),m=void 0,h=void 0)}),X.then(B=>{ie?.removeEventListener("abort",$),O(B)},B=>{ie?.removeEventListener("abort",$),D(B instanceof Error?B:new Error(String(B)))})}),I=null,!R)throw new Error("ACP prompt completed without a result boundary");u.turnInFlight=!1,u.completedTurns+=1,ge(`acp: bundle result received (${R.result.length} chars, stopReason=${R.stopReason})`);let x=s&&n.length>0?[...n]:void 0;return s=!1,{result:R.result,sessionId:R.sessionId,stopReason:R.stopReason,durationMs:Date.now()-N,sawActivity:R.sawActivity,...x!==void 0?{warnings:x}:{}}}catch(R){throw I=null,T.cancelTurn(),u.turnInFlight=!1,u.exited?y():R}finally{m=void 0,h=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(w=>{tt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),w()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let S=t.closeTimeoutMs??2e3;await Promise.race([b(),A(S)]),u.exited||await te(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})})()),u.closing}}}var Ua=L(()=>{"use strict";re();Qt();Dr();bn();rt();re();qe();kn();xa();Om();$a();Ma();kn()});function le(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Hm(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=tv){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 Wm(){let t=new Map;return(e,r)=>{rv(e,Hm(t,r))}}function rv(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(le(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(le(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:le(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=le(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:le(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:le(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(`
|
|
1652
|
+
${r}`:r}function YS(t,e){return Ln(t)?.filterExpectedStderr?.(e)??e}function Cm(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 Om(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&&ge(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(D({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 Dm(t,e,r){let n=ue(e.env,e.cwd,e.sessionId);t.preSpawn?.({...r,cwd:e.cwd,env:n});let s=e.binaryPath||t.binary,i=t.argv(r),o=t.yoloAssertion==="always-yolo"?"yolo":r.permissionMode;if(he(e.tool,i,o),e.cwd&&!VS(e.cwd))throw D({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new se(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function Mm(t){let{sendRpc:e,sendNotification:r,opts:n,outputProcessor:s}=t,i=t.strictSessionIdentity===!0,o=await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}});r("notifications/initialized");let a=n.sessionId||"",l;if(n.sessionId){let c;try{if(o.result?.agentCapabilities?.loadSession===!1)throw new Error("provider advertises loadSession=false");c=await e("session/load",{sessionId:n.sessionId,cwd:n.cwd,mcpServers:[]})}catch(u){if(i||n.requireResume)throw new Error(`Cannot resume session ${n.sessionId} via ACP: ${u instanceof Error?u.message:String(u)}`);process.stderr.write(`[acp] session/load failed for ${n.sessionId}, creating new session
|
|
1653
|
+
`),D({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:u instanceof Error?u.message:String(u)});let f=await e("session/new",{cwd:n.cwd,mcpServers:[]});return a=gt(f),s.setSessionId(a),{sessionId:a,sessionResponse:f}}let d=gt(c);if(n.requireResume&&d!==""&&d!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${d}"`);if(i){let u=gt(c);if(u!==""&&u!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${u}"`);if(u===""){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(c)}a=n.sessionId}else a=gt(c,n.sessionId);l=c,s.setSessionId(a)}else{let c=await e("session/new",{cwd:n.cwd,mcpServers:[]});a=gt(c),l=c,s.setSessionId(a)}return{sessionId:a,sessionResponse:l}}function Fm(t,e){let r=Ln(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{Lm(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:k=>{o.push(k)}}},l,c,d;try{({binary:l,spawnArgs:c,spawnEnv:d}=Dm(r,e,a))}catch(k){return s(k instanceof Error?k:new Error(String(k)))}let u=Rm(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:d}),f=Date.now(),p=!1,_=!1,E=0,m=!1,h=!1;if(e.signal){if(e.signal.aborted)return p=!0,D({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),te(u).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{p=!0,D({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-f}),te(u).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let T=e.sessionId||"",g=pi({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});g.setSessionId(T);let y=Ot(u,{provider:e.tool,onEvent:k=>{E=Date.now(),Cm(k)&&(h=!0),e.onEvent?.(k)},onNotification:k=>{E=Date.now(),g.processMessage(k)}}),{sendRpc:S,sendNotification:I}=y,b="";u.stderr?.on("data",k=>{b+=k.toString()}),u.on("error",k=>{y.close(k),D({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:k.message,elapsed_ms:Date.now()-f}),s(new se(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${k.message}`,{cause:k}))}),u.on("exit",k=>{if(_=!0,y.close(new se(`ACP process exited with code ${String(k)}`)),p)return;let v=g.finalize();if(v!==null)r.onExitFinalization?.({...a,sessionId:v.sessionId,result:v.result,stopReason:v.stopReason,exitCode:k}),n({result:v.result,sessionId:v.sessionId,durationMs:Date.now()-f,stopReason:v.stopReason,exitCode:k,sawActivity:v.sawActivity,...o.length>0?{warnings:o}:{}});else{let w=YS(e.tool,b);D({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:k,stderr_tail:w.slice(0,500),elapsed_ms:Date.now()-f}),s(new Error(KS({tool:e.tool,exitCode:k,stderr:w})))}}),(async()=>{try{let k=await Mm({sendRpc:S,sendNotification:I,opts:e,outputProcessor:g});T=k.sessionId;let v=k.sessionResponse;await Om(r,a,{sessionId:T,response:v},S),g.beginTurn(),m=!0,ge(`acp: prompt sent (${t.length} chars)`);let w;if(await S("session/prompt",{sessionId:T,prompt:[{type:"text",text:t}]},N=>{N.error?g.cancelTurn():w=g.completeTurn(N)}),!w)throw new Error("ACP prompt completed without a result boundary");m=!1,ge(`acp: result received (${w.result.length} chars, stopReason=${w.stopReason})`),tt(e.holdOpen,{isAborted:()=>p,hasChildExited:()=>_,isTurnInFlight:()=>m,lastEventAtMs:()=>E,closeStdin:()=>{u.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>h})}catch(k){te(u).catch(()=>{}),s(k instanceof Error?k:new Error(String(k)))}})()})}async function Pm(t){let e=Ln(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&Lm(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:v=>{n.push(v)}}},{binary:o,spawnArgs:a,spawnEnv:l}=Dm(e,t,i),c=Rm(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,p=t.sessionId||"",_=null,E="";c.stderr?.on("data",v=>{E+=v.toString()});let m,h,T=pi({tool:t.tool,onDelta:v=>m?.(v),...e.isolateResult?{isolateResult:e.isolateResult}:{}});T.setSessionId(p);let g=Ot(c,{provider:t.tool,onEvent:v=>{u.lastEventAtMs=Date.now(),Cm(v)&&(u.backgroundJobLaunched=!0),h?.(v)},onNotification:v=>{u.lastEventAtMs=Date.now(),T.processMessage(v)}}),y=()=>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`),S=[],I=()=>u.exited?Promise.resolve():new Promise(v=>{S.push(v)}),b=null;c.on("error",v=>{_=new se(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${v.message}`,{cause:v}),D({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:v.message,elapsed_ms:Date.now()-d}),g.close(v)}),c.on("exit",v=>{if(u.exited=!0,u.exitCode=v,g.close(new se(`ACP process exited with code ${String(v)}`)),!u.telemetryFired){u.telemetryFired=!0;let w=T.finalize();w!==null&&e.onExitFinalization?.({...i,sessionId:w.sessionId,result:w.result,stopReason:w.stopReason,exitCode:v})}if(b!==null){let w=b;b=null,w(y())}for(let w of S.splice(0))w()});try{let v=await Mm({sendRpc:g.sendRpc,sendNotification:g.sendNotification,opts:t,outputProcessor:T,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async w=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:w,cwd:t.cwd,env:l})});p=v.sessionId,await Om(e,i,{sessionId:v.sessionId,response:v.sessionResponse},g.sendRpc)}catch(v){let w=_??(v instanceof Error?v:new Error(String(v)));throw te(c).catch(()=>{}),w}let k=v=>new Promise(w=>{setTimeout(w,v).unref?.()});return{tool:t.tool,get sessionId(){return p},get completedTurns(){return u.completedTurns},async sendTurn(v,w={}){if(f&&await f,u.closed||u.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(u.exited)throw y();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(w.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:p,cwd:t.cwd,env:l}),u.exited)throw y();if(w.signal?.aborted)throw new Error("Aborted")}u.turnInFlight=!0,m=w.onDelta,h=w.onEvent;let N=Date.now();try{T.beginTurn(),ge(`acp: bundle prompt sent (${v.length} chars)`);let A,R=!1;if(await new Promise((O,M)=>{b=M;let X,$=()=>{R=!0,f=Promise.resolve().then(()=>X).catch(()=>{}),T.cancelTurn(),g.sendNotification("session/cancel",{sessionId:p}),M(new Error("Aborted"))},ie=w.signal;ie?.addEventListener("abort",$,{once:!0}),X=g.sendRpc("session/prompt",{sessionId:p,prompt:[{type:"text",text:v}]},B=>{R||(B.error?T.cancelTurn():A=T.completeTurn(B),m=void 0,h=void 0)}),X.then(B=>{ie?.removeEventListener("abort",$),O(B)},B=>{ie?.removeEventListener("abort",$),M(B instanceof Error?B:new Error(String(B)))})}),b=null,!A)throw new Error("ACP prompt completed without a result boundary");u.turnInFlight=!1,u.completedTurns+=1,ge(`acp: bundle result received (${A.result.length} chars, stopReason=${A.stopReason})`);let x=s&&n.length>0?[...n]:void 0;return s=!1,{result:A.result,sessionId:A.sessionId,stopReason:A.stopReason,durationMs:Date.now()-N,sawActivity:A.sawActivity,...x!==void 0?{warnings:x}:{}}}catch(A){throw b=null,T.cancelTurn(),u.turnInFlight=!1,u.exited?y():A}finally{m=void 0,h=void 0}},close(){return u.closing!==null||(u.closing=(async()=>{if(u.closed=!0,u.exited||(t.holdOpen!==void 0?await new Promise(w=>{tt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>u.exited,isTurnInFlight:()=>u.turnInFlight,lastEventAtMs:()=>u.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),w()},label:t.tool,wasBackgroundJobLaunched:()=>u.backgroundJobLaunched})}):c.stdin?.end(),u.exited))return;let v=t.closeTimeoutMs??2e3;await Promise.race([I(),k(v)]),u.exited||await te(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{})})()),u.closing}}}var $a=L(()=>{"use strict";re();Qt();Lr();wn();rt();re();qe();bn();Ia();Nm();Pa();Da();bn()});function le(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function $m(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=zS){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 Um(){let t=new Map;return(e,r)=>{QS(e,$m(t,r))}}function QS(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(le(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(le(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:le(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=le(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:le(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:le(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(`
|
|
1654
1654
|
`).length} lines, ${u.length} chars`;else if(Array.isArray(u)){let f=u.map(p=>typeof p=="object"&&p&&"text"in p?p.text:"").filter(Boolean).join("");f&&(d=`${f.split(`
|
|
1655
|
-
`).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
|
|
1655
|
+
`).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 Ei(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?Um():void 0;if(e.bundleSession!==void 0)return pt(e.bundleSession,r,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=await Vf(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 Ti(t){let e=t.binary==="qwen"?"qwen":"claude",r=await Kf({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=Um(),o=await r.sendTurn(n,{onText:s.onDelta,onEvent:a=>{s.onEvent?.(a),s.onProgress&&i(a,s.onProgress)},signal:s.signal});return{text:o.result,sessionId:o.sessionId,durationMs:o.durationMs,...o.warnings!==void 0?{warnings:o.warnings}:{}}},close:()=>r.close()}}function jm(){let t=new Map;return(e,r)=>{ZS(e,$m(t,r))}}function ZS(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:le(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:le(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=le(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:le(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 ${le(c,80)}`:"running\u2026";e({kind:"other",summary:d,id:a})}return}e({kind:"other",summary:i})}}function Bm(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function nt(t,e){let r=e.acpTool||e.binary,n=e.onProgress?jm():void 0;if(e.bundleSession!==void 0)return pt(e.bundleSession,r,e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let s=[];if(e.model&&r==="copilot"){let a="copilot --acp does not implement per-session model selection";Se({event:"model_ignored",provider:r,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await Fm(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,...Bm(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function st(t){let e=t.acpTool||t.binary,r=await Pm({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=jm(),o=await r.sendTurn(n,{...s,onEvent:a=>{s.onEvent?.(a),s.onProgress&&i(a,s.onProgress)}});return{text:o.result,sessionId:o.sessionId,durationMs:o.durationMs,stopReason:o.stopReason,sawActivity:o.sawActivity,...Bm(o.result,o.sawActivity)?{status:"empty"}:{},...o.warnings!==void 0?{warnings:o.warnings}:{}}},close:()=>r.close()}}function Hm(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: ${le(o,120)}`}:{kind:"other",summary:`codex error: ${le(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:le(c||"(command)"),id:a});else{let d=s.exitCode,u=s.status||"",f=typeof s.durationMs=="number"?s.durationMs:void 0,p=typeof d=="number"?`exit ${d}`:u||"done",_=[];typeof d=="number"?_.push(`exit ${d}`):u&&_.push(u),typeof f=="number"&&_.push(`${Math.round(f/1e3)}s`),e({kind:"tool_result",summary:_.join(", ")||"done",status:p,elapsedMs:f,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(o){let l=s.changes,c=Array.isArray(l)?l.map(d=>d.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:le(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:le(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:le(s)}:{kind:"text",summary:le(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:le(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
1656
1656
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${le(o,60)}`:le(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r==="item/commandExecution/terminalInteraction"||r==="item/commandExecution/outputChunk"||r==="item/commandExecution/output"){let s=(typeof n?.stdin=="string"?n.stdin:"")||(typeof n?.delta=="string"?n.delta:"")||(typeof n?.output=="string"?n.output:"")||(typeof n?.text=="string"?n.text:"")||(typeof n?.content=="string"?n.content:"")||(typeof n?.chunk=="string"?n.chunk:"")||"";if(s){let i=s.split(`
|
|
1657
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${le(o,60)}`:le(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r.startsWith("item/")){e({kind:"other",summary:r.slice(5)});return}}async function
|
|
1658
|
-
`):"";y&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(y.trimStart())&&!y.trimStart().startsWith("lmctl seed initial connection only.")&&E.push(y)}if(typeof g=="string"){let y=g.trim();if(y.includes("<command-name>")||y.includes("<local-command-")||/^<task-notification>\s*</u.test(y)||y.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(y))continue;d||(d=H(g.trim(),80)),u=H(g.trim(),80),_=void 0,s.push({role:"user",timestamp:T,content:ne(g.trim())})}else if(Array.isArray(g)){for(let y of g)if(y.type==="tool_result"){let
|
|
1659
|
-
`);try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1660
|
-
`);
|
|
1661
|
-
`);
|
|
1662
|
-
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:
|
|
1663
|
-
`).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?
|
|
1657
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${le(o,60)}`:le(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 Wm(t,e){if(e.bundleSession!==void 0)return pt(e.bundleSession,"codex",e.sessionId,t,{onDelta:e.onDelta,onProgress:e.onProgress,signal:e.signal});let r=await rm(t,{threadId:e.sessionId,requireResume:e.requireResume,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=>Hm(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function Xm(t){let e=await nm({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,onEvent:i=>{n.onEvent?.(i),n.onProgress&&Hm(i,n.onProgress)}});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var zS,_t=L(()=>{"use strict";wa();wa();sm();$a();Ar();re();zS=256});function Ua(t={}){let e=Ea(t.miniplayerHome),r=n=>({...n??process.env,MINIPLAYER_HOME:e});return new class extends ee{constructor(){super({provider:new si({miniplayerHome:e}),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeSession:!1,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none",leaderSetupHint:"Miniplayer provides native file, shell and web tools. Live ACP sessions cannot be resumed after exit."},binary:"miniplayer",seedArgs:[],resumeTemplate:"",startTemplate:"miniplayer run",transport:(n,s)=>{if(s.sessionId||s.requireResume)throw new Error('miniplayer does not support resume; use lmctl prompt --provider miniplayer --model <model> "<prompt>"');return nt(n,{...s,env:r(s.env),acpTool:"miniplayer",requireResume:!1})}})}openSession(n){if(n.sessionId)throw new Error("miniplayer cannot reopen a closed ACP session; start a fresh conversation");return st({...n,env:r(n.env),binary:"miniplayer",acpTool:"miniplayer"})}manualSeedHint(){return{launchCommand:"miniplayer --help",postLaunchNote:'Use lmctl prompt --provider miniplayer --model <model> "<prompt>". Each invocation creates a fresh run.',lsCommand:"lmctl ls --provider miniplayer"}}resumeCommand(){throw new Error("miniplayer has no interactive terminal or session resume")}async seed(){return{success:!1,error:'miniplayer does not support team session resume; use lmctl prompt --provider miniplayer --model <model> "<prompt>"'}}}}var ja=L(()=>{"use strict";Te();$f();_t()});import{readdir as wi,stat as qm,unlink as ev}from"node:fs/promises";import{join as Dr,basename as Gm}from"node:path";function tv(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function rv(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return ne(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 Jm(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of oe(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=H(d.trim(),80)}}else if(c.type==="assistant"&&c.message){let d=c.message.content;if(Array.isArray(d))for(let f of d)f.type==="text"&&e++;let u=c.message.usage;if(u){let f=u.input_tokens||0,p=u.cache_creation_input_tokens||0,_=u.cache_read_input_tokens||0,E=u.output_tokens||0;r+=f+p+_,n+=_,s+=p,i+=E;let m=f+p+_;m&&(o=m),a={inputTokens:f,cacheWriteInputTokens:p,cachedInputTokens:_,outputTokens:E}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function nv(t){let e=sv(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 sv(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 Si,Vm=L(()=>{"use strict";pe();Si=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Dr(V,".claude"),this.projectsDir=Dr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await wi(this.projectsDir)}catch{return e}for(let n of r){let s=Dr(this.projectsDir,n);if(!(await qm(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await wi(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Gm(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Dr(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await Oe(e,50),s=await ce(e),i="",o,a,l,c,d,u;for(let p of n)if(!tv(p.type)&&(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!u&&p.timestamp&&(u=new Date(p.timestamp)),p.type==="assistant"&&p.message?.model&&(l=p.message.model),p.type==="user"&&!p.isMeta&&p.message)){let _=p.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;c||(c=H(_.trim(),80)),d=H(_.trim(),80)}}if(!i)return null;let f=await Jm(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,p=e,_,E=[];for await(let h of oe(r))if(h.type!=="file-history-snapshot"&&!h.isSidechain){if(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!c&&h.gitBranch&&(c=h.gitBranch),!f&&h.timestamp&&(f=new Date(h.timestamp)),h.sessionId&&(p=h.sessionId),h.type==="system"||h.type==="progress"||h.type==="queue-operation"){s.push({role:"system",timestamp:new Date(h.timestamp||0),content:rv(h)});continue}if(h.type==="user"&&h.message){if(h.isMeta)continue;let T=new Date(h.timestamp||0),g=h.message.content;if(h.isCompactSummary!==!0&&h.isVisibleInTranscriptOnly!==!0&&h.promptSource!=="system"&&h.toolUseResult===void 0&&h.origin?.kind!=="task-notification"&&h.interruptedMessageId===void 0&&h.interruptedByShutdown!==!0&&h.scheduledTaskId===void 0&&h.scheduledFireId===void 0&&!(Array.isArray(g)&&g.some(y=>y.type==="tool_result"))){let y=typeof g=="string"?g:Array.isArray(g)?g.filter(S=>S.type==="text"&&typeof S.text=="string").map(S=>S.text).join(`
|
|
1658
|
+
`):"";y&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(y.trimStart())&&!y.trimStart().startsWith("lmctl seed initial connection only.")&&E.push(y)}if(typeof g=="string"){let y=g.trim();if(y.includes("<command-name>")||y.includes("<local-command-")||/^<task-notification>\s*</u.test(y)||y.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(y))continue;d||(d=H(g.trim(),80)),u=H(g.trim(),80),_=void 0,s.push({role:"user",timestamp:T,content:ne(g.trim())})}else if(Array.isArray(g)){for(let y of g)if(y.type==="tool_result"){let S=typeof y.content=="string"?ne(y.content):JSON.stringify(y.content);s.push({role:"tool_result",timestamp:T,content:S,toolCallId:y.tool_use_id})}}}if(h.type==="assistant"&&h.message){h.message.stop_reason===null||h.message.stop_reason==="tool_use"?_="in_progress":typeof h.message.stop_reason=="string"&&(_="complete"),h.message.model&&(l=h.message.model);let T=new Date(h.timestamp||0),g=h.message.content;if(Array.isArray(g))for(let y of g)y.type==="text"&&y.text?s.push({role:"assistant",timestamp:T,content:ne(y.text),model:h.message.model,...typeof h.message.stop_reason=="string"?{stopReason:h.message.stop_reason}:{}}):y.type==="tool_use"?s.push({role:"tool_use",timestamp:T,content:y.name||"unknown tool",toolName:y.name,toolInput:JSON.stringify(y.input,null,2),toolInputData:y.input,toolCallId:y.id,model:h.message.model,...typeof h.message.stop_reason=="string"?{stopReason:h.message.stop_reason}:{}}):y.type==="thinking"&&y.thinking&&s.push({role:"thinking",timestamp:T,content:y.thinking})}}if(!i)return null;nv(s);let m=await Jm(r);return{provider:"claude",sessionId:p,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:_,firstUserMessage:d,lastUserMessage:u,messageCount:m.messageCount,filePath:r,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:m.totalCacheWriteInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage,messages:s,userPrompts:E}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await ev(r),!0):!1}async resolveSessionFile(e){let r;try{r=await wi(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Dr(this.projectsDir,o);if(!(await qm(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await wi(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=Gm(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Dr(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 Oe(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{join as Km}from"node:path";function Ha(t){return new Ba(t)}var Ba,Wa=L(()=>{"use strict";Vm();Te();pe();_t();Ee();Ba=class extends ee{claudeDir;constructor(e){super({provider:new Si(e),protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",Y,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:Ei}),this.claudeDir=e?.claudeDir??Km(V,".claude")}openSession(e){return Ti({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[Km(this.claudeDir,"projects")]})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as iv,stat as Ym,unlink as ov}from"node:fs/promises";import{join as Cn,basename as av}from"node:path";function lv(t,e,r){return`${t}|${e.toISOString()}|${r}`}function On(t,e,r){let n=lv(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function zm(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function cv(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 Mr(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 Mr(r)}).filter(r=>r.length>0).join(`
|
|
1659
|
+
`);try{return JSON.stringify(t)}catch{return String(t)}}function dv(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 uv(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 Qm(t){let e=0,r=0,n=0,s=0,i=0,o,a,l;for await(let c of oe(t)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let d=c.payload.message||c.payload.text;d&&(l=H(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=H(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=cv(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 vi,Zm=L(()=>{"use strict";pe();vi=class{name="codex";codexDirs;constructor(e={}){let r=[Cn(V,".codex"),Cn(V,".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:Cn(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=Cn(r,"sessions");try{await Ym(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 iv(e)}catch{return r}for(let s of n){let i=Cn(e,s),o=await Ym(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=av(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 Oe(e,30),n=await ce(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,d,u,f;for(let _ of r){if(_.type==="session_meta"&&_.payload&&(_.payload.id&&(s=_.payload.id),_.payload.cwd&&(i=_.payload.cwd),_.payload.cli_version&&(o=_.payload.cli_version),_.payload.timestamp&&(l=new Date(_.payload.timestamp)),_.payload.originator&&(u=_.payload.originator),_.payload.source&&(f=_.payload.source)),_.type==="turn_context"&&_.payload&&(_.payload.model&&(a=_.payload.model),!i&&_.payload.cwd&&(i=_.payload.cwd)),_.type==="event_msg"&&_.payload?.type==="user_message"){let E=_.payload.message||_.payload.text;E&&(c||(c=H(E.trim(),80)),d=H(E.trim(),80))}if(_.type==="response_item"&&_.payload?.type==="message"&&_.payload.role==="user"&&_.payload.content){let E=_.payload.content.find(m=>m.type==="input_text"&&typeof m.text=="string"&&m.text);typeof E?.text=="string"&&(c||(c=H(E.text.trim(),80)),d=H(E.text.trim(),80))}}if(!i)return null;let p=await Qm(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:zm(u,f),firstUserMessage:c,lastUserMessage:p.lastUserMessage??d,messageCount:p.messageCount,filePath:e,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCachedInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,totalReasoningOutputTokens:p.totalReasoningOutputTokens||void 0,lastInputTokens:p.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:p.lastTokenUsage,modelContextWindow:p.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await ce(r),s=[],i="",o,a,l,c,d,u=e,f,p,_=new Set,E=[],m=new Set,h=[],T=(S,I)=>{let b=h.find(k=>!k.mirrored&&k.source!==I&&k.text===S);b?b.mirrored=!0:h.push({text:S,source:I,mirrored:!1})},g=()=>{E.push(...h.map(S=>S.text)),h=[]};for await(let S of oe(r)){let I=S.timestamp?new Date(S.timestamp):new Date;if(S.type==="session_meta"&&S.payload){S.payload.id&&(u=S.payload.id),S.payload.cwd&&(i=S.payload.cwd),S.payload.cli_version&&(o=S.payload.cli_version),S.payload.timestamp&&(l=new Date(S.payload.timestamp)),f=zm(S.payload.originator,S.payload.source);continue}if(S.type==="turn_context"&&S.payload){S.payload.model&&(a=S.payload.model),!i&&S.payload.cwd&&(i=S.payload.cwd);continue}if(S.type==="response_item"&&S.payload){let b=S.payload;if(b.type==="message"){if(b.role==="user"&&b.content){let k=b.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(k)){let v=b.content.filter((w,N)=>k[N]==="user.text"&&typeof w.text=="string").map(w=>w.text).join(`
|
|
1660
|
+
`);k.includes("user.text")&&v&&(!b.id||!m.has(b.id))&&(T(v,"metadata"),b.id&&m.add(b.id))}for(let v of b.content)if(v.type==="input_text"&&typeof v.text=="string"&&v.text){let w=v.text.trim();c||(c=H(w,80)),d=H(w,80),On(s,_,{role:"user",timestamp:I,content:ne(w)})}continue}if(b.role==="assistant"&&b.content){for(let k of b.content)k.type==="output_text"&&typeof k.text=="string"&&k.text&&On(s,_,{role:"assistant",timestamp:I,content:ne(k.text),model:a});continue}if(b.role!=="user"&&b.role!=="assistant"&&b.content){for(let k of b.content)(k.type==="input_text"||k.type==="output_text")&&typeof k.text=="string"&&k.text&&On(s,_,{role:"system",timestamp:I,content:ne(k.text.trim())});continue}}if(b.type==="function_call"){s.push({role:"tool_use",timestamp:I,content:b.name||"unknown tool",toolName:b.name,toolInput:b.arguments!==void 0?ne(Mr(b.arguments)):void 0,toolInputData:dv(b.arguments),toolCallId:b.call_id});continue}if(b.type==="function_call_output"){s.push({role:"tool_result",timestamp:I,content:ne(Mr(b.output)),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:I,content:b.name||"unknown tool",toolName:b.name,toolInput:b.input!==void 0?ne(Mr(b.input)):void 0,toolInputData:uv(b.name,b.input),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:I,content:ne(Mr(b.output)),toolCallId:b.call_id});continue}if(b.type==="reasoning"&&b.summary){let k=b.summary.map(v=>Mr(v.text)).join(`
|
|
1661
|
+
`);k.trim()&&On(s,_,{role:"thinking",timestamp:I,content:ne(k)});continue}}if(S.type==="event_msg"&&S.payload&&(S.payload.type==="task_started"?(g(),p="in_progress"):S.payload.type==="task_complete"?p="complete":S.payload.type==="turn_aborted"&&(p="aborted"),S.payload.type==="user_message"&&typeof S.payload.message=="string"&&T(S.payload.message,"event"),S.payload.type==="agent_reasoning")){let b=S.payload.message||S.payload.text;b&&On(s,_,{role:"thinking",timestamp:I,content:ne(b)})}}if(!i)return null;g();let y=await Qm(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,turnStatus:p,firstUserMessage:c,lastUserMessage:d,messageCount:y.messageCount,filePath:r,totalInputTokens:y.totalInputTokens||void 0,totalCachedInputTokens:y.totalCachedInputTokens||void 0,totalOutputTokens:y.totalOutputTokens||void 0,totalReasoningOutputTokens:y.totalReasoningOutputTokens||void 0,lastInputTokens:y.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:y.lastTokenUsage,modelContextWindow:y.modelContextWindow,messages:s,userPrompts:E}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await ov(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 Oe(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 Ga(t){return new qa(t)}var Xa,qa,Ja=L(()=>{"use strict";Zm();Te();_t();Ee();Xa="gpt-5.6-sol",qa=class extends ee{constructor(e){super({provider:new vi(e),protocol:{transport:"codex-app-server",perTurnCancellation:"process",persistentCancellation:"turn"},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:`${Y}
|
|
1662
|
+
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Wm})}openSession(e){return Xm({...e,model:e.model??Xa})}seedArgsFor(e){let r=super.seedArgsFor(e),n=e?.model??Xa;return[...r.slice(0,-1),"--model",n,r[r.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:Xa}}}});function Dn(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 bi(t){let e=Dn(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(`
|
|
1663
|
+
`).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?fv(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 fv(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(`
|
|
1664
1664
|
`)+`
|
|
1665
|
-
`}var
|
|
1666
|
-
`).trim();
|
|
1667
|
-
`)}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:
|
|
1668
|
-
`)){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 tr(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function
|
|
1669
|
-
`).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
|
|
1670
|
-
`).trim():""}function
|
|
1671
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return rr(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
|
|
1665
|
+
`}var Va=L(()=>{"use strict"});import{createHash as mv}from"node:crypto";import{readdir as Mn,readFile as rp,stat as Ii,unlink as pv}from"node:fs/promises";import{join as De,basename as hv,dirname as gv}from"node:path";import{cwd as _v}from"node:process";function Ka(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function np(t){return t==="user"}function Ya(t){return t==="gemini"||t==="assistant"}function er(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function yv(t){return`${t.sessionId}\0${t.cwd}`}function Ev(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 xi(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(!Ya(a.type)||!a.tokens)continue;let l=xi(a.tokens.input),c=xi(a.tokens.cached),d=Math.max(l-c,0),u=xi(a.tokens.output),f=xi(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 Tv(t){return mv("sha256").update(t).digest("hex")}function Fn(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=gv(r);if(n===r)break;r=n}}var ki,ip=L(()=>{"use strict";pe();Va();re();ki=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||De(V,".gemini");this.geminiProjectsFile=De(r,"projects.json"),this.geminiTmpDir=De(r,"tmp");let n=e.claudeDir||De(V,".claude");this.claudeProjectsDir=De(n,"projects");let s=[De(V,".codex"),De(V,".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=>De(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=yv(s),o=r.get(i);r.set(i,o?Ev(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,p;for(let h of a){let T=er(h.timestamp),g=h.type,y=ne(Ka(h.content));if(np(g)){let I=Ka(h.content);I&&o.push(I);let b=y.trim();b&&(u||(u=H(b,80)),f=H(b,80)),i.push({role:"user",timestamp:T,content:b||y});continue}if(Ya(g)){h.model&&(p=h.model);for(let I of h.thoughts||[]){let b=[I.subject,I.description].filter(Boolean).join(`
|
|
1666
|
+
`).trim();b&&i.push({role:"thinking",timestamp:er(I.timestamp,T),content:ne(b)})}i.push({role:"assistant",timestamp:T,content:y,model:h.model});continue}let S=g?`[${g}] `:"";i.push({role:"system",timestamp:T,content:`${S}${y}`.trim()})}let _=er(n.startTime,s.createdAt),E=er(n.lastUpdated,s.modifiedAt),m=sp(a);return{provider:"gemini",sessionId:l,cwd:d,createdAt:_,modifiedAt:E,model:p,startCommand:"gemini",firstUserMessage:u,lastUserMessage:f,messageCount:i.filter(h=>h.role==="user"||h.role==="assistant").length,filePath:r,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage,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 p of s)if(np(p.type)){u++;let _=Ka(p.content).trim();_&&(l||(l=H(ne(_),80)),c=H(ne(_),80))}else Ya(p.type)&&(u++,p.model&&(d=p.model));let f=sp(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:er(r.startTime,n.createdAt),modifiedAt:er(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 rp(e,"utf-8");if(Dn(r)==="unknown")return D({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 bi(r)}catch{return null}}extractSessionIdFromFilename(e){let r=hv(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 Mn(this.geminiTmpDir)}catch{return e}for(let n of r){let s=De(this.geminiTmpDir,n,"chats");if(!(await Ii(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Mn(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(De(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await pv(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:er(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;Fn(e,_v());for(let n of this.extraWorkspacePaths)Fn(e,n);for(let n of await this.collectGeminiProjectPaths())Fn(e,n);for(let n of await this.collectCodexCwds())Fn(e,n);for(let n of await this.collectClaudeCwds())Fn(e,n);let r=new Map;for(let n of e)r.set(Tv(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await rp(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 Oe(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await Mn(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=De(this.claudeProjectsDir,n);if(!(await Ii(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Mn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=De(s,a),d=(await Oe(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await Ii(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await Mn(e)}catch{return r}for(let i of s){let o=De(e,i),a=await Ii(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 wv,writeFileSync as Sv,mkdirSync as vv}from"node:fs";import{join as bv,dirname as Iv}from"node:path";import{randomUUID as xv}from"node:crypto";function Qa(t){return new za(t)}var za,Za=L(()=>{"use strict";vr();ip();Te();Ee();Va();za=class extends ee{constructor(e){super({provider:new ki(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!1,canResumeInteractive:!1,canFork:!0,forkSupport:"automatic",canStructuredTurn:!1,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",Y,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:()=>Promise.reject(new Error(kt))})}seed(e,r){return Promise.resolve({success:!1,error:kt})}sendTurn(e,r){return Promise.reject(new Error(kt))}openSession(e){return Promise.reject(new Error(kt))}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(`
|
|
1667
|
+
`)}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:Ks,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=wv(n,"utf-8"),i=Dn(s),o=bi(s),a=xv();o.sessionId=a,o.kind="main";let l=Iv(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=i==="jsonl"?".jsonl":".json",u=`session-${c}-${a.slice(0,8)}${d}`,f=bv(l,u);return vv(l,{recursive:!0}),Sv(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 op,readFile as kv,rm as Av,stat as Fr}from"node:fs/promises";import{basename as Nv,join as Ge}from"node:path";function Rv(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 el(){return{shutdownTotals:null,assistantOutputSum:0}}function lp(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=Rv(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function ap(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 Lv(t){let e={};for(let r of t.split(`
|
|
1668
|
+
`)){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 tr(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function Cv(t){let e=0,r=el(),n;for await(let s of oe(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=H(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;lp(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function Ov(t){let e=Dv(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(`
|
|
1669
|
+
`).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 Dv(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 Ai,cp=L(()=>{"use strict";pe();Ai=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||Ge(V,".copilot");this.sessionStateDir=Ge(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await op(this.sessionStateDir)}catch{return e}for(let n of r){let s=Ge(this.sessionStateDir,n);if((await Fr(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=Ge(r,"events.jsonl"),i=await Fr(s).catch(()=>null),o=i?s:Ge(r,"workspace.yaml"),a=await ce(i?s:r),l=[],c=[],d=n?.cwd||"(unknown workspace)",u,f,p,_,E,m,h=n?.id||Nv(r)||e,T=el();if(i)for await(let g of oe(s)){let y=tr(g.timestamp)||a.modifiedAt;if(lp(T,g),g.type==="session.start"&&g.data){g.data.sessionId&&(h=g.data.sessionId),g.data.copilotVersion&&(f=g.data.copilotVersion),g.data.startTime&&(m=tr(g.data.startTime)),g.data.selectedModel&&(u=g.data.selectedModel),g.data.context&&(g.data.context.cwd&&(d=g.data.context.cwd),g.data.context.branch&&(p=g.data.context.branch));continue}if(g.type==="session.model_change"&&g.data?.newModel){u=g.data.newModel;continue}if(g.type==="user.message"&&g.data){let S=g.data.content||"";S&&c.push(S);let I=S.trim();I&&(_||(_=H(I,80)),E=H(I,80)),l.push({role:"user",timestamp:y,content:ne(I||S)});continue}if(g.type==="assistant.message"&&g.data){let S=(g.data.content||"").trim();if(S&&l.push({role:"assistant",timestamp:y,content:ne(S),model:u}),g.data.toolRequests)for(let I of g.data.toolRequests)l.push({role:"tool_use",timestamp:y,content:I.name||"unknown tool",toolName:I.name,toolInput:I.arguments?JSON.stringify(I.arguments,null,2):void 0,toolInputData:Ue(I.arguments),toolCallId:I.toolCallId});continue}if(g.type==="tool.execution_complete"&&g.data){let S=g.data.result?.content||"",I=g.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:y,content:ne(S),toolDetailedContent:I?ne(I):void 0,toolCallId:g.data.toolCallId});continue}if(g.type==="assistant.reasoning"&&g.data?.content){l.push({role:"thinking",timestamp:y,content:ne(g.data.content)});continue}if(g.type==="session.error"||g.type==="session.warning"||g.type==="session.info"||g.type==="system.message"){let S=g.data?.message||"";S.trim()&&l.push({role:"system",timestamp:y,content:ne(S)});continue}}if(!_){let g=(n?.summary||"").trim();g&&(_=H(g,80))}return Ov(l),{provider:"copilot",sessionId:h,cwd:d,createdAt:m??tr(n?.created_at)??a.createdAt,modifiedAt:tr(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",gitBranch:p,firstUserMessage:_,lastUserMessage:E,messageCount:l.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:o,...ap(T),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=Ge(e,"events.jsonl"),i=await Fr(s).catch(()=>null),o=i?s:Ge(e,"workspace.yaml"),a=await ce(i?s:e),l=i?await Oe(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,f,p,_,E;for(let h of l)if(h.type==="session.start"&&h.data&&(h.data.sessionId&&(c=h.data.sessionId),h.data.copilotVersion&&(f=h.data.copilotVersion),h.data.startTime&&(p=tr(h.data.startTime)),h.data.selectedModel&&(u=h.data.selectedModel),h.data.context?.cwd&&(d=h.data.context.cwd)),h.type==="session.model_change"&&h.data?.newModel&&(u||(u=h.data.newModel)),h.type==="user.message"&&h.data){let T=(h.data.content||"").trim();T&&(_||(_=H(T,80)),E=H(T,80))}if(!_){let h=(n?.summary||"").trim();h&&(_=H(h,80))}let m=i?await Cv(s):{messageCount:0,tokens:el()};return{provider:"copilot",sessionId:c,cwd:d,createdAt:p??tr(n?.created_at)??a.createdAt,modifiedAt:tr(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",firstUserMessage:_,lastUserMessage:m.lastUserMessage??E,messageCount:m.messageCount,filePath:o,...ap(m.tokens)}}async readWorkspaceYaml(e){let r=Ge(e,"workspace.yaml");try{let n=await kv(r,"utf-8");return Lv(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await Av(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await op(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=Ge(this.sessionStateDir,e);if((await Fr(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=Ge(this.sessionStateDir,s);(await Fr(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=Ge(this.sessionStateDir,s);if(!(await Fr(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 rl(t){return new tl(t)}var tl,nl=L(()=>{"use strict";cp();Te();_t();re();Ee();tl=class extends ee{copilotDir;constructor(e){super({provider:new Ai(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",Y,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>nt(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return st({...e,env:this.copilotDir!==void 0?{...e.env??process.env,COPILOT_HOME:this.copilotDir}:e.env,binary:"copilot",acpTool:"copilot"})}async seed(e,r){let n=await super.seed(e,r);if(r?.model===void 0||r.model.trim().length===0)return n;let s="copilot seed does not implement per-session model selection";return Se({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function il(){return new sl}var sl,ol=L(()=>{"use strict";_i();Te();_t();Ee();sl=class extends ee{constructor(){super({provider:new Or,protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},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",Y],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>nt(e,{...r,acpTool:"opencode"})})}openSession(e){return st({...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??Y),r}}});import{appendFile as Mv,mkdir as Fv,readFile as dp,readdir as up,rm as Pv,stat as fp}from"node:fs/promises";import{basename as $v,dirname as Uv,isAbsolute as mp,join as rr,relative as jv,resolve as al}from"node:path";function ll(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function Xv(t){return typeof t=="number"?new Date(t):ll(t)??new Date(0)}function pp(t){return typeof t=="string"?t.trim():Array.isArray(t)?t.map(e=>e&&typeof e=="object"&&"text"in e&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
1670
|
+
`).trim():""}function hp(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function qv(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:hp(t)??""}function Gv(t){let e=Jv(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 Jv(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 Bv,Hv,Wv,Ni,gp=L(()=>{"use strict";pe();Bv="1.4",Hv="1.5",Wv=new Set([Bv,Hv]),Ni=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=al(e?.kimiHome??process.env.KIMI_CODE_HOME??rr(V,".kimi-code")),this.sessionsDir=rr(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 Pv(r.sessionDir,{recursive:!0,force:!0}),await Fv(Uv(this.indexPath()),{recursive:!0,mode:448}),await Mv(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
1671
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return rr(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 up(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=rr(this.sessionsDir,s.name),o;try{o=await up(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=rr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await dp(this.indexPath(),"utf-8")}catch{return new Map}let r=new Map;for(let n of e.split(/\r?\n/))if(n.trim())try{let s=JSON.parse(n);if(typeof s.sessionId!="string")continue;s.deleted===!0?r.delete(s.sessionId):typeof s.sessionDir=="string"&&typeof s.workDir=="string"&&r.set(s.sessionId,{sessionId:s.sessionId,sessionDir:al(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:rr(r,"state.json"),wirePath:rr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!mp(e)||$v(e)!==r)return!1;let n=jv(this.sessionsDir,al(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!mp(n)}async findSession(e){let r=await this.sessionFiles(),n=r.find(i=>i.sessionId===e);if(n)return n;let s=r.filter(i=>i.sessionId.startsWith(e));return s.length===1?s[0]:null}async readState(e){try{let r=JSON.parse(await dp(e,"utf-8"));return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}async summary(e){let r=await this.readState(e.statePath);if(!r)return null;let n;try{n=await fp(e.wirePath)}catch{return null}let s=await fp(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=ll(r.createdAt)??s.birthtime,a=ll(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?H(r.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let r=[],n=[],s=new Set,i=!0,o,a,l,c=0,d=0,u=0,f=0,p=!1,_=0,E,m;for await(let h of oe(e)){let T=Xv(h.time??h.created_at);if(i&&(i=!1,h.type==="metadata"&&!Wv.has(h.protocol_version))){let y=`Kimi transcript wire protocol version ${JSON.stringify(h.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:T,content:y}],userPrompts:[],messageCount:1,firstUserMessage:y,lastUserMessage:y}}if((h.type==="config.update"||h.type==="profile.bind")&&h.modelAlias&&(o=h.modelAlias),h.type==="usage.record"){h.model&&(o=h.model),p||=h.usage!==void 0;let y=h.usage?.inputOther??0,S=h.usage?.inputCacheRead??0,I=h.usage?.inputCacheCreation??0,b=h.usage?.output??0;c+=y,d+=S,u+=I,f+=b,h.usageScope==="turn"&&(E=y+S+I,m={inputTokens:y,cachedInputTokens:S,cacheWriteInputTokens:I,outputTokens:b,totalTokens:E+b});continue}if(h.type==="turn.prompt"&&h.origin?.kind==="user"){let y=pp(h.input);y&&((!h.promptId||!s.has(h.promptId))&&(n.push(y),h.promptId&&s.add(h.promptId)),a??=H(y,80),l=H(y,80),r.push({role:"user",timestamp:T,content:y}),_++);continue}if(h.type==="turn.steer"){let y=pp(h.input);y&&(r.push({role:"system",timestamp:T,content:y}),_++);continue}if(h.type!=="context.append_loop_event"||!h.event)continue;let g=h.event;g.type==="content.part"&&g.part?.type==="text"&&g.part.text?(r.push({role:"assistant",timestamp:T,content:g.part.text,model:o}),_++):g.type==="content.part"&&g.part?.type==="think"&&g.part.think?r.push({role:"thinking",timestamp:T,content:g.part.think,model:o}):g.type==="tool.call"?r.push({role:"tool_use",timestamp:T,content:g.name??"tool",toolName:g.name,toolInput:hp(g.args),toolInputData:Ue(g.args),toolCallId:g.toolCallId,model:o}):g.type==="tool.result"&&r.push({role:"tool_result",timestamp:T,content:qv(g.result),toolCallId:g.toolCallId,model:o})}return Gv(r),{messages:r,userPrompts:n,messageCount:_,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:p?c:void 0,totalCachedInputTokens:p?d:void 0,totalCacheWriteInputTokens:p?u:void 0,totalOutputTokens:p?f:void 0,lastInputTokens:E,lastTokenUsage:m}}}});function dl(t){return new cl(t)}var cl,ul=L(()=>{"use strict";gp();Te();_t();Ee();cl=class extends ee{kimiHome;constructor(e){super({provider:new Ni(e),protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},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",Y,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>nt(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return st({...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??Y,"--output-format","stream-json"),r}}});import{spawn as Vv}from"node:child_process";import{mkdirSync as Kv}from"node:fs";function ml(t){return new fl(t)}async function Yv(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"});he("lmplayer",n,e.permissionMode??"yolo");let s=await Ep(e.binary,n,{cwd:e.cwd,env:ue(e.env,e.cwd,e.sessionId),signal:e.signal,onText:i=>{e.onProgress?.({kind:"text",summary:i.slice(0,120)}),e.onDelta?.(i)}});if(s.code!==0&&s.code!==null)throw new Error(yp(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(...Dt("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function yp(t){if(t.error)return t.error;let e=gn(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function Ep(t,e,r){return new Promise((n,s)=>{let i;try{i=Vv(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(E){s(E);return}let o="",a="",l="",c,d,u,f=[],p=!1,_=E=>{let m=E.trim();if(!m)return;let h;try{h=JSON.parse(m)}catch{f.push(E),r.onText?.(E);return}if(!Pr(h))return;let T=Ri(h,!1);c===void 0&&T!==void 0&&(c=T),d=Ri(h,!0)??d;let g=zv(h);g!==void 0&&(u=g);let y=Tp(h);y&&(f.push(y),r.onText?.(y))};i.stdout?.on("data",E=>{let m=E.toString("utf8");o+=m,l+=m;let h=l.indexOf(`
|
|
1672
1672
|
`);for(;h>=0;){let T=l.slice(0,h);l=l.slice(h+1),_(T),h=l.indexOf(`
|
|
1673
|
-
`)}}),i.stderr?.on("data",E=>{a+=E.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",E=>{p||(p=!0,l.length>0&&_(l),n({code:E,stdout:o,stderr:a,sessionId:c??d,text:f.join(""),error:u}))}),i.on("error",E=>{p||(p=!0,s(E))})})}function
|
|
1673
|
+
`)}}),i.stderr?.on("data",E=>{a+=E.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",E=>{p||(p=!0,l.length>0&&_(l),n({code:E,stdout:o,stderr:a,sessionId:c??d,text:f.join(""),error:u}))}),i.on("error",E=>{p||(p=!0,s(E))})})}function zv(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(Pr(e)){let r=e.data;if(Pr(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 Tp(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(Pr(r)){let n=Tp(r);if(n)return n}}}function Ri(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(Pr(r)){let n=Ri(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(Pr(s)){let i=Ri(s,e);if(i!==void 0)return i}}}function Pr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var fl,pl=L(()=>{"use strict";_i();Te();Ee();rt();qe();la();fl=class extends ee{constructor(e){super({provider:new Or({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),protocol:{transport:"lmplayer",perTurnCancellation:"process"},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",Y],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:Yv})}async sendTurn(e,r){let n=await super.sendTurn(e,r);return r.permissionMode==="plan"?{...n,warnings:[...n.warnings??[],"lmplayer does not enforce plan mode; this turn used full permissions"]}:n}seedArgsFor(e){return _p({prompt:e?.prompt??Y,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){Kv(e,{recursive:!0});let n=this.seedArgsFor(r);he("lmplayer",n);try{let s=await Ep(this.binary,n,{cwd:e,env:Nr(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:yp(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 "${Y}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as Li,readFile as Qv,rm as Zv}from"node:fs/promises";import{basename as wp,join as Pt}from"node:path";function eb(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function Pn(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function tb(t,e){if(!e)return;t.observed=!0;let r=Pn(e.promptTokenCount),n=Pn(e.cachedContentTokenCount),s=Pn(e.candidatesTokenCount),i=Pn(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:Pn(e.totalTokenCount)||r+s}}function rb(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 Sp(t){return t.type==="user"||t.message?.role==="user"}function vp(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function bp(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(`
|
|
1674
1674
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1675
|
-
`):"":""}function Np(t){return t.model||t.message?.model}function ab(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:Lp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function Bn(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 lb(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return Bn(e.output??e.error??t)}return Bn(t)}function Lp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function Rp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:Bn(t.args,!0),toolInputData:Ue(t.args),toolCallId:t.id,model:r}}var Oi,Cp=L(()=>{"use strict";pe();Oi=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Pt(V,".qwen")}async discoverSessions(){let e=Pt(this.baseDir,"projects"),r;try{r=await Ci(e)}catch{return[]}let n=[];for(let s of r){let i=Pt(e,s,"chats"),o;try{o=await Ci(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Pt(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 oe(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)),xp(u)){let f=Ap(u).trim();f&&(l||(l=H(f,80)),c=H(f,80),d++)}if(kp(u)){let f=Np(u);f&&(o=f),d+=ab(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=Ip(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=sb();for await(let p of oe(e)){if(ib(f,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let _=p.message,E=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let m=Lp(p).filter(h=>h.functionResponse!==void 0);m.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:E,content:Bn(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let h of m){let T=h.functionResponse,g=lb(T.response),y=Bn(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:E,content:y??g??p.toolCallResult?.status??"tool result",toolName:T.name,toolCallId:p.toolCallResult?.callId??T.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(xp(p)){let m=Ap(p);m.trim()&&(c||(c=H(m.trim(),80)),d=H(m.trim(),80)),u.push({role:"user",timestamp:E,content:m})}else if(kp(p)){let m=Np(p);if(m&&(i=m),Array.isArray(_.content))for(let h of _.content)h.type==="text"&&h.text?u.push({role:"assistant",timestamp:E,content:h.text,model:m}):h.type==="thinking"&&h.thinking?u.push({role:"thinking",timestamp:E,content:h.thinking}):h.functionCall&&u.push(Rp(h.functionCall,E,m));else if(typeof _.content=="string")u.push({role:"assistant",timestamp:E,content:_.content,model:m});else if(Array.isArray(_.parts))for(let h of _.parts)if(h.thought||h.type==="thinking"){let T=h.thinking||h.text;T&&u.push({role:"thinking",timestamp:E,content:T})}else h.functionCall?u.push(Rp(h.functionCall,E,m)):h.text&&u.push({role:"assistant",timestamp:E,content:h.text,model:m})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...ob(f),messages:u}}async resolveSessionPath(e){let r=Pt(this.baseDir,"projects");try{let n=await Ci(r),s=[];for(let i of n){let o=Pt(r,i,"chats",`${e}.jsonl`);try{return await rb(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Pt(r,i,"chats"),a;try{a=await Ci(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Ip(l,".jsonl").startsWith(e)&&s.push(Pt(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 nb(r),!0}catch{return!1}}}});function _l(){return new gl}var gl,yl=L(()=>{"use strict";Cp();Te();_t();Ee();gl=class extends ee{constructor(){super({provider:new Oi,protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",Y,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:Ti})}openSession(e){return wi({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Op,readFile as Dp,rm as Mp,stat as Fp}from"node:fs/promises";import{basename as El,join as it}from"node:path";import{fileURLToPath as cb}from"node:url";async function db(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 ub(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Pp(t){return t.type==="USER_INPUT"}function $p(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function fb(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function Up(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function jp(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 mb(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function pb(t){for await(let e of oe(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=hb(s);if(i)return i}let n=gb(e.content);if(n)return n}return null}function hb(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 gb(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function _b(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 yb(t,e){let r=new Set;for(let n of e){let s=Eb(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 Eb(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:vb(r.event.content);if(n!==void 0)return Bp(t.filter(i=>!e.has(i)&&bb(i)===n),r.event.step_index);let s=Sb(r.event);if(s!==void 0)return Bp(t.filter(i=>!e.has(i)&&Tb(i.name,r.event.type)&&Wp(wb(i))===s),r.event.step_index)}function Bp(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 Tb(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 wb(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function Sb(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]),Wp(e)}function Wp(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return cb(e)}catch{return}}function vb(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function bb(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 Hp(t){if(t.endsWith(".db"))return El(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Di,Xp=L(()=>{"use strict";pe();Di=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||it(V,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:it(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=it(this.baseDir,"conversations"),r;try{r=await Op(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=El(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return it(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return it(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 Fp(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await db([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of oe(n)){let f=jp(u.content);if(f&&(a=f),Pp(u)){let p=Up(u.content).trim();p&&(l||(l=H(p,80)),c=H(p,80)),d++}else $p(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=Hp(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 oe(i)){let p=ub(f.created_at,s.modifiedAt),_=jp(f.content);if(_&&(a=_),Pp(f)){let E=Up(f.content),m=E.trim();m&&(l||(l=H(m,80)),c=H(m,80)),o.push({role:"user",timestamp:p,content:E});continue}if(Array.isArray(f.tool_calls))for(let E of f.tool_calls){let m=E.name||"tool",h=mb(E.args),T=Ue(E.args),g={role:"tool_use",timestamp:p,content:h,toolName:m,toolInput:h,toolInputData:T};o.push(g),d.push({name:m,stepIndex:f.step_index,input:T,message:g})}if($p(f)&&f.content)o.push({role:"assistant",timestamp:p,content:f.content,model:a});else if(fb(f)&&f.content){let E=_b(f,n),m=E===void 0?null:await this.readTaskLog(n,E),h={role:"tool_result",timestamp:m?.modifiedAt??p,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:E,...m===null?{}:{toolDetailedContent:m.content}};o.push(h),u.push({event:f,message:h})}f.thinking&&o.push({role:"thinking",timestamp:p,content:f.thinking})}return yb(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 Fp(r),r}catch{}let n=it(this.baseDir,"conversations");try{let s=[];for(let i of await Op(n)){if(!i.endsWith(".db"))continue;El(i,".db").startsWith(e)&&s.push(it(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=Hp(r);return n?(await Mp(this.conversationPath(n),{force:!0}),await Mp(it(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 pb(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=it(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Dp(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=it(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Dp(n,"utf8"),ce(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as Ib}from"node:child_process";import{StringDecoder as qp}from"node:string_decoder";function Mi(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 xb(t.label,r.binary,s,{cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function xb(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=Ib(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new qp("utf8"),d=new qp("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let _=p?`signal ${p}`:`exit code ${f}`,E=l.trim()||a.trim();i(new Error(`${t} failed (${_})${E?`: ${E}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var Tl=L(()=>{"use strict";qe()});import{basename as kb}from"node:path";import{randomUUID as Ab}from"node:crypto";function Sl(t){return new wl(t)}function Rb(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var wl,Nb,vl=L(()=>{"use strict";Xp();Te();Ee();rt();Tl();wl=class extends ee{constructor(e){super({provider:new Di(e),protocol:{transport:"print",perTurnCancellation:"process"},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",Y,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:Nb})}async sendTurn(e,r){if(r.requireResume){let s=await this.resolvePath(r.sessionId);if(s===null||kb(s)!==`${r.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${r.sessionId}"`)}let n=await super.sendTurn(e,r);return r.permissionMode==="plan"?{...n,warnings:[...n.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:n}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${Ab()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1676
|
-
${r?.prompt??Y}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstUserMessage?.startsWith(n));if(s.success&&i.length===1)return{...s,sessionId:i[0].sessionId};for(let o of i)await this.provider.deleteSession(o.sessionId);return{...s,success:!1,error:s.error??`agy seed created ${i.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},
|
|
1677
|
-
`))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=$t(this.sessionsDir,e,r,"session.jsonl.zstd");return
|
|
1678
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function
|
|
1675
|
+
`):"":""}function Ip(t){return t.model||t.message?.model}function nb(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:kp(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function $n(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 sb(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return $n(e.output??e.error??t)}return $n(t)}function kp(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function xp(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:$n(t.args,!0),toolInputData:Ue(t.args),toolCallId:t.id,model:r}}var Ci,Ap=L(()=>{"use strict";pe();Ci=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||Pt(V,".qwen")}async discoverSessions(){let e=Pt(this.baseDir,"projects"),r;try{r=await Li(e)}catch{return[]}let n=[];for(let s of r){let i=Pt(e,s,"chats"),o;try{o=await Li(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=Pt(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 oe(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)),Sp(u)){let f=bp(u).trim();f&&(l||(l=H(f,80)),c=H(f,80),d++)}if(vp(u)){let f=Ip(u);f&&(o=f),d+=nb(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=wp(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=eb();for await(let p of oe(e)){if(tb(f,p.usageMetadata),p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.gitBranch&&(a=p.gitBranch)),p.type==="system"&&p.cwd&&(s=p.cwd,p.version&&(o=p.version),p.model&&(i=p.model),p.gitBranch&&(a=p.gitBranch)),!p.message)continue;let _=p.message,E=p.timestamp?new Date(p.timestamp):n.modifiedAt;if(p.type==="tool_result"){let m=kp(p).filter(h=>h.functionResponse!==void 0);m.length===0&&p.toolCallResult?.callId&&u.push({role:"tool_result",timestamp:E,content:$n(p.toolCallResult.resultDisplay??p.toolCallResult.error??p.toolCallResult.status)??"tool result",toolCallId:p.toolCallResult.callId});for(let h of m){let T=h.functionResponse,g=sb(T.response),y=$n(p.toolCallResult?.resultDisplay);u.push({role:"tool_result",timestamp:E,content:y??g??p.toolCallResult?.status??"tool result",toolName:T.name,toolCallId:p.toolCallResult?.callId??T.id,...g!==void 0?{toolDetailedContent:g}:{}})}}else if(Sp(p)){let m=bp(p);m.trim()&&(c||(c=H(m.trim(),80)),d=H(m.trim(),80)),u.push({role:"user",timestamp:E,content:m})}else if(vp(p)){let m=Ip(p);if(m&&(i=m),Array.isArray(_.content))for(let h of _.content)h.type==="text"&&h.text?u.push({role:"assistant",timestamp:E,content:h.text,model:m}):h.type==="thinking"&&h.thinking?u.push({role:"thinking",timestamp:E,content:h.thinking}):h.functionCall&&u.push(xp(h.functionCall,E,m));else if(typeof _.content=="string")u.push({role:"assistant",timestamp:E,content:_.content,model:m});else if(Array.isArray(_.parts))for(let h of _.parts)if(h.thought||h.type==="thinking"){let T=h.thinking||h.text;T&&u.push({role:"thinking",timestamp:E,content:T})}else h.functionCall?u.push(xp(h.functionCall,E,m)):h.text&&u.push({role:"assistant",timestamp:E,content:h.text,model:m})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...rb(f),messages:u}}async resolveSessionPath(e){let r=Pt(this.baseDir,"projects");try{let n=await Li(r),s=[];for(let i of n){let o=Pt(r,i,"chats",`${e}.jsonl`);try{return await Qv(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=Pt(r,i,"chats"),a;try{a=await Li(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;wp(l,".jsonl").startsWith(e)&&s.push(Pt(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 Zv(r),!0}catch{return!1}}}});function gl(){return new hl}var hl,_l=L(()=>{"use strict";Ap();Te();_t();Ee();hl=class extends ee{constructor(){super({provider:new Ci,protocol:{transport:"stream-json",perTurnCancellation:"process",persistentCancellation:"session"},capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",Y,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:Ei})}openSession(e){return Ti({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as Np,readFile as Rp,rm as Lp,stat as Cp}from"node:fs/promises";import{basename as yl,join as it}from"node:path";import{fileURLToPath as ib}from"node:url";async function ob(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 ab(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function Op(t){return t.type==="USER_INPUT"}function Dp(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function lb(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function Mp(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function Fp(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 cb(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function db(t){for await(let e of oe(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=ub(s);if(i)return i}let n=fb(e.content);if(n)return n}return null}function ub(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 fb(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function mb(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 pb(t,e){let r=new Set;for(let n of e){let s=hb(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 hb(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:Eb(r.event.content);if(n!==void 0)return Pp(t.filter(i=>!e.has(i)&&Tb(i)===n),r.event.step_index);let s=yb(r.event);if(s!==void 0)return Pp(t.filter(i=>!e.has(i)&&gb(i.name,r.event.type)&&Up(_b(i))===s),r.event.step_index)}function Pp(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 gb(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 _b(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function yb(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]),Up(e)}function Up(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return ib(e)}catch{return}}function Eb(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function Tb(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 $p(t){if(t.endsWith(".db"))return yl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Oi,jp=L(()=>{"use strict";pe();Oi=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||it(V,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:it(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=it(this.baseDir,"conversations"),r;try{r=await Np(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=yl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return it(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return it(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 Cp(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await ob([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n)for await(let u of oe(n)){let f=Fp(u.content);if(f&&(a=f),Op(u)){let p=Mp(u.content).trim();p&&(l||(l=H(p,80)),c=H(p,80)),d++}else Dp(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=$p(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 oe(i)){let p=ab(f.created_at,s.modifiedAt),_=Fp(f.content);if(_&&(a=_),Op(f)){let E=Mp(f.content),m=E.trim();m&&(l||(l=H(m,80)),c=H(m,80)),o.push({role:"user",timestamp:p,content:E});continue}if(Array.isArray(f.tool_calls))for(let E of f.tool_calls){let m=E.name||"tool",h=cb(E.args),T=Ue(E.args),g={role:"tool_use",timestamp:p,content:h,toolName:m,toolInput:h,toolInputData:T};o.push(g),d.push({name:m,stepIndex:f.step_index,input:T,message:g})}if(Dp(f)&&f.content)o.push({role:"assistant",timestamp:p,content:f.content,model:a});else if(lb(f)&&f.content){let E=mb(f,n),m=E===void 0?null:await this.readTaskLog(n,E),h={role:"tool_result",timestamp:m?.modifiedAt??p,content:f.content,toolName:f.type?.toLowerCase(),backgroundTaskId:E,...m===null?{}:{toolDetailedContent:m.content}};o.push(h),u.push({event:f,message:h})}f.thinking&&o.push({role:"thinking",timestamp:p,content:f.thinking})}return pb(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 Cp(r),r}catch{}let n=it(this.baseDir,"conversations");try{let s=[];for(let i of await Np(n)){if(!i.endsWith(".db"))continue;yl(i,".db").startsWith(e)&&s.push(it(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=$p(r);return n?(await Lp(this.conversationPath(n),{force:!0}),await Lp(it(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 db(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=it(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await Rp(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=it(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([Rp(n,"utf8"),ce(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as wb}from"node:child_process";import{StringDecoder as Bp}from"node:string_decoder";function Di(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 Sb(t.label,r.binary,s,{cwd:r.cwd,env:ue(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function Sb(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=wb(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(f){i(f);return}let a="",l="",c=new Bp("utf8"),d=new Bp("utf8");o.stdout?.on("data",f=>{a+=c.write(f)}),o.stderr?.on("data",f=>{l+=d.write(f)});let u=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",f=>{n.signal?.removeEventListener("abort",u),i(f)}),o.on("close",(f,p)=>{if(n.signal?.removeEventListener("abort",u),a+=c.end(),l+=d.end(),f===0){s({stdout:a,stderr:l});return}let _=p?`signal ${p}`:`exit code ${f}`,E=l.trim()||a.trim();i(new Error(`${t} failed (${_})${E?`: ${E}`:""}`))}),n.signal?.aborted?u():n.signal?.addEventListener("abort",u,{once:!0})})}var El=L(()=>{"use strict";qe()});import{basename as vb}from"node:path";import{randomUUID as bb}from"node:crypto";function wl(t){return new Tl(t)}function xb(t){return t!==void 0&&t<=0?"0":t===void 0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Tl,Ib,Sl=L(()=>{"use strict";jp();Te();Ee();rt();El();Tl=class extends ee{constructor(e){super({provider:new Oi(e),protocol:{transport:"print",perTurnCancellation:"process"},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",Y,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:Ib})}async sendTurn(e,r){if(r.requireResume){let s=await this.resolvePath(r.sessionId);if(s===null||vb(s)!==`${r.sessionId}.db`)throw new Error(`agy cannot resume missing conversation "${r.sessionId}"`)}let n=await super.sendTurn(e,r);return r.permissionMode==="plan"?{...n,warnings:[...n.warnings??[],"agy does not enforce plan mode; this turn used full permissions"]}:n}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${bb()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1676
|
+
${r?.prompt??Y}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstUserMessage?.startsWith(n));if(s.success&&i.length===1)return{...s,sessionId:i[0].sessionId};for(let o of i)await this.provider.deleteSession(o.sessionId);return{...s,success:!1,error:s.error??`agy seed created ${i.length} identifiable sessions; expected one`}}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}},Ib=Di({label:"agy",buildArgs:(t,e)=>{let r=[...e.sessionId?["--conversation",e.sessionId]:[],"-p",t,"--dangerously-skip-permissions","--print-timeout",xb(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>he("agy",t,e.permissionMode??"yolo")})});import kb from"node:zlib";function Fb(t,e){return t[e]===Nb&&t[e+1]===Rb&&t[e+2]===Lb&&t[e+3]===Cb}function Hp(t,e){return(t[e]&240)===80&&t[e+1]===Ob&&t[e+2]===Db&&t[e+3]===Mb}function Pb(t,e){if(Hp(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!Fb(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 $b(t){let e=[],r=0;for(;r+4<=t.length;){let n=Pb(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Mi(t){let e=[];for(let r of $b(t))Hp(r,0)||e.push(Ab(r).toString("utf8"));return e.join("")}var Ab,Nb,Rb,Lb,Cb,Ob,Db,Mb,vl=L(()=>{"use strict";Ab=kb.zstdDecompressSync,Nb=40,Rb=181,Lb=47,Cb=253,Ob=42,Db=77,Mb=24});import{readdir as bl,rm as Ub,stat as jb}from"node:fs/promises";import{join as $t}from"node:path";function Bb(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Il(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 Hb(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 Wp(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:Il(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of Hb(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Il(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:Il(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function Wb(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 Xp(t,e,r){let n=t.find(p=>p.type==="session");if(!n)return null;let s=n,i=n.data,o=s.id??i?.id;if(!o)return null;let a;for(let p of t)if(p.type==="request/header"){let _=p.data?.header;_?.config?.model&&(a=_.config.model)}let l=t.map(p=>p.time).filter(p=>typeof p=="number"),c=s.createdAt??i?.createdAt,d=c?new Date(c):new Date(0),u=l.length>0?new Date(Math.max(...l)):d,f=r.filter(p=>p.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:d,modifiedAt:u,model:a,firstUserMessage:f[0]?.content,lastUserMessage:f.at(-1)?.content,messageCount:r.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:e,...Xb(t)}}function Xb(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=Fi(c.inputTokens),u=Fi(c.cacheReadTokens),f=Fi(c.outputTokens),p=Fi(c.reasoningTokens);r+=d,n+=u,s+=f,i+=p,o=d+u,a={inputTokens:d,cachedInputTokens:u,outputTokens:f,reasoningOutputTokens:p,totalTokens:d+u+f}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function Fi(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var Pi,qp=L(()=>{"use strict";pe();vl();Pi=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||$t(V,".dsh");this.sessionsDir=$t(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await bl(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await bl($t(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=Wp(n),i=Xp(n,r.filePath,s);return i?{...i,turnStatus:Wb(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 Ub($t(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return $t(this.sessionsDir,Bb(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await bl(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=$t(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await jb(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=$t(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Mi(i),a=[];for(let l of o.split(`
|
|
1677
|
+
`))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=$t(this.sessionsDir,e,r,"session.jsonl.zstd");return Xp(n,s,Wp(n))}}});import{spawn as qb}from"node:child_process";async function $i(t,e=r=>xl.spawn(r)){if(Ut){let r=await Ut.catch(()=>{});if(r?.alive)return r;Ut=void 0}return Ut=e(t),Ut}async function Un(){if(!Ut)return;(await Ut.catch(()=>{}))?.shutdown(),Ut=void 0}var Gb,Gp,$r,xl,Ut,Jp=L(()=>{"use strict";Gb=/dsh web:\s*(https?:\/\/\S+)/,Gp=2e4,$r=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)}},xl=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 $r(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 $r(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 $r(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new $r(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=qb("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 ${Gp}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Gp);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let d=Gb.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 Vp}from"node:crypto";import{existsSync as Kp}from"node:fs";import{readFile as Jb,mkdir as Vb}from"node:fs/promises";function Rl(t){return new Nl(t)}function Al(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function Yb(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 Ui(t){return t instanceof Error?t.message:String(t)}async function zb(t){let e=await Yp(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 Yp(t){let e;try{e=await Jb(t)}catch{return[]}let r=Mi(e),n=[];for(let s of r.split(`
|
|
1678
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function Qb(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 Kb,kl,Nl,Ll=L(()=>{"use strict";Ar();Te();qp();vl();Jp();Ee();rt();Kb=500,kl=8*60*60*1e3;Nl=class extends ee{dshProvider;constructor(e){let r=new Pi(e);super({provider:r,protocol:{transport:"dsh-rpc",perTurnCancellation:"unsupported",persistentCancellation:"session"},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 Vb(e,{recursive:!0});let n=`session-${Vp()}`,s=Al(process.env);he("dsh",[],"yolo");try{let i;try{i=await $i(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${Ui(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${Ui(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: ${Ui(a)}`}}let o=r?.prompt??Y;try{await this.promptAndWait(i,e,n,o,kl)}catch(a){return{success:!1,error:`seed turn failed: ${Ui(a)}`}}return{success:!0,sessionId:n}}finally{await Un()}}async dshPromptTurn(e,r){let n=Date.now();if(r.bundleSession!==void 0)return pt(r.bundleSession,"dsh",r.sessionId,e,{onDelta:r.onDelta,onProgress:r.onProgress,signal:r.signal});let s=Al(r.env??process.env);he("dsh",[],r.permissionMode??"yolo");let i=!r.sessionId,o=i?`session-${Vp()}`:r.sessionId,a;try{let l=await $i(s);i&&await l.rpc("session.create",{sessionId:o,cwd:r.cwd}),r.model&&(await l.rpc("session.selectModel",{sessionId:o,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"}),a=await this.promptAndWait(l,r.cwd,o,e,r.timeoutMs??kl,r.signal)}finally{await Un()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:a,sessionId:o,durationMs:Date.now()-n}}async openSession(e){let r=Al(e.env??process.env);he("dsh",[],e.permissionMode??"yolo");let n=await $i(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!Kp(s))throw await Un(),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 Un())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(p,_={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(d)throw new Error("dsh bundle session has a turn still in flight");if(_.signal?.aborted)throw new Error("Aborted");if(!Kp(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 E=Date.now();try{let m=o.promptAndWait(n,e.cwd,i,p,kl,_.signal);m.catch(()=>{});let h=await Promise.race([m,new Promise((T,g)=>{_.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await f()})().finally(()=>g(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:h,sessionId:i,durationMs:Date.now()-E}}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 zb(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=i>0?Date.now()+i:1/0;for(;;){if(o?.aborted)throw new Error("Aborted");let d=await Yp(a),u=d.find(f=>f.type==="turn/end"&&(f.seq??-1)>l);if(u){let f=u.data?.reason,p=[...d].reverse().find(E=>E.type==="assistant/message"),_=p?Qb(p):"";if(f?.kind!=="completed"&&!_)throw new Error(Yb(f));return _}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(f=>setTimeout(f,Kb))}}}});import{existsSync as Zb}from"node:fs";import{join as th,resolve as eI}from"node:path";import{createRequire as tI}from"node:module";function rI(){return Cl===null&&(Cl=tI(import.meta.url)("node:sqlite").DatabaseSync),Cl}function Ol(t={}){return eI(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||th(V,".hermes"))}function nI(t={}){return th(Ol(t),"state.db")}function jn(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function Ne(t){return typeof t=="string"&&t.length>0?t:void 0}function sI(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Zp(t){return Ne(t.cwd)??Ne(sI(t.model_config).cwd)??"(unknown)"}function iI(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function oI(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 eh(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 Cl,zp,Qp,ji,rh=L(()=>{"use strict";pe();re();Cl=null;zp="acp";Qp=`id, source, model, model_config, started_at,
|
|
1679
1679
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
1680
|
-
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;
|
|
1680
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;ji=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=nI(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!Zb(this.dbPath))return null;let e=null;try{return e=new(rI())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(r){return e?.close(),D({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 ${Qp} FROM sessions WHERE id = ? AND source = ?`).get(r,zp)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let r=e.prepare(`SELECT ${Qp} FROM sessions
|
|
1681
1681
|
WHERE source = ?
|
|
1682
1682
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1683
|
-
LIMIT ?`).all(
|
|
1683
|
+
LIMIT ?`).all(zp,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:Ne(s.title),cwd:Zp(s),createdAt:jn(s.started_at),modifiedAt:jn(s.last_activity_at??s.started_at),model:Ne(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...eh(s)})}return n}catch(r){return D({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,
|
|
1684
1684
|
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 = ?
|
|
1685
|
-
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?H(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=Wn(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=H(u,80)),l=H(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:Ne(c.tool_call_id),toolName:Ne(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Ne(n.model),stopReason:Ne(c.finish_reason)});for(let f of cI(c.tool_calls)){let p=dI(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Ne(f.function?.name)??"tool_call",toolName:Ne(f.function?.name),toolCallId:Ne(f.call_id)??Ne(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:Ue(p)})}}return{provider:this.name,sessionId:n.id,slug:Ne(n.title),cwd:nh(n),createdAt:Wn(n.started_at),modifiedAt:Wn(n.last_activity_at??n.started_at),model:Ne(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...sh(n),messages:i,userPrompts:o}}catch(n){return M({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 uI}from"node:fs/promises";function mI(t){return fI.test(t)}function ah(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 pI}function Fl(t){return new Ml(t)}var fI,pI,Ml,Pl=L(()=>{"use strict";Te();oh();_t();Ee();re();fI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;pI="dont_ask";Ml=class extends ee{hermesProvider;hermesHome;constructor(e){let r=new Bi(e);super({provider:r,protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},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)=>nt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:ah(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Dl(e)}async openSession(e){return st({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:ah(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await uI(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";M({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??Y,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return mI(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(M({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 lh,rm as hI,stat as gI}from"node:fs/promises";import{join as $l}from"node:path";function Ul(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 ch(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Hi,dh=L(()=>{"use strict";pe();Hi=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||$l(V,".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 lh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=$l(this.baseDir,n);try{if(!(await gI(s)).isDirectory())continue;for(let i of await lh(s))i.endsWith(".jsonl")&&r.push($l(s,i))}catch{}}return r}async readHeader(e){for await(let r of oe(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,p=0,_;for await(let E of oe(e)){if(E.type==="model_change"&&E.provider&&E.modelId){s=`${E.provider}/${E.modelId}`;continue}if(E.type!=="message"||!E.message)continue;let m=E.message;if(m.provider&&m.model&&(s=`${m.provider}/${m.model}`),m.role==="user"){let h=Ul(m).trim();h&&(i||(i=H(h,80)),o=H(h,80)),a++}else if(m.role==="assistant"){a++;let h=m.usage;h&&(l+=h.input??0,c+=h.cacheRead??0,d+=h.cacheWrite??0,u+=h.output??0,f+=h.reasoning??0,p=h.input??0,_={inputTokens:h.input,cachedInputTokens:h.cacheRead,cacheWriteInputTokens:h.cacheWrite,outputTokens:h.output,reasoningOutputTokens:h.reasoning,totalTokens:h.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:p,lastTokenUsage:_}}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 oe(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:Ul(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:ch(c.arguments),toolName:c.name??"tool",toolInput:ch(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:Ul(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 hI(r,{force:!0}),!0):!1}}});function Bl(t){return new jl(t)}var jl,_I,Hl=L(()=>{"use strict";dh();Te();Ee();rt();Tl();jl=class extends ee{constructor(e){super({provider:new Hi(e),protocol:{transport:"print",perTurnCancellation:"process"},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",Y],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:_I})}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}`}}},_I=Mi({label:"pi",buildArgs:(t,e)=>{let r=[...e.sessionId?["--session",e.sessionId]:[],"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>he("pi",t,e.permissionMode??"yolo")})});import{createHash as yI}from"node:crypto";import{existsSync as EI,mkdirSync as Xl,readFileSync as TI,renameSync as wI,rmdirSync as yh,statSync as SI,writeFileSync as vI}from"node:fs";import{dirname as Vl,join as uh,resolve as Wl}from"node:path";function bI(t){return yI("sha256").update(t).digest("hex").slice(0,8)}function II(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function xI(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 Eh(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Wi(t){return Math.max(1,Math.ceil(t.length/4))}function Wr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Wl(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?uh(Vl(Wl(r)),".lmctl-claude-mock","sessions.json"):uh(Wl(t),".lmctl-claude-mock","sessions.json")}function fh(){return{schemaVersion:1,sessions:{}}}function Xn(t){if(!EI(t))return fh();try{let e=JSON.parse(TI(t,"utf8")),r=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0,s=typeof e.scriptContains=="object"&&e.scriptContains!==null?e.scriptContains:void 0,i=ql(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return fh()}}function Th(t,e){Xl(Vl(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;vI(r,`${JSON.stringify(e,null,2)}
|
|
1686
|
-
`,"utf8"),wI(r,t)}function NI(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function RI(t){let e=`${t}.lock`;Xl(Vl(t),{recursive:!0});let r=Date.now()+mh;for(;;)try{return Xl(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-SI(e).mtimeMs>kI){try{yh(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${mh}ms: ${e}`);NI(AI)}}function LI(t){try{yh(t)}catch{}}function wh(t,e){let r=RI(t);try{return e()}finally{LI(r)}}function CI(t){return{...t,timestamp:t.timestamp.toISOString()}}function OI(t){return{...t,timestamp:new Date(t.timestamp)}}function DI(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(CI)}}function Sh(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(OI)}}function Xi(t,e=process.cwd()){let r=Hr.get(t);if(r!==void 0)return r;let s=Xn(Wr(e)).sessions[t];if(s===void 0)return;let i=Sh(s);return Hr.set(i.sessionId,i),i}function ph(t){Hr.set(t.sessionId,t);let e=Wr(t.cwd);wh(e,()=>{let r=Xn(e);r.sessions[t.sessionId]=DI({...t,filePath:e}),Th(e,r)})}function MI(t,e=process.cwd()){let r=Wr(e);return wh(r,()=>{let n=Xn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],Th(r,n)),s})}function FI(){let t=Xn(Wr()),e=Object.values(t.sessions).map(Sh);for(let r of e)Hr.set(r.sessionId,r);return e}function ql(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function hh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=ql(t.delayMs);return{kind:"success",text:t.text,...e!==void 0?{delayMs:e}:{}}}if(t!==void 0&&typeof t.error=="string"&&typeof t.text!="string"){let e=ql(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function gh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function PI(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=hh(r[t]??r[Eh(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=hh(n[s]);if(i!==void 0)return i}}}function _h(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function Kl(){return new Jl}var Hr,kI,AI,mh,Gl,Jl,Yl=L(()=>{"use strict";Hr=new Map;kI=5e3,AI=15,mh=1e4;Gl=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of FI())e.set(r.sessionId,r);for(let r of Hr.values())e.set(r.sessionId,r);return[...e.values()].map(_h)}async loadSession(e){let r=Xi(e);return r===void 0?null:{..._h(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Xi(e)?.filePath??null}async deleteSession(e){let r=Hr.delete(e),n=MI(e);return r||n}},Jl=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new Gl;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=II(xI(e,r)),s=`mock-${n}-${bI(`${e}:${n}`)}`,i=new Date,o=Wr(e),a=Xi(s,e),l=r?.prompt??"ClaudeMock seed",c=Wi(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+=Wi("ACK: ClaudeMock seeded"),ph(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=Xi(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Xn(Wr(r.cwd)),a=PI(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await gh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${Eh(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+=Wi(e),s.totalOutputTokens+=Wi(c),ph(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await gh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function jt(t){let e=[_a({museDataHome:t?.museDataHome}),ja({miniplayerHome:t?.miniplayerHome}),Wa({claudeDir:t?.claudeDir}),Ja({codexDir:t?.codexDir,codeDir:t?.codeDir}),Za({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),nl({copilotDir:t?.copilotDir}),ol(),ul({kimiHome:t?.kimiHome}),pl({lmplayerDbPath:t?.lmplayerDbPath}),_l(),Sl({agyDir:t?.agyDir}),Ll({dshHome:t?.dshHome}),Fl({hermesHome:t?.hermesHome}),Bl({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Kl()),e}var zl=L(()=>{"use strict";ya();ya();Ba();Ba();Xa();Va();el();sl();al();fl();hl();yl();vl();Cl();Pl();Hl();Yl();Xa();Va();el();sl();al();fl();hl();yl();vl();Cl();Pl();Hl();Yl()});var vh,bh,Ih=L(()=>{"use strict";vh=["claude","qwen","codex","dsh","miniplayer","muse","gemini","copilot","opencode","kimi","hermes"],bh=["agy","pi","lmplayer"]});var kh={};Xc(kh,{BUNDLE_CAPABLE_PROVIDERS:()=>vh,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>bh,ProviderRegistry:()=>yn,TransportConnectionError:()=>se,TransportError:()=>Ct,TransportJsonError:()=>Zs,TransportProcessError:()=>wn,TransportRpcError:()=>Sn,_resetDefaultRegistryForTests:()=>$I,bundleSupportedProviders:()=>Ji,canUsePersistentSession:()=>Js,chat:()=>qn,countTokens:()=>BI,createAdapterRegistry:()=>Lt,createAllAdapters:()=>jt,deleteSession:()=>tc,listSessions:()=>ec,openBundleSession:()=>Ql,openConversation:()=>UI,seed:()=>Zl});function Bt(){return qi===null&&(qi=Lt(jt())),qi}function $I(){qi=null}function Gi(t,e){Ds(e);let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function qn(t){let e=t.registry??Bt(),r=Gi(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=t.bundleSession===void 0?await Vs(r,{...n,execution:"per-turn",requireResume:t.requireResume??!1}):void 0,i;try{i=s?await s.sendTurn(t.prompt,{onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal}):await r.sendTurn(t.prompt,n)}finally{await s?.close()}return{text:i.text,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,numTurns:i.numTurns,status:i.status,stalledAfterMs:i.stalledAfterMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}}function Ji(t){return(t??Bt()).getAllAdapters().filter(r=>ut(r.name)&&r.openSession!==void 0).map(r=>r.name)}async function Ql(t){let e=t.registry??Bt(),r=Gi(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${Ji(e).join(", ")})`);return Vs(r,{...t,execution:"persistent"})}async function UI(t){return Vs(Gi(t.registry??Bt(),t.provider),t)}async function Zl(t){let e=t.registry??Bt(),r=Gi(e,t.provider),n=await xh(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(s.success&&s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await xh(e,t.provider,t.cwd),a=jI(n,o);return s.success?a?{success:!0,sessionId:a,...i}:{success:!0,...i}:(a&&await r.delete?.(a).catch(()=>{}),{success:!1,error:s.error,...i})}async function xh(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 jI(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 ec(t={}){return(t.registry??Bt()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function tc(t,e,r=Bt()){return r.deleteSession(e,t)}async function BI(t){let r=await(t.registry??Bt()).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 qi,Gn=L(()=>{"use strict";Lr();vr();ia();zl();Lr();ia();zl();Ih();Qt();qi=null});function Vi(t){return ut(t)&&WI.has(t)}function nc(){return rc===null&&(rc=Lt(jt())),rc}function sc(t,e,r={}){if(!Vi(t))return null;try{let n=nc().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?li({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?HI[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,...Ah[t]??[]]}catch{return null}}function Rh(t,e,r={}){let n=sc(t,e,r);return n===null?null:n.join(" ")}function Xr(t,e){return nc().getSession(t,e)}async function Lh(t){return(await nc().resolveSessions(t)).map(r=>r.provider.name)}var Ah,HI,WI,Nh,rc,Ki=L(()=>{"use strict";vr();Gn();va();Ah={muse:["--yolo"],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:[]},HI={muse:t=>["--model",t],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]},WI=new Set(Object.keys(Ah)),Nh=/^[\w.:-]+$/;rc=null});import{randomUUID as VI}from"node:crypto";import{hostname as Mh,networkInterfaces as KI}from"node:os";function Fh(t){let e=(t.now??new Date).toISOString();return{lock_id:VI(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??Mh(),holder_ips:t.ips??ex(),started_at:e,last_heartbeat:e}}function Ph(t=process.env){return $h(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,YI)}function QI(t=process.env){return $h(t.LMCTL_TERMINAL_LOCK_STALE_MS,zI)}function ac(t,e={}){let r=e.now??new Date,n=e.localHost??Mh(),s=e.staleMs??QI();if(t.holder_host===n)return(e.isProcessAlive??ZI)(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 Jn(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function $h(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 ZI(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 ex(){let t=new Set;for(let e of Object.values(KI()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var YI,zI,Yi=L(()=>{"use strict";YI=15e3,zI=12e4});import{execFileSync as $N}from"node:child_process";import{resolve as P_}from"node:path";function UN(t){return t.filter(e=>e.state!=="retired")}function $_(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?K(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=$N("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return K(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=P_(s),o=e.listProjects().find(a=>P_(a.local_path)===i);return o===void 0?K(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function U_(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?K(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?K(t,`project ${r.name} has no assigned team; use --team <name>`):s}function j_(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?K(t,`member not found: ${n}`):i}let s=UN(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?K(t,`team ${r.name} has no active agent member`):s}var B_=L(()=>{"use strict";Kt()});function H_(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}var W_=L(()=>{"use strict"});var G_={};Xc(G_,{SIZE_WARN_EST_TOKENS:()=>ts,estimateTokens:()=>q_,runTerminal:()=>WN});import{spawn as jN}from"node:child_process";import{statSync as BN}from"node:fs";async function WN(t,e){if(t.includes("--help")||t.includes("-h"))return YN(e);let r=Wo(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return K(e,r.error);if(bt(e)&&!Vt(r,"--size"))return K(e,"terminal opens an interactive TUI; non-interactive mode is enabled");let n=It(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return K(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return K(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"?Vt(r,o):It(r,o)!==void 0)return K(e,`--run is mutually exclusive with ${o}`);try{return await G(e,async o=>{let a=It(r,"--alias"),l=H_(o,s,a);return"err"in l?K(e,l.err):jc(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 Cs(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?Vt(r,l):It(r,l)!==void 0)return K(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return K(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=Gu(HN,{target:i,alias:o,flags:{}});return a.mode==="error"?K(e,a.message):a.mode!=="ai-team"?K(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?K(e,"terminal: alias required for the teamfile target"):await G(e,l=>XN(e,a.teamfile,a.alias,l,Vt(r,"--json")))}try{return await G(e,async s=>{let i=JN(e,s,r);if(typeof i=="number")return i;let o=It(r,"--alias");return Vt(r,"--size")?KN(e,s,i,o,Vt(r,"--json")):VN(e,s,i,o)})}catch(s){return Cs(e,s)}}async function XN(t,e,r,n,s){let i;try{i=mt(e,r,n)}catch(f){return f instanceof ye?K(t,f.message):Cs(t,f)}let o=hr(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:Rt()});if(!o.acquired){let f=o.current.holder_pid,p=f===null?null:ve(f)?"live":"dead",_=`${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}, ${p})`);return s?(Xo(t,{status:"error",errorKind:"busy",message:_,holder_pid:f,holder_liveness:p}),1):K(t,_)}let a=Fh({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,d=null,u=[];try{n.setTerminalLock(a),c=qN(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 p=new Date().toISOString(),_=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,p);_&&n.heartbeatAgentInflight(o.lease,o.leaseId,p),!_&&l!==null&&(clearInterval(l),l=null)}catch{}},Ph()),l.unref?.();try{Ar(t,Xe(i.teamfile),i.teamfile)}catch{}return d=await jc(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},p=>{u.push(`${p.provider} terminal ignored model=${p.model}: ${p.reason}`)}),d}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),GN(n,c,d,u)}}function qN(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:Sr(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 GN(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 jc(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!Vi(n))return K(t,`no resume incantation for provider "${n}"`);if(!Nh.test(s))return K(t,"refusing to resume: malformed sessionid");let a=sc(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}
|
|
1687
|
-
`),Se({event:"model_ignored",provider:d.provider,model:d.model,reason:d.reason}),r?.(d)}});if(a===null||a.length===0)return K(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(d=>{let u=
|
|
1688
|
-
`),t.stdout.write(`${
|
|
1685
|
+
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?H(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=jn(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=H(u,80)),l=H(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:Ne(c.tool_call_id),toolName:Ne(c.tool_name)});continue}u.length>0&&i.push({role:"assistant",timestamp:d,content:u,model:Ne(n.model),stopReason:Ne(c.finish_reason)});for(let f of iI(c.tool_calls)){let p=oI(f.function?.arguments);i.push({role:"tool_use",timestamp:d,content:Ne(f.function?.name)??"tool_call",toolName:Ne(f.function?.name),toolCallId:Ne(f.call_id)??Ne(f.id),toolInput:typeof f.function?.arguments=="string"?f.function.arguments:JSON.stringify(f.function?.arguments??{}),toolInputData:Ue(p)})}}return{provider:this.name,sessionId:n.id,slug:Ne(n.title),cwd:Zp(n),createdAt:jn(n.started_at),modifiedAt:jn(n.last_activity_at??n.started_at),model:Ne(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...eh(n),messages:i,userPrompts:o}}catch(n){return D({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 aI}from"node:fs/promises";function cI(t){return lI.test(t)}function nh(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 dI}function Ml(t){return new Dl(t)}var lI,dI,Dl,Fl=L(()=>{"use strict";Te();rh();_t();Ee();re();lI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;dI="dont_ask";Dl=class extends ee{hermesProvider;hermesHome;constructor(e){let r=new ji(e);super({provider:r,protocol:{transport:"acp",perTurnCancellation:"process",persistentCancellation:"turn"},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)=>nt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:nh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=Ol(e)}async openSession(e){return st({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:nh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await aI(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";D({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??Y,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return cI(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(D({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 sh,rm as uI,stat as fI}from"node:fs/promises";import{join as Pl}from"node:path";function $l(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 ih(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Bi,oh=L(()=>{"use strict";pe();Bi=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||Pl(V,".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 sh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=Pl(this.baseDir,n);try{if(!(await fI(s)).isDirectory())continue;for(let i of await sh(s))i.endsWith(".jsonl")&&r.push(Pl(s,i))}catch{}}return r}async readHeader(e){for await(let r of oe(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,p=0,_;for await(let E of oe(e)){if(E.type==="model_change"&&E.provider&&E.modelId){s=`${E.provider}/${E.modelId}`;continue}if(E.type!=="message"||!E.message)continue;let m=E.message;if(m.provider&&m.model&&(s=`${m.provider}/${m.model}`),m.role==="user"){let h=$l(m).trim();h&&(i||(i=H(h,80)),o=H(h,80)),a++}else if(m.role==="assistant"){a++;let h=m.usage;h&&(l+=h.input??0,c+=h.cacheRead??0,d+=h.cacheWrite??0,u+=h.output??0,f+=h.reasoning??0,p=h.input??0,_={inputTokens:h.input,cachedInputTokens:h.cacheRead,cacheWriteInputTokens:h.cacheWrite,outputTokens:h.output,reasoningOutputTokens:h.reasoning,totalTokens:h.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:d,totalOutputTokens:u,totalReasoningOutputTokens:f,lastInputTokens:p,lastTokenUsage:_}}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 oe(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:$l(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:ih(c.arguments),toolName:c.name??"tool",toolInput:ih(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:$l(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 uI(r,{force:!0}),!0):!1}}});function jl(t){return new Ul(t)}var Ul,mI,Bl=L(()=>{"use strict";oh();Te();Ee();rt();El();Ul=class extends ee{constructor(e){super({provider:new Bi(e),protocol:{transport:"print",perTurnCancellation:"process"},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",Y],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:mI})}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}`}}},mI=Di({label:"pi",buildArgs:(t,e)=>{let r=[...e.sessionId?["--session",e.sessionId]:[],"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>he("pi",t,e.permissionMode??"yolo")})});import{createHash as pI}from"node:crypto";import{existsSync as hI,mkdirSync as Wl,readFileSync as gI,renameSync as _I,rmdirSync as ph,statSync as yI,writeFileSync as EI}from"node:fs";import{dirname as Jl,join as ah,resolve as Hl}from"node:path";function TI(t){return pI("sha256").update(t).digest("hex").slice(0,8)}function wI(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function SI(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 hh(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Hi(t){return Math.max(1,Math.ceil(t.length/4))}function jr(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return Hl(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?ah(Jl(Hl(r)),".lmctl-claude-mock","sessions.json"):ah(Hl(t),".lmctl-claude-mock","sessions.json")}function lh(){return{schemaVersion:1,sessions:{}}}function Bn(t){if(!hI(t))return lh();try{let e=JSON.parse(gI(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=Xl(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return lh()}}function gh(t,e){Wl(Jl(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;EI(r,`${JSON.stringify(e,null,2)}
|
|
1686
|
+
`,"utf8"),_I(r,t)}function II(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function xI(t){let e=`${t}.lock`;Wl(Jl(t),{recursive:!0});let r=Date.now()+ch;for(;;)try{return Wl(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-yI(e).mtimeMs>vI){try{ph(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${ch}ms: ${e}`);II(bI)}}function kI(t){try{ph(t)}catch{}}function _h(t,e){let r=xI(t);try{return e()}finally{kI(r)}}function AI(t){return{...t,timestamp:t.timestamp.toISOString()}}function NI(t){return{...t,timestamp:new Date(t.timestamp)}}function RI(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(AI)}}function yh(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(NI)}}function Wi(t,e=process.cwd()){let r=Ur.get(t);if(r!==void 0)return r;let s=Bn(jr(e)).sessions[t];if(s===void 0)return;let i=yh(s);return Ur.set(i.sessionId,i),i}function dh(t){Ur.set(t.sessionId,t);let e=jr(t.cwd);_h(e,()=>{let r=Bn(e);r.sessions[t.sessionId]=RI({...t,filePath:e}),gh(e,r)})}function LI(t,e=process.cwd()){let r=jr(e);return _h(r,()=>{let n=Bn(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],gh(r,n)),s})}function CI(){let t=Bn(jr()),e=Object.values(t.sessions).map(yh);for(let r of e)Ur.set(r.sessionId,r);return e}function Xl(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function uh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=Xl(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=Xl(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function fh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function OI(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=uh(r[t]??r[hh(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=uh(n[s]);if(i!==void 0)return i}}}function mh(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 Vl(){return new Gl}var Ur,vI,bI,ch,ql,Gl,Kl=L(()=>{"use strict";Ur=new Map;vI=5e3,bI=15,ch=1e4;ql=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of CI())e.set(r.sessionId,r);for(let r of Ur.values())e.set(r.sessionId,r);return[...e.values()].map(mh)}async loadSession(e){let r=Wi(e);return r===void 0?null:{...mh(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Wi(e)?.filePath??null}async deleteSession(e){let r=Ur.delete(e),n=LI(e);return r||n}},Gl=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new ql;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=wI(SI(e,r)),s=`mock-${n}-${TI(`${e}:${n}`)}`,i=new Date,o=jr(e),a=Wi(s,e),l=r?.prompt??"ClaudeMock seed",c=Hi(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+=Hi("ACK: ClaudeMock seeded"),dh(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=Wi(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=Bn(jr(r.cwd)),a=OI(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await fh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${hh(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+=Hi(e),s.totalOutputTokens+=Hi(c),dh(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await fh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function jt(t){let e=[ga({museDataHome:t?.museDataHome}),Ua({miniplayerHome:t?.miniplayerHome}),Ha({claudeDir:t?.claudeDir}),Ga({codexDir:t?.codexDir,codeDir:t?.codeDir}),Qa({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),rl({copilotDir:t?.copilotDir}),il(),dl({kimiHome:t?.kimiHome}),ml({lmplayerDbPath:t?.lmplayerDbPath}),gl(),wl({agyDir:t?.agyDir}),Rl({dshHome:t?.dshHome}),Ml({hermesHome:t?.hermesHome}),jl({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(Vl()),e}var Yl=L(()=>{"use strict";_a();_a();ja();ja();Wa();Ja();Za();nl();ol();ul();pl();_l();Sl();Ll();Fl();Bl();Kl();Wa();Ja();Za();nl();ol();ul();pl();_l();Sl();Ll();Fl();Bl();Kl()});var Eh,Th,wh=L(()=>{"use strict";Eh=["claude","qwen","codex","dsh","miniplayer","muse","gemini","copilot","opencode","kimi","hermes"],Th=["agy","pi","lmplayer"]});var vh={};Wc(vh,{BUNDLE_CAPABLE_PROVIDERS:()=>Eh,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>Th,ProviderRegistry:()=>hn,TransportConnectionError:()=>se,TransportError:()=>Ct,TransportJsonError:()=>Qs,TransportProcessError:()=>yn,TransportRpcError:()=>En,_resetDefaultRegistryForTests:()=>DI,bundleSupportedProviders:()=>Gi,canUsePersistentSession:()=>Gs,chat:()=>Hn,countTokens:()=>PI,createAdapterRegistry:()=>Lt,createAllAdapters:()=>jt,deleteSession:()=>ec,listSessions:()=>Zl,openBundleSession:()=>zl,openConversation:()=>MI,seed:()=>Ql});function Bt(){return Xi===null&&(Xi=Lt(jt())),Xi}function DI(){Xi=null}function qi(t,e){Ls(e);let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function Hn(t){let e=t.registry??Bt(),r=qi(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=t.bundleSession===void 0?await Js(r,{...n,execution:"per-turn",requireResume:t.requireResume??!1}):void 0,i;try{i=s?await s.sendTurn(t.prompt,{onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal}):await r.sendTurn(t.prompt,n)}finally{await s?.close()}return{text:i.text,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,numTurns:i.numTurns,status:i.status,stalledAfterMs:i.stalledAfterMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}}function Gi(t){return(t??Bt()).getAllAdapters().filter(r=>ut(r.name)&&r.openSession!==void 0).map(r=>r.name)}async function zl(t){let e=t.registry??Bt(),r=qi(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${Gi(e).join(", ")})`);return Js(r,{...t,execution:"persistent"})}async function MI(t){return Js(qi(t.registry??Bt(),t.provider),t)}async function Ql(t){let e=t.registry??Bt(),r=qi(e,t.provider),n=await Sh(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(s.success&&s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await Sh(e,t.provider,t.cwd),a=FI(n,o);return s.success?a?{success:!0,sessionId:a,...i}:{success:!0,...i}:(a&&await r.delete?.(a).catch(()=>{}),{success:!1,error:s.error,...i})}async function Sh(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 FI(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 Zl(t={}){return(t.registry??Bt()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function ec(t,e,r=Bt()){return r.deleteSession(e,t)}async function PI(t){let r=await(t.registry??Bt()).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 Xi,Wn=L(()=>{"use strict";Ar();vr();sa();Yl();Ar();sa();Yl();wh();Qt();Xi=null});function Ji(t){return ut(t)&&UI.has(t)}function rc(){return tc===null&&(tc=Lt(jt())),tc}function nc(t,e,r={}){if(!Ji(t))return null;try{let n=rc().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?ai({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?$I[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,...bh[t]??[]]}catch{return null}}function xh(t,e,r={}){let n=nc(t,e,r);return n===null?null:n.join(" ")}function Br(t,e){return rc().getSession(t,e)}async function kh(t){return(await rc().resolveSessions(t)).map(r=>r.provider.name)}var bh,$I,UI,Ih,tc,Vi=L(()=>{"use strict";vr();Wn();Sa();bh={muse:["--yolo"],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:[]},$I={muse:t=>["--model",t],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]},UI=new Set(Object.keys(bh)),Ih=/^[\w.:-]+$/;tc=null});import{randomUUID as XI}from"node:crypto";import{hostname as Lh,networkInterfaces as qI}from"node:os";function Ch(t){let e=(t.now??new Date).toISOString();return{lock_id:XI(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??Lh(),holder_ips:t.ips??YI(),started_at:e,last_heartbeat:e}}function Oh(t=process.env){return Dh(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,GI)}function VI(t=process.env){return Dh(t.LMCTL_TERMINAL_LOCK_STALE_MS,JI)}function oc(t,e={}){let r=e.now??new Date,n=e.localHost??Lh(),s=e.staleMs??VI();if(t.holder_host===n)return(e.isProcessAlive??KI)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Xn(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function Dh(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 KI(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 YI(){let t=new Set;for(let e of Object.values(qI()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var GI,JI,Ki=L(()=>{"use strict";GI=15e3,JI=12e4});import{execFileSync as LN}from"node:child_process";import{resolve as O_}from"node:path";function CN(t){return t.filter(e=>e.state!=="retired")}function D_(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?K(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=LN("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return K(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=O_(s),o=e.listProjects().find(a=>O_(a.local_path)===i);return o===void 0?K(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function M_(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?K(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?K(t,`project ${r.name} has no assigned team; use --team <name>`):s}function F_(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?K(t,`member not found: ${n}`):i}let s=CN(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?K(t,`team ${r.name} has no active agent member`):s}var P_=L(()=>{"use strict";Kt()});function $_(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}var U_=L(()=>{"use strict"});var H_={};Wc(H_,{SIZE_WARN_EST_TOKENS:()=>Qn,estimateTokens:()=>B_,runTerminal:()=>FN});import{spawn as ON}from"node:child_process";import{statSync as DN}from"node:fs";async function FN(t,e){if(t.includes("--help")||t.includes("-h"))return WN(e);let r=Ho(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return K(e,r.error);if(bt(e)&&!Vt(r,"--size"))return K(e,"terminal opens an interactive TUI; non-interactive mode is enabled");let n=It(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return K(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return K(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"?Vt(r,o):It(r,o)!==void 0)return K(e,`--run is mutually exclusive with ${o}`);try{return await G(e,async o=>{let a=It(r,"--alias"),l=$_(o,s,a);return"err"in l?K(e,l.err):Uc(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 Ns(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?Vt(r,l):It(r,l)!==void 0)return K(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return K(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=qu(MN,{target:i,alias:o,flags:{}});return a.mode==="error"?K(e,a.message):a.mode!=="ai-team"?K(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?K(e,"terminal: alias required for the teamfile target"):await G(e,l=>PN(e,a.teamfile,a.alias,l,Vt(r,"--json")))}try{return await G(e,async s=>{let i=jN(e,s,r);if(typeof i=="number")return i;let o=It(r,"--alias");return Vt(r,"--size")?HN(e,s,i,o,Vt(r,"--json")):BN(e,s,i,o)})}catch(s){return Ns(e,s)}}async function PN(t,e,r,n,s){let i;try{i=mt(e,r,n)}catch(f){return f instanceof ye?K(t,f.message):Ns(t,f)}let o=hr(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:Rt()});if(!o.acquired){let f=o.current.holder_pid,p=f===null?null:ve(f)?"live":"dead",_=`${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}, ${p})`);return s?(Wo(t,{status:"error",errorKind:"busy",message:_,holder_pid:f,holder_liveness:p}),1):K(t,_)}let a=Ch({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,d=null,u=[];try{n.setTerminalLock(a),c=$N(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 p=new Date().toISOString(),_=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,p);_&&n.heartbeatAgentInflight(o.lease,o.leaseId,p),!_&&l!==null&&(clearInterval(l),l=null)}catch{}},Oh()),l.unref?.();try{xr(t,Xe(i.teamfile),i.teamfile)}catch{}return d=await Uc(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},p=>{u.push(`${p.provider} terminal ignored model=${p.model}: ${p.reason}`)}),d}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),UN(n,c,d,u)}}function $N(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:Sr(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 UN(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 Uc(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!Ji(n))return K(t,`no resume incantation for provider "${n}"`);if(!Ih.test(s))return K(t,"refusing to resume: malformed sessionid");let a=nc(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}
|
|
1687
|
+
`),Se({event:"model_ignored",provider:d.provider,model:d.model,reason:d.reason}),r?.(d)}});if(a===null||a.length===0)return K(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(d=>{let u=ON(l,c,{stdio:"inherit",cwd:i,env:ue(process.env,i,s,"terminal")});u.on("error",f=>{d(K(t,`failed to launch ${l}: ${f.message}`))}),u.on("exit",f=>d(f??0))})}function jN(t,e,r){let n=It(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?K(t,`team not found: ${n}`):o}let s=D_(t,e,It(r,"--project"));return typeof s=="number"?s:M_(t,e,s,void 0)}async function BN(t,e,r,n){let s=F_(t,e,r,n);if(typeof s=="number")return s;let i=s.sessionid;return i===null||i.trim().length===0?K(t,`member ${s.alias} has no session yet \u2014 seed it first: lmctl seed <teamfile> (check with lmctl status <teamfile>)`):Uc(t,{provider:$o(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function B_(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=DN(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 HN(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 K(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=$o(a),d=a.model??null,u=null;Ji(c)&&(u=await Br(l,c));let f=B_(u),p=f.est>Qn;o.push({alias:a.alias,provider:c,sessionid:l,messages:f.messages,bytes:f.bytes,est_tokens:f.est,estimate:!0,over_guide:p,model:d,resume_incantation:p?xh(c,l,d!==null?{model:d}:{}):null})}if(s)return Wo(t,{estimate:!0,legend:j_,guide_tokens:Qn,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
1688
|
+
`),t.stdout.write(`${j_}
|
|
1689
1689
|
`);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)
|
|
1690
1690
|
`),a.over_guide&&t.stdout.write(` \u26A0 ${a.alias}: estimated ~${a.est_tokens} tokens \u2014 ESTIMATE only, exceeds the 200K guide.
|
|
1691
1691
|
Nothing was changed automatically. If you choose to compact, open the
|
|
1692
1692
|
session yourself:
|
|
1693
1693
|
${a.resume_incantation??"(no resume incantation for provider "+a.provider+")"}
|
|
1694
1694
|
(or: lmctl terminal --team ${r.name} --alias ${a.alias})
|
|
1695
|
-
`)}return 0}function
|
|
1695
|
+
`)}return 0}function WN(t){return t.stdout.write(`usage: lmctl terminal <teamfile>:<alias> [--json]
|
|
1696
1696
|
lmctl terminal <teamfile> <alias> [--json]
|
|
1697
1697
|
lmctl terminal --run <id> [--alias A]
|
|
1698
1698
|
lmctl terminal [--project P] [--team T] [--alias A] [--size] [--json]
|
|
@@ -1721,17 +1721,17 @@ ${r?.prompt??Y}`}),i=(await this.provider.discoverSessions()).filter(o=>o.firstU
|
|
|
1721
1721
|
exact provider count: the messages path slightly
|
|
1722
1722
|
under-counts code-dense text; the byte fallback
|
|
1723
1723
|
over-counts (JSONL overhead \u2192 safe over-warn); CJK is
|
|
1724
|
-
denser (under-warns). At >${
|
|
1724
|
+
denser (under-warns). At >${Qn} est
|
|
1725
1725
|
tokens it surfaces the resume incantation so YOU can
|
|
1726
1726
|
open & self-compact. Nothing is ever changed
|
|
1727
|
-
automatically; ${
|
|
1728
|
-
`),0}var
|
|
1727
|
+
automatically; ${Qn} is a guide, not a gate.
|
|
1728
|
+
`),0}var MN,Qn,j_,W_=L(()=>{"use strict";Er();Vi();Kt();P_();Yt();ft();qe();Ws();qt();Xs();Ki();U_();re();Xt();MN={name:"terminal",allowsBareTeamfile:!1,supportsRaw:!1},Qn=2e5,j_="est = rough local heuristic (~4 chars/token), NOT an exact provider token count \u2014 open the session to verify before acting."});import{spawn as qc,spawnSync as go}from"node:child_process";import{randomUUID as iy}from"node:crypto";import{tmpdir as oy}from"node:os";import*as U from"node:fs";import*as me from"node:path";import*as ed from"node:readline";import{fileURLToPath as td}from"node:url";var C=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}},ke=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};function rd(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{U.existsSync(t.file)&&U.statSync(t.file).isFile()&&(n=U.readFileSync(t.file,"utf-8"))}catch{}if(!n)return`[${t.severity.toUpperCase()} at ${r}] ${t.message}`;let s=n.split(`
|
|
1729
1729
|
`),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}
|
|
1730
1730
|
`+l+`
|
|
1731
1731
|
${c}${a}
|
|
1732
|
-
${l}${d}^`}function
|
|
1732
|
+
${l}${d}^`}function nd(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 Ye(t,e){return t!=null&&Object.hasOwn(t,e)?t[e]:void 0}function Et(t,e,r){String(e)==="__proto__"?Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0}):t[e]=r}function Kr(t,e){if(t==null)return;let r=Array.isArray(e)?e:String(e).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),n=t;for(let s of r){if(n==null||typeof n!="object")return;n=Ye(n,s)}return n}var _o=10*1024*1024;function sd(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=`
|
|
1733
1733
|
const target = process.argv[1];
|
|
1734
|
-
const maxBytes = ${
|
|
1734
|
+
const maxBytes = ${_o};
|
|
1735
1735
|
const controller = new AbortController();
|
|
1736
1736
|
const timer = setTimeout(() => controller.abort(), 30000);
|
|
1737
1737
|
try {
|
|
@@ -1757,19 +1757,19 @@ try {
|
|
|
1757
1757
|
} finally {
|
|
1758
1758
|
clearTimeout(timer);
|
|
1759
1759
|
}
|
|
1760
|
-
`,n=
|
|
1760
|
+
`,n=go(process.execPath,["--input-type=module","-e",r,t],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:_o+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 ay(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>_o)throw await s.cancel().catch(()=>{}),r.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(r.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}var ns=new Set,ts=1e3;process.on("exit",()=>{for(let t of ns)try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,"SIGKILL"):t.kill("SIGKILL")}catch{}ns.clear()});function ss(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 id(t){let e=String(t);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function od(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=go(d,u,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=go(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 ss(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 ss(o,a,l,c,!1,s,i)}function ad(t,e=6e4){return new Promise((r,n)=>{if(!Number.isSafeInteger(e)||e<0){n(new Error("system() timeout must be a non-negative safe integer in milliseconds"));return}let s=performance.now();try{let i=process.platform!=="win32",o;if(Array.isArray(t)){if(t.length===0){n(new Error("system() argv array must not be empty"));return}let g=String(t[0]),y=t.slice(1).map(String);o=qc(g,y,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]})}else o=qc(t,{shell:!0,detached:i,stdio:["ignore","pipe","pipe"]});ns.add(o);let a="",l="",c=null,d=null,u=0,f=!1,p=!1,_,E=!1,m,h=()=>{if(E)return;E=!0,ns.delete(o),m&&clearTimeout(m);try{o.stdout?.destroy(),o.stderr?.destroy()}catch{}let g=Math.max(0,Math.round(performance.now()-s)),y=typeof o.pid=="number"?o.pid:null;if(_){n(_);return}if(p){r(ss(a,l,null,d||"SIGKILL",!0,g,y));return}r(ss(a,l,c,d,!1,g,y))};e>0&&(m=setTimeout(()=>{p=!0,d="SIGKILL";try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}h()},e));let T=10*1024*1024;o.stdout?.setEncoding("utf-8"),o.stderr?.setEncoding("utf-8"),o.stdout?.on("data",g=>{let y=Buffer.byteLength(g,"utf-8");if(u+y>T){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(`
|
|
1761
1761
|
`)?`
|
|
1762
1762
|
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),h()}return}u+=y,a+=g}),o.stderr?.on("data",g=>{let y=Buffer.byteLength(g,"utf-8");if(u+y>T){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(`
|
|
1763
1763
|
`)?`
|
|
1764
|
-
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),h()}return}u+=y,l+=g}),o.on("error",g=>{_||(_=g)}),o.on("close",(g,y)=>{g!==null?(c=g,d=null):(c=null,d=y?String(y):null),h()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function
|
|
1765
|
-
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function
|
|
1764
|
+
`:"")+"system() output exceeds 10 MiB limit",_=new Error("system() output exceeds 10 MiB limit"),h()}return}u+=y,l+=g}),o.on("error",g=>{_||(_=g)}),o.on("close",(g,y)=>{g!==null?(c=g,d=null):(c=null,d=y?String(y):null),h()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function ly(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 Zr(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=U.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===`
|
|
1765
|
+
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function en(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=ed.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 Gc(t,e=!0,r=","){nd(r);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let u=0;u<t.length;u++){let f=t[u],p=t[u+1];if(l=!0,o)f==='"'?p==='"'?(i+='"',u++):(o=!1,a=!0):i+=f;else{if(a&&f!==r&&f!=="\r"&&f!==`
|
|
1766
1766
|
`)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"?(p===`
|
|
1767
1767
|
`&&u++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):f===`
|
|
1768
|
-
`?(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(
|
|
1769
|
-
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>
|
|
1770
|
-
`)}return t.map(n=>
|
|
1771
|
-
`)}function
|
|
1772
|
-
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}var
|
|
1768
|
+
`?(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(Jc));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],p={};for(let _=0;_<c.length;_++)Et(p,c[_],_<f.length?Jc(f[_]):null);d.push(p)}return d}function Jc(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 Vc(t,e=","){if(nd(e),!Array.isArray(t)||t.length===0)return"";let r=t[0];if(Array.isArray(r))return t.map(n=>n.map(s=>rs(s,e)).join(e)).join(`
|
|
1769
|
+
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>rs(o,e)).join(e),i=t.map(o=>n.map(a=>rs(Ye(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
1770
|
+
`)}return t.map(n=>rs(n,e)).join(`
|
|
1771
|
+
`)}function rs(t,e){let r=t==null?"":String(t);return r===""||r.includes(e)||r.includes('"')||r.includes(`
|
|
1772
|
+
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}var Kc={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"},Yr=class{diagnostics=[];formattedDepth=0;modes=[];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=[];return this.scanTokens(e),e.push({type:"EOF",value:"",line:this.line,column:this.column}),e}position(){return{offset:this.pos,line:this.line,column:this.column}}spannedToken(e,r,n){return{type:e,value:r,line:n.line,column:n.column,offset:n.offset,endOffset:this.pos,endLine:this.line,endColumn:this.column}}scanTokens(e,r){for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let n=this.position(),s=this.peek();if(r&&r.delimiters.length===0){if(s==="}"){if(r.lastToken===void 0)throw new C("Empty formatted-string field",n.line,n.column,"LEXER",this.file);this.advance(),e.push(this.spannedToken("FSTRING_FIELD_END","}",n));return}if(s==="?"&&r.pendingQuestions++,s===":")if(r.pendingQuestions>0)r.pendingQuestions--;else throw new C("Format specifications are not supported in formatted strings",n.line,n.column,"LEXER",this.file);if(r.lastToken&&["IDENTIFIER","NUMBER","STRING","TRUE","FALSE","NULL","RPAREN","RBRACKET","RBRACE","FSTRING_END"].includes(r.lastToken)&&s==="!"&&/[rsa]/.test(this.peekNext())&&this.peekNext()!=="")throw new C("Conversion suffixes (!r, !s, !a) are not supported in formatted strings",n.line,n.column,"LEXER",this.file);if(s==="="&&this.peekNext()!=="=")throw new C("Assignment/debug fields ({x=}) are not supported in formatted strings",n.line,n.column,"LEXER",this.file)}let i=e.length;this.readNextToken(e);for(let o of e.slice(i))o.offset===void 0&&(o.offset=n.offset,o.endOffset=this.pos,o.endLine=this.line,o.endColumn=this.column);if(r){let o=e[i],a={RPAREN:"LPAREN",RBRACKET:"LBRACKET",RBRACE:"LBRACE"};if(["LPAREN","LBRACKET","LBRACE"].includes(o.type))r.delimiters.push(o.type);else if(a[o.type]&&r.delimiters.pop()!==a[o.type])throw new C("Mismatched delimiter in formatted-string field",o.line,o.column,"LEXER",this.file);r.lastToken=e[e.length-1].type}}if(r)throw new C("Unterminated formatted-string field; expected '}'",r.opener.line,r.opener.column,"LEXER",this.file)}readNextToken(e){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));return}if(s==='"'||s==="'"){e.push(this.source.startsWith(s.repeat(3),this.pos)?this.readModernString("",r,n,e):this.readString(s,r,n));return}if(s==="<"&&this.peekNext()==="<"&&/^<<[A-Za-z_][A-Za-z0-9_]*(?:\r\n|\r|\n)/.test(this.source.slice(this.pos)))throw new C('Heredocs are not supported; use raw triple-quoted strings (r"""...""")',r,n,"LEXER",this.file);if(this.isAlpha(s)){let i=this.pos+1;for(;i<this.length&&this.isAlphaNumeric(this.source[i]);)i++;if(this.source[i]==='"'||this.source[i]==="'"){let o=this.source.slice(this.pos,i);if(!/^(r|f|rf|fr)$/i.test(o)){let a=this.modes.at(-1);throw a?.kind==="field"&&a.delimiters.length===0?new C("Unterminated formatted-string field; expected '}' before enclosing quote",a.opener.line,a.opener.column,"LEXER",this.file):new C("Unsupported string prefix '"+o+"'; separate an identifier or keyword from its string with whitespace",r,n,"LEXER",this.file)}e.push(this.readModernString(o,r,n,e));return}e.push(this.readIdentifier(r,n));return}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:r,column:n});break;case"?":e.push({type:"QUESTION",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 C("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 C("Unexpected character '|'. Did you mean '||'?",r,n,"LEXER",this.file);break;default:throw new C(`Unexpected character: '${s}'`,r,n,"LEXER",this.file)}}peek(){return this.source[this.pos]||""}peekNext(){return this.source[this.pos+1]||""}advance(){let e=this.source[this.pos++];return e==="\r"||e===`
|
|
1773
1773
|
`?((e!==`
|
|
1774
1774
|
`||this.source[this.pos-2]!=="\r")&&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===`
|
|
1775
1775
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
@@ -1781,7 +1781,7 @@ try {
|
|
|
1781
1781
|
`)return this.consumeStringNewline(),"";let i={"\\":"\\",'"':'"',"'":"'",a:"\x07",b:"\b",f:"\f",n:`
|
|
1782
1782
|
`,r:"\r",t:" ",v:"\v"};if(Object.hasOwn(i,s))return this.advance(),i[s];if(s==="N")throw new C("Named Unicode escapes (\\N) are not supported",r,n,"LEXER",this.file);if(s==="x"||s==="u"||s==="U"){this.advance();let o=s==="x"?2:s==="u"?4:8,a=this.source.slice(this.pos,this.pos+o);if(a.length!==o||!/^[0-9a-fA-F]+$/.test(a))throw new C("Invalid \\"+s+" escape; expected "+o+" hexadecimal digits",r,n,"LEXER",this.file);let l=Number.parseInt(a,16);if(l>1114111||l>=55296&&l<=57343)throw new C("Invalid Unicode scalar in string escape",r,n,"LEXER",this.file);for(let c=0;c<o;c++)this.advance();return String.fromCodePoint(l)}if(/[0-7]/.test(s)){let o=this.advance();for(;o.length<3&&this.peek()!==""&&/[0-7]/.test(this.peek());)o+=this.advance();return String.fromCodePoint(Number.parseInt(o,8))}return this.diagnostics.push({message:"Unknown escape '\\"+s+"'; backslash preserved",severity:"warning",line:r,column:n,file:this.file}),e&&(s==="{"||s==="}")?"\\":"\\"+this.advance()}readModernString(e,r,n,s){let i=this.pos;for(let p=0;p<e.length;p++)this.advance();let o=this.peek(),a=this.source.startsWith(o.repeat(3),this.pos),l=o.repeat(a?3:1),c={prefix:e.toLowerCase(),raw:/r/i.test(e),triple:a,formatted:/f/i.test(e)};if(c.formatted&&this.formattedDepth>=64)throw new C("Formatted-string nesting exceeds limit 64",r,n,"LEXER",this.file);c.formatted&&this.formattedDepth++;for(let p=0;p<l.length;p++)this.advance();if(this.modes.push({kind:"string",delimiter:l}),c.formatted){let p=this.spannedToken("FSTRING_START",e+l,{offset:i,line:r,column:n});p.stringLiteral=c,s.push(p)}let d=this.position(),u="",f=()=>{if(this.pos>d.offset){let p=this.spannedToken("FSTRING_TEXT",u,d);p.literal=u,s.push(p)}u=""};try{for(;this.pos<this.length;){if(this.source.startsWith(l,this.pos)){c.formatted&&f();let _=this.position();for(let E=0;E<l.length;E++)this.advance();return c.formatted?this.spannedToken("FSTRING_END",l,_):{type:"STRING",value:u,literal:u,line:r,column:n,offset:i,endOffset:this.pos,endLine:this.line,endColumn:this.column,stringLiteral:c}}let p=this.peek();if(c.formatted&&(p==="{"||p==="}"))if(this.peekNext()===p)this.advance(),this.advance(),u+=p;else{if(p==="}")throw new C("Unmatched '}' in formatted-string text; use '}}' for a literal brace",this.line,this.column,"LEXER",this.file);{f();let _=this.position();this.advance();let E=this.spannedToken("FSTRING_FIELD_START","{",_);s.push(E);let m={kind:"field",opener:E,delimiters:[],pendingQuestions:0};this.modes.push(m);try{this.scanTokens(s,m)}finally{this.modes.pop()}d=this.position()}}else if(p==="\r"||p===`
|
|
1783
1783
|
`){if(!a)throw new C("Unterminated short string across newline",r,n,"LEXER",this.file);u+=this.consumeStringNewline()}else p==="\\"?c.raw?(u+=this.advance(),this.pos<this.length&&!(c.formatted&&(this.peek()==="{"||this.peek()==="}"))&&(u+=this.peek()==="\r"||this.peek()===`
|
|
1784
|
-
`?this.consumeStringNewline():this.advance())):u+=this.readModernEscape(c.formatted):u+=this.advance()}throw new C("Unterminated string literal; expected "+l,r,n,"LEXER",this.file)}finally{this.modes.pop(),c.formatted&&this.formattedDepth--}}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(Yc,n)?Yc[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};function zc(t,e){try{if(Array.isArray(t))return Array.from({length:t.length},(n,s)=>t[s]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new C(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof C?r:new C(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function Eo(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)Eo(s,e);else n&&typeof n=="object"&&Eo(n,e)}}}var To=Object.freeze({startsWith:"starts_with",endsWith:"ends_with",indexOf:"index_of",lastIndexOf:"last_index_of",toUpperCase:"upper",toLowerCase:"lower",parseInt:"num",parseFloat:"num",trimStart:"trim_start",trimLeft:"trim_start",trimEnd:"trim_end",trimRight:"trim_end",strip:"trim",lstrip:"trim_start",rstrip:"trim_end",length:"len",append:"push",prepend:"unshift",push_back:"push",push_front:"unshift","JSON.parse":"json_parse","JSON.stringify":"json_stringify"});function ls(t,e="Call to undefined function"){let r=`${e} '${t}'`;if(!Object.hasOwn(To,t))return r;let n=r+`; did you mean '${To[t]}'?`;return t==="parseInt"||t==="parseFloat"?n+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":n}var en=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&&Eo(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 C("'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 C?r:new C(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous();if(this.check("FSTRING_START")){let n=this.peek();throw new C("Import paths require an unprefixed short string",n.line,n.column,"PARSER",this.file)}let r=this.consume("STRING","Expected file path string after 'import'");if(r.stringLiteral?.prefix||r.stringLiteral?.triple)throw new C("Import paths require an unprefixed short string",r.line,r.column,"PARSER",this.file);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 C("'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 C("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();if(this.consume("LPAREN","Expected '(' after 'for'"),this.check("IDENTIFIER")&&this.tokens[this.current+1]?.type==="COMMA")throw new C("For-in requires one binding; use 'for (x in expr)'",this.peek().line,this.peek().column,"PARSER",this.file);if(this.check("IDENTIFIER")&&this.tokens[this.current+1]?.type==="IDENTIFIER"&&this.tokens[this.current+1].value==="in"){let o=this.advance().value;if(this.advance(),this.check("RPAREN"))throw new C("Expected expression after 'in' in for-loop",this.peek().line,this.peek().column,"PARSER",this.file);let a=this.parseExpression();this.consume("RPAREN","Expected ')' after for-in expression");let l=this.parseStatement();return{kind:"ForInStmt",name:o,iterable:a,body:l,line:e.line,column:e.column}}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.parseConditional();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 C("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 C("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseConditional(){let e=this.parseLogicalOr();if(!this.match("QUESTION"))return e;let r=this.previous(),n=()=>["COLON","SEMICOLON","RPAREN","RBRACKET","RBRACE","FSTRING_FIELD_END","EOF","COMMA"].includes(this.peek().type);if(n())throw new C("Expected true arm after '?'",this.peek().line,this.peek().column,"PARSER",this.file);let s=this.parseAssignment();if(this.consume("COLON","Expected ':' after conditional true arm"),n())throw new C("Expected false arm after ':'",this.peek().line,this.peek().column,"PARSER",this.file);let i=this.parseAssignment();return{kind:"ConditionalExpr",condition:e,trueArm:s,falseArm:i,line:r.line,column:r.column}}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"){if(e.kind==="IndexExpr"&&e.target.kind==="IdentifierExpr"&&e.index.kind==="LiteralExpr"){let n=e.target.name+"."+e.index.value;if(Object.hasOwn(To,n))throw new C(ls(n),e.line,e.column,"PARSER",this.file)}throw new C("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.check("FSTRING_START"))return this.parseFormattedString();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 C("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 C("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 C(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}parseFormattedString(){let e=this.advance(),r=[];for(;!this.check("FSTRING_END")&&!this.isAtEnd();){if(this.match("FSTRING_TEXT")){r.push(this.previous().value);continue}let n=this.consume("FSTRING_FIELD_START","Expected formatted-string text or field"),s=this.parseExpression();this.validateFieldExpression(s);let i=this.consume("FSTRING_FIELD_END","Expected '}' after one formatted-string expression");r.push({expression:s,line:n.line,column:n.column,file:this.file,offset:n.offset,endOffset:i.endOffset})}return this.consume("FSTRING_END","Unterminated formatted string"),{kind:"InterpolatedStringExpr",parts:r,line:e.line,column:e.column,file:this.file}}validateFieldExpression(e){let r=[];switch(e.kind){case"AssignExpr":case"IndexAssignExpr":case"TupleAssignExpr":case"ParallelExpr":throw new C("Assignment and parallel expressions are not permitted in formatted-string fields",e.line,e.column,"PARSER",this.file);case"UnaryExpr":r=[e.operand];break;case"BinaryExpr":r=[e.left,e.right];break;case"ConditionalExpr":r=[e.condition,e.trueArm,e.falseArm];break;case"GroupingExpr":r=[e.expression];break;case"CallExpr":r=e.args;break;case"ArrayExpr":case"TupleExpr":r=e.elements;break;case"ObjectExpr":r=e.properties.map(n=>n.value);break;case"IndexExpr":r=[e.target,e.index];break;case"InterpolatedStringExpr":r=e.parts.flatMap(n=>typeof n=="string"?[]:[n.expression]);break;case"LiteralExpr":case"IdentifierExpr":break}for(let n of r)this.validateFieldExpression(n)}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 C(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},my=`# LMScript Standard Library (std.lms)
|
|
1784
|
+
`?this.consumeStringNewline():this.advance())):u+=this.readModernEscape(c.formatted):u+=this.advance()}throw new C("Unterminated string literal; expected "+l,r,n,"LEXER",this.file)}finally{this.modes.pop(),c.formatted&&this.formattedDepth--}}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(Kc,n)?Kc[n]:void 0;if(s){let i;return s==="TRUE"&&(i=!0),s==="FALSE"&&(i=!1),s==="NULL"&&(i=null),{type:s,value:n,literal:i,line:e,column:r}}return{type:"IDENTIFIER",value:n,line:e,column:r}}};function Yc(t,e){try{if(Array.isArray(t))return Array.from({length:t.length},(n,s)=>t[s]);if(typeof t=="string")return Array.from(t);if(t!==null&&typeof t=="object"&&(Object.getPrototypeOf(t)===Object.prototype||Object.getPrototypeOf(t)===null))return Object.keys(t);let r=t===null?"null":t instanceof Date?"Date":typeof t;throw new C(`Cannot iterate value of type ${r}; expected list, map or string`,e.line,e.column,"RUNTIME",e.file)}catch(r){throw r instanceof C?r:new C(`Cannot snapshot iterable: ${r instanceof Error?r.message:String(r)}`,e.line,e.column,"RUNTIME",e.file)}}function yo(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)yo(s,e);else n&&typeof n=="object"&&yo(n,e)}}}var Eo=Object.freeze({startsWith:"starts_with",endsWith:"ends_with",indexOf:"index_of",lastIndexOf:"last_index_of",toUpperCase:"upper",toLowerCase:"lower",parseInt:"num",parseFloat:"num",trimStart:"trim_start",trimLeft:"trim_start",trimEnd:"trim_end",trimRight:"trim_end",strip:"trim",lstrip:"trim_start",rstrip:"trim_end",length:"len",append:"push",prepend:"unshift",push_back:"push",push_front:"unshift","JSON.parse":"json_parse","JSON.stringify":"json_stringify"});function is(t,e="Call to undefined function"){let r=`${e} '${t}'`;if(!Object.hasOwn(Eo,t))return r;let n=r+`; did you mean '${Eo[t]}'?`;return t==="parseInt"||t==="parseFloat"?n+" num uses whole-value Number conversion; it does not provide prefix parsing or integer truncation.":n}var zr=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&&yo(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 C("'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 C?r:new C(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous();if(this.check("FSTRING_START")){let n=this.peek();throw new C("Import paths require an unprefixed short string",n.line,n.column,"PARSER",this.file)}let r=this.consume("STRING","Expected file path string after 'import'");if(r.stringLiteral?.prefix||r.stringLiteral?.triple)throw new C("Import paths require an unprefixed short string",r.line,r.column,"PARSER",this.file);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 C("'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 C("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();if(this.consume("LPAREN","Expected '(' after 'for'"),this.check("IDENTIFIER")&&this.tokens[this.current+1]?.type==="COMMA")throw new C("For-in requires one binding; use 'for (x in expr)'",this.peek().line,this.peek().column,"PARSER",this.file);if(this.check("IDENTIFIER")&&this.tokens[this.current+1]?.type==="IDENTIFIER"&&this.tokens[this.current+1].value==="in"){let o=this.advance().value;if(this.advance(),this.check("RPAREN"))throw new C("Expected expression after 'in' in for-loop",this.peek().line,this.peek().column,"PARSER",this.file);let a=this.parseExpression();this.consume("RPAREN","Expected ')' after for-in expression");let l=this.parseStatement();return{kind:"ForInStmt",name:o,iterable:a,body:l,line:e.line,column:e.column}}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.parseConditional();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 C("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 C("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseConditional(){let e=this.parseLogicalOr();if(!this.match("QUESTION"))return e;let r=this.previous(),n=()=>["COLON","SEMICOLON","RPAREN","RBRACKET","RBRACE","FSTRING_FIELD_END","EOF","COMMA"].includes(this.peek().type);if(n())throw new C("Expected true arm after '?'",this.peek().line,this.peek().column,"PARSER",this.file);let s=this.parseAssignment();if(this.consume("COLON","Expected ':' after conditional true arm"),n())throw new C("Expected false arm after ':'",this.peek().line,this.peek().column,"PARSER",this.file);let i=this.parseAssignment();return{kind:"ConditionalExpr",condition:e,trueArm:s,falseArm:i,line:r.line,column:r.column}}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"){if(e.kind==="IndexExpr"&&e.target.kind==="IdentifierExpr"&&e.index.kind==="LiteralExpr"){let n=e.target.name+"."+e.index.value;if(Object.hasOwn(Eo,n))throw new C(is(n),e.line,e.column,"PARSER",this.file)}throw new C("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.check("FSTRING_START"))return this.parseFormattedString();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 C("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 C("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 C(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}parseFormattedString(){let e=this.advance(),r=[];for(;!this.check("FSTRING_END")&&!this.isAtEnd();){if(this.match("FSTRING_TEXT")){r.push(this.previous().value);continue}let n=this.consume("FSTRING_FIELD_START","Expected formatted-string text or field"),s=this.parseExpression();this.validateFieldExpression(s);let i=this.consume("FSTRING_FIELD_END","Expected '}' after one formatted-string expression");r.push({expression:s,line:n.line,column:n.column,file:this.file,offset:n.offset,endOffset:i.endOffset})}return this.consume("FSTRING_END","Unterminated formatted string"),{kind:"InterpolatedStringExpr",parts:r,line:e.line,column:e.column,file:this.file}}validateFieldExpression(e){let r=[];switch(e.kind){case"AssignExpr":case"IndexAssignExpr":case"TupleAssignExpr":case"ParallelExpr":throw new C("Assignment and parallel expressions are not permitted in formatted-string fields",e.line,e.column,"PARSER",this.file);case"UnaryExpr":r=[e.operand];break;case"BinaryExpr":r=[e.left,e.right];break;case"ConditionalExpr":r=[e.condition,e.trueArm,e.falseArm];break;case"GroupingExpr":r=[e.expression];break;case"CallExpr":r=e.args;break;case"ArrayExpr":case"TupleExpr":r=e.elements;break;case"ObjectExpr":r=e.properties.map(n=>n.value);break;case"IndexExpr":r=[e.target,e.index];break;case"InterpolatedStringExpr":r=e.parts.flatMap(n=>typeof n=="string"?[]:[n.expression]);break;case"LiteralExpr":case"IdentifierExpr":break}for(let n of r)this.validateFieldExpression(n)}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 C(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},cy=`# LMScript Standard Library (std.lms)
|
|
1785
1785
|
|
|
1786
1786
|
# String Utilities
|
|
1787
1787
|
fn is_blank(s) {
|
|
@@ -1876,22 +1876,22 @@ fn clamp(val, low, high) {
|
|
|
1876
1876
|
}
|
|
1877
1877
|
return val;
|
|
1878
1878
|
}
|
|
1879
|
-
`,go=null;function py(){if(!go){let e=new Zr(my,"<std>").tokenize(),n=new en(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);go=n}return{kind:"Program",statements:[...go.statements],line:1,column:1,file:"<std>"}}function hy(t,e={}){let r=[],n=e.file||"<main>",s=e.baseDir||(e.file?me.dirname(me.resolve(e.file)):process.cwd()),i=new Map,o=new Set;function a(h,T){if(e.moduleResolver)return e.moduleResolver(h,T).path;let g=s;T&&T!=="<main>"&&T!=="<std>"&&(g=me.dirname(T));let y=me.resolve(g,h);try{return U.realpathSync(y)}catch{return y}}function l(h,T){let g,y;if(e.moduleResolver){let S=e.moduleResolver(h,T);g=S.path,y=S.source}else{if(g=a(h,T),i.has(g))return i.get(g);if(o.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};try{y=U.readFileSync(g,"utf-8")}catch(S){throw new C(`Cannot resolve import '${h}': ${S?.message||String(S)}`,1,1,"PARSER",T)}}if(i.has(g))return i.get(g);if(o.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};o.add(g);let v=new Zr(y,g),b=v.tokenize();r.push(...v.diagnostics);let A=new en(b,g).parse();for(let S of A.statements)if(S.kind!=="FunctionDeclStmt"&&S.kind!=="ImportStmt")throw new C(`Library '${g}' cannot contain top-level executable statements; libraries must only declare functions. Found '${S.kind}'.`,S.line,S.column,"CHECKER",g);for(let S of A.statements)S.kind==="ImportStmt"&&l(S.path,g);return o.delete(g),i.set(g,A),A}let c=new Zr(t,n),d=c.tokenize();r.push(...c.diagnostics);let f=new en(d,n).parse(),p=n!=="<main>"?a(n):"<main>";i.set(p,f);for(let h of f.statements)h.kind==="ImportStmt"&&l(h.path,n);let _=[];if(!e.noStdlib){let h=py();for(let T of h.statements)T.kind==="FunctionDeclStmt"&&_.push(T)}for(let[h,T]of i.entries())if(h!==p)for(let g of T.statements)g.kind==="FunctionDeclStmt"&&_.push(g);for(let h of f.statements)h.kind!=="ImportStmt"&&_.push(h);let E={kind:"Program",statements:_,line:f.line,column:f.column,file:n},m=Array.from(i.keys());return{program:E,loadedFiles:m,diagnostics:r}}var yt=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}},wo=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new yt;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 yt,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 yt(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"ForInStmt":{this.checkExpr(e.iterable);let r=this.currentScope;if(this.currentScope=new yt(r),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let n of e.body.statements)this.checkStmt(n);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=r;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new yt(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 yt(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(!U.statSync(r.value).isFile())throw new Error("path is not a regular file");U.accessSync(r.value,U.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"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;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"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);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(ls(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}}}};function So(t,e){let r,n=o=>{throw r=e?new C("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),r},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):n("nonfinite number");if(typeof o!="object")return n(o===void 0?"undefined":"unsupported "+typeof o);let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(!a&&l!==Object.prototype&&l!==null)return n("unsupported host object");if(s.has(o))return n("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(f=>typeof f=="symbol"))return n("symbol-keyed collection");let c=a?Array.from({length:o.length},(f,p)=>String(p)):Object.keys(o);if(a&&c.some(f=>!Object.hasOwn(o,f)))return n("sparse array");let d=Object.getOwnPropertyNames(o).filter(f=>!a||f!=="length");if(d.length!==c.length||d.some(f=>!c.includes(f)))return n("extra or non-enumerable collection property");let u=[];for(let f of c){let p=Object.getOwnPropertyDescriptor(o,f);if(!p)return n("sparse array");if(!Object.hasOwn(p,"value"))return n("accessor property");let _=i(p.value);u.push(a?_:JSON.stringify(f)+":"+_)}return a?"["+u.join(",")+"]":"{"+u.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===r)throw o;return n("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function Qc(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return So(t)}return t===null?"null":String(t)}var ur=class{value;constructor(e){this.value=e}},Ve=class{},Ke=class{},fr=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Re=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,r=!1){this.parent=e,this.isFunctionBoundary=r}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},cs=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()}}},vo=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new cs,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new cs,this.objectLocks.set(e,r)),r}},ds=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new vo;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 Re,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stdout(h),h},arity:{min:0},description:"Formats values into an output-log entry rendered as a line by the CLI; returns text without a newline",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stdout(h),h},arity:{min:0},description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(m,...h)=>{let T=tn(m,h,"printf");return this.stdout(T),T},arity:{min:1},description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stderr?this.stderr(`error: ${h}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${h}
|
|
1880
|
-
`):console.error(`error: ${h}`),this.recordedErrors.push(h),h},arity:{min:1},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:(m,h=6e4)=>{if(!Number.isSafeInteger(h)||h<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?
|
|
1881
|
-
`)+(
|
|
1882
|
-
`:""),
|
|
1883
|
-
`)+(
|
|
1884
|
-
`:""),A=b.exitCode!==void 0?b.exitCode:b.success?0:1,S={success:b.success&&A===0,stdout:I,output:[...b.output],value:b.value,exit_code:A,code:A,errors:b.errors??[]};return S.toString=()=>I,S}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:m=>this.isAsync?uy(m):id(m),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let E=e.get("sleep");(!E||E.isDefault)&&this.hostFunctions.set("sleep",{fn:m=>{if(typeof m!="number"||!Number.isFinite(m)||m<0)throw new Error("sleep() duration must be a non-negative finite number");if(m>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(T=>setTimeout(T,m));let h=Date.now()+m;for(;Date.now()<h;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Re,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 Re(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 C(`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 C("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 Ve)break;if(s instanceof Ke)continue;throw s}}return}case"ForInStmt":{let n=zc(this.evalExpr(e.iterable,r),e),s=0;for(let i of n){if(++s>1e6)throw new C("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new Re(r);o.define(e.name,i);try{if(e.body.kind==="BlockStmt")for(let a of e.body.statements)this.execStmt(a,o);else this.execStmt(e.body,o)}catch(a){if(a instanceof Ve)break;if(a instanceof Ke)continue;throw a}}return}case"ForStmt":{let n=new Re(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 C("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 Ve)break;if(!(i instanceof Ke))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new ur(n)}case"BreakStmt":throw new Ve;case"ContinueStmt":throw new Ke;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new C("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"InterpolatedStringExpr":{let n="";for(let s of e.parts)n+=typeof s=="string"?s:So(this.evalExpr(s.expression,r),s);return n}case"ParallelExpr":throw new C("'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 C(`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),Et(n,s,i),i;throw new C("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)Et(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 C("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]:Ye(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 C(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.evalExpr(e.trueArm,r):this.evalExpr(e.falseArm,r)}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 C("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 C(`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 fr)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>ss)throw this.callDepth--,new C(`Execution fuel exhausted: maximum function call depth exceeded (${ss})`,s,i,"RUNTIME",o);let l=new Re(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof ur)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 ke||l?.name==="LMScriptExit"||l?.isControlFlow?l:new C(`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 C(`'${e}' is not a function`,s,i,"RUNTIME",o):new C(ls(e,"Undefined function"),s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new fr(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Re,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 Re(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 C(`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 C("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 Ve)break;if(i instanceof Ke)continue;throw i}}return}case"ForInStmt":{let s=zc(await this.evalExprAsync(e.iterable,r,n),e),i=0;for(let o of s){if(++i>1e6)throw new C("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new Re(r);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)await this.execStmtAsync(l,a,n);else await this.execStmtAsync(e.body,a,n)}catch(l){if(l instanceof Ve)break;if(l instanceof Ke)continue;throw l}}return}case"ForStmt":{let s=new Re(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 C("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 Ve)break;if(!(o instanceof Ke))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 ur(s)}case"BreakStmt":throw new Ve;case"ContinueStmt":throw new Ke;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new C(`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 C("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),Et(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new C("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 C(`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 C("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"InterpolatedStringExpr":{let s="";for(let i of e.parts)s+=typeof i=="string"?i:So(await this.evalExprAsync(i.expression,r,n),i);return s}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 C(`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),Et(s,i,o),o;throw new C("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)Et(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 C("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]:Ye(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 C(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,r,n):await this.evalExprAsync(e.falseArm,r,n)}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 C("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 C(`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>ss)throw this.asyncCallDepth.set(o,d-1),new C(`Execution fuel exhausted: maximum function call depth exceeded (${ss})`,s,i,"RUNTIME",a);let u=new Re(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof ur)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 ke||d?.name==="LMScriptExit"||d?.isControlFlow?d:new C(`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 C(`'${l}' is not a function`,s,i,"RUNTIME",a):new C(ls(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},gy=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"conditional",category:"Language Constructs",signature:"condition ? trueExpr : falseExpr",description:"Lazy, right-associative conditional expression. Precedence is below || and above assignment; only the selected arm is evaluated.",example:'label = count > 0 ? "some" : "none";'},{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 (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter. For C-style counters, use 'let' in the init clause so nested loops do not mutate an outer counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],_y=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",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:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(clock(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Alias for strftime: epoch milliseconds first, format second, using local time and the same supported tokens and validation.",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 (including no arguments).",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:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by a required delimiter. Pass an explicit empty delimiter to split into characters.",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 a substring or a strictly equal array element, or returns -1 when absent.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Alias for index_of; finds a substring or strictly equal array element.",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 substring or strictly equal array element, or returns -1 when absent.",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 by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",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 %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width and non-float precision are limited to 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{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, ...items: 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, ...items: 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(first: array, ...rest: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array; no values returns Infinity.",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; no values returns -Infinity.",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(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf.",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding 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 lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Alias for str; lists and plain maps become compact JSON, while scalar text and + coercion stay unchanged.",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");'}],yy=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];function Ey(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 Zc(t,e){if(typeof t!="number"||!Number.isFinite(t)||typeof e!="string")throw new Error("strftime: expected epoch milliseconds first and format string second");let r=new Date(t);if(!Number.isFinite(r.getTime()))throw new Error("strftime: invalid epoch milliseconds");let n=(s,i=2)=>String(s).padStart(i,"0");return 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 tn(t,e,r="sprintf"){let n=0,s=i=>new Error(r+": "+i);return String(t).replace(/%(-?0?)(\d+)?(?:\.(\d+))?([sdf%])|%/g,(i,o="",a,l,c)=>{if(i==="%%")return"%";if(!c||c==="%")throw s("unsupported or malformed directive");if(n>=e.length)throw s("missing value for "+i);let d=a===void 0?0:Number(a),u=l===void 0?void 0:Number(l);if(d>1e4||u!==void 0&&u>(c==="f"?100:1e4))throw s("width or precision exceeds supported limit");let f=e[n++],p;if(c==="s")p=f!==null&&typeof f=="object"?JSON.stringify(f):String(f),u!==void 0&&(p=p.slice(0,u));else{let _=Number(f);if(!Number.isFinite(_))throw s("numeric directive needs a finite number");if(c==="f")p=u===void 0?String(_):_.toFixed(u);else{let E=Math.trunc(_);p=BigInt(Math.abs(E)).toString().padStart(u??0,"0"),E<0&&(p="-"+p)}}return o.includes("-")?p.padEnd(d," "):c!=="s"&&o.includes("0")&&!(c==="d"&&u!==void 0)?p.startsWith("-")?"-"+p.slice(1).padStart(Math.max(0,d-1),"0"):p.padStart(d,"0"):p.padStart(d," ")})}var at=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 gy)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of _y)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of yy)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=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=U.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
1879
|
+
`,ho=null;function dy(){if(!ho){let e=new Yr(cy,"<std>").tokenize(),n=new zr(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);ho=n}return{kind:"Program",statements:[...ho.statements],line:1,column:1,file:"<std>"}}function uy(t,e={}){let r=[],n=e.file||"<main>",s=e.baseDir||(e.file?me.dirname(me.resolve(e.file)):process.cwd()),i=new Map,o=new Set;function a(h,T){if(e.moduleResolver)return e.moduleResolver(h,T).path;let g=s;T&&T!=="<main>"&&T!=="<std>"&&(g=me.dirname(T));let y=me.resolve(g,h);try{return U.realpathSync(y)}catch{return y}}function l(h,T){let g,y;if(e.moduleResolver){let v=e.moduleResolver(h,T);g=v.path,y=v.source}else{if(g=a(h,T),i.has(g))return i.get(g);if(o.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};try{y=U.readFileSync(g,"utf-8")}catch(v){throw new C(`Cannot resolve import '${h}': ${v?.message||String(v)}`,1,1,"PARSER",T)}}if(i.has(g))return i.get(g);if(o.has(g))return{kind:"Program",statements:[],line:1,column:1,file:g};o.add(g);let S=new Yr(y,g),I=S.tokenize();r.push(...S.diagnostics);let k=new zr(I,g).parse();for(let v of k.statements)if(v.kind!=="FunctionDeclStmt"&&v.kind!=="ImportStmt")throw new C(`Library '${g}' cannot contain top-level executable statements; libraries must only declare functions. Found '${v.kind}'.`,v.line,v.column,"CHECKER",g);for(let v of k.statements)v.kind==="ImportStmt"&&l(v.path,g);return o.delete(g),i.set(g,k),k}let c=new Yr(t,n),d=c.tokenize();r.push(...c.diagnostics);let f=new zr(d,n).parse(),p=n!=="<main>"?a(n):"<main>";i.set(p,f);for(let h of f.statements)h.kind==="ImportStmt"&&l(h.path,n);let _=[];if(!e.noStdlib){let h=dy();for(let T of h.statements)T.kind==="FunctionDeclStmt"&&_.push(T)}for(let[h,T]of i.entries())if(h!==p)for(let g of T.statements)g.kind==="FunctionDeclStmt"&&_.push(g);for(let h of f.statements)h.kind!=="ImportStmt"&&_.push(h);let E={kind:"Program",statements:_,line:f.line,column:f.column,file:n},m=Array.from(i.keys());return{program:E,loadedFiles:m,diagnostics:r}}var yt=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}},To=class{diagnostics=[];hostFunctions=new Map;options;functions=new Map;currentScope=new yt;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 yt,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 yt(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"ForInStmt":{this.checkExpr(e.iterable);let r=this.currentScope;if(this.currentScope=new yt(r),this.currentScope.define(e.name),this.loopDepth++,e.body.kind==="BlockStmt")for(let n of e.body.statements)this.checkStmt(n);else this.checkStmt(e.body);this.loopDepth--,this.currentScope=r;break}case"ForStmt":{let r=this.currentScope;this.currentScope=new yt(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 yt(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(!U.statSync(r.value).isFile())throw new Error("path is not a regular file");U.accessSync(r.value,U.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"InterpolatedStringExpr":for(let r of e.parts)typeof r!="string"&&this.checkExpr(r.expression);break;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"ConditionalExpr":{this.checkExpr(e.condition),this.checkExpr(e.trueArm),this.checkExpr(e.falseArm);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(is(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}}}};function wo(t,e){let r,n=o=>{throw r=e?new C("Cannot interpolate value: "+o,e.line,e.column,"RUNTIME",e.file):new Error("Cannot convert value to text: "+o),r},s=new Set,i=o=>{if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="boolean")return String(o);if(typeof o=="number")return Number.isFinite(o)?String(o):n("nonfinite number");if(typeof o!="object")return n(o===void 0?"undefined":"unsupported "+typeof o);let a=Array.isArray(o),l=Object.getPrototypeOf(o);if(!a&&l!==Object.prototype&&l!==null)return n("unsupported host object");if(s.has(o))return n("cyclic collection");s.add(o);try{if(Reflect.ownKeys(o).some(f=>typeof f=="symbol"))return n("symbol-keyed collection");let c=a?Array.from({length:o.length},(f,p)=>String(p)):Object.keys(o);if(a&&c.some(f=>!Object.hasOwn(o,f)))return n("sparse array");let d=Object.getOwnPropertyNames(o).filter(f=>!a||f!=="length");if(d.length!==c.length||d.some(f=>!c.includes(f)))return n("extra or non-enumerable collection property");let u=[];for(let f of c){let p=Object.getOwnPropertyDescriptor(o,f);if(!p)return n("sparse array");if(!Object.hasOwn(p,"value"))return n("accessor property");let _=i(p.value);u.push(a?_:JSON.stringify(f)+":"+_)}return a?"["+u.join(",")+"]":"{"+u.join(",")+"}"}finally{s.delete(o)}};try{return typeof t=="string"?t:i(t)}catch(o){if(o===r)throw o;return n("serialization failed: "+(o instanceof Error?o.message:String(o)))}}function zc(t){if(t!==null&&typeof t=="object"){let e=Object.getPrototypeOf(t);if(Array.isArray(t)||e===Object.prototype||e===null)return wo(t)}return t===null?"null":String(t)}var ur=class{value;constructor(e){this.value=e}},Ve=class{},Ke=class{},fr=class{name;constructor(e){this.name=e}toString(){return`<function ${this.name}>`}},Re=class t{static nextId=1;id=t.nextId++;values=new Map;parent;isFunctionBoundary;constructor(e,r=!1){this.parent=e,this.isFunctionBoundary=r}resolveBinding(e){if(this.values.has(e))return{env:this,name:e};if(this.parent)return this.parent.resolveBinding(e)}define(e,r){this.values.set(e,r)}get(e){if(this.values.has(e))return this.values.get(e);if(this.parent)return this.parent.get(e)}has(e){return this.values.has(e)||(this.parent?.has(e)??!1)}set(e,r){if(this.values.has(e)){this.values.set(e,r);return}if(!this.isFunctionBoundary&&this.parent?.has(e)){this.parent.set(e,r);return}this.values.set(e,r)}},os=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()}}},So=class{bindingLocks=new Map;objectLocks=new WeakMap;getBindingLock(e){let r=this.bindingLocks.get(e);return r||(r=new os,this.bindingLocks.set(e,r)),r}getObjectLock(e){let r=this.objectLocks.get(e);return r||(r=new os,this.objectLocks.set(e,r)),r}},as=class{globalEnv;userFunctions=new Map;hostFunctions;stdout;stderr;lockManager=new So;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 Re,this.hostFunctions=new Map(e);let o=e.get("print");(!o||o.isDefault)&&this.hostFunctions.set("print",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stdout(h),h},arity:{min:0},description:"Formats values into an output-log entry rendered as a line by the CLI; returns text without a newline",isDefault:!0});let a=e.get("println");(!a||a.isDefault)&&this.hostFunctions.set("println",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stdout(h),h},arity:{min:0},description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline",isDefault:!0});let l=e.get("printf");(!l||l.isDefault)&&this.hostFunctions.set("printf",{fn:(m,...h)=>{let T=Qr(m,h,"printf");return this.stdout(T),T},arity:{min:1},description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",isDefault:!0});let c=e.get("error");(!c||c.isDefault)&&this.hostFunctions.set("error",{fn:(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return this.stderr?this.stderr(`error: ${h}`):typeof process<"u"&&process.stderr?process.stderr.write(`error: ${h}
|
|
1880
|
+
`):console.error(`error: ${h}`),this.recordedErrors.push(h),h},arity:{min:1},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:(m,h=6e4)=>{if(!Number.isSafeInteger(h)||h<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsync?ad(m,h):od(m,h)},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:m=>this.isAsync?en(m):Zr(m),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:m=>id(m),arity:1,description:"Quotes string safely for POSIX shell command execution",isDefault:!0});let p=e.get("run_script");(!p||p.isDefault)&&this.hostFunctions.set("run_script",{fn:(m,h=[])=>{let T=me.resolve(String(m));if(!U.existsSync(T))throw new Error(`run_script: file not found: '${T}'`);let g=U.readFileSync(T,"utf-8"),y=Array.isArray(h)?h.map(String):[],S=new at;for(let[I,b]of this.hostFunctions)S.hasFunction(I)?b.isDefault||S.registerFunction(I,b.fn,b.arity,{description:b.description,allowOverwrite:!0},!1,b.isContainerMutation):S.registerFunction(I,b.fn,b.arity,b.description,b.isDefault,b.isContainerMutation);if(S.setGlobal("args",[...y]),S.setGlobal("ARGV",[T,...y]),this.isAsync)return(async()=>{let I=await S.runAsync(g,{file:T}),b=I.output.join(`
|
|
1881
|
+
`)+(I.output.length>0?`
|
|
1882
|
+
`:""),k=I.exitCode!==void 0?I.exitCode:I.success?0:1,v={success:I.success&&k===0,stdout:b,output:[...I.output],value:I.value,exit_code:k,code:k,errors:I.errors??[]};return v.toString=()=>b,v})();{let I=S.run(g,{file:T}),b=I.output.join(`
|
|
1883
|
+
`)+(I.output.length>0?`
|
|
1884
|
+
`:""),k=I.exitCode!==void 0?I.exitCode:I.success?0:1,v={success:I.success&&k===0,stdout:b,output:[...I.output],value:I.value,exit_code:k,code:k,errors:I.errors??[]};return v.toString=()=>b,v}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let _=e.get("urlget");(!_||_.isDefault)&&this.hostFunctions.set("urlget",{fn:m=>this.isAsync?ay(m):sd(m),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let E=e.get("sleep");(!E||E.isDefault)&&this.hostFunctions.set("sleep",{fn:m=>{if(typeof m!="number"||!Number.isFinite(m)||m<0)throw new Error("sleep() duration must be a non-negative finite number");if(m>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(T=>setTimeout(T,m));let h=Date.now()+m;for(;Date.now()<h;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new Re,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 Re(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 C(`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 C("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 Ve)break;if(s instanceof Ke)continue;throw s}}return}case"ForInStmt":{let n=Yc(this.evalExpr(e.iterable,r),e),s=0;for(let i of n){if(++s>1e6)throw new C("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let o=new Re(r);o.define(e.name,i);try{if(e.body.kind==="BlockStmt")for(let a of e.body.statements)this.execStmt(a,o);else this.execStmt(e.body,o)}catch(a){if(a instanceof Ve)break;if(a instanceof Ke)continue;throw a}}return}case"ForStmt":{let n=new Re(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 C("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 Ve)break;if(!(i instanceof Ke))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new ur(n)}case"BreakStmt":throw new Ve;case"ContinueStmt":throw new Ke;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new C("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"InterpolatedStringExpr":{let n="";for(let s of e.parts)n+=typeof s=="string"?s:wo(this.evalExpr(s.expression,r),s);return n}case"ParallelExpr":throw new C("'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 C(`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),Et(n,s,i),i;throw new C("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)Et(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 C("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]:Ye(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 C(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let n=this.evalExpr(e.condition,r);return this.isTruthy(n)?this.evalExpr(e.trueArm,r):this.evalExpr(e.falseArm,r)}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 C("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 C(`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 fr)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>ts)throw this.callDepth--,new C(`Execution fuel exhausted: maximum function call depth exceeded (${ts})`,s,i,"RUNTIME",o);let l=new Re(this.globalEnv,!0);for(let c=0;c<a.params.length;c++)l.define(a.params[c],r[c]);try{for(let c of a.body.statements)this.execStmt(c,l)}catch(c){if(c instanceof ur)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 ke||l?.name==="LMScriptExit"||l?.isControlFlow?l:new C(`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 C(`'${e}' is not a function`,s,i,"RUNTIME",o):new C(is(e,"Undefined function"),s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new fr(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new Re,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 Re(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 C(`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 C("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 Ve)break;if(i instanceof Ke)continue;throw i}}return}case"ForInStmt":{let s=Yc(await this.evalExprAsync(e.iterable,r,n),e),i=0;for(let o of s){if(++i>1e6)throw new C("Execution fuel exhausted: for-in loop exceeded maximum iterations limit (1000000)",e.line,e.column,"RUNTIME",e.file);let a=new Re(r);a.define(e.name,o);try{if(e.body.kind==="BlockStmt")for(let l of e.body.statements)await this.execStmtAsync(l,a,n);else await this.execStmtAsync(e.body,a,n)}catch(l){if(l instanceof Ve)break;if(l instanceof Ke)continue;throw l}}return}case"ForStmt":{let s=new Re(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 C("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 Ve)break;if(!(o instanceof Ke))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 ur(s)}case"BreakStmt":throw new Ve;case"ContinueStmt":throw new Ke;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new C(`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 C("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),Et(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new C("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 C(`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 C("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"InterpolatedStringExpr":{let s="";for(let i of e.parts)s+=typeof i=="string"?i:wo(await this.evalExprAsync(i.expression,r,n),i);return s}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 C(`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),Et(s,i,o),o;throw new C("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)Et(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 C("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]:Ye(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 C(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"ConditionalExpr":{let s=await this.evalExprAsync(e.condition,r,n);return this.isTruthy(s)?await this.evalExprAsync(e.trueArm,r,n):await this.evalExprAsync(e.falseArm,r,n)}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 C("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 C(`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>ts)throw this.asyncCallDepth.set(o,d-1),new C(`Execution fuel exhausted: maximum function call depth exceeded (${ts})`,s,i,"RUNTIME",a);let u=new Re(this.globalEnv,!0);for(let f=0;f<c.params.length;f++)u.define(c.params[f],r[f]);try{for(let f of c.body.statements)await this.execStmtAsync(f,u,o)}catch(f){if(f instanceof ur)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 ke||d?.name==="LMScriptExit"||d?.isControlFlow?d:new C(`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 C(`'${l}' is not a function`,s,i,"RUNTIME",a):new C(is(l,"Undefined function"),s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},fy=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"conditional",category:"Language Constructs",signature:"condition ? trueExpr : falseExpr",description:"Lazy, right-associative conditional expression. Precedence is below || and above assignment; only the selected arm is evaluated.",example:'label = count > 0 ? "some" : "none";'},{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 (x in expr) { ... }; for (init; condition; update) { ... }",description:"For-in visits a snapshot of list values, map keys or string Unicode code points with a fresh local binding. C-style loops remain supported; use let for an isolated counter. For C-style counters, use 'let' in the init clause so nested loops do not mutate an outer counter.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],my=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file_exclusive",category:"File I/O",signature:"write_file_exclusive(path: string, content: any): boolean",description:"Creates a new file exclusively; errors if it already exists.",example:'write_file_exclusive("new.txt", "hello");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator; no arguments returns dot.",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:"Takes epoch milliseconds first and format second, using local time. Supports %Y, %m, %d, %H, %M, %S and %% only; other tokens remain literal. Invalid dates or argument types are errors.",example:'s = strftime(clock(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Alias for strftime: epoch milliseconds first, format second, using local time and the same supported tokens and validation.",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 (including no arguments).",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:"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; all three arguments are evaluated. Use condition ? thenVal : elseVal for lazy selection.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:"split(s: string, delimiter: string): array",description:"Splits a string by a required delimiter. Pass an explicit empty delimiter to split into characters.",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 a substring or a strictly equal array element, or returns -1 when absent.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Alias for index_of; finds a substring or strictly equal array element.",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 substring or strictly equal array element, or returns -1 when absent.",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 by start and optional length; negative starts count from the end and clamp at zero. Nonpositive lengths return empty text.",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 %s, %d, %f and %% with optional decimal width and .precision, - left alignment and 0 numeric padding. String precision truncates; integer precision pads digits; float precision rounds (0..100). Bare %f keeps normal number text. Width and non-float precision are limited to 10000. Unsupported directives and missing values are errors; extra arguments are ignored.",example:'s = sprintf("%05.2f|%s|%d", 3.14159, "x", 42);'},{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, ...items: 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, ...items: 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(first: array, ...rest: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array; no values returns Infinity.",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; no values returns -Infinity.",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(value: any, ...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats values into an output-log entry rendered as a line by the CLI. Returns the formatted text without adding a newline.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf.",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding 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 lists and plain maps to compact JSON using the f-string collection rule; scalars retain normal text. Cyclic or lossy collections are errors. Does not change + coercion.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Alias for str; lists and plain maps become compact JSON, while scalar text and + coercion stay unchanged.",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");'}],py=[{name:"is_blank",category:"Strings",signature:"is_blank(s: any): boolean",description:"Returns true if string is null, empty, or whitespace only.",example:'if (is_blank(user_input)) { println("input required"); }'},{name:"chunk",category:"Lists & Arrays",signature:"chunk(arr: array, size: number): array",description:"Splits an array into chunks of specified size.",example:"batches = chunk(items, 10);"},{name:"compact",category:"Lists & Arrays",signature:"compact(arr: array): array",description:"Returns a new array with all null elements removed.",example:"valid = compact([1, null, 2, null, 3]);"},{name:"zip",category:"Lists & Arrays",signature:"zip(arr1: array, arr2: array): array",description:"Combines two arrays into an array of pairs [[a1, b1], [a2, b2], ...].",example:'pairs = zip(["a", "b"], [1, 2]);'},{name:"enumerate",category:"Lists & Arrays",signature:"enumerate(arr: array): array",description:"Returns an array of [index, value] pairs, JS/Python-familiar alongside zip (Rule 1, operator 2026-09-29).",example:'pairs = enumerate(["a", "b"]);'},{name:"take",category:"Lists & Arrays",signature:"take(arr: array, n: number): array",description:"Returns the first n elements of an array.",example:"first_three = take(items, 3);"},{name:"drop",category:"Lists & Arrays",signature:"drop(arr: array, n: number): array",description:"Returns a new array with the first n elements omitted.",example:"rest = drop(items, 3);"},{name:"clamp",category:"Math",signature:"clamp(val: number, low: number, high: number): number",description:"Restricts a numeric value to lie within [low, high] bounds.",example:"bounded = clamp(score, 0, 100);"}];function hy(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 Qc(t,e){if(typeof t!="number"||!Number.isFinite(t)||typeof e!="string")throw new Error("strftime: expected epoch milliseconds first and format string second");let r=new Date(t);if(!Number.isFinite(r.getTime()))throw new Error("strftime: invalid epoch milliseconds");let n=(s,i=2)=>String(s).padStart(i,"0");return 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 Qr(t,e,r="sprintf"){let n=0,s=i=>new Error(r+": "+i);return String(t).replace(/%(-?0?)(\d+)?(?:\.(\d+))?([sdf%])|%/g,(i,o="",a,l,c)=>{if(i==="%%")return"%";if(!c||c==="%")throw s("unsupported or malformed directive");if(n>=e.length)throw s("missing value for "+i);let d=a===void 0?0:Number(a),u=l===void 0?void 0:Number(l);if(d>1e4||u!==void 0&&u>(c==="f"?100:1e4))throw s("width or precision exceeds supported limit");let f=e[n++],p;if(c==="s")p=f!==null&&typeof f=="object"?JSON.stringify(f):String(f),u!==void 0&&(p=p.slice(0,u));else{let _=Number(f);if(!Number.isFinite(_))throw s("numeric directive needs a finite number");if(c==="f")p=u===void 0?String(_):_.toFixed(u);else{let E=Math.trunc(_);p=BigInt(Math.abs(E)).toString().padStart(u??0,"0"),E<0&&(p="-"+p)}}return o.includes("-")?p.padEnd(d," "):c!=="s"&&o.includes("0")&&!(c==="d"&&u!==void 0)?p.startsWith("-")?"-"+p.slice(1).padStart(Math.max(0,d-1),"0"):p.padStart(d,"0"):p.padStart(d," ")})}var at=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 fy)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of my)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of py)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=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read",e=>U.readFileSync(e,"utf-8"),1,"Reads entire file as UTF-8 string"),this.registerFunction("read_lines",e=>{let r=U.readFileSync(e,"utf-8"),n=r.length>0;return r.endsWith(`\r
|
|
1885
1885
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
1886
1886
|
`)&&(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(`
|
|
1887
1887
|
`)+`
|
|
1888
|
-
`;return U.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(U.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 U.readdirSync(me.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(U.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(U.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,r)=>(U.writeFileSync(e,String(r),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,r)=>(U.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=U.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(U.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=U.readFileSync(e,"utf-8");return
|
|
1888
|
+
`;return U.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(U.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 U.readdirSync(me.resolve(String(e)))}catch{return[]}},1,"Lists filenames in a directory"),this.registerFunction("write_file",(e,r)=>(U.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write",(e,r)=>(U.writeFileSync(e,String(r),"utf-8"),!0),2,"Writes string content to file"),this.registerFunction("write_file_exclusive",(e,r)=>(U.writeFileSync(e,String(r),{encoding:"utf8",flag:"wx"}),!0),2,"Creates a new file; refuses to overwrite an existing path"),this.registerFunction("append_file",(e,r)=>(U.appendFileSync(e,String(r),"utf-8"),!0),2,"Appends string content to file"),this.registerFunction("read_json",e=>{let r=U.readFileSync(e,"utf-8");return JSON.parse(r)},1,"Reads file and parses JSON content"),this.registerFunction("write_json",(e,r,n=2)=>(U.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=U.readFileSync(e,"utf-8");return Gc(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=",")=>(U.writeFileSync(e,Vc(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Gc,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",Vc,{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=me.resolve(oy(),`lmscript-${iy()}`),r=U.openSync(e,"wx",384);return U.closeSync(r),e},0,"Creates an empty temporary file and returns its absolute path; caller deletes it"),this.registerFunction("file_exists",e=>U.existsSync(e),1,"Checks if file exists"),this.registerFunction("exit",(e=0)=>{throw new ke(Number(e))},{min:0,max:1},"Terminates script execution with an optional exit code (default: 0)"),this.registerFunction("delete_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("remove_file",e=>U.existsSync(e)?(U.unlinkSync(e),!0):!1,1,"Deletes file if it exists"),this.registerFunction("mkdir",(e,r=!0)=>(U.mkdirSync(e,{recursive:!!r}),!0),{min:1,max:2},"Creates a directory (recursive by default)"),this.registerFunction("rmdir",(e,r=!1)=>U.existsSync(e)?(r?U.rmSync(e,{recursive:!0,force:!0}):U.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)=>(U.copyFileSync(e,r),!0),2,"Copies a file to a new path"),this.registerFunction("move_file",(e,r)=>(U.renameSync(e,r),!0),2,"Moves/renames a file"),this.registerFunction("basename",(e,r)=>me.basename(e,r),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>me.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>me.join(...e),{min:0},"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>me.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,{min:0},"Creates a new list/array"),this.registerFunction("array",(...e)=>e,{min:0},"Creates a new list/array"),this.registerFunction("push",(e,...r)=>(e.push(...r),e),{min:1},"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),{min:1},"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),{min:1},"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)))},{min:1,max:2},"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("sorted",(e,r)=>this.hostFunctions.get("sort").fn(e,r),{min:1,max:2},"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?ad(e,r):od(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=me.resolve(String(e));if(!U.existsSync(n))throw new Error(`run_script: file not found: '${n}'`);let s=U.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(`
|
|
1889
1889
|
`)+(a.output.length>0?`
|
|
1890
1890
|
`:""),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(`
|
|
1891
1891
|
`)+(a.output.length>0?`
|
|
1892
1892
|
`:""),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}
|
|
1893
|
-
`):console.error(`error: ${r}`),r},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>
|
|
1894
|
-
`):console.error(`error: ${String(r)}`),new ke(2);return e},2,'Stops the script (stderr message, exit 2) if value is missing -- "", null, [], or false -- else returns value unchanged, so it composes with getstr/getnum/getbool/getlist'),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Ye(i,a)==null||typeof Ye(i,a)!="object")&&Et(i,a,{}),i=Ye(i,a)}return s.length>0&&Et(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=>Ye(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Ye(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&&Ye(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},{min:0},"Formats values into an output-log entry rendered as a line by the CLI; returns text without a newline",!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},{min:0},"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline",!0),this.registerFunction("printf",(e,...r)=>{let n=tn(e,r,"printf");return this.outputLogs.push(n),n},{min:1},"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",!0),this.registerFunction("split",(e,r)=>String(e).split(r),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i:null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),{min:1,max:2},"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)=>Array.isArray(e)?e.indexOf(r,n):String(e).indexOf(r,n),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent"),this.registerFunction("indexOf",(e,r,n)=>Array.isArray(e)?e.indexOf(r,n):String(e).indexOf(r,n),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>Array.isArray(e)?e.lastIndexOf(r):String(e).lastIndexOf(r),2,"Finds last substring or strictly equal array element index; -1 if absent"),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),i=Math.trunc(Number(r))||0,o=i<0?Math.max(0,s.length+i):Math.min(s.length,i);if(n===void 0)return s.slice(o);let a=Math.max(0,Math.trunc(Number(n))||0);return s.slice(o,o+a)},{min:2,max:3},"Returns substring by end-relative start and optional length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),{min:2,max:3},"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",{min:2,max:3},"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),{min:1,max:2},"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),{min: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),{min:2,max:3},"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),{min:2,max:3},"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 fr,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>od(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},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>tn(e,r),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; 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},{min:1,max:3},"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)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},{min: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)=>Zc(e,r),2,"Formats local time: epoch milliseconds first, format string second"),this.registerFunction("date_format",(e,r)=>Zc(e,r),2,"Alias for strftime with timestamp-first local-time formatting"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},{min: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,"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; arguments evaluate eagerly"),this.registerFunction("str",e=>Qc(e),1,"Converts lists and maps to compact JSON; scalars to normal text"),this.registerFunction("to_string",e=>Qc(e),1,"Alias for str: converts lists and maps to compact JSON"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof fr?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${p}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:Ey(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,diagnostics:s}=hy(e,r),i=[...this.initialGlobals.keys(),...r.globals||[]],o=new wo(this.hostFunctions,{...r,globals:i}),a=[...s,...o.check(n)];return{ast:n,diagnostics:a,hasConcurrency:o.hasConcurrency}}catch(n){return n instanceof C?{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 ds(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 ke||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let _=typeof c.exitCode=="number"?c.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:i,output:n,errors:d}}let u=c instanceof C?c.line:1,f=c instanceof C?c.column:1,p=c instanceof C&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new ds(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 ke||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof C?l.line:1,u=l instanceof C?l.column:1,f=l instanceof C&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:f}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function Ty(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1893
|
+
`):console.error(`error: ${r}`),r},{min:1},"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>sd(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?en(e):Zr(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)=>ly(e,r),{min:1,max:2},"Safely parses JSON string with preamble/fence recovery, returning fallback (default null) on failure without throwing",!0),this.registerFunction("json_stringify",(e,r)=>JSON.stringify(e,null,r),{min:1,max:2},"Serializes value into JSON string"),this.registerFunction("keys",e=>e&&typeof e=="object"?Object.keys(e):[],1,"Returns array of object keys"),this.registerFunction("values",e=>e&&typeof e=="object"?Object.values(e):[],1,"Returns array of object values"),this.registerFunction("entries",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs"),this.registerFunction("items",e=>e&&typeof e=="object"?Object.entries(e):[],1,"Returns array of [key, value] pairs (alias for entries)"),this.registerFunction("has_key",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("has",(e,r)=>e&&typeof e=="object"?Object.hasOwn(e,r):!1,2,"Checks if object has key"),this.registerFunction("get",(e,r,n=null)=>{let s=Kr(e,r);return s!==void 0?s:n},{min:2,max:3},"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r,n="")=>{let s=Kr(e,r);return s==null?n:String(s)},{min:2,max:3},'Reads a string field from a map/request form; fallback (default "") when missing or null (never the string "null"). A distinguishable non-"" fallback (e.g. "?") tells "missing" apart from a real empty string.'),this.registerFunction("getnum",(e,r,n=0)=>{let s=Kr(e,r);return s==null?n:Number(s)},{min:2,max:3},"Reads a numeric field from a map/request form; fallback (default 0) when missing or null"),this.registerFunction("getbool",(e,r,n=!1)=>{let s=Kr(e,r);if(s==null)return n;if(typeof s=="boolean")return s;if(typeof s=="string"){let i=s.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return!!s},{min:2,max:3},'Reads a boolean field from a map/request form ("true"/"false" strings included); fallback (default false) when missing or null'),this.registerFunction("getlist",(e,r,n=[])=>{let s=Kr(e,r);return Array.isArray(s)?s:n},{min:2,max:3},"Reads an array field from a map/request form; fallback (default []) when missing, null, or not actually an array"),this.registerFunction("require",(e,r)=>{if(e==null||e===""||e===!1||Array.isArray(e)&&e.length===0)throw typeof process<"u"&&process.stderr?process.stderr.write(`error: ${String(r)}
|
|
1894
|
+
`):console.error(`error: ${String(r)}`),new ke(2);return e},2,'Stops the script (stderr message, exit 2) if value is missing -- "", null, [], or false -- else returns value unchanged, so it composes with getstr/getnum/getbool/getlist'),this.registerFunction("set",(e,r,n)=>{if(e==null||typeof e!="object")return e;let s=Array.isArray(r)?r:String(r).replace(/\[(\w+)\]/g,".$1").split(".").filter(Boolean),i=e;for(let o=0;o<s.length-1;o++){let a=s[o];(Ye(i,a)==null||typeof Ye(i,a)!="object")&&Et(i,a,{}),i=Ye(i,a)}return s.length>0&&Et(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=>Ye(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&Ye(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&&Ye(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},{min:0},"Formats values into an output-log entry rendered as a line by the CLI; returns text without a newline",!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},{min:0},"Alias of print: both log formatted values rendered as a line by the CLI and return text without adding a newline",!0),this.registerFunction("printf",(e,...r)=>{let n=Qr(e,r,"printf");return this.outputLogs.push(n),n},{min:1},"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",!0),this.registerFunction("split",(e,r)=>String(e).split(r),2,"Splits string by required delimiter; use explicit empty delimiter for characters"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i:null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),{min:1,max:2},"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)=>Array.isArray(e)?e.indexOf(r,n):String(e).indexOf(r,n),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent"),this.registerFunction("indexOf",(e,r,n)=>Array.isArray(e)?e.indexOf(r,n):String(e).indexOf(r,n),{min:2,max:3},"Finds substring or strictly equal array element index; -1 if absent (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>Array.isArray(e)?e.lastIndexOf(r):String(e).lastIndexOf(r),2,"Finds last substring or strictly equal array element index; -1 if absent"),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),i=Math.trunc(Number(r))||0,o=i<0?Math.max(0,s.length+i):Math.min(s.length,i);if(n===void 0)return s.slice(o);let a=Math.max(0,Math.trunc(Number(n))||0);return s.slice(o,o+a)},{min:2,max:3},"Returns substring by end-relative start and optional length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),{min:2,max:3},"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",{min:2,max:3},"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),{min:1,max:2},"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),{min: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),{min:2,max:3},"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),{min:2,max:3},"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 fr,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>id(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},{min:1},"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>Qr(e,r),{min:1},"Formats %s/%d/%f/%% with bounded width, alignment and precision; 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},{min:1,max:3},"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)},{min:0},"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},{min: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)=>Qc(e,r),2,"Formats local time: epoch milliseconds first, format string second"),this.registerFunction("date_format",(e,r)=>Qc(e,r),2,"Alias for strftime with timestamp-first local-time formatting"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},{min: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,"Eager compatibility helper: returns thenVal if cond is truthy, else elseVal; arguments evaluate eagerly"),this.registerFunction("str",e=>zc(e),1,"Converts lists and maps to compact JSON; scalars to normal text"),this.registerFunction("to_string",e=>zc(e),1,"Alias for str: converts lists and maps to compact JSON"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof fr?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},{min:1,max:2},"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,d=typeof s=="object"?s.doc:void 0,u=typeof s=="object"?!!s.allowOverwrite:!1,f=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,p=this.functionOriginModule.get(e);if(p&&p!==f&&!u)throw new Error(`Cannot register function '${e}' from module '${f}': already registered by module '${p}'`);return this.functionOriginModule.set(e,f),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:d}),d?this.functionDocs.set(e,{...d,module:d.module??f}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:f,signature:hy(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,diagnostics:s}=uy(e,r),i=[...this.initialGlobals.keys(),...r.globals||[]],o=new To(this.hostFunctions,{...r,globals:i}),a=[...s,...o.check(n)];return{ast:n,diagnostics:a,hasConcurrency:o.hasConcurrency}}catch(n){return n instanceof C?{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 as(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 ke||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let _=typeof c.exitCode=="number"?c.exitCode:0;return{success:_===0,value:_,exitCode:_,diagnostics:i,output:n,errors:d}}let u=c instanceof C?c.line:1,f=c instanceof C?c.column:1,p=c instanceof C&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:u,column:f,severity:"error",file:p}],output:n,errors:d}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new as(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 ke||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let p=typeof l.exitCode=="number"?l.exitCode:0;return{success:p===0,value:p,exitCode:p,diagnostics:i,output:n,errors:c}}let d=l instanceof C?l.line:1,u=l instanceof C?l.column:1,f=l instanceof C&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:d,column:u,severity:"error",file:f}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};async function gy(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1895
1895
|
`);let t=new at,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
|
|
1896
1896
|
fn factorial(n) {
|
|
1897
1897
|
if (n <= 1) {
|
|
@@ -1915,7 +1915,7 @@ fn clamp(val, low, high) {
|
|
|
1915
1915
|
assert(sumVal == 12, "sum must be 12");
|
|
1916
1916
|
`);n.success?(console.log(n.output.map(T=>" [out] "+T).join(`
|
|
1917
1917
|
`)),console.log(` -> Passed!
|
|
1918
|
-
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),t.registerFunction("base64Encode",T=>Buffer.from(T).toString("base64"),1,"Base64 encodes a string"),t.registerFunction("addVectors",(T,g)=>T.map((y,
|
|
1918
|
+
`)):(console.error(" -> Failed:",n.diagnostics),e=!1),console.log("Test Suite 2: TS Predefined Builtins & Host Registration"),t.registerFunction("base64Encode",T=>Buffer.from(T).toString("base64"),1,"Base64 encodes a string"),t.registerFunction("addVectors",(T,g)=>T.map((y,S)=>y+(g[S]||0)),2,"Adds two numeric arrays element-wise");let i=t.run(`
|
|
1919
1919
|
let text = "TypeScript Engine";
|
|
1920
1920
|
let encoded = base64Encode(text);
|
|
1921
1921
|
print("Encoded base64:", encoded);
|
|
@@ -1948,7 +1948,7 @@ fn clamp(val, low, high) {
|
|
|
1948
1948
|
|
|
1949
1949
|
undefinedFunctionCall(); // ERROR 4: undefined function
|
|
1950
1950
|
base64Encode("hello", "extra_arg"); // ERROR 5: arity mismatch
|
|
1951
|
-
`,a=t.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let T of a.diagnostics)console.log(" "+
|
|
1951
|
+
`,a=t.run(o);console.log(" Executed successfully?",a.success),console.log(" Formatted visual diagnostics caught BEFORE execution:");for(let T of a.diagnostics)console.log(" "+rd(T,o).split(`
|
|
1952
1952
|
`).join(`
|
|
1953
1953
|
`));!a.success&&a.diagnostics.length===5?console.log(` -> Passed! (All 5 static errors caught upfront with visual carets)
|
|
1954
1954
|
`):(console.error(" -> Failed! Expected 5 diagnostics, got",a.diagnostics.length),e=!1),console.log("Test Suite 4: Forward Function Declarations & Mutual Recursion");let c=t.run(`
|
|
@@ -2118,102 +2118,101 @@ fn clamp(val, low, high) {
|
|
|
2118
2118
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
2119
2119
|
`);return h.success?(console.log(h.output.map(T=>" [out] "+T).join(`
|
|
2120
2120
|
`)),console.log(` -> Passed!
|
|
2121
|
-
`)):(console.error(" -> Failed:",h.diagnostics),e=!1),e}async function
|
|
2121
|
+
`)):(console.error(" -> Failed:",h.diagnostics),e=!1),e}async function _y(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await gy()||(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:me.resolve(t[0]),o=s?t[1]:U.readFileSync(i,"utf-8"),a=new at,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(rd(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 Zc=me.basename(td(import.meta.url));(Zc==="lmscript.ts"||Zc==="lmscript.js")&&process.argv[1]&&U.existsSync(process.argv[1])&&U.realpathSync(td(import.meta.url))===U.realpathSync(me.resolve(process.argv[1]))&&_y();re();import{readFileSync as Dy}from"node:fs";import{homedir as My}from"node:os";import{join as _d,resolve as Fy}from"node:path";function Ay(t,e){let r=t.slice(0,e).split(/\r?\n/);return[r.length,r.pop().length+1]}function Ny(t,e,r){let n=t.split(/\r?\n/),s="",i=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=n[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
|
|
2122
2122
|
`,o===e&&(s+=" ".repeat(i+r+2),s+=`^
|
|
2123
|
-
`))}return s}var q=class t extends Error{line;column;codeblock;constructor(e,r){let[n,s]=
|
|
2123
|
+
`))}return s}var q=class t extends Error{line;column;codeblock;constructor(e,r){let[n,s]=Ay(r.toml,r.ptr),i=Ny(r.toml,n,s);super(`Invalid TOML document: ${e}
|
|
2124
2124
|
|
|
2125
|
-
${i}`,r),this.line=n,this.column=s,this.codeblock=i}static x(e,r,n){throw new t(e,{toml:r.s,ptr:n??r.p})}};function
|
|
2126
|
-
`:r===102?o+="\f":r===114?o+="\r":r===101?o+="\x1B":r===34?o+='"':r===92?o+="\\":q.x("unrecognised escape sequence",t),a=t.p+1,l=0);else r!==32&&r!==9&&(l===2&&q.x("invalid escape: only line-ending whitespace may be escaped",t,a),l=!s&&r===92?1:0,a=t.p);q.x("unfinished string",t,e)}var Dy=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,sn=class t extends Date{#t=!1;#r=!1;#e=null;constructor(e,r,n){let s=!0,i=!0,o="Z",a;if(typeof e=="string")if(r)e:{if(r<3){if(+e.slice(11,13)>23){e="";break e}r===2?(o=null,e+="Z"):(a=e.charCodeAt(e.length-1))!==90&&a!==122&&(o=e.slice(e.length-6)),n&&(e=e.slice(0,10)+"T"+e.slice(11))}else r===4&&(e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`);s=r!==4,i=r!==3}else{let l=e.match(Dy);l?(l[1]||(s=!1,e=`0000-01-01T${e}`),i=!!l[2],i&&e[10]===" "&&(e=e.replace(" ","T")),l[2]&&+l[2]>23?e="":(o=l[3]||null,!o&&i&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=s,this.#r=i,this.#e=o)}isDateTime(){return this.#t&&this.#r}isLocal(){return!this.#t||!this.#r||!this.#e}isDate(){return this.#t&&!this.#r}isTime(){return this.#r&&!this.#t}isValid(){return this.#t||this.#r}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let r=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return r=this.#e[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,r="Z"){let n=new t(e);return n.#e=r,n}static wrapAsLocalDateTime(e){let r=new t(e);return r.#e=null,r}static wrapAsLocalDate(e){let r=new t(e);return r.#r=!1,r.#e=null,r}static wrapAsLocalTime(e){let r=new t(e);return r.#t=!1,r.#e=null,r}};function Ce(t,e=10){return e===16?t>47&&t<58||t>64&&t<71||t>96&&t<103:t>47&&t<48+e}function xo(t,e){return t===32||t===9||t===10||t===13||e&&(t===e||t===44)||t===35}function an(t,e){let r=t.p,n=t.s.charCodeAt(t.p);if(n===91||n===123){t.d--||q.x("document contains excessively nested structures. aborting.",t);let s=n===91?hd(t):pd(t);return t.d++,s}return n===34||n===39?ms(t):n===116?((t.s.charCodeAt(++t.p)!==114||t.s.charCodeAt(++t.p)!==117||t.s.charCodeAt(++t.p)!==101)&&q.x("invalid value",t,r),t.p++,!0):n===102?((t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==108||t.s.charCodeAt(++t.p)!==115||t.s.charCodeAt(++t.p)!==101)&&q.x("invalid value",t,r),t.p++,!1):n===43||n===45?ps(t,t.p,t.s.charCodeAt(++t.p),44-n,e):t.s.charCodeAt(t.p+4)===45&&t.s.charCodeAt(t.p+7)===45?My(t,n,e):t.s.charCodeAt(t.p+2)===58?Fy(t,n,e):ps(t,t.p,n,0,e)}function ps(t,e,r,n,s){let i=r,o=0,a=!1;if(i===105)return(t.s.charCodeAt(++t.p)!==110||t.s.charCodeAt(++t.p)!==102)&&q.x("invalid value",t,e),t.p++,(n||1)/0;if(i===110)return(t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==110)&&q.x("invalid value",t,e),t.p++,NaN;if(i===48){if(++t.p>=t.s.length||xo(i=t.s.charCodeAt(t.p),s))return t.bi===!0?0n:0;if(!n){if(i===120)return Io(t,e,16,s);if(i===98)return Io(t,e,2,s);if(i===111)return Io(t,e,8,s)}i===46?o=2:i===101||i===69?o=4:q.x("illegal leading zero",t,e)}else Ce(i)||q.x("invalid value",t,e);for(;++t.p<t.s.length&&(i=t.s.charCodeAt(t.p),!xo(i,s));)o||(o=1),i===95?(o&1||q.x("illegal underscore",t),o+=11,a=!0):o===1&&i===46?o=2:(o===1||o===3)&&(i===101||i===69)?o=4:o===4&&(i===43||i===45)||(Ce(i)?o>9?o-=11:o&1||o++:q.x("illegal character in numeric literal",t));if(!o){let c=(r-48)*(n||1);return t.bi===!0?BigInt(c):c}o&1||q.x("unfinished numeric value",t,e);let l=t.s.slice(e,t.p);return a&&(l=l.replaceAll("_","")),o>1?parseFloat(l):md(t,l,10,e)}function Io(t,e,r,n){let s,i=1;for(;++t.p<t.s.length&&(s=t.s.charCodeAt(t.p),!xo(s,n));)s===95?(i&1&&q.x("illegal underscore",t),i=3):Ce(s,r)?i&1&&i--:q.x("illegal character in numeric literal",t);i&1&&q.x("unfinished numeric value",t);let o=t.s.slice(e+2,t.p);return i&&(o=o.replaceAll("_","")),md(t,o,r,e)}function md(t,e,r,n){if(t.bi!==!0)e:{let s=parseInt(e,r);if(!Number.isSafeInteger(s)){if(t.bi)break e;q.x("integer value cannot be represented losslessly",t,n)}return s}return BigInt(r===10?e:(r===2?"0b":r===8?"0o":"0x")+e)}function My(t,e,r){let n=t.p++,s;if(!Ce(e)||!Ce(t.s.charCodeAt(t.p++))||!Ce(t.s.charCodeAt(t.p++))||!Ce(t.s.charCodeAt(t.p++)))return ps(t,t.p=n,e,0,r);if(t.p+=5,Ce(t.s.charCodeAt(t.p++))||q.x("invalid date-time: date part is malformed",t,n),t.p>=t.s.length||((e=t.s.charCodeAt(t.p))!==32||(s=!0,!Ce(t.s.charCodeAt(t.p+1))))&&e!==84&&e!==116){let o=t.s.slice(n,t.p);return on(t,o,3,!1,n)}if(t.s.charCodeAt(t.p+=3)!==58&&q.x("invalid date-time: time part is malformed",t,n),t.s.charCodeAt(t.p+=3)===58&&(t.p+=3),t.s.charCodeAt(t.p)===46)for(;Ce(t.s.charCodeAt(++t.p)););if(e=t.s.charCodeAt(t.p)){if(e===90||e===122){let o=t.s.slice(n,++t.p);return on(t,o,1,s,n,"[+00:00]")}if(e===43||e===45){let o=t.s.slice(n,t.p+=6);return on(t,o,1,s,n,!t.ld&&"["+t.s.slice(t.p-6,t.p)+"]")}}let i=t.s.slice(n,t.p);return on(t,i,2,s,n)}function Fy(t,e,r){let n=t.p;if(!Ce(e)||!Ce(t.s.charCodeAt(++t.p)))return ps(t,--t.p,e,0,r);if(t.s.charCodeAt(t.p+=4)===58&&(t.p+=3),t.s.charCodeAt(t.p)===46)for(;Ce(t.s.charCodeAt(++t.p)););let s=t.s.slice(n,t.p);return on(t,s,4,!1,n)}function on(t,e,r,n,s,i){if(t.ld){let o=new sn(e,r,n);return o.isValid()||q.x("invalid date",t,s),o}try{switch(i&&(e+=i),r){case 1:return Temporal.ZonedDateTime.from(e);case 2:return Temporal.PlainDateTime.from(e);case 3:return Temporal.PlainDate.from(e);case 4:return Temporal.PlainTime.from(e)}}catch(o){q.x(o instanceof Error?o.message:""+o,t,s)}}function Py(t){for(;t.p<t.s.length;t.p++){let e=t.s.charCodeAt(t.p);if(e===10)break;if(e===13&&t.s.charCodeAt(t.p+1)===10){t.p++;break}(e<32&&e!==9||e===127)&&q.x("control characters are not allowed in comments",t)}}function He(t,e,r){let n;for(;t.p<t.s.length;){for(;t.p<t.s.length&&((n=t.s.charCodeAt(t.p))===32||n===9||!e&&(n===10||n===13&&t.s.charCodeAt(t.p+1)===10));)t.p++;if(r||n!==35)break;Py(t)}}function hs(t,e=61){let r,n=0,s=[],i,o=t.s.charCodeAt(r=t.p);do{if(o===e)return n||q.x("unexpected end of key",t),n===1&&s.push(t.s.slice(i,t.p)),t.p++,s;o===46?(n||q.x("illegal empty bare key",t),n===1&&s.push(t.s.slice(i,t.p)),n=0):!n&&(o===34||o===39)?(o===t.s.charCodeAt(t.p+1)&&o===t.s.charCodeAt(t.p+2)&&q.x("illegal quoted key: multiline strings are not allowed",t),s.push(ms(t)),n=2,t.p--):o===32||o===9?n===1&&(s.push(t.s.slice(i,t.p)),n=2):n===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?q.x("illegal character in key",t):n||(n=1,i=t.p)}while(o=t.s.charCodeAt(++t.p));q.x("incomplete key-value: cannot find end of key",t,r)}function pd(t){let e=t.p++,r=Object.create(null),n=new Set,s;for(;t.p<t.s.length;){if(He(t),(s=t.s.charCodeAt(t.p))===125)return t.p++,r;let i,o=r,a=!1,l=t.p,c=hs(t);for(let u=0;u<c.length;u++){u&&(o=a?o[i]:o[i]=Object.create(null)),i=c[u],(a=Object.hasOwn(o,i))&&(typeof o[i]!="object"||n.has(o[i]))&&q.x("trying to redefine an already defined value",t,l);let f=i==="__proto__";if(t.uk&&(f||i==="constructor")){o=t.uk!==1&&q.x("document contains an unsafe property",t,l);break}!a&&f&&Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0})}a&&q.x("trying to redefine an already defined value",t,l),He(t,!0,!0);let d=an(t,125);if(o&&typeof(o[i]=d)=="object"&&n.add(d),He(t),(s=t.s.charCodeAt(t.p++))===125)return r;s!==44&&q.x("expected comma or end of structure",t,t.p-1)}q.x("unfinished table",t,e)}function hd(t){let e=t.p++,r=[],n;for(;t.p<t.s.length;){if(He(t),(n=t.s.charCodeAt(t.p))===93)return t.p++,r;if(r.push(an(t,93)),He(t),(n=t.s.charCodeAt(t.p++))===93)return r;n!==44&&q.x("expected comma or end of structure",t,t.p-1)}q.x("unfinished array",t,e)}function gd(t,e,r,n,s){let i=r,o=n,a,l=!1,c;for(let d=0;d<e.length;d++){if(d){if(i=l?i[a]:i[a]=Object.create(null),o=(c=o[a]).c,s===0&&(c.t===1||c.t===2))return null;if(c.t===2){let u=i.length-1;i=i[u],o=o[u].c}}if(a=e[d],(l=Object.hasOwn(i,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!l){let u=a==="__proto__";if(t.uk&&(u||a==="constructor"))return!1;u&&(Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})),o[a]={t:d<e.length-1&&s===2?3:s,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==s&&!(s===1&&c.t===3)||(s===2&&(c.d||(c.d=!0,i[a]=[]),i[a].push(i=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}),c.d))return null;if(c.d=!0,s===1)i=l?i[a]:i[a]=Object.create(null);else if(s===0&&l)return null;return[a,i,c.c]}function _d(t,e,r){(e===null||t.uk===2)&&q.x(e===null?"trying to redefine an already defined table or value":"document contains an unsafe property",t,r)}function gs(t,e={}){let r={s:t,p:0,d:e.maxDepth??1e3,bi:e.integersAsBigInt??!1,ld:e.useLegacyDate??!0,uk:e.unsafeKeyBehaviour==="throw"?2:e.unsafeKeyBehaviour==="drop"?1:0},n=Object.create(null),s=Object.create(null),i,o=!1,a=n,l=s;for(t.charCodeAt(0)===65279&&r.p++,He(r);r.p<t.length;){if(t.charCodeAt(r.p)===91){let c=t.charCodeAt(++r.p)===91;i=r.p+=+c,o=!1;let d=hs(r,93);c&&(t.charCodeAt(r.p)!==93&&q.x("expected end of table array declaration",r),r.p++);let u=gd(r,d,n,s,c?2:1);u?(l=u[2],a=u[1]):(_d(r,u,i),o=!0)}else{i=r.p;let c=hs(r),d=gd(r,c,a,l,0);!d&&!o&&_d(r,d,i),He(r,!0,!0);let u=an(r,void 0);d&&!o&&(d[1][d[0]]=u)}He(r,!0),r.p<t.length&&(i=t.charCodeAt(r.p))!==10&&(i!==13||t.charCodeAt(r.p+1)!==10)&&q.x("each key-value declaration must be followed by an end-of-line",r),He(r)}return n}var WR=!!"".isWellFormed;var Ed=["Provider1","Provider2","Provider3"],Td=["provider","model1","model2","model3"];function ln(t=process.env,e){let r=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?jy(e):yd(r||yd(t.HOME||Uy(),".lmctl"),"init.toml")}var Tt=class extends Error{path;kind;line;column;constructor(e,r,n,s=1,i=1){super(r==="missing"?"Missing "+e+". Run lmctl init first.":(r==="read"?"Cannot read "+e+": "+n:"Invalid "+e+":"+s+":"+i+": "+n)+". Fix the file or run lmctl init."),this.path=e,this.kind=r,this.line=s,this.column=i}};function _s(t,e="<init.toml>"){let r;try{r=gs(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(s){let i=s;throw new Tt(e,"syntax",i.message,i.line??1,(i.column??1)+(t.startsWith("\uFEFF")&&i.line===1?1:0))}let n={};for(let s of Ed){let i=r[s];if(!i||typeof i!="object"||Array.isArray(i)||i instanceof Date)throw new Tt(e,"schema","missing or invalid table ["+s+"]");let o={};for(let a of Td){let l=i[a];if(typeof l!="string"||!l.trim())throw new Tt(e,"schema",s+"."+a+" must be a nonempty string");o[a]=l}n[s.toLowerCase()]=o}return{raw:t,document:r,config:n,path:e}}function ys(t=ln()){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode($y(t))}catch(r){let n=r;throw new Tt(t,n.code==="ENOENT"?"missing":"read",n.message)}return _s(e,t)}Kt();var Nu="Environment names (Provider1..3, Model1..3, Directory, NonInteractive) are supplied by ~/.lmctl/init.toml via lmctl init.";function Os(t){return t.includes("Undeclared variable '")&&!t.includes(Nu)?t+" "+Nu:t}function Ru(t,e,r={}){let n=ys(ln(e,r.initConfigPath)).config,s={Directory:t.cwd??process.cwd(),NonInteractive:bt({...t,env:e})};for(let i of[1,2,3]){let o="Provider"+i,a=n["provider"+i];s[o]=a.provider,s["Model"+i]=a.model1}return s}import{readFileSync as zN,rmSync as QN}from"node:fs";import{createInterface as ZN}from"node:readline";Yt();ft();Xs();function cf(t){let e=af(t.registry,t.fromTeamfile);if(e===void 0)return Nr(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!lf(e,t.fromAlias))return Nr(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=af(t.registry,t.toTeamfile);return r===void 0?Nr(`target team is not registered in policy graph: ${t.toTeamfile}`):lf(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Nr(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Nr(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Nr(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function af(t,e){return t.teams.find(r=>r.teamfile===e)}function lf(t,e){return t.aliases.some(r=>r===e)}function Nr(t){return{allowed:!1,outOfPolicy:!0,reason:t}}gn();qs();re();Kt();qt();Yt();Er();qt();function bw(t,e){if(Bd(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 Gs(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2125
|
+
${i}`,r),this.line=n,this.column=s,this.codeblock=i}static x(e,r,n){throw new t(e,{toml:r.s,ptr:n??r.p})}};function ds(t){let e=t.p,r=t.s.charCodeAt(t.p++),n=r,s=r===39,i=r===t.s.charCodeAt(t.p)&&r===t.s.charCodeAt(t.p+1);i&&((r=t.s.charCodeAt(t.p+=2))===10?t.p++:r===13&&t.s.charCodeAt(t.p+1)===10&&(t.p+=2));let o="",a=t.p,l=0;for(;t.p<t.s.length;t.p++)if(r=t.s.charCodeAt(t.p),i&&(r===10||r===13&&t.s.charCodeAt(t.p+1)===10))l=l&&3;else if(r<32&&r!==9||r===127)q.x("control characters are not allowed in strings",t);else if((!l||l===3)&&r===n&&(!i||t.s.charCodeAt(t.p+1)===n&&t.s.charCodeAt(t.p+2)===n)){if(i&&(t.s.charCodeAt(t.p+3)===n&&t.p++,t.s.charCodeAt(t.p+3)===n&&t.p++),!l){let c=t.s.slice(a,t.p);o=o?o+c:c}return t.p+=i?3:1,o}else if(!l)!s&&r===92&&(o+=t.s.slice(a,a=t.p),l=1);else if(l===1)if(r===120||r===117||r===85){let c=t.p++-1,d=0,u=r===120?2:r===117?4:8;for(let f=0;f<u;f++,t.p++){let p=t.s.charCodeAt(t.p),_=p>=48&&p<=57?p-48:p>=65&&p<=70?p-65+10:p>=97&&p<=102?p-97+10:-1;_<0&&q.x("invalid non-hex character in unicode escape",t),d=d<<4|_}(d<0||d>1114111||d>=55296&&d<=57343)&&q.x("invalid unicode escape",t,c),o+=String.fromCodePoint(d),a=t.p--,l=0}else i&&(r===32||r===9)?l=2:(r===98?o+="\b":r===116?o+=" ":r===110?o+=`
|
|
2126
|
+
`:r===102?o+="\f":r===114?o+="\r":r===101?o+="\x1B":r===34?o+='"':r===92?o+="\\":q.x("unrecognised escape sequence",t),a=t.p+1,l=0);else r!==32&&r!==9&&(l===2&&q.x("invalid escape: only line-ending whitespace may be escaped",t,a),l=!s&&r===92?1:0,a=t.p);q.x("unfinished string",t,e)}var Ry=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i,tn=class t extends Date{#t=!1;#r=!1;#e=null;constructor(e,r,n){let s=!0,i=!0,o="Z",a;if(typeof e=="string")if(r)e:{if(r<3){if(+e.slice(11,13)>23){e="";break e}r===2?(o=null,e+="Z"):(a=e.charCodeAt(e.length-1))!==90&&a!==122&&(o=e.slice(e.length-6)),n&&(e=e.slice(0,10)+"T"+e.slice(11))}else r===4&&(e=+e.slice(0,2)>23?"":`0000-01-01T${e}Z`);s=r!==4,i=r!==3}else{let l=e.match(Ry);l?(l[1]||(s=!1,e=`0000-01-01T${e}`),i=!!l[2],i&&e[10]===" "&&(e=e.replace(" ","T")),l[2]&&+l[2]>23?e="":(o=l[3]||null,!o&&i&&(e+="Z"))):e=""}super(e),isNaN(this.getTime())||(this.#t=s,this.#r=i,this.#e=o)}isDateTime(){return this.#t&&this.#r}isLocal(){return!this.#t||!this.#r||!this.#e}isDate(){return this.#t&&!this.#r}isTime(){return this.#r&&!this.#t}isValid(){return this.#t||this.#r}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z"||this.#e==="z")return e;let r=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return r=this.#e[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,r="Z"){let n=new t(e);return n.#e=r,n}static wrapAsLocalDateTime(e){let r=new t(e);return r.#e=null,r}static wrapAsLocalDate(e){let r=new t(e);return r.#r=!1,r.#e=null,r}static wrapAsLocalTime(e){let r=new t(e);return r.#t=!1,r.#e=null,r}};function Ce(t,e=10){return e===16?t>47&&t<58||t>64&&t<71||t>96&&t<103:t>47&&t<48+e}function Io(t,e){return t===32||t===9||t===10||t===13||e&&(t===e||t===44)||t===35}function nn(t,e){let r=t.p,n=t.s.charCodeAt(t.p);if(n===91||n===123){t.d--||q.x("document contains excessively nested structures. aborting.",t);let s=n===91?pd(t):md(t);return t.d++,s}return n===34||n===39?ds(t):n===116?((t.s.charCodeAt(++t.p)!==114||t.s.charCodeAt(++t.p)!==117||t.s.charCodeAt(++t.p)!==101)&&q.x("invalid value",t,r),t.p++,!0):n===102?((t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==108||t.s.charCodeAt(++t.p)!==115||t.s.charCodeAt(++t.p)!==101)&&q.x("invalid value",t,r),t.p++,!1):n===43||n===45?us(t,t.p,t.s.charCodeAt(++t.p),44-n,e):t.s.charCodeAt(t.p+4)===45&&t.s.charCodeAt(t.p+7)===45?Ly(t,n,e):t.s.charCodeAt(t.p+2)===58?Cy(t,n,e):us(t,t.p,n,0,e)}function us(t,e,r,n,s){let i=r,o=0,a=!1;if(i===105)return(t.s.charCodeAt(++t.p)!==110||t.s.charCodeAt(++t.p)!==102)&&q.x("invalid value",t,e),t.p++,(n||1)/0;if(i===110)return(t.s.charCodeAt(++t.p)!==97||t.s.charCodeAt(++t.p)!==110)&&q.x("invalid value",t,e),t.p++,NaN;if(i===48){if(++t.p>=t.s.length||Io(i=t.s.charCodeAt(t.p),s))return t.bi===!0?0n:0;if(!n){if(i===120)return bo(t,e,16,s);if(i===98)return bo(t,e,2,s);if(i===111)return bo(t,e,8,s)}i===46?o=2:i===101||i===69?o=4:q.x("illegal leading zero",t,e)}else Ce(i)||q.x("invalid value",t,e);for(;++t.p<t.s.length&&(i=t.s.charCodeAt(t.p),!Io(i,s));)o||(o=1),i===95?(o&1||q.x("illegal underscore",t),o+=11,a=!0):o===1&&i===46?o=2:(o===1||o===3)&&(i===101||i===69)?o=4:o===4&&(i===43||i===45)||(Ce(i)?o>9?o-=11:o&1||o++:q.x("illegal character in numeric literal",t));if(!o){let c=(r-48)*(n||1);return t.bi===!0?BigInt(c):c}o&1||q.x("unfinished numeric value",t,e);let l=t.s.slice(e,t.p);return a&&(l=l.replaceAll("_","")),o>1?parseFloat(l):fd(t,l,10,e)}function bo(t,e,r,n){let s,i=1;for(;++t.p<t.s.length&&(s=t.s.charCodeAt(t.p),!Io(s,n));)s===95?(i&1&&q.x("illegal underscore",t),i=3):Ce(s,r)?i&1&&i--:q.x("illegal character in numeric literal",t);i&1&&q.x("unfinished numeric value",t);let o=t.s.slice(e+2,t.p);return i&&(o=o.replaceAll("_","")),fd(t,o,r,e)}function fd(t,e,r,n){if(t.bi!==!0)e:{let s=parseInt(e,r);if(!Number.isSafeInteger(s)){if(t.bi)break e;q.x("integer value cannot be represented losslessly",t,n)}return s}return BigInt(r===10?e:(r===2?"0b":r===8?"0o":"0x")+e)}function Ly(t,e,r){let n=t.p++,s;if(!Ce(e)||!Ce(t.s.charCodeAt(t.p++))||!Ce(t.s.charCodeAt(t.p++))||!Ce(t.s.charCodeAt(t.p++)))return us(t,t.p=n,e,0,r);if(t.p+=5,Ce(t.s.charCodeAt(t.p++))||q.x("invalid date-time: date part is malformed",t,n),t.p>=t.s.length||((e=t.s.charCodeAt(t.p))!==32||(s=!0,!Ce(t.s.charCodeAt(t.p+1))))&&e!==84&&e!==116){let o=t.s.slice(n,t.p);return rn(t,o,3,!1,n)}if(t.s.charCodeAt(t.p+=3)!==58&&q.x("invalid date-time: time part is malformed",t,n),t.s.charCodeAt(t.p+=3)===58&&(t.p+=3),t.s.charCodeAt(t.p)===46)for(;Ce(t.s.charCodeAt(++t.p)););if(e=t.s.charCodeAt(t.p)){if(e===90||e===122){let o=t.s.slice(n,++t.p);return rn(t,o,1,s,n,"[+00:00]")}if(e===43||e===45){let o=t.s.slice(n,t.p+=6);return rn(t,o,1,s,n,!t.ld&&"["+t.s.slice(t.p-6,t.p)+"]")}}let i=t.s.slice(n,t.p);return rn(t,i,2,s,n)}function Cy(t,e,r){let n=t.p;if(!Ce(e)||!Ce(t.s.charCodeAt(++t.p)))return us(t,--t.p,e,0,r);if(t.s.charCodeAt(t.p+=4)===58&&(t.p+=3),t.s.charCodeAt(t.p)===46)for(;Ce(t.s.charCodeAt(++t.p)););let s=t.s.slice(n,t.p);return rn(t,s,4,!1,n)}function rn(t,e,r,n,s,i){if(t.ld){let o=new tn(e,r,n);return o.isValid()||q.x("invalid date",t,s),o}try{switch(i&&(e+=i),r){case 1:return Temporal.ZonedDateTime.from(e);case 2:return Temporal.PlainDateTime.from(e);case 3:return Temporal.PlainDate.from(e);case 4:return Temporal.PlainTime.from(e)}}catch(o){q.x(o instanceof Error?o.message:""+o,t,s)}}function Oy(t){for(;t.p<t.s.length;t.p++){let e=t.s.charCodeAt(t.p);if(e===10)break;if(e===13&&t.s.charCodeAt(t.p+1)===10){t.p++;break}(e<32&&e!==9||e===127)&&q.x("control characters are not allowed in comments",t)}}function He(t,e,r){let n;for(;t.p<t.s.length;){for(;t.p<t.s.length&&((n=t.s.charCodeAt(t.p))===32||n===9||!e&&(n===10||n===13&&t.s.charCodeAt(t.p+1)===10));)t.p++;if(r||n!==35)break;Oy(t)}}function fs(t,e=61){let r,n=0,s=[],i,o=t.s.charCodeAt(r=t.p);do{if(o===e)return n||q.x("unexpected end of key",t),n===1&&s.push(t.s.slice(i,t.p)),t.p++,s;o===46?(n||q.x("illegal empty bare key",t),n===1&&s.push(t.s.slice(i,t.p)),n=0):!n&&(o===34||o===39)?(o===t.s.charCodeAt(t.p+1)&&o===t.s.charCodeAt(t.p+2)&&q.x("illegal quoted key: multiline strings are not allowed",t),s.push(ds(t)),n=2,t.p--):o===32||o===9?n===1&&(s.push(t.s.slice(i,t.p)),n=2):n===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?q.x("illegal character in key",t):n||(n=1,i=t.p)}while(o=t.s.charCodeAt(++t.p));q.x("incomplete key-value: cannot find end of key",t,r)}function md(t){let e=t.p++,r=Object.create(null),n=new Set,s;for(;t.p<t.s.length;){if(He(t),(s=t.s.charCodeAt(t.p))===125)return t.p++,r;let i,o=r,a=!1,l=t.p,c=fs(t);for(let u=0;u<c.length;u++){u&&(o=a?o[i]:o[i]=Object.create(null)),i=c[u],(a=Object.hasOwn(o,i))&&(typeof o[i]!="object"||n.has(o[i]))&&q.x("trying to redefine an already defined value",t,l);let f=i==="__proto__";if(t.uk&&(f||i==="constructor")){o=t.uk!==1&&q.x("document contains an unsafe property",t,l);break}!a&&f&&Object.defineProperty(o,i,{enumerable:!0,configurable:!0,writable:!0})}a&&q.x("trying to redefine an already defined value",t,l),He(t,!0,!0);let d=nn(t,125);if(o&&typeof(o[i]=d)=="object"&&n.add(d),He(t),(s=t.s.charCodeAt(t.p++))===125)return r;s!==44&&q.x("expected comma or end of structure",t,t.p-1)}q.x("unfinished table",t,e)}function pd(t){let e=t.p++,r=[],n;for(;t.p<t.s.length;){if(He(t),(n=t.s.charCodeAt(t.p))===93)return t.p++,r;if(r.push(nn(t,93)),He(t),(n=t.s.charCodeAt(t.p++))===93)return r;n!==44&&q.x("expected comma or end of structure",t,t.p-1)}q.x("unfinished array",t,e)}function hd(t,e,r,n,s){let i=r,o=n,a,l=!1,c;for(let d=0;d<e.length;d++){if(d){if(i=l?i[a]:i[a]=Object.create(null),o=(c=o[a]).c,s===0&&(c.t===1||c.t===2))return null;if(c.t===2){let u=i.length-1;i=i[u],o=o[u].c}}if(a=e[d],(l=Object.hasOwn(i,a))&&o[a]?.t===0&&o[a]?.d)return null;if(!l){let u=a==="__proto__";if(t.uk&&(u||a==="constructor"))return!1;u&&(Object.defineProperty(i,a,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})),o[a]={t:d<e.length-1&&s===2?3:s,d:!1,i:0,c:Object.create(null)}}}if(c=o[a],c.t!==s&&!(s===1&&c.t===3)||(s===2&&(c.d||(c.d=!0,i[a]=[]),i[a].push(i=Object.create(null)),c.c[c.i++]=c={t:1,d:!1,i:0,c:Object.create(null)}),c.d))return null;if(c.d=!0,s===1)i=l?i[a]:i[a]=Object.create(null);else if(s===0&&l)return null;return[a,i,c.c]}function gd(t,e,r){(e===null||t.uk===2)&&q.x(e===null?"trying to redefine an already defined table or value":"document contains an unsafe property",t,r)}function ms(t,e={}){let r={s:t,p:0,d:e.maxDepth??1e3,bi:e.integersAsBigInt??!1,ld:e.useLegacyDate??!0,uk:e.unsafeKeyBehaviour==="throw"?2:e.unsafeKeyBehaviour==="drop"?1:0},n=Object.create(null),s=Object.create(null),i,o=!1,a=n,l=s;for(t.charCodeAt(0)===65279&&r.p++,He(r);r.p<t.length;){if(t.charCodeAt(r.p)===91){let c=t.charCodeAt(++r.p)===91;i=r.p+=+c,o=!1;let d=fs(r,93);c&&(t.charCodeAt(r.p)!==93&&q.x("expected end of table array declaration",r),r.p++);let u=hd(r,d,n,s,c?2:1);u?(l=u[2],a=u[1]):(gd(r,u,i),o=!0)}else{i=r.p;let c=fs(r),d=hd(r,c,a,l,0);!d&&!o&&gd(r,d,i),He(r,!0,!0);let u=nn(r,void 0);d&&!o&&(d[1][d[0]]=u)}He(r,!0),r.p<t.length&&(i=t.charCodeAt(r.p))!==10&&(i!==13||t.charCodeAt(r.p+1)!==10)&&q.x("each key-value declaration must be followed by an end-of-line",r),He(r)}return n}var FR=!!"".isWellFormed;var yd=["Provider1","Provider2","Provider3"],Ed=["provider","model1","model2","model3"];function sn(t=process.env,e){let r=t.LMCTL_HOME||(t.HOME===void 0?process.env.LMCTL_HOME:void 0);return e!==void 0?Fy(e):_d(r||_d(t.HOME||My(),".lmctl"),"init.toml")}var Tt=class extends Error{path;kind;line;column;constructor(e,r,n,s=1,i=1){super(r==="missing"?"Missing "+e+". Run lmctl init first.":(r==="read"?"Cannot read "+e+": "+n:"Invalid "+e+":"+s+":"+i+": "+n)+". Fix the file or run lmctl init."),this.path=e,this.kind=r,this.line=s,this.column=i}};function ps(t,e="<init.toml>"){let r;try{r=ms(t.startsWith("\uFEFF")?t.slice(1):t,{integersAsBigInt:"asNeeded",useLegacyDate:!0})}catch(s){let i=s;throw new Tt(e,"syntax",i.message,i.line??1,(i.column??1)+(t.startsWith("\uFEFF")&&i.line===1?1:0))}let n={};for(let s of yd){let i=r[s];if(!i||typeof i!="object"||Array.isArray(i)||i instanceof Date)throw new Tt(e,"schema","missing or invalid table ["+s+"]");let o={};for(let a of Ed){let l=i[a];if(typeof l!="string"||!l.trim())throw new Tt(e,"schema",s+"."+a+" must be a nonempty string");o[a]=l}n[s.toLowerCase()]=o}return{raw:t,document:r,config:n,path:e}}function hs(t=sn()){let e;try{e=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(Dy(t))}catch(r){let n=r;throw new Tt(t,n.code==="ENOENT"?"missing":"read",n.message)}return ps(e,t)}Kt();var Au="Environment names (Provider1..3, Model1..3, Directory, NonInteractive) are supplied by ~/.lmctl/init.toml via lmctl init.";function Rs(t){return t.includes("Undeclared variable '")&&!t.includes(Au)?t+" "+Au:t}function Nu(t,e,r={}){let n=hs(sn(e,r.initConfigPath)).config,s={Directory:t.cwd??process.cwd(),NonInteractive:bt({...t,env:e})};for(let i of[1,2,3]){let o="Provider"+i,a=n["provider"+i];s[o]=a.provider,s["Model"+i]=a.model1}return s}import{readFileSync as XN,rmSync as qN}from"node:fs";import{createInterface as GN}from"node:readline";Yt();ft();Ws();mn();Xs();re();Kt();qt();Yt();Er();qt();function Tw(t,e){if(jd(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 qs(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
2127
2127
|
FROM tracked_invocation
|
|
2128
2128
|
WHERE target_teamfile = ?
|
|
2129
2129
|
AND target_alias = ?
|
|
2130
|
-
AND status = 'running'`,e,r),s=0;for(let i of n)
|
|
2130
|
+
AND status = 'running'`,e,r),s=0;for(let i of n)Tw(t,i)!==null&&(s+=1);return s}re();Vi();Yt();var Ah=36e5;function jI(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return Ah;let r=Number(e);return!Number.isFinite(r)||r<=0?Ah:r}async function BI(t,e,r){try{let n=mt(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 kh(s);if(c.length!==1)return null;i=c[0]}let o=await Br(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 Nh(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??jI(),o=await BI(t,r,n),a=o!==null&&o>=i;return a&&D({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}Xt();var Rh=Xc(Bo(),1);function HI(t){return t===null?null:ve(t)?"live":"dead"}function sc(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:HI(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function WI(t){return(0,Rh.formatDuration)(t)}function ic(t){let e=[];return t.idle_ms!==null&&e.push(`active ${WI(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("; ")})`}Ki();qe();un();mn();function Yi(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
2131
2131
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
2132
|
-
Consulted ${
|
|
2133
|
-
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function
|
|
2134
|
-
`)}function ix(t){return`${t.teamfile}:${t.alias}`}As();var jh=256*1024,Wh=3e4;async function dc(t){let e=t.onEvent??(()=>{}),r=ox(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,d=null,u=t.prompt;try{let f=await G(r,k=>mt(t.teamfile,t.alias,k));if(t.expectedSession!==void 0&&(f.provider!==t.expectedSession.provider||f.sessionid!==t.expectedSession.sessionid))throw new ye(`session changed for ${f.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${f.provider}:${f.sessionid}`);let p=f.teamfile,_=await G(r,k=>_x(k,t.env??process.env)),E=_.sender,m=await yx(r,{explicitRoot:t.rootFlag,sender:E,receiverTeamfile:p,operatorOrigin:_.origin==="operator"}),h=E===null?null:await Ex(r,{rootTeamfile:m,sender:E,receiverTeamfile:p,receiverAlias:f.alias});h!==null&&!h.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${h.reason}
|
|
2135
|
-
`});let T=t.env??process.env,g=await G(r,k=>k.getRootTeam(m)?.name??null);g!==null&&(T.LMBEE_TEAM_NAME=g),i=await dx(r,{receiverTeamfile:p,receiverAlias:f.alias,sender:E,rootTeamfile:m,provider:f.provider,model:f.model,sessionId:f.sessionid,cwd:f.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:Sr(T.LMCTL_INVOCATION_ID)}),o=px(r,i),i!==null&&(T.LMCTL_INVOCATION_ID=String(i));try{Ar(r,Xe(p),p)}catch{}n={root_teamfile:m,sender_teamfile:E?.teamfile??null,sender_alias:E?.alias??null,receiver_teamfile:p,receiver_alias:f.alias,receiver_provider:f.provider,receiver_session_id:f.sessionid,origin:_.origin,message_type:t.messageType??null,policy:h};let y=await qh(r,p,f.alias);if(y!==null){let k=Jn(y);return nr(i,n,t.prompt,k,"unavailable"),d=cc(k,null),{status:"busy",message:k,teamChatLogId:null}}let v=!1;if(t.heldLease!==void 0){let k=t.heldLease;if(!await G(r,O=>{let D=O.getAgentInflight(p,f.alias);return D===null||D.sender_teamfile!==k.row.sender_teamfile||D.sender_alias!==k.row.sender_alias||D.started_at!==k.row.started_at||D.holder_pid!==process.pid?!1:O.heartbeatAgentInflight(k.row,k.leaseId,new Date().toISOString())})){let O=`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 nr(i,n,t.prompt,O,"unavailable"),d=Vn(O,null),{status:"error",errorKind:"provider",message:O,teamChatLogId:null,messageId:null}}}else{let k=await ax(r,p,f.alias);if(k.busy){let x=await lx(r,p,f.alias);return x+=await cx(r,p,f.alias),nr(i,n,t.prompt,x,"unavailable"),d=cc(x,null),{status:"busy",message:x,teamChatLogId:null}}v=k.idleReclaim}if(E!==null&&E.teamfile!==p){let k=await G(r,x=>ff(x,{root:m,sender:E,receiverTeamfile:p,receiverAlias:f.alias,now:new Date}));if(k.stop){let x=pf(k.chain);return nr(i,n,t.prompt,x,"cycle"),d=Vn(x,null),{status:"error",errorKind:"cycle",message:x,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let k=await Sx(r,{receiver_teamfile:p,receiver_alias:f.alias,sender_teamfile:E?.teamfile??p,sender_alias:E?.alias??"operator",...v?{force:!0,reclaimReason:"session-idle"}:{}});if(!k.acquired){let x=Gh(p,f.alias,k.current);return x+=` ${oc(ic({holderPid:k.current.holder_pid,since:k.current.started_at}))}`,nr(i,n,t.prompt,x,"unavailable"),d=cc(x,null),{status:"busy",message:x,teamChatLogId:null}}s={row:k.lease,leaseId:k.leaseId},a=bs(x=>G(r,O=>O.heartbeatAgentInflight(s.row,s.leaseId,x)),{intervalMs:Wh,onError:x=>{ae()&&Le(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:x instanceof Error?x.message:String(x)}))}})}let b=await Uh({sender:E??{teamfile:p,alias:"operator"},receiver:{teamfile:p,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:E===null?"operator":`${E.teamfile}:${E.alias}`,io:r,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:k=>e({kind:"delta",chunk:k}),onProgress:k=>e({kind:"progress",alias:f.alias,event:k}),onPromptBuilt:async k=>{u=k,l===null&&(l=await bx(r,{...n,message:k}),l!==null&&(t.onAccepted?.(lt(l)),i!==null&&await mx(r,i,l))),i!==null&&await fx(r,i,k)}});u=b.prompt;let I=b.status==="stalled",A=b.status==="empty",S=null,w=I?`provider stalled${b.stalledAfterMs!==void 0?` after ${b.stalledAfterMs}ms`:""}`:A?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":b.status==="error"?b.error??b.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,N=I||A||b.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await Hh(r,l,{...n,message:u,response:b.receipt,status:N,error_detail:w}),c=!0,S=l):S=await xx(r,{...n,message:u,response:b.receipt,status:N,error_detail:w});let R=b.status!=="error"?b.warnings:void 0;if(I||A){let k=w;nr(i,n,u,k,"error"),d=Vn(k,S,b.receipt,R)}else d=hx(b.receipt,S,R);return{status:I?"stalled":A?"empty":"ok",replyText:b.receipt,wroteDelta:b.wroteDelta,teamChatLogId:S,messageId:S===null?null:lt(S),durationMs:b.durationMs}}catch(f){let p=f instanceof Error?f.message:String(f);return l!==null&&!c&&n!==null&&(await Hh(r,l,{...n,message:u,response:null,status:"error",error_detail:p}),c=!0),nr(i,n,u,p,"error"),d=Vn(p,l),{status:"error",errorKind:f instanceof ye?"target":"provider",message:p,teamChatLogId:l,messageId:l===null?null:lt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await Ix(r,n,lt(l)),s!==null&&await vx(r,s.row,s.leaseId),i!==null&&await ux(r,i,d??Vn("chat turn exited without a terminal outcome",null))}}function ox(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function ax(t,e,r){let n=await G(t,i=>(Gs(i,e,r),Is(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await G(t,i=>Oh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function lx(t,e,r){let n=await qh(t,e,r);if(n!==null)return Jn(n);let s=await G(t,i=>i.getAgentInflight(e,r));return s!==null?Gh(e,r,s):`${r} is busy; wait and retry`}async function cx(t,e,r){let n=await G(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${oc(ic({holderPid:n.holder_pid,since:n.started_at}))}`}async function dx(t,e){try{return(await G(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:gx(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 ae()&&Le(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function ux(t,e,r){try{await G(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function fx(t,e,r){try{await G(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function mx(t,e,r){try{await G(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function px(t,e){if(e===null)return;let r=setInterval(()=>{G(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{ae()&&Le(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Wh);return r.unref?.(),r}function Xh(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function hx(t,e,r){return{status:"done",result_summary:Kn(t),error:null,team_chat_log_id:e,...Xh(r)}}function cc(t,e){return{status:"busy",result_summary:Kn(t),error:t,team_chat_log_id:e}}function Vn(t,e,r,n){return{status:"error",result_summary:Kn(r===void 0?t:r),error:t,team_chat_log_id:e,...Xh(n)}}function Kn(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function gx(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function _x(t,e){let r=Qi(e,t);if(r.ok)return{sender:Zi(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(zi("chat"))}async function yx(t,e){if(e.explicitRoot!==void 0)return await G(t,n=>Ze(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await G(t,n=>mf(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function Ex(t,e){return await G(t,r=>cf({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:Tx(r,e.sender.teamfile,e.receiverTeamfile)}))}function Tx(t,e,r){return{teams:[e,r].map(s=>wx(s,t))}}function wx(t,e){let r=xr(t,e),n=Ir(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function Sx(t,e){return await G(t,r=>{let n=ae(),s=hr(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:Rt(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Le(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:Bh(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Le(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:Bh(s.current)})),{acquired:!1,current:s.current})})}async function qh(t,e,r){return await G(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(ac(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:ac(s).live?s:null})}function Bh(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 vx(t,e,r){try{await G(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)}
|
|
2136
|
-
`)}}function
|
|
2137
|
-
`)
|
|
2138
|
-
`)}}async function
|
|
2139
|
-
`)}}async function xx(t,e){let r=Yn(e.message),n=e.response===null?null:Yn(e.response);try{return await G(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)}
|
|
2140
|
-
`),null}}function nr(t,e,r,n,s){t!==null||e===null||M({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:Kn(r)})}function Yn(t){return t.length<=jh?{text:t,truncated:!1}:{text:t.slice(0,jh),truncated:!0}}Yt();ft();import{createHash as Nk}from"node:crypto";import{accessSync as Rk,constants as Ng,existsSync as Lk,readFileSync as Ic,realpathSync as xc,statSync as Ck,writeFileSync as Rg}from"node:fs";import{dirname as lr,resolve as Lg}from"node:path";import{spawnSync as Sc}from"node:child_process";import{existsSync as Tg,readFileSync as wg}from"node:fs";import{homedir as Sg}from"node:os";import{resolve as Tc}from"node:path";import{mkdirSync as eg,readFileSync as kx,renameSync as Ax,writeFileSync as Nx,existsSync as tg}from"node:fs";import{homedir as Rx}from"node:os";import{dirname as rg,join as eo,resolve as to}from"node:path";import{fileURLToPath as Lx}from"node:url";var Cx="https://lmctl.com/dataset/model_list.json",Ox="https://lmctl.com/dataset/aliases.json",Dx=1e3,Mx=1e4,Jh=6*60*60*1e3;function Fx(){return eo(Rx(),".lmctl","cache","lmprice")}var fc="model_list.json",mc="aliases.json",ng="meta.json",Px="model_list.meta.json";function qr(t,e){return eo(t,e)}function sr(t){try{return JSON.parse(kx(t,"utf-8"))}catch{return null}}function sg(t,e){let r=`${t}.tmp-${process.pid}`;Nx(r,e),Ax(r,t)}function uc(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 uc(s.input_per_1m_tokens)&&uc(s.output_per_1m_tokens)&&uc(s.input_cache_read_per_1m_tokens)})}var $x=new Set(["established","asserted","unresolved"]);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"&&$x.has(i.evidence)});return r&&n}function Ux(t){let e=sr(qr(t,ng)),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=sr(qr(t,Px));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 jx(t){let e=Ux(t),r=sr(qr(t,fc)),n=sr(qr(t,mc));return{catalog:ro(r)?r:null,aliases:no(n)?n:null,meta:e}}function Bx(t,e){try{eg(t,{recursive:!0}),sg(qr(t,ng),JSON.stringify(e))}catch{}}function Vh(t,e,r){try{eg(t,{recursive:!0}),sg(qr(t,e),JSON.stringify(r))}catch{}}function Hx(t,e){let r=Wx(t),n=r?[to(r,"data",e)]:[to(t,"..","..","data",e)];for(let s of n)if(tg(s))return s;return null}function Wx(t){let e=to(t);for(;;){if(tg(to(e,"package.json")))return e;let r=rg(e);if(r===e)return null;e=r}}function Kh(t,e,r){let n=r!==void 0?r:Hx(t,e);return n===null?null:sr(n)}function Xx(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Jh;let e=Number(t);return!Number.isFinite(e)||e<0?Jh:e*1e3}function qx(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function Yh(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(Dx)});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(Mx)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}var pc=null;var zh=null;function ig(t={}){return Object.keys(t).length===0?(zh??=Qh(t),zh):Qh(t)}async function Qh(t){let e=rg(Lx(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:qx();if(r!==null&&r!==""){let _=sr(eo(r,fc)),E=sr(eo(r,mc));if(ro(_)&&no(E)){let m={catalog:_,aliases:E,source:"pinned",generatedAt:_.generated_at??null};return pc=m.generatedAt,m}return Zh(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??Fx(),i=t.now??Date.now(),o=t.ttlMs??Xx(),a=jx(s),l=(_,E)=>_!==null&&E.last_checked!==null&&i-Date.parse(E.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,f={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},p=!1;if(!l(c,a.meta.model_list)){let _=await Yh(n,Cx,c,a.meta.model_list.etag);_.kind==="match"?(f.model_list.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(f.model_list.last_checked=new Date(i).toISOString(),p=!0,ro(_.payload)&&(c=_.payload,_.etag!==null&&(f.model_list.etag=_.etag),Vh(s,fc,c),u=!0))}if(!l(d,a.meta.aliases)){let _=await Yh(n,Ox,d,a.meta.aliases.etag);_.kind==="match"?(f.aliases.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(f.aliases.last_checked=new Date(i).toISOString(),p=!0,no(_.payload)&&(d=_.payload,_.etag!==null&&(f.aliases.etag=_.etag),Vh(s,mc,d),u=!0))}if((p||u)&&Bx(s,f),c!==null||d!==null){let _={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return pc=_.generatedAt,_}return Zh(t,e)}function Zh(t,e){let r=Kh(e,"price-data.json",t.bundledPath),n=Kh(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 pc=o.generatedAt,o}function or(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function ir(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return or(r)}function ag(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(or(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function Gx(t,e){let r=new Set,n=l=>{r.add(or(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 Gr(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=>Gx(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=ag(n);return s.some(o=>i.has(o))}}}var lg=Gr({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),cg=Gr({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)(-|$)/}),dg=Gr({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),ug=Gr({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),fg=Gr({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),mg=Gr({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),Jx=/\s*\(([^()]+)\)\s*$/;function Vx(t){let e=t.trim(),r=Jx.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}var Kx={"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"},Yx=["gemini","google","vertex_ai-language-models","anthropic"],zx={normalize(t){let{model:e}=Vx(t),r=Kx[e.toLowerCase()];return r===void 0?[]:[or(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=ag(t);return e.some(n=>r.has(n))}},zn={claude:lg,codex:cg,gemini:dg,agy:zx,kimi:ug,qwen:fg,hermes:mg},og={claude:lg.firstPartyProviders,codex:cg.firstPartyProviders,gemini:dg.firstPartyProviders,agy:Yx,kimi:ug.firstPartyProviders,qwen:fg.firstPartyProviders,hermes:mg.firstPartyProviders};function Qx(t,e,r){let n=e.trim().toLowerCase(),s=or(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 Zx(t,e,r){let n=[];for(let[s,i]of Object.entries(zn))s!==r&&Qx(i,t,e)&&n.push(s);return n}function so(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function ek(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 tk(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}${or(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!ek(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 rk(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 pg(t,e){return t.map(rk).sort((r,n)=>{let s=so(r.source)-so(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 nk(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function sk(t,e,r){let n=tk(t),s=pg(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 hc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=sk(t,e,r),s=n.offers.find(nk);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}var gc=[];function ik(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function ok(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=ir(i),a=r.records.filter(l=>ir(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:hc(a,o,gc)}function ak(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=[e.trim().toLowerCase()];E.push(`${t.toLowerCase()}/${E[0]}`);let m=n.aliases.find(h=>E.includes(h.alias.toLowerCase()));if(m){if(m.evidence==="unresolved"||m.standard_slug===null)return{state:{kind:"unresolved",alias:m.alias},viaAlias:!0,pinRoute:null};let h=ik(n,m.standard_slug);return{state:ok(m,h,r),viaAlias:!0,pinRoute:h?.catalog_record_id?.toLowerCase()??null}}}let s=zn[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=E=>({state:E,viaAlias:!1,pinRoute:null}),l=or(i),c=r.records.filter(E=>E.source_model_id.toLowerCase()===i&&s.matchRow(E,[l]));if(c.length>0){let E=ir(c[0]),m=r.records.filter(h=>s.matchRow(h,[E])&&ir(h)===E);return a(hc(m.length>0?m:c,E,og[t]??gc))}let d=r.records.filter(E=>s.matchRow(E,o));if(d.length===0){let E=Zx(e,r,t);return E.length>0?a({kind:"wrong-provider",declared:e,otherProviders:E}):a({kind:"unknown",declared:e})}let u=new Map;for(let E of d){let m=ir(E),h=u.get(m);h?h.push(E):u.set(m,[E])}let f=og[t]??gc,p=null,_=null;for(let E of u.values()){let m=pg(E,f);(_===null||lk(m[0],_[0],f)<0)&&(p=E,_=m)}return a(hc(p,ir(p[0]),f))}function hg(t,e,r,n){return ak(t,e,r,n).state}function gg(t,e){let r=zn[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(ir(s));return n.size}function lk(t,e,r){let n=so(t.source)-so(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 vg=new Set(Object.keys(zn).filter(t=>t!=="codex"&&t!=="kimi")),ck=/\d\.(?=\d)/,_g=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],yg=["deepseek-flash","deepseek-pro"],Eg="gpt-5.3-codex-spark",dk=15e3;function Jr(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 uk(){let t=Sc("agy",["models"],{encoding:"utf-8",timeout:dk});return{status:t.status,stdout:t.stdout??"",error:t.error}}var _c=null;function fk(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 mk(t){if(!t&&_c)return _c;let e=s=>(t||(_c=s),s),r;try{r=(t??uk)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Jr("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Jr("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=fk(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}var pk=5e3;function hk(){let t=Sc("codex",["debug","models"],{encoding:"utf-8",timeout:pk});return{status:t.status,stdout:t.stdout??"",error:t.error}}var yc=null;function gk(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 _k(t){if(!t&&yc)return yc;let e=s=>(t||(yc=s),s),r;try{r=(t??hk)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Jr("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Jr("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=gk(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}var yk=5e3;function Ek(t){let e=Sc("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:yk});return{status:e.status,stdout:e.stdout??"",error:e.error}}var Ec=new Map;function Tk(t,e){if(!e&&Ec.has(t))return Ec.get(t);let r=o=>(e||Ec.set(t,o),o),n=t?`opencode models ${t}`:"opencode models",s;try{s=(e??Ek)(t)}catch(o){return r({available:!1,models:[],reason:o instanceof Error?Jr(n,o):`${n} could not be run: ${String(o)}`})}if(s.error)return r({available:!1,models:[],reason:Jr(n,s.error)});if(s.status!==0)return r({available:!1,models:[],reason:`${n} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?r({available:!1,models:[],reason:`${n} returned no models`}):r({available:!0,models:i})}function vc(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&s!=="muse"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model)continue;let i=vk(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=Tk(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=wk(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: ${Qn(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=mk(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: ${Qn(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||yg.includes(n.model))continue;_g.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Qn(_g)}. 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): ${Qn(yg)}. 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===Eg&&r.push(`[${n.alias}] model="${Eg}" 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=_k(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: ${Qn(i.models)}`);continue}n.model&&(vg.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 bg(t,e={}){let r=t.filter(o=>o.model!==void 0&&vg.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await ig();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=hg(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=gg(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")&&ck.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 Ig(t,e={}){return(await bg(t,e)).warnings}async function xg(t,e={}){return(await bg(t,e)).errors}function wk(t){let e=process.env.KIMI_CODE_HOME||Tc(Sg(),".kimi-code"),r=t??Tc(e,"config.toml");if(!Tg(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=wg(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=Sk(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 Sk(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 vk(t){let e=t??Tc(Sg(),".config","opencode","opencode.json");if(!Tg(e))return{available:!0,models:[]};let r;try{r=JSON.parse(wg(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:bk(r)}}function bk(t){if(!wc(t))return[];let e=io(t.provider)??io(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!wc(s))continue;let i=io(s.models)??io(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function io(t){return wc(t)?t:null}function wc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Qn(t){return t.length>0?t.join(", "):"(none)"}Na();Ua();Ki();Kt();gn();ft();import{homedir as Ik}from"node:os";var xk={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>hn(t.teamfile),home:()=>Ik(),date:t=>t.date},kk=/{{\s*([A-Za-z0-9_-]+)\s*}}/g;function kg(t,e){let r=new Set;return{text:t.replace(kk,(s,i)=>{let o=i.trim(),a=xk[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function Ag(t){return{workdir:t.workdir,teamfile:t.teamfile,date:Ak(t.date)}}function Ak(t){return t.toISOString().slice(0,10)}Xs();ea();Ee();var Zn=5;var Ok={existsSync:Lk,statSync:Ck,accessSync:Rk},Dk=async t=>{let{seed:e}=await Promise.resolve().then(()=>(Gn(),kh)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Vr=Ok,Mk=Ei,Cg,Og,oo;function Dg(t){return Ig(t,oo!==void 0?{snapshot:oo}:{})}function Mg(t){return xg(t,oo!==void 0?{snapshot:oo}:{})}async function Fk(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 Mk({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 Pk(t,e){let r=lr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=Lg(o);if(n.has(a))continue;let l=$k(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 $k(t){try{if(Vr.existsSync(t)){if(!Vr.statSync(t).isDirectory())return"ENOTDIR";Vr.accessSync(t,Ng.W_OK);return}let e=jk(t);if(e===void 0)return;if(!Vr.statSync(e).isDirectory())return"ENOTDIR";Vr.accessSync(e,Ng.W_OK);return}catch(e){return Bk(e)??"permission check failed"}}function Uk(t){let e=Lg(t);try{return xc(e)}catch{return e}}function jk(t){let e=t;for(;;){try{if(Vr.existsSync(e))return e}catch{return}let r=lr(e);if(r===e)return;e=r}}function Bk(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 Hk(t,e){let r;try{r=await G(e,l=>Ze(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=Xe(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=Vo(n,lr(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2141
|
-
`);let
|
|
2142
|
-
`);for(let l of n.members)kc([l],e),l.session!==void 0&&l.session.length<Zn&&i.push(`${l.alias}: sessionid is shorter than ${Zn} chars; run lmctl seed to refresh it`);return{ok:!0,result:{config:n,absTeamfile:r,errors:s,warnings:i}}}var Wk=/^\[([^\]]+)\]\s+(.*)$/s,Xk=/^([^:\s][^:]*):\s+(.*)$/s;function qk(t,e){let r=Wk.exec(t);if(r){let s=e.get(r[1].toLowerCase());if(s!==void 0)return{alias:s,message:r[2]}}let n=Xk.exec(t);if(n){let s=e.get(n[1].toLowerCase());if(s!==void 0)return{alias:s,message:n[2]}}return{alias:"",message:t}}async function Fg(t,e){let r=await Hk(t,e);if(!r.ok)return{status:"error",errors:[{alias:"",message:r.message}],warnings:[],counts:{errors:1,warnings:0}};let{config:n,errors:s,warnings:i}=r.result,o=new Map(n.members.map(c=>[c.alias.toLowerCase(),c.alias])),a=s.map(c=>({alias:o.get(c.field.toLowerCase())??"",message:c.message})),l=i.map(c=>qk(c,o));for(let c of l)e.stderr.write(`warning: ${c.alias?`${c.alias}: `:""}${c.message}
|
|
2132
|
+
Consulted ${xu(dt())}
|
|
2133
|
+
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function zi(t,e){let r=zI(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function zI(t,e){let r=t[aa];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=Ps(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]}}Yt();function Qi(t){let e=Us(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}Wn();re();Er();un();Xt();qt();var h1=60*60*1e3,QI=2e3,ZI=5e3;function ac(t,e,r){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=Jt({path:dt()})),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&&ve(a.holder_pid)),pollMs:QI,settleMs:ZI,maxHoldMs:gr(r),onHold:()=>D({event:"delivery_hold_open_started",receiver:n}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&D({event:"delivery_hold_open_released",receiver:n,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function Mh(t){let e=ex(t.newMessage,{newMessageFrom:t.newMessageFrom??tx(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=ae(),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=ac(t.io,t.receiver,t.env),await t.onPromptBuilt?.(e);let l=await Hn(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&&Le(JSON.stringify({event:"chat_return",alias:t.receiver.alias,provider:t.receiver.provider,streamed:r,blockCount:s,streamedBytes:i,resultTextBytes:Buffer.byteLength(l.text,"utf8"),lastChunkBytes:o,tailPreview:l.text.slice(-200)})),l.status==="stalled"?{status:"stalled",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,stalledAfterMs:l.stalledAfterMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:l.status==="empty"?{status:"empty",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:{status:"ok",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function ex(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
2134
|
+
`)}function tx(t){return`${t.teamfile}:${t.alias}`}Is();var Fh=256*1024,Uh=3e4;async function cc(t){let e=t.onEvent??(()=>{}),r=rx(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,d=null,u=t.prompt;try{let f=await G(r,A=>mt(t.teamfile,t.alias,A));if(t.expectedSession!==void 0&&(f.provider!==t.expectedSession.provider||f.sessionid!==t.expectedSession.sessionid))throw new ye(`session changed for ${f.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${f.provider}:${f.sessionid}`);let p=f.teamfile,_=await G(r,A=>mx(A,t.env??process.env)),E=_.sender,m=await px(r,{explicitRoot:t.rootFlag,sender:E,receiverTeamfile:p,operatorOrigin:_.origin==="operator"}),h=t.env??process.env,T=await G(r,A=>A.getRootTeam(m)?.name??null);T!==null&&(h.LMBEE_TEAM_NAME=T),i=await ox(r,{receiverTeamfile:p,receiverAlias:f.alias,sender:E,rootTeamfile:m,provider:f.provider,model:f.model,sessionId:f.sessionid,cwd:f.sessiondir,prompt:t.prompt,origin:_.origin,parentInvocationId:Sr(h.LMCTL_INVOCATION_ID)}),o=dx(r,i),i!==null&&(h.LMCTL_INVOCATION_ID=String(i));try{xr(r,Xe(p),p)}catch{}n={root_teamfile:m,sender_teamfile:E?.teamfile??null,sender_alias:E?.alias??null,receiver_teamfile:p,receiver_alias:f.alias,receiver_provider:f.provider,receiver_session_id:f.sessionid,origin:_.origin,message_type:t.messageType??null};let g=await Bh(r,p,f.alias);if(g!==null){let A=Xn(g);return nr(i,n,t.prompt,A,"unavailable"),d=lc(A,null),{status:"busy",message:A,teamChatLogId:null}}let y=!1;if(t.heldLease!==void 0){let A=t.heldLease;if(!await G(r,x=>{let O=x.getAgentInflight(p,f.alias);return O===null||O.sender_teamfile!==A.row.sender_teamfile||O.sender_alias!==A.row.sender_alias||O.started_at!==A.row.started_at||O.holder_pid!==process.pid?!1:x.heartbeatAgentInflight(A.row,A.leaseId,new Date().toISOString())})){let x=`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 nr(i,n,t.prompt,x,"unavailable"),d=qn(x,null),{status:"error",errorKind:"provider",message:x,teamChatLogId:null,messageId:null}}}else{let A=await nx(r,p,f.alias);if(A.busy){let R=await sx(r,p,f.alias);return R+=await ix(r,p,f.alias),nr(i,n,t.prompt,R,"unavailable"),d=lc(R,null),{status:"busy",message:R,teamChatLogId:null}}y=A.idleReclaim}if(E!==null&&E.teamfile!==p){let A=await G(r,R=>lf(R,{root:m,sender:E,receiverTeamfile:p,receiverAlias:f.alias,now:new Date}));if(A.stop){let R=df(A.chain);return nr(i,n,t.prompt,R,"cycle"),d=qn(R,null),{status:"error",errorKind:"cycle",message:R,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let A=await hx(r,{receiver_teamfile:p,receiver_alias:f.alias,sender_teamfile:E?.teamfile??p,sender_alias:E?.alias??"operator",...y?{force:!0,reclaimReason:"session-idle"}:{}});if(!A.acquired){let R=Hh(p,f.alias,A.current);return R+=` ${ic(sc({holderPid:A.current.holder_pid,since:A.current.started_at}))}`,nr(i,n,t.prompt,R,"unavailable"),d=lc(R,null),{status:"busy",message:R,teamChatLogId:null}}s={row:A.lease,leaseId:A.leaseId},a=ws(R=>G(r,x=>x.heartbeatAgentInflight(s.row,s.leaseId,R)),{intervalMs:Uh,onError:R=>{ae()&&Le(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:R instanceof Error?R.message:String(R)}))}})}let S=await Mh({sender:E??{teamfile:p,alias:"operator"},receiver:{teamfile:p,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:E===null?"operator":`${E.teamfile}:${E.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:A=>e({kind:"delta",chunk:A}),onProgress:A=>e({kind:"progress",alias:f.alias,event:A}),onPromptBuilt:async A=>{u=A,l===null&&(l=await _x(r,{...n,message:A}),l!==null&&(t.onAccepted?.(lt(l)),i!==null&&await cx(r,i,l))),i!==null&&await lx(r,i,A)}});u=S.prompt;let I=S.status==="stalled",b=S.status==="empty",k=null,v=I?`provider stalled${S.stalledAfterMs!==void 0?` after ${S.stalledAfterMs}ms`:""}`:b?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":S.status==="error"?S.error??S.receipt:null,w=I||b||S.status==="error"?"error":"ok";l!==null?(await $h(r,l,{...n,message:u,response:S.receipt,status:w,error_detail:v}),c=!0,k=l):k=await Ex(r,{...n,message:u,response:S.receipt,status:w,error_detail:v});let N=S.status!=="error"?S.warnings:void 0;if(I||b){let A=v;nr(i,n,u,A,"error"),d=qn(A,k,S.receipt,N)}else d=ux(S.receipt,k,N);return{status:I?"stalled":b?"empty":"ok",replyText:S.receipt,wroteDelta:S.wroteDelta,teamChatLogId:k,messageId:k===null?null:lt(k),durationMs:S.durationMs}}catch(f){let p=f instanceof Error?f.message:String(f);return l!==null&&!c&&n!==null&&(await $h(r,l,{...n,message:u,response:null,status:"error",error_detail:p}),c=!0),nr(i,n,u,p,"error"),d=qn(p,l),{status:"error",errorKind:f instanceof ye?"target":"provider",message:p,teamChatLogId:l,messageId:l===null?null:lt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await yx(r,n,lt(l)),s!==null&&await gx(r,s.row,s.leaseId),i!==null&&await ax(r,i,d??qn("chat turn exited without a terminal outcome",null))}}function rx(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function nx(t,e,r){let n=await G(t,i=>(qs(i,e,r),Ss(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await G(t,i=>Nh(i,n,e,r));return{busy:!s,idleReclaim:s}}async function sx(t,e,r){let n=await Bh(t,e,r);if(n!==null)return Xn(n);let s=await G(t,i=>i.getAgentInflight(e,r));return s!==null?Hh(e,r,s):`${r} is busy; wait and retry`}async function ix(t,e,r){let n=await G(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${ic(sc({holderPid:n.holder_pid,since:n.started_at}))}`}async function ox(t,e){try{return(await G(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:fx(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 ae()&&Le(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function ax(t,e,r){try{await G(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function lx(t,e,r){try{await G(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function cx(t,e,r){try{await G(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){ae()&&Le(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function dx(t,e){if(e===null)return;let r=setInterval(()=>{G(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{ae()&&Le(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Uh);return r.unref?.(),r}function jh(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function ux(t,e,r){return{status:"done",result_summary:Gn(t),error:null,team_chat_log_id:e,...jh(r)}}function lc(t,e){return{status:"busy",result_summary:Gn(t),error:t,team_chat_log_id:e}}function qn(t,e,r,n){return{status:"error",result_summary:Gn(r===void 0?t:r),error:t,team_chat_log_id:e,...jh(n)}}function Gn(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function fx(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function mx(t,e){let r=zi(e,t);if(r.ok)return{sender:Qi(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Yi("chat"))}async function px(t,e){if(e.explicitRoot!==void 0)return await G(t,n=>Ze(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await G(t,n=>cf(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function hx(t,e){return await G(t,r=>{let n=ae(),s=hr(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:Rt(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Le(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:Ph(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Le(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:Ph(s.current)})),{acquired:!1,current:s.current})})}async function Bh(t,e,r){return await G(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(oc(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:oc(s).live?s:null})}function Ph(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 gx(t,e,r){try{await G(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)}
|
|
2135
|
+
`)}}function Hh(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 _x(t,e){let r=Jn(e.message);try{return await G(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)}
|
|
2136
|
+
`),null}}async function $h(t,e,r){let n=Jn(r.message),s=r.response===null?null:Jn(r.response);try{await G(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)}
|
|
2137
|
+
`)}}async function yx(t,e,r){if(e!==null)try{await G(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)}
|
|
2138
|
+
`)}}async function Ex(t,e){let r=Jn(e.message),n=e.response===null?null:Jn(e.response);try{return await G(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)}
|
|
2139
|
+
`),null}}function nr(t,e,r,n,s){t!==null||e===null||D({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:Gn(r)})}function Jn(t){return t.length<=Fh?{text:t,truncated:!1}:{text:t.slice(0,Fh),truncated:!0}}Yt();ft();import{createHash as Sk}from"node:crypto";import{accessSync as vk,constants as Ig,existsSync as bk,readFileSync as bc,realpathSync as Ic,statSync as Ik,writeFileSync as xg}from"node:fs";import{dirname as lr,resolve as kg}from"node:path";import{spawnSync as wc}from"node:child_process";import{existsSync as gg,readFileSync as _g}from"node:fs";import{homedir as yg}from"node:os";import{resolve as Ec}from"node:path";import{mkdirSync as Yh,readFileSync as Tx,renameSync as wx,writeFileSync as Sx,existsSync as zh}from"node:fs";import{homedir as vx}from"node:os";import{dirname as Qh,join as Zi,resolve as eo}from"node:path";import{fileURLToPath as bx}from"node:url";var Ix="https://lmctl.com/dataset/model_list.json",xx="https://lmctl.com/dataset/aliases.json",kx=1e3,Ax=1e4,Wh=6*60*60*1e3;function Nx(){return Zi(vx(),".lmctl","cache","lmprice")}var uc="model_list.json",fc="aliases.json",Zh="meta.json",Rx="model_list.meta.json";function Hr(t,e){return Zi(t,e)}function sr(t){try{return JSON.parse(Tx(t,"utf-8"))}catch{return null}}function eg(t,e){let r=`${t}.tmp-${process.pid}`;Sx(r,e),wx(r,t)}function dc(t){return t===null||typeof t=="number"}function to(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)})}var Lx=new Set(["established","asserted","unresolved"]);function ro(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"&&Lx.has(i.evidence)});return r&&n}function Cx(t){let e=sr(Hr(t,Zh)),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=sr(Hr(t,Rx));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 Ox(t){let e=Cx(t),r=sr(Hr(t,uc)),n=sr(Hr(t,fc));return{catalog:to(r)?r:null,aliases:ro(n)?n:null,meta:e}}function Dx(t,e){try{Yh(t,{recursive:!0}),eg(Hr(t,Zh),JSON.stringify(e))}catch{}}function Xh(t,e,r){try{Yh(t,{recursive:!0}),eg(Hr(t,e),JSON.stringify(r))}catch{}}function Mx(t,e){let r=Fx(t),n=r?[eo(r,"data",e)]:[eo(t,"..","..","data",e)];for(let s of n)if(zh(s))return s;return null}function Fx(t){let e=eo(t);for(;;){if(zh(eo(e,"package.json")))return e;let r=Qh(e);if(r===e)return null;e=r}}function qh(t,e,r){let n=r!==void 0?r:Mx(t,e);return n===null?null:sr(n)}function Px(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Wh;let e=Number(t);return!Number.isFinite(e)||e<0?Wh:e*1e3}function $x(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function Gh(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(kx)});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(Ax)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}var mc=null;var Jh=null;function tg(t={}){return Object.keys(t).length===0?(Jh??=Vh(t),Jh):Vh(t)}async function Vh(t){let e=Qh(bx(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:$x();if(r!==null&&r!==""){let _=sr(Zi(r,uc)),E=sr(Zi(r,fc));if(to(_)&&ro(E)){let m={catalog:_,aliases:E,source:"pinned",generatedAt:_.generated_at??null};return mc=m.generatedAt,m}return Kh(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??Nx(),i=t.now??Date.now(),o=t.ttlMs??Px(),a=Ox(s),l=(_,E)=>_!==null&&E.last_checked!==null&&i-Date.parse(E.last_checked)<o,c=a.catalog,d=a.aliases,u=!1,f={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},p=!1;if(!l(c,a.meta.model_list)){let _=await Gh(n,Ix,c,a.meta.model_list.etag);_.kind==="match"?(f.model_list.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(f.model_list.last_checked=new Date(i).toISOString(),p=!0,to(_.payload)&&(c=_.payload,_.etag!==null&&(f.model_list.etag=_.etag),Xh(s,uc,c),u=!0))}if(!l(d,a.meta.aliases)){let _=await Gh(n,xx,d,a.meta.aliases.etag);_.kind==="match"?(f.aliases.last_checked=new Date(i).toISOString(),p=!0):_.kind==="payload"&&(f.aliases.last_checked=new Date(i).toISOString(),p=!0,ro(_.payload)&&(d=_.payload,_.etag!==null&&(f.aliases.etag=_.etag),Xh(s,fc,d),u=!0))}if((p||u)&&Dx(s,f),c!==null||d!==null){let _={catalog:c,aliases:d,source:u?"network":"cache",generatedAt:c?.generated_at??null};return mc=_.generatedAt,_}return Kh(t,e)}function Kh(t,e){let r=qh(e,"price-data.json",t.bundledPath),n=qh(e,"price-aliases.json",t.bundledAliasesPath),s=to(r)?r:null,i=ro(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return mc=o.generatedAt,o}function or(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function ir(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return or(r)}function ng(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(or(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function Ux(t,e){let r=new Set,n=l=>{r.add(or(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 Wr(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=>Ux(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=ng(n);return s.some(o=>i.has(o))}}}var sg=Wr({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),ig=Wr({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)(-|$)/}),og=Wr({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),ag=Wr({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),lg=Wr({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),cg=Wr({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),jx=/\s*\(([^()]+)\)\s*$/;function Bx(t){let e=t.trim(),r=jx.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}var Hx={"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"},Wx=["gemini","google","vertex_ai-language-models","anthropic"],Xx={normalize(t){let{model:e}=Bx(t),r=Hx[e.toLowerCase()];return r===void 0?[]:[or(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=ng(t);return e.some(n=>r.has(n))}},Vn={claude:sg,codex:ig,gemini:og,agy:Xx,kimi:ag,qwen:lg,hermes:cg},rg={claude:sg.firstPartyProviders,codex:ig.firstPartyProviders,gemini:og.firstPartyProviders,agy:Wx,kimi:ag.firstPartyProviders,qwen:lg.firstPartyProviders,hermes:cg.firstPartyProviders};function qx(t,e,r){let n=e.trim().toLowerCase(),s=or(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 Gx(t,e,r){let n=[];for(let[s,i]of Object.entries(Vn))s!==r&&qx(i,t,e)&&n.push(s);return n}function no(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function Jx(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 Vx(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}${or(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!Jx(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 Kx(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 dg(t,e){return t.map(Kx).sort((r,n)=>{let s=no(r.source)-no(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 Yx(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function zx(t,e,r){let n=Vx(t),s=dg(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 pc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=zx(t,e,r),s=n.offers.find(Yx);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}var hc=[];function Qx(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function Zx(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=ir(i),a=r.records.filter(l=>ir(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:pc(a,o,hc)}function ek(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=[e.trim().toLowerCase()];E.push(`${t.toLowerCase()}/${E[0]}`);let m=n.aliases.find(h=>E.includes(h.alias.toLowerCase()));if(m){if(m.evidence==="unresolved"||m.standard_slug===null)return{state:{kind:"unresolved",alias:m.alias},viaAlias:!0,pinRoute:null};let h=Qx(n,m.standard_slug);return{state:Zx(m,h,r),viaAlias:!0,pinRoute:h?.catalog_record_id?.toLowerCase()??null}}}let s=Vn[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=E=>({state:E,viaAlias:!1,pinRoute:null}),l=or(i),c=r.records.filter(E=>E.source_model_id.toLowerCase()===i&&s.matchRow(E,[l]));if(c.length>0){let E=ir(c[0]),m=r.records.filter(h=>s.matchRow(h,[E])&&ir(h)===E);return a(pc(m.length>0?m:c,E,rg[t]??hc))}let d=r.records.filter(E=>s.matchRow(E,o));if(d.length===0){let E=Gx(e,r,t);return E.length>0?a({kind:"wrong-provider",declared:e,otherProviders:E}):a({kind:"unknown",declared:e})}let u=new Map;for(let E of d){let m=ir(E),h=u.get(m);h?h.push(E):u.set(m,[E])}let f=rg[t]??hc,p=null,_=null;for(let E of u.values()){let m=dg(E,f);(_===null||tk(m[0],_[0],f)<0)&&(p=E,_=m)}return a(pc(p,ir(p[0]),f))}function ug(t,e,r,n){return ek(t,e,r,n).state}function fg(t,e){let r=Vn[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(ir(s));return n.size}function tk(t,e,r){let n=no(t.source)-no(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 Eg=new Set(Object.keys(Vn).filter(t=>t!=="codex"&&t!=="kimi")),rk=/\d\.(?=\d)/,mg=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],pg=["deepseek-flash","deepseek-pro"],hg="gpt-5.3-codex-spark",nk=15e3;function Xr(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 sk(){let t=wc("agy",["models"],{encoding:"utf-8",timeout:nk});return{status:t.status,stdout:t.stdout??"",error:t.error}}var gc=null;function ik(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 ok(t){if(!t&&gc)return gc;let e=s=>(t||(gc=s),s),r;try{r=(t??sk)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Xr("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Xr("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=ik(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}var ak=5e3;function lk(){let t=wc("codex",["debug","models"],{encoding:"utf-8",timeout:ak});return{status:t.status,stdout:t.stdout??"",error:t.error}}var _c=null;function ck(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 dk(t){if(!t&&_c)return _c;let e=s=>(t||(_c=s),s),r;try{r=(t??lk)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?Xr("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:Xr("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=ck(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}var uk=5e3;function fk(t){let e=wc("opencode",t?["models",t]:["models"],{encoding:"utf-8",timeout:uk});return{status:e.status,stdout:e.stdout??"",error:e.error}}var yc=new Map;function mk(t,e){if(!e&&yc.has(t))return yc.get(t);let r=o=>(e||yc.set(t,o),o),n=t?`opencode models ${t}`:"opencode models",s;try{s=(e??fk)(t)}catch(o){return r({available:!1,models:[],reason:o instanceof Error?Xr(n,o):`${n} could not be run: ${String(o)}`})}if(s.error)return r({available:!1,models:[],reason:Xr(n,s.error)});if(s.status!==0)return r({available:!1,models:[],reason:`${n} exited with status ${s.status??"unknown"}`});let i=s.stdout.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0);return i.length===0?r({available:!1,models:[],reason:`${n} returned no models`}):r({available:!0,models:i})}function Sc(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&s!=="muse"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model)continue;let i=gk(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=mk(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=pk(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: ${Kn(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=ok(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: ${Kn(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||pg.includes(n.model))continue;mg.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Kn(mg)}. 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): ${Kn(pg)}. 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===hg&&r.push(`[${n.alias}] model="${hg}" 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=dk(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: ${Kn(i.models)}`);continue}n.model&&(Eg.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 Tg(t,e={}){let r=t.filter(o=>o.model!==void 0&&Eg.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await tg();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=ug(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let d=fg(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")&&rk.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 wg(t,e={}){return(await Tg(t,e)).warnings}async function Sg(t,e={}){return(await Tg(t,e)).errors}function pk(t){let e=process.env.KIMI_CODE_HOME||Ec(yg(),".kimi-code"),r=t??Ec(e,"config.toml");if(!gg(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=_g(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=hk(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 hk(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 gk(t){let e=t??Ec(yg(),".config","opencode","opencode.json");if(!gg(e))return{available:!0,models:[]};let r;try{r=JSON.parse(_g(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:_k(r)}}function _k(t){if(!Tc(t))return[];let e=so(t.provider)??so(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Tc(s))continue;let i=so(s.models)??so(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function so(t){return Tc(t)?t:null}function Tc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Kn(t){return t.length>0?t.join(", "):"(none)"}Aa();$a();Vi();Kt();mn();ft();import{homedir as yk}from"node:os";var Ek={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>fn(t.teamfile),home:()=>yk(),date:t=>t.date},Tk=/{{\s*([A-Za-z0-9_-]+)\s*}}/g;function vg(t,e){let r=new Set;return{text:t.replace(Tk,(s,i)=>{let o=i.trim(),a=Ek[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function bg(t){return{workdir:t.workdir,teamfile:t.teamfile,date:wk(t.date)}}function wk(t){return t.toISOString().slice(0,10)}Ws();Zo();Ee();var Yn=5;var xk={existsSync:bk,statSync:Ik,accessSync:vk},kk=async t=>{let{seed:e}=await Promise.resolve().then(()=>(Wn(),vh)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},qr=xk,Ak=yi,Ag,Ng,io;function Rg(t){return wg(t,io!==void 0?{snapshot:io}:{})}function Lg(t){return Sg(t,io!==void 0?{snapshot:io}:{})}async function Nk(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 Ak({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 Rk(t,e){let r=lr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=kg(o);if(n.has(a))continue;let l=Lk(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 Lk(t){try{if(qr.existsSync(t)){if(!qr.statSync(t).isDirectory())return"ENOTDIR";qr.accessSync(t,Ig.W_OK);return}let e=Ok(t);if(e===void 0)return;if(!qr.statSync(e).isDirectory())return"ENOTDIR";qr.accessSync(e,Ig.W_OK);return}catch(e){return Dk(e)??"permission check failed"}}function Ck(t){let e=kg(t);try{return Ic(e)}catch{return e}}function Ok(t){let e=t;for(;;){try{if(qr.existsSync(e))return e}catch{return}let r=lr(e);if(r===e)return;e=r}}function Dk(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 Mk(t,e){let r;try{r=await G(e,l=>Ze(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=Xe(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=Jo(n,lr(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2140
|
+
`);let i=Sc(n.members,{agyModelsRunner:Ag,codexModelsRunner:Ng});i.push(...await Rg(n.members)),s.push(...await Lg(n.members));let o=bc(r,"utf8"),a=vg(o,bg({workdir:lr(r),teamfile:r,date:new Date})).unknownNames;a.length>0&&i.push(`unknown template placeholder${a.length===1?"":"s"}: ${a.map(l=>`{{${l}}}`).join(", ")}`),i.push(...ka(n.members,lr(r))),i.push(...Rk(n.members,r)),i.push(...await Nk(n.members,lr(r),e.env));for(let l of s)e.stderr.write(`error: ${l.field}: ${l.message}
|
|
2141
|
+
`);for(let l of n.members)xc([l],e),l.session!==void 0&&l.session.length<Yn&&i.push(`${l.alias}: sessionid is shorter than ${Yn} chars; run lmctl seed to refresh it`);return{ok:!0,result:{config:n,absTeamfile:r,errors:s,warnings:i}}}var Fk=/^\[([^\]]+)\]\s+(.*)$/s,Pk=/^([^:\s][^:]*):\s+(.*)$/s;function $k(t,e){let r=Fk.exec(t);if(r){let s=e.get(r[1].toLowerCase());if(s!==void 0)return{alias:s,message:r[2]}}let n=Pk.exec(t);if(n){let s=e.get(n[1].toLowerCase());if(s!==void 0)return{alias:s,message:n[2]}}return{alias:"",message:t}}async function Cg(t,e){let r=await Mk(t,e);if(!r.ok)return{status:"error",errors:[{alias:"",message:r.message}],warnings:[],counts:{errors:1,warnings:0}};let{config:n,errors:s,warnings:i}=r.result,o=new Map(n.members.map(c=>[c.alias.toLowerCase(),c.alias])),a=s.map(c=>({alias:o.get(c.field.toLowerCase())??"",message:c.message})),l=i.map(c=>$k(c,o));for(let c of l)e.stderr.write(`warning: ${c.alias?`${c.alias}: `:""}${c.message}
|
|
2143
2142
|
`);return e.stderr.write(`notice: ${a.length} error${a.length===1?"":"s"}, ${l.length} warning${l.length===1?"":"s"}
|
|
2144
|
-
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}function
|
|
2143
|
+
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}function Uk(t,e,r,n){if(e.preamble===void 0)return t.toLowerCase()!=="lead"?void 0:`${Y}
|
|
2145
2144
|
|
|
2146
2145
|
Teamfile ${r}:
|
|
2147
2146
|
${n}
|
|
2148
2147
|
|
|
2149
|
-
After this seed finishes, use \`lmctl prompt ${JSON.stringify(r)} <alias> "<message>"\` to send a message. Do not run or use lmctl prompt during this seed. Reply only with the ACK above and wait.`;if(typeof e.preamble=="string")return e.preamble;for(let[s,i]of Object.entries(e.preamble))if(s.toLowerCase()===t.toLowerCase())return i}async function
|
|
2150
|
-
`),c=a,d=
|
|
2151
|
-
`);return 1}try{
|
|
2152
|
-
`);for(let g of
|
|
2153
|
-
`);for(let g of await
|
|
2154
|
-
`);for(let g of
|
|
2155
|
-
`);let f=await
|
|
2156
|
-
`);return 1}let p=r.replaceSession;if(p){let g=o.members.find(y=>y.alias.toLowerCase()===p.alias.toLowerCase());if(!g||g.teamfile||g.session!==p.sessionid)return ar(e,"Session binding changed; refresh cancelled.")}let _=0,E=o.members.filter(g=>g.teamfile!==void 0?!1:p?g.alias.toLowerCase()===p.alias.toLowerCase():g.session===void 0||g.session.length<
|
|
2157
|
-
`),1;for(let g of o.members){if(g.teamfile!==void 0||p&&g.alias.toLowerCase()!==p.alias.toLowerCase())continue;if(!p&&g.session!==void 0&&g.session.length>=
|
|
2148
|
+
After this seed finishes, use \`lmctl prompt ${JSON.stringify(r)} <alias> "<message>"\` to send a message. Do not run or use lmctl prompt during this seed. Reply only with the ACK above and wait.`;if(typeof e.preamble=="string")return e.preamble;for(let[s,i]of Object.entries(e.preamble))if(s.toLowerCase()===t.toLowerCase())return i}async function Og(t,e,r={}){let n;try{n=await G(e,g=>Ze(t,g))}catch(g){return ar(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let s;try{s=Ic(n)}catch(g){return ar(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let i=lr(n),o;try{o=Xe(n)}catch(g){return ar(e,`${t}: ${g instanceof Error?g.message:String(g)}`)}let a=bc(n,"utf8"),l=a.split(`
|
|
2149
|
+
`),c=a,d=Wk(l),u=Jo(o,i);if(u.length>0){xc(o.members,e);for(let g of u)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2150
|
+
`);return 1}try{xr(e,o,n)}catch{}xc(o.members,e),e.stderr.write(`notice: checking teamfile and models ...
|
|
2151
|
+
`);for(let g of Sc(o.members,{agyModelsRunner:Ag,codexModelsRunner:Ng}))e.stderr.write(`warning: ${g}
|
|
2152
|
+
`);for(let g of await Rg(o.members))e.stderr.write(`warning: ${g}
|
|
2153
|
+
`);for(let g of ka(o.members,i))e.stderr.write(`warning: ${g}
|
|
2154
|
+
`);let f=await Lg(o.members);if(f.length>0){for(let g of f)e.stderr.write(`error: ${g.field}: ${g.message}
|
|
2155
|
+
`);return 1}let p=r.replaceSession;if(p){let g=o.members.find(y=>y.alias.toLowerCase()===p.alias.toLowerCase());if(!g||g.teamfile||g.session!==p.sessionid)return ar(e,"Session binding changed; refresh cancelled.")}let _=0,E=o.members.filter(g=>g.teamfile!==void 0?!1:p?g.alias.toLowerCase()===p.alias.toLowerCase():g.session===void 0||g.session.length<Yn);for(let g of E)if(!Jk(g.provider))return e.stderr.write(`error: ${g.alias}: invalid provider "${g.provider}"
|
|
2156
|
+
`),1;for(let g of o.members){if(g.teamfile!==void 0||p&&g.alias.toLowerCase()!==p.alias.toLowerCase())continue;if(!p&&g.session!==void 0&&g.session.length>=Yn){e.stderr.write(`warning: ${g.alias}: existing sessionid preserved; skipping
|
|
2158
2157
|
`);continue}let y=g.sessiondir??i;e.stderr.write(`${g.alias}: launching ${g.provider} seed session; this can take several seconds
|
|
2159
|
-
`);let
|
|
2160
|
-
`),
|
|
2158
|
+
`);let S=wr(e,v=>`${g.alias}: still launching (${v}s elapsed)
|
|
2159
|
+
`),I=p?l.map((v,w)=>w===d.get(g.alias.toLowerCase())?v.replace(/\s+sessionid=(?:"[^"]*"|\S+)/g,""):v).join(`
|
|
2161
2160
|
`):l.join(`
|
|
2162
|
-
`),
|
|
2163
|
-
`);if(
|
|
2161
|
+
`),b=Uk(g.alias,r,n,I),k;try{k=Hu(n,g.alias)}catch(v){return S.stop(),ar(e,v instanceof Error?v.message:String(v))}try{let v;try{v=await kk({provider:g.provider,cwd:y,...g.model!==void 0?{model:g.model}:{},...g.effort!==void 0?{effort:g.effort}:{},...b!==void 0?{prompt:b}:{}})}finally{S.stop()}for(let x of v.warnings??[])e.stderr.write(`warning: ${g.alias}: ${x}
|
|
2162
|
+
`);if(v.error!==void 0||v.sessionId===void 0||v.sessionId.length<Yn){let x=`provider did not report a sessionid; no new session was found for ${y} (possible provider workspace/cwd mismatch)`;return e.stderr.write(`error: ${g.alias}: seed failed${v.error!==void 0?`: ${v.error}`:`; ${x}`}
|
|
2164
2163
|
`),1}let w=d.get(g.alias.toLowerCase());if(w===void 0)return e.stderr.write(`error: ${g.alias}: could not find matching _MEMBER_ line to update
|
|
2165
|
-
`),1;let N=
|
|
2166
|
-
`),
|
|
2167
|
-
`)}finally{
|
|
2168
|
-
`),h=
|
|
2169
|
-
`);let T=new Date().toISOString();try{await G(e,g=>{
|
|
2164
|
+
`),1;let N=Ck(y),A=vc(l[w],"sessionid",v.sessionId);A=vc(A,"sessiondir",N);let R=g.model;if(g.model===void 0){let x;try{x=(await Br(v.sessionId,g.provider))?.model}catch{x=void 0}x!==void 0&&x.length>0&&(A=vc(A,"model",x),R=x)}if((p||r.guardFile)&&bc(n,"utf8")!==c)return ar(e,`Teamfile changed during seeding; new session ${v.sessionId} was not attached. Existing bindings preserved.`);l[w]=A,_+=1,c=l.join(`
|
|
2165
|
+
`),xg(n,c,"utf8"),e.stdout.write(`${g.alias}: seeded ${v.sessionId} provider=${g.provider} sessiondir=${N} model=${R?JSON.stringify(R):"default (not reported)"}
|
|
2166
|
+
`)}finally{k()}}let m=l.join(`
|
|
2167
|
+
`),h=Gk(m,Ic(n));h!==m&&xg(n,h,"utf8"),_===0&&e.stdout.write(`no members needed seeding
|
|
2168
|
+
`);let T=new Date().toISOString();try{await G(e,g=>{Hk(g,{teamfilePath:s,name:o.name,rawText:h,now:T})})}catch(g){return ar(e,g instanceof Error?g.message:String(g))}return 0}function jk(t){return Sk("sha256").update(t).digest("hex")}function Bk(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:jk(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function Hk(t,e){let r=Fs(e.rawText,e.teamfilePath);Yo(t,e.teamfilePath,r);let n=Bk(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(n),n}function Wk(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=Xk(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function Xk(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function vc(t,e,r){let n=`${e}=${qk(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(i,o)=>`${o}${n}`):`${t.trimEnd()} ${n}`}function qk(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function Gk(t,e){let r=`#teamfile: ${e}`,n=t.indexOf(`
|
|
2170
2169
|
`),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}
|
|
2171
2170
|
${i}`:`${r}
|
|
2172
2171
|
`:t.length>0?`${r}
|
|
2173
2172
|
${t}`:`${r}
|
|
2174
|
-
`}function
|
|
2175
|
-
`),1}function
|
|
2176
|
-
`)}ft();var
|
|
2177
|
-
${i}`)}function Yr(t,e,r=[]){let n;try{let i=JSON.parse(e);n=typeof i?.error=="string"?i.error:i?.error?.message??i?.message??i?.detail}catch{/^\s*[<{[]/.test(e)||(n=e.trim())}if(typeof n!="string"||!n.trim())return t;let s=Kr(n,r);return{...t,detail:s,provider_message:s}}import{spawnSync as nA}from"node:child_process";import{readdirSync as sA,readFileSync as iA}from"node:fs";import{join as oA}from"node:path";var Wg="ANTIGRAVITY_LS_ADDRESS",Xg="ANTIGRAVITY_CSRF_TOKEN",aA="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",lA=["-p","/usage"],cA=(t,e)=>{let r=nA("agy",lA,{encoding:"utf8",timeout:t,maxBuffer:16777216,env:e,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:typeof r.stdout=="string"?r.stdout:"",error:r.error}},dA=async(t,e,r)=>{let n=await fetch(t,{method:"POST",headers:e,body:"{}",signal:AbortSignal.timeout(r)});return{status:n.status,body:await n.text()}},uA=cA,fA=dA;function mA(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function pA(t){let e=t.trim().toLowerCase(),r={"gemini models":"gemini","claude and gpt models":"3p",gemini:"gemini","3p models":"3p","3p":"3p"};return r[e]?r[e]:e.replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function hA(t){let e=t.toLowerCase();return e.includes("weekly")?"weekly":e.includes("five hour")||e.includes("5-hour")||e.includes("5 hour")?"five_hour":e.includes("monthly")||e.includes("month")?"monthly":null}function gA(t){let e={weekly:"weekly",five_hour:"5h",monthly:"monthly"},r=[];for(let n of t.split(/\r?\n/)){let s=n.trim().split(" ").map(l=>l.trim());if(s.length<3||!s[0]||!s[1])continue;let i=hA(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=xe(o/100);r.push(Me({bucket_id:`${pA(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:xe(1-a),remaining_fraction:a,resets_at_iso:s[3]||null,raw_value:o,raw_scale:"remaining_percent"}))}return r.sort((n,s)=>String(n.group_name??"").localeCompare(String(s.group_name??""))||String(n.bucket_id??"").localeCompare(String(s.bucket_id??"")))}function es(t,e,r){return Fe("agy","provider_unavailable",t,e,"agy_cli_print")}function _A(t,e,r={}){try{let n=uA(Math.max(t,60)*1e3,mA(e));if(je(r,"agy_cli_print",n.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),n.error?.code==="ENOENT")return es("agy_not_found","the agy CLI is not on PATH",t);if(n.error?.code==="ETIMEDOUT")return es("cli_timeout","agy -p /usage did not finish in time",t);if(n.error)return es("cli_failed",n.error.message,t);let s=gA(n.stdout??"");return s.length===0?es("cli_unparseable",`exit ${n.status??1}; no buckets parsed from CLI output`,t):we("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(n){return es("cli_failed",n instanceof Error?n.message:String(n),t)}}function yA(t){let e=[],r=new Set,n=(s,i,o)=>{!s||!i||r.has(`${s}\0${i}`)||(r.add(`${s}\0${i}`),e.push([s,i,o]))};n(t[Wg],t[Xg],-1);try{for(let s of sA("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of iA(oA("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[Wg],i[Xg],Number(s))}catch{}}catch{}return e}function EA(t){if(typeof t!="object"||t===null)return null;let e=t.response;if(typeof e!="object"||e===null)return null;let r=e.groups;if(!Array.isArray(r))return null;let n=[];for(let s of r){if(typeof s!="object"||s===null)continue;let i=s,o=typeof i.displayName=="string"?i.displayName:null;if(Array.isArray(i.buckets))for(let a of i.buckets){if(typeof a!="object"||a===null)continue;let l=a,c=ot(l.remainingFraction,"fraction");n.push(Me({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:Bg(l.window),used_fraction:c===null?null:xe(1-c),remaining_fraction:c,resets_at_iso:l.resetTime??null,raw_value:l.remainingFraction??null,raw_scale:"remaining_fraction"}))}}return n.length===0?null:(n.sort((s,i)=>String(s.group_name??"").localeCompare(String(i.group_name??""))||String(s.bucket_id??"").localeCompare(String(i.bucket_id??""))),we("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function TA(t,e,r={}){let n=yA(e);if(n.length===0)return Fe("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let s=[];for(let[i,o,a]of n)try{let l=await fA(`http://${i}${aA}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":o},t*1e3);if(je(r,"agy_connect_rpc",l.body,[o],l.status),l.status===200){let c;try{c=JSON.parse(l.body)}catch{s.push(`pid=${a}: unparseable response`);continue}let d=EA(c);if(d)return d;s.push(`pid=${a}: response had no quota groups`)}else l.status===401||l.status===403?s.push(`pid=${a}: HTTP ${l.status} unauthorized`):s.push(`pid=${a}: HTTP ${l.status}`)}catch(l){s.push(`pid=${a}: ${l instanceof Error?l.message:String(l)}`)}return Fe("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${s.slice(0,5).join("; ")}`,"agy_connect_rpc",n.map(([,i])=>i))}async function qg(t){let e=_A(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let r=await TA(t.timeoutSeconds,t.env,t);return r.status==="ok"?r:Fe("agy","provider_unavailable","cli_and_language_server_unavailable",`cli: ${String(e.reason??e.status)} (${String(e.detail??"no detail")}); connect: ${String(r.reason??r.status)} (${String(r.detail??"no detail")})`,"agy_cli_print")}import{spawnSync as t_}from"node:child_process";import{randomUUID as Vg}from"node:crypto";import{mkdirSync as wA,readFileSync as Ac,realpathSync as SA,renameSync as vA,rmSync as Nc,statSync as Gg,writeFileSync as Kg}from"node:fs";import{homedir as bA}from"node:os";import{join as Rc}from"node:path";import{setTimeout as IA}from"node:timers/promises";var xA="9d1c250a-e61b-44d9-88ed-5944d1962f5e",kA="https://console.anthropic.com/v1/oauth/token",AA=3e5;function Oc(t){return Rc(t.CLAUDE_CONFIG_DIR??Rc(t.HOME??bA(),".claude"),".credentials.json")}function Lc(t){let e=JSON.parse(Ac(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function Cc(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Yg(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=Oc(t);try{let r=Cc(Lc(e));return typeof r?.accessToken=="string"&&r.accessToken?{oauth:r,path:SA(e)}:{error:"not_claude_ai_subscriber"}}catch(r){return r.code==="ENOENT"?{error:t.ANTHROPIC_API_KEY?"not_claude_ai_subscriber":"no_credentials_found"}:{error:"credentials_unreadable"}}}function ao(t){return typeof t.expiresAt=="number"&&Date.now()+AA>=t.expiresAt}function Jg(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function NA(t,e){let r=`${t}.lmctl-refresh.lock`,n=Rc(r,"owner.json"),s=Vg();for(;;){e.throwIfAborted();try{wA(r,{mode:448});try{Kg(n,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Nc(r,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(Ac(n,"utf8")).token===s&&Nc(r,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(Ac(n,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-Gg(r).mtimeMs>6e4}catch{try{o=Date.now()-Gg(r).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await IA(50,void 0,{signal:e})}}}async function zg(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let r=await NA(t.path,e);try{let n=Cc(Lc(t.path));if(!n||typeof n.accessToken!="string")throw new Error("credentials_changed");if(!Jg(n,t.oauth)&&!ao(n))return n;if(typeof n.refreshToken!="string"||!n.refreshToken)throw new Error("no_refresh_token");let s=await fetch(kA,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:xA})});if(!s.ok)throw new Error(`refresh_http_${s.status}`);let i=await s.json();if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||i.refresh_token!==void 0&&(typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)))throw new Error("invalid_refresh_response");let o=Math.floor(Date.now()+i.expires_in*1e3);if(!Number.isSafeInteger(o)||o<=Date.now())throw new Error("invalid_refresh_response");let a=Lc(t.path),l=Cc(a);if(!l||!Jg(n,l)){if(l&&typeof l.accessToken=="string"&&!ao(l))return l;throw new Error("credentials_changed")}let c={...l,accessToken:i.access_token,refreshToken:i.refresh_token??n.refreshToken,expiresAt:o,...typeof i.scope=="string"?{scopes:i.scope.split(/\s+/).filter(Boolean)}:{}},d=`${t.path}.${Vg()}.tmp`;try{Kg(d,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),vA(d,t.path)}finally{Nc(d,{force:!0})}return c}finally{r()}}var RA="https://api.anthropic.com",LA="oauth-2025-04-20",Qg="user:profile";function CA(t){let e=String(t??"").toLowerCase();return e.includes("session")||e.includes("five")||e.includes("5h")?"five_hour":e.includes("week")||e.includes("seven")||e.includes("7d")?"weekly":e.includes("month")||e.includes("30d")?"monthly":"unknown"}var _e={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};function r_(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function OA(t){try{let e=t_("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:r_(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function Je(t,e,r,n="claude_oauth_api",s){return Fe("claude",t,e,r,n,void 0,s)}function DA(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function MA(t){if(!t)return;let e=/^([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?$/i.exec(t.trim());if(!e)return;let r=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"].indexOf(e[1].slice(0,3).toLowerCase());if(r<0)return;let n=Number(e[3]),s=Number(e[4]??0);(e[5]??"").toLowerCase()==="pm"&&n!==12&&(n+=12),(e[5]??"").toLowerCase()==="am"&&n===12&&(n=0);let i=new Date(Date.UTC(new Date().getUTCFullYear(),r,Number(e[2]),n,s));return Number.isFinite(i.getTime())?Math.floor(i.getTime()/1e3):void 0}var FA=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/;function PA(t){let e=[];for(let r of t.split(/\r?\n/)){let n=FA.exec(r.trim());if(!n)continue;let s=n[1].trim(),o=s.toLowerCase()==="session",a=/\(([^)]+)\)/.exec(s)?.[1]?.trim()??s,l=o?"session":a.toLowerCase()==="all models"?"week-all-models":`week-scoped-${a}`,c=o?"five_hour":"weekly";e.push(Me({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:ot(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:MA(n[3])}))}return e.sort((r,n)=>String(r.window_type).localeCompare(String(n.window_type))||String(r.bucket_id).localeCompare(String(n.bucket_id)))}function $A(t){let e={},r;for(let n of t.split(/\r?\n/)){let s=/^Last\s+(\S+)\s*[·-]\s*(\d+)\s+requests?\s*[·-]\s*(\d+)\s+sessions?\s*$/.exec(n.trim());if(s){r={requests:Number(s[2]),sessions:Number(s[3])},e[`window_${s[1].toLowerCase()}`]=r;continue}let i=/^\s+(\d+)%\s+of your usage\s+(.+?)\s*$/.exec(n);if(!i||!r)continue;let o=i[2].toLowerCase(),a=o.includes(">150k context")?"pct_high_context":o.includes("active for 8+ hours")?"pct_long_sessions":o.includes("subagent-heavy")?"pct_subagent_heavy":o.includes("ran in parallel")?"pct_parallel_sessions":void 0;a&&(r[a]=Number(i[1]))}return e}function Zg(t){if(!t||typeof t!="object")return;let e=t,r=e.limit&&typeof e.limit=="object"?e.limit:{},n=e.used&&typeof e.used=="object"?e.used:{},s=r.exponent??n.exponent??2,i=l=>l==null||!Number.isFinite(Number(l))?void 0:(Number(l)/10**Number(s)).toFixed(2),o=ot(e.percent,"percent"),a={limit_usd:i(r.amount_minor),used_usd:i(n.amount_minor),remaining_fraction:o==null?void 0:Math.max(0,1-o),resets_at_iso:e.resets_at};return Object.values(a).every(l=>l==null)?void 0:a}async function e_(t,e,r,n={}){try{let s=t_("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:r_(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";je(n,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=PA(i);if(!o.length)return;let a=$A(i);return we("claude",_e.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:o,...Object.keys(a).length?{characteristics:a}:{}})}catch{return}}async function n_({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s=Yg(e);if(s.error==="not_claude_ai_subscriber")return Je(_e.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return Je(_e.unavailable,"credentials_missing",`credentials file not found: ${Oc(e)}`);if(s.error)return Je(_e.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(Qg))return Je(_e.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${Qg} scope required by the usage endpoint`);let a=new AbortController,l=setTimeout(()=>a.abort(),t*1e3),c,d;try{let m=!1,h=async()=>{try{i=await zg({...s,oauth:i},a.signal),m=!0}catch(g){let y=g instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(g.message)?g.message:"refresh_failed";if(y==="refresh_http_429")return Je(_e.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(y==="refresh_lock_stale")return Je(_e.expired,"oauth_refresh_locked","a previous Claude credential refresh exited without releasing its lock; remove the stale .credentials.json.lmctl-refresh.lock directory before retrying");let v=y==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(y);return Je(v?_e.expired:_e.unavailable,v?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${y})${v?"; renew Claude login":"; try again later"}`)}};if(ao(i)){let g=await h();if(g)return g}let T=()=>fetch(`${RA}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":LA,"Content-Type":"application/json","User-Agent":OA(e)},signal:a.signal});if(c=await T(),d=await c.text(),je({debug:r,onRawResponse:n},"claude_oauth_api",d,[i.accessToken,i.refreshToken],c.status),c.status===401&&!m&&s.path&&i.refreshToken){let g=await h();if(g)return g;c=await T(),d=await c.text(),je({debug:r,onRawResponse:n},"claude_oauth_api",d,[i.accessToken,i.refreshToken],c.status)}}catch(m){let h=await e_(i,e,t,{debug:r,onRawResponse:n});return h||Je(_e.unavailable,"request_failed",`${m instanceof Error?m.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let u=(...m)=>Yr(Je(...m),d,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return u(_e.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return u(_e.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let m=DA(c.headers),h=await e_(i,e,t,{debug:r,onRawResponse:n});return h||u(_e.throttled,"rate_limited",`usage endpoint rate limited${m==null?"":`; retry after ${m}s`}`,"claude_oauth_api",m)}if(c.status!==200)return u(_e.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let f;try{f=JSON.parse(d)}catch{return Je(_e.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!f||typeof f!="object"||Array.isArray(f))return Je(_e.unavailable,"malformed_response","response was not an object");let p=f,_=Array.isArray(p.limits)?p.limits:[],E=_.length?_.flatMap(m=>{if(!m||typeof m!="object")return[];let h=m.kind,T=CA(h==="session"?"session":h),g=m.scope?.model?.display_name,y=h==="session"?"session":h==="weekly_all"?"week-all-models":`week-scoped-${g||h}`;return[Me({bucket_id:y,group_name:h==="session"?"session":"weekly",window_type:T,used_fraction:ot(m.percent,"percent"),resets_at_iso:m.resets_at,raw_value:m.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(m=>{let h=p[m];return!h||typeof h!="object"?[]:[Me({bucket_id:m==="five_hour"?"session":"week-all-models",group_name:m==="five_hour"?"session":"weekly",window_type:m==="five_hour"?"five_hour":"weekly",used_fraction:ot(h.utilization,"percent"),resets_at_iso:h.resets_at,raw_value:h.utilization,raw_scale:"used_percent"})]});return we("claude",_e.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:E.sort((m,h)=>String(m.window_type).localeCompare(String(h.window_type))||String(m.bucket_id).localeCompare(String(h.bucket_id))),...Zg(p.spend)?{spend_control:Zg(p.spend)}:{}})}import{readFileSync as UA}from"node:fs";import{homedir as jA}from"node:os";import{join as BA}from"node:path";var HA="https://chatgpt.com/backend-api",WA="codex-cli";function Be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function s_(t){let e=typeof t=="number"?t:Number(t);if(!Number.isFinite(e)||e<=0)return"unknown";let r=e/60;return r>=240&&r<=360?"five_hour":r>=9e3&&r<=11500?"weekly":r>=38e3&&r<=46e3?"monthly":"unknown"}function i_(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function XA(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||BA(jA(),".codex","auth.json");try{let r=JSON.parse(UA(e,"utf8")),n=Be(r)&&Be(r.tokens)?r.tokens:void 0,s=n?.access_token,i=n?.account_id;return{token:typeof s=="string"?s:void 0,accountId:typeof i=="string"?i:void 0}}catch{return{}}}function qA(t){if(Be(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function GA(t){let e=[],r=Be(t.rate_limit)?t.rate_limit:{},n=typeof r.allowed=="boolean"?r.allowed:void 0,s=typeof r.limit_reached=="boolean"?r.limit_reached:void 0;for(let o of["primary_window","secondary_window"]){let a=Be(r[o])?r[o]:void 0;if(!a)continue;let l=s_(a.limit_window_seconds);e.push(Me({bucket_id:`codex-${i_(l)}`,group_name:"codex",window_type:l,used_fraction:ot(a.used_percent,"percent"),resets_at:a.reset_at,raw_value:a.used_percent,raw_scale:"used_percent",...n===void 0?{}:{allowed:n},...s===void 0?{}:{limit_reached:s}}))}let i=Array.isArray(t.additional_rate_limits)?t.additional_rate_limits:[];for(let o of i){if(!Be(o))continue;let a=Be(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,d=c||l||"additional",u=typeof a.allowed=="boolean"?a.allowed:void 0,f=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let p of["primary_window","secondary_window"]){let _=Be(a[p])?a[p]:void 0;if(!_)continue;let E=s_(_.limit_window_seconds);e.push(Me({bucket_id:`${d}-${i_(E)}`,group_name:l||d,window_type:E,used_fraction:ot(_.used_percent,"percent"),resets_at:_.reset_at,raw_value:_.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...u===void 0?{}:{allowed:u},...f===void 0?{}:{limit_reached:f}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function JA(t){let e=Be(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=Be(t.spend_control)?t.spend_control:void 0,s=Be(t.credits)?t.credits:void 0;return we("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:GA(t),...s?{credits:qA(s)}:{},...n?{spend_control:n}:{}})}async function o_(t){let{timeoutSeconds:e,env:r,debug:n,onRawResponse:s}=t,i=XA(r);if(!i.token)return we("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let o=new AbortController,a=setTimeout(()=>o.abort(),Math.ceil(e*1e3));try{let l={Authorization:`Bearer ${i.token}`,"User-Agent":WA,"Content-Type":"application/json",Accept:"application/json"};i.accountId&&(l["ChatGPT-Account-Id"]=i.accountId);let c=(r.CODEX_BASE_URL||HA).replace(/\/$/,""),d=await fetch(`${c}/wham/usage`,{headers:l,signal:o.signal}),u=await d.text();je({debug:n,onRawResponse:s},"codex_http",u,[i.token],d.status);let f=(_,E)=>Yr(we("codex",_,E),u,[i.token]);if(d.status===401)return f("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(d.status===429){let _=d.headers.get("retry-after"),E=_===null?void 0:Number.parseInt(_,10);return f("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...E!==void 0&&Number.isFinite(E)&&E>=0?{retry_after_seconds:E}:{}})}if(!d.ok)return f("provider_unavailable",{source:"codex_http",reason:`http_${d.status}`,detail:"codex usage endpoint returned an unexpected status"});let p;try{p=JSON.parse(u)}catch(_){return we("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Kr(String(_),[i.token])})}return Be(p)?JA(p):we("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(l){let c=l instanceof Error?`${l.name}: ${l.message}`:String(l);return we("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Kr(c,[i.token])})}finally{clearTimeout(a)}}import{createHash as VA,randomUUID as KA}from"node:crypto";import{readFileSync as u_,openSync as YA,fsyncSync as zA,closeSync as QA,mkdirSync as a_,writeFileSync as f_,renameSync as ZA,rmSync as eN,rmdirSync as tN,statSync as Dc,utimesSync as rN}from"node:fs";import{homedir as nN}from"node:os";import{basename as sN,dirname as iN,join as lo}from"node:path";import{setTimeout as m_}from"node:timers/promises";var l_="https://api.kimi.com/coding/v1",Mc="https://auth.kimi.com",oN="17e5f671-d194-4dfb-9706-5516cb48c098",c_=t=>t.trim().replace(/\/+$/,"");function aN(t){let e;try{e=u_(t,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new Error("config_unreadable")}let r={},n="other";for(let s of e.split(/\r?\n/)){let i=/^\s*\[providers\.(?:"managed:kimi-code"|'managed:kimi-code')(\.oauth)?\]\s*(?:#.*)?$/.exec(s);if(i){n=i[1]?"oauth.":"";continue}if(/^\s*\[/.test(s)){if(s.includes("managed:kimi-code"))throw new Error("config_format_unsupported");n="other";continue}if(n==="other")continue;if(/^\s*oauth\s*=/.test(s))throw new Error("config_format_unsupported");let o=/^\s*(base_url|oauth_host|storage|key)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(s);if(!o&&/^\s*(base_url|oauth_host|storage|key)\s*=/.test(s))throw new Error("config_malformed");if(o)try{r[n+o[1]]=o[2].startsWith('"')?JSON.parse(o[2]):o[2].slice(1,-1)}catch{throw new Error("config_malformed")}}return r}function co(t){let e;try{e=JSON.parse(u_(t,"utf8"))}catch(r){throw new Error(r.code==="ENOENT"?"credentials_missing":"credentials_malformed")}if(e&&typeof e=="object"&&e.access_token===""&&e.refresh_token==="")throw new Error("credentials_revoked");if(!e||typeof e!="object"||Array.isArray(e)||typeof e.access_token!="string"||!e.access_token.trim())throw new Error("credentials_malformed");return e}function p_(t){let e=t.KIMI_CODE_HOME??lo(t.HOME??nN(),".kimi-code"),r=aN(t.KIMI_CODE_CONFIG_PATH??lo(e,"config.toml")),n=t.KIMI_CODE_BASE_URL!==void 0||t.KIMI_CODE_OAUTH_HOST!==void 0||t.KIMI_OAUTH_HOST!==void 0,s=c_(t.KIMI_CODE_BASE_URL??r.base_url??l_),i=c_(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(n?Mc:r["oauth.oauth_host"]??Mc)),o=s===l_&&i===Mc?"kimi-code":`kimi-code-env-${VA("sha256").update(JSON.stringify({oauthHost:i,baseUrl:s})).digest("hex").slice(0,16)}`;if(!t.KIMI_CREDENTIALS_PATH&&!n&&r["oauth.key"]===`oauth/${o}`&&r["oauth.storage"]&&r["oauth.storage"]!=="file")throw new Error("credential_storage_unsupported");let a=t.KIMI_CREDENTIALS_PATH??lo(e,"credentials",`${o}.json`),l=co(a),c=a,d=sN(a,".json");return{home:e,path:c,lockTarget:lo(e,"oauth",d),baseUrl:s,oauthHost:i,token:l}}function uo(t){if(typeof t.expires_at!="number")return!1;let e=typeof t.expires_in=="number"?t.expires_in:0;return t.expires_at-Date.now()/1e3<Math.max(300,e*.5)}function d_(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.expires_at===e.expires_at&&t.expires_in===e.expires_in}async function lN(t,e){a_(iN(t),{recursive:!0}),f_(t,"",{flag:"a",mode:384});let r=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{a_(r);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-Dc(r).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await m_(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let n=Dc(r),s=()=>{let o;try{o=Dc(r)}catch{throw new Error("refresh_lock_lost")}if(o.ino!==n.ino||o.dev!==n.dev)throw new Error("refresh_lock_lost")},i=setInterval(()=>{try{s();let o=new Date;rN(r,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),tN(r)}catch{}}}}async function h_(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let r=await lN(t.lockTarget,e);try{let n=co(t.path);if(!d_(n,t.token)&&!uo(n))return n;if(typeof n.refresh_token!="string"||!n.refresh_token)throw new Error("no_refresh_token");let s;for(let u=0;u<3;u++){try{if(s=await fetch(`${t.oauthHost}/api/oauth/token`,{method:"POST",signal:e,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":"lmctl"},body:new URLSearchParams({client_id:oN,grant_type:"refresh_token",refresh_token:n.refresh_token})}),![429,500,502,503,504].includes(s.status)||u===2)break;await s.body?.cancel()}catch{if(e.aborted||u===2)throw new Error("refresh_request_failed")}await m_(1e3*2**u,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let u=co(t.path);if(u.refresh_token!==n.refresh_token)return u}catch{}throw new Error(`refresh_http_${s.status}`)}let i=await s.json(),o=Number(i?.expires_in);if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)||!Number.isFinite(o)||o<=0)throw new Error("invalid_refresh_response");let a=Math.floor(Date.now()/1e3)+o;if(!Number.isSafeInteger(a))throw new Error("invalid_refresh_response");r.assertOwned();let l=co(t.path);if(!d_(l,n)){if(!uo(l))return l;throw new Error("credentials_changed")}let c={...l,access_token:i.access_token,refresh_token:i.refresh_token,expires_at:a,expires_in:o,...typeof i.scope=="string"?{scope:i.scope}:{},...typeof i.token_type=="string"?{token_type:i.token_type}:{}},d=`${t.path}.${KA()}.tmp`;try{let u=YA(d,"wx",384);try{f_(u,JSON.stringify(c,null,2)+`
|
|
2178
|
-
`),zA(u)}finally{QA(u)}r.assertOwned(),ZA(d,t.path)}finally{eN(d,{force:!0})}return c}finally{r.release()}}function g_(t){let e=o=>{if(typeof o!="number"&&typeof o!="string"||typeof o=="string"&&o.trim()==="")return;let a=Number(o);return Number.isFinite(a)&&a>=0?a:void 0},r=e(t.limit),n=e(t.used),s=e(t.remaining);if(r===void 0||r<=0||n===void 0&&(s===void 0||s>r))return;let i=n??r-s;return{used:i,limit:r,remaining:Math.max(0,r-i)}}async function __({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s;try{s=p_(e)}catch(E){let m=E instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(E.message)?E.message:"credentials_unreadable";return Fe("kimi",m==="credentials_revoked"?"auth_expired":"provider_unavailable",m,m==="credentials_revoked"?"Kimi login was revoked; run kimi login":m.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let E=!1,m=async()=>{i=await h_({...s,token:i},o.signal),E=!0};uo(i)&&await m();let h=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await h(),c=await l.text(),je({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!E&&i.refresh_token&&(await m(),l=await h(),c=await l.text(),je({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(E){let m=E instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(E.message)?E.message:"request_failed",h=m==="credentials_revoked"||m==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(m),T=m==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":h?`Kimi credential renewal failed (${m}); run kimi login`:`Kimi quota request failed (${m})`;return Fe("kimi",h?"auth_expired":"provider_unavailable",m,T,"kimi_http")}finally{clearTimeout(a)}let d=(E,m,h)=>Yr(Fe("kimi",E,m,m,"kimi_http",[],h),c,[i.access_token]);if(l.status===401)return d("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return d("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let E=Hg(l.headers);return d("reader_throttled","HTTP 429 from Kimi usage endpoint",E)}if(l.status!==200)return d("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let u;try{u=JSON.parse(c)}catch{return Fe("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!u||typeof u!="object")return Fe("kimi","provider_unavailable","malformed_response","response was not an object");let f=[],p=new Set;function _(E){let m=String(E.bucket_id),h=m,T=2;for(;p.has(m);)m=`${h}-${T}`,T++;p.add(m),E.bucket_id=m,f.push(Me(E))}if(Array.isArray(u.limits))for(let E of u.limits){if(!E||typeof E!="object")continue;let m=E.window,h=E.detail;if(!m||typeof m!="object"||!h||typeof h!="object")continue;let T=0;if(m.timeUnit==="TIME_UNIT_MINUTE")T=Number(m.duration);else if(m.timeUnit==="TIME_UNIT_HOUR")T=Number(m.duration)*60;else if(m.timeUnit==="TIME_UNIT_DAY")T=Number(m.duration)*1440;else if(m.timeUnit==="TIME_UNIT_WEEK")T=Number(m.duration)*10080;else if(m.timeUnit==="TIME_UNIT_MONTH")T=Number(m.duration)*43200;else continue;let g=jg(T),y="window";g==="five_hour"&&(y="5h"),g==="weekly"&&(y="weekly"),g==="monthly"&&(y="monthly");let v=g_(h);if(!v)continue;let{used:b,limit:I,remaining:A}=v;_({bucket_id:`kimi-${y}`,window_type:g,used_fraction:xe(b/I),remaining_fraction:xe(A/I),resets_at_iso:h.resetTime,raw_value:b,raw_scale:"count"})}if(u.usage&&typeof u.usage=="object"){let E=g_(u.usage);E&&_({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:xe(E.used/E.limit),remaining_fraction:xe(E.remaining/E.limit),resets_at_iso:u.usage.resetTime,raw_value:E.used,raw_scale:"count"})}if(u.usages&&typeof u.usages=="object"){let E=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:m,id:h,type:T}of E){let g=u.usages[m];if(!g||typeof g!="object"||g.used_ratio==null||g.used_ratio===""||typeof g.used_ratio=="boolean")continue;let y=Number(g.used_ratio);!Number.isFinite(y)||y<0||p.has(h)||(p.add(h),f.push(Me({bucket_id:h,window_type:T,used_fraction:xe(y),resets_at_iso:typeof g.reset_time=="string"&&g.reset_time?g.reset_time:null,raw_value:y,raw_scale:"ratio"})))}}return we("kimi","ok",{source:"kimi_http",buckets:f})}var y_=["all","codex","agy","claude","kimi"],cN=15;async function E_(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let a of e)if(!y_.includes(a))return{status:"error",error:`unknown provider: ${a} (valid targets: ${y_.join(", ")})`,readings:[]};let r=t.timeoutSeconds??cN;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=new Set(e.includes("all")?["codex","agy","claude","kimi"]:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let o=Object.entries({codex:o_,agy:qg,claude:n_,kimi:__}).filter(([a])=>s.has(a)).map(async([,a])=>{let l=[],c=await a({timeoutSeconds:r,env:n,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:d=>l.push(d)}:{}});return t.includeRaw?{...c,raw_responses:l}:c});try{return{status:"ok",readings:(await Promise.all(o)).filter(Boolean)}}catch(a){return{status:"error",error:String(a),readings:[]}}}aa();Gn();Kt();Er();pn();qt();Yi();qs();Es();import{execFile as dN}from"node:child_process";import{mkdtempSync as uN,realpathSync as $c,rmSync as fN,statSync as k_}from"node:fs";import{tmpdir as A_}from"node:os";import{isAbsolute as Uc,join as T_,relative as mN}from"node:path";import{promisify as pN}from"node:util";var hN=pN(dN),gN=[{name:"lmbee_queue_list",category:"Queue Management",signature:"lmbee_queue_list(snapshot_db, team = null, options = null)",description:"Lists queue rows from a temporary lmbee database copy, read directly (no lmbee executable needed).",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"},{name:"options",type:"map",description:`Optional { scope, limit, after_id }: scope "recent" (default) is the newest 30 rows; scope "unfinished" is every genuinely open row (lmauto's listUnfinishedQueue predicate); scope "all" is every row. limit (1-200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:"{ queue: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; each row carries hasAnswer (current, non-superseded answer)"},example:'page = lmbee_queue_list("/tmp/lmbee-copy/state.db", null, {"scope":"unfinished","limit":200});'},{name:"lmbee_queue_get",category:"Queue Management",signature:"lmbee_queue_get(snapshot_db, id)",description:"Gets one queue row from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer queue ID"}],returns:{type:"map",description:"{ queue: row, hasAnswer: boolean } or a queue_not_found error object"},example:'item = lmbee_queue_get("/tmp/lmbee-copy/state.db", 7);'},{name:"lmbee_queue_stats",category:"Queue Management",signature:"lmbee_queue_stats(snapshot_db, team = null)",description:"Reads per-recipient queue counts from a temporary lmbee database copy, without a row window.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"}],returns:{type:"map",description:"{ stats: [...] } most-stale-first; team_progress-sourced fields (escalationAttemptCount, lastEscalationAttemptTs, quota*) default to 0/null when the snapshot predates that table"},example:'counts = lmbee_queue_stats("/tmp/lmbee-copy/state.db", "worker");'},{name:"lmbee_tasks",category:"Queue Management",signature:"lmbee_tasks(snapshot_db, options = null)",description:"Lists task-ledger rows (lmauto entities: epics, tasks, subtasks) from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:`Optional { scope, status, owner, team, limit, after_id }: scope "recent" (default) is the newest 30 rows and is NOT pageable (limit/after_id require unfinished or all; use a paged scope to traverse completely); scope "unfinished" excludes rows whose normalized status (trim, lowercase, separators to hyphens -- lmauto's normalizeStatus) is done/closed/cancelled, the audit terminal set -- a deliberate bridge choice, since lmauto itself uses done/closed for epic completeness and done-only for dependency satisfaction; scope "all" is every row. status exact-matches the stored value with the ARGUMENT trimmed (lmauto listEntities). owner exact-matches owner_alias; alias-only is a cross-team match -- add team (exact match on the stored canonical team path) to pin one team. limit (1-200, default 200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:`{ tasks: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; rows carry id, kind, project, parent_id, title, status, owner_team_path, owner_alias, created_at, updated_at -- updated_at is the entity's own update time, NOT "last activity" (delivery bookkeeping deliberately does not touch it)`},example:'tasks = lmbee_tasks("/tmp/lmbee-copy/state.db", {"scope":"unfinished","owner":"worker","limit":50});'},{name:"lmbee_task_get",category:"Queue Management",signature:"lmbee_task_get(snapshot_db, id)",description:'Gets one task-ledger row with its direct children, so "does this parent still have open children" is a single field.',parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer entity ID"}],returns:{type:"map",description:"{ task, children, open_children } or a task_not_found error object; children is id-ascending and DIRECT only, and open_children counts those direct children whose normalized status is not done/closed/cancelled -- it claims nothing about grandchildren"},example:'t = lmbee_task_get("/tmp/lmbee-copy/state.db", 12);'},{name:"lmbee_cron_list",category:"Queue Management",signature:"lmbee_cron_list(snapshot_db, options = null)",description:"Lists cron jobs from a temporary lmbee database copy. Jobs are operator-created and few, so there is deliberately no paging.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { enabled }: true/false to filter; omitted lists all"}],returns:{type:"map",description:'{ jobs: [...] } by ascending id, with enabled as a real boolean. Two traps: legacy command/enqueue jobs NEVER write cron_runs -- for them "did it run" is last_fired_ts/last_fire_status/last_fire_error on this row; and running_since_ts non-null means a legacy execution is currently claimed'},example:'jobs = lmbee_cron_list("/tmp/lmbee-copy/state.db", {"enabled":true});'},{name:"lmbee_cron_runs",category:"Queue Management",signature:"lmbee_cron_runs(snapshot_db, options = null)",description:"Lists cron run-ledger rows (run-based job kinds: script/session/miniplayer) from a temporary lmbee database copy, newest-first.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { job_id, status, limit, after_id }: status is one of pending/running/succeeded/failed/escalated; limit (1-200) defaults to 50 -- the ledger only grows, so page with after_id rather than reading unbounded"}],returns:{type:"map",description:"{ runs: [...], meta: { next_cursor } }. Outcome (status) and execution liveness (execution_state) are SEPARATE: succeeded can coexist with an active execution fence. An empty result does NOT mean a job never ran -- legacy command/enqueue jobs write nothing here; check the job row via lmbee_cron_list. run_token_hash is never returned (lmbee's own public projection)"},example:'runs = lmbee_cron_runs("/tmp/lmbee-copy/state.db", {"job_id":3,"limit":50});'},{name:"lmbee_snapshot",category:"Queue Management",signature:"lmbee_snapshot(source_db)",description:"Creates a WAL-aware temporary database backup, removed when the script ends.",parameters:[{name:"source_db",type:"string",description:"Absolute path to an existing lmbee database"}],returns:{type:"string",description:"Temporary snapshot path for lmbee queue functions"},example:'snapshot = lmbee_snapshot(env("HOME") + "/.lmbee/state.db");'}];function N_(t){if(typeof t!="string"||!t||!Uc(t))throw new Error("lmbee: snapshot_db must be an absolute path to a temporary database copy");let e;try{e=$c(t);let n=k_(e);if(!n.isFile()||n.nlink!==1)throw new Error("not a standalone file")}catch{throw new Error("lmbee: snapshot_db must be an existing temporary database copy")}let r=mN($c(A_()),e);if(!r||r===".."||r.startsWith("../")||Uc(r))throw new Error("lmbee: snapshot_db must be a temporary database copy inside the system temp directory");return e}function w_(t){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error("lmbee: team must be a nonempty string");return t}}function _N(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");return{scope:r,limit:n,afterId:s}}var yN=["id","from_id","to_id","status","created_ts","expects_response","in_reply_to","retracted_ts","escalation_claimed_ts"],EN=["prompt_queue_id","superseded_at"],TN=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],R_=["id","kind","project","parent_id","title","status","owner_team_path","owner_alias","created_at","updated_at"],fo=R_.join(", "),wN="replace(replace(lower(trim(status, char(9, 10, 11, 12, 13, 32, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279))), ' ', '-'), '_', '-')",L_=`${wN} NOT IN ('done', 'closed', 'cancelled')`,C_=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","session_teamfile","session_alias","session_seeded_at","session_generation","enabled","last_checked_ts","last_fired_ts","last_fire_status","last_fire_error","running_systemd_unit","timezone","running_since_ts","created_at","updated_at","revision"],S_=C_.join(", "),O_=["id","job_id","status","execution_state","trigger_kind","config_snapshot","execution_identity","pid","summary","artifacts","escalation_reason","escalation_action","escalation_owner","escalation_resolved_at","escalation_resolution","escalation_resolution_actor","escalation_resolution_note","execution_gone_at","execution_uncertain_reason","execution_confirmation_note","reported_at","created_at","started_at","finished_at","updated_at"],SN=O_.join(", "),vN=new Set(["pending","running","succeeded","failed","escalated"]),bN=`q.status != 'merged'
|
|
2173
|
+
`}function Jk(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 ar(t,e){return t.stderr.write(`error: ${e}
|
|
2174
|
+
`),1}function xc(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_
|
|
2175
|
+
`)}ft();var Vk="https://lmctl.com/schemas/lmratelimit-v1.json";function xe(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);return Number.isFinite(e)?Math.round(Math.min(1,Math.max(0,e))*1e6)/1e6:null}function ot(t,e){if(t==null||typeof t=="boolean")return null;let r=Number(t);return xe(e==="percent"?r/100:r)}function Dg(t){if(t==null||typeof t=="boolean")return null;let e=Number(t);if(!Number.isFinite(e))return null;try{return new Date(Math.trunc(e)*1e3).toISOString().replace(".000Z","Z")}catch{return null}}function Mg(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function Fg(t){let e=Number(t);return Number.isFinite(e)?e===300||e>=240&&e<=360?"five_hour":e===10080||e>=9e3&&e<=11500?"weekly":e===43200||e===44640||e>=38e3&&e<=46e3?"monthly":"unknown":"unknown"}function Pg(t){let e=String(t??"").trim().toLowerCase().replace(/-/g,"_").split("_").filter(Boolean);for(let r of[e[0],e.at(-1)]){if(r?.startsWith("5h")||r?.startsWith("five")||r==="session")return"five_hour";if(r?.startsWith("7d")||r?.startsWith("seven")||r?.startsWith("week"))return"weekly";if(r?.startsWith("30d")||r?.startsWith("month"))return"monthly"}return"unknown"}var Kk=[/sk-ant-[A-Za-z0-9_-]{4,}/g,/sk-[A-Za-z0-9_-]{16,}/g,/\bbearer\s+[A-Za-z0-9._-]{8,}/gi,/\boat01[-_][A-Za-z0-9_-]{8,}/g,/\bcsrf[-_][A-Za-z0-9_-]{4,}/gi,/\b(?:csrf[-_]?token|x-codeium-csrf-token)\s*[:=]\s*['"]?[A-Za-z0-9._-]{4,}/gi];function Gr(t,e=[]){let r=t==null?"":String(t);for(let n of e)typeof n=="string"&&n.length>=4&&(r=r.replaceAll(n,"***REDACTED***"));for(let n of Kk)r=r.replace(n,"***REDACTED***");return r}function Me(t){let e=xe(t.used_fraction),r=xe(t.remaining_fraction),n=t.resets_at==null?Mg(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?Dg(n):Dg(Mg(t.resets_at_iso)),i={bucket_id:t.bucket_id,...t.group_name!=null?{group_name:t.group_name}:{},window_type:t.window_type??"unknown",used_fraction:e??(r===null?null:xe(1-r)),remaining_fraction:r??(e===null?null:xe(1-e)),resets_at:n==null||!Number.isFinite(n)?null:Math.trunc(n),resets_at_iso:s,is_exhausted:t.is_exhausted??(r!==null?r<=0:e!==null?e>=1:null)};for(let o of["raw_value","raw_scale","limit_name","metered_feature","allowed","limit_reached"])t[o]!=null&&(i[o]=t[o]);return i}function we(t,e,r={}){let n={$schema:Vk,provider:t,status:e,source:r.source??null,read_at:r.read_at??Math.floor(Date.now()/1e3),account_id:r.account_id??null,plan_type:r.plan_type??null,ordinary_usage_allowed:r.ordinary_usage_allowed??null,buckets:r.buckets??[]};for(let s of["credits","spend_control","characteristics","reason","detail","retry_after_seconds"])r[s]!=null&&(n[s]=r[s]);return n}function Fe(t,e,r,n,s,i=[],o){return we(t,e,{source:s??null,reason:r,...n==null?{}:{detail:Gr(n,i)},...o==null?{}:{retry_after_seconds:o}})}function $g(t){let e=t.get("retry-after");if(e===null)return null;let r=Number.parseFloat(e);return Number.isFinite(r)&&r>=0?Math.trunc(r):null}function je(t,e,r,n=[],s){if(!t.debug&&!t.onRawResponse)return;let i=Gr(r,[...n].filter(o=>typeof o=="string")).replace(/("(?:access[_-]?token|refresh[_-]?token|authorization|api[_-]?key|password)"\s*:\s*")[^"\r\n]*(")/gi,"$1***REDACTED***$2");t.onRawResponse?.({source:e,...s===void 0?{}:{http_status:s},text:i}),t.debug?.(`[debug] ${e}${s===void 0?"":` HTTP ${s}`} raw response:
|
|
2176
|
+
${i}`)}function Jr(t,e,r=[]){let n;try{let i=JSON.parse(e);n=typeof i?.error=="string"?i.error:i?.error?.message??i?.message??i?.detail}catch{/^\s*[<{[]/.test(e)||(n=e.trim())}if(typeof n!="string"||!n.trim())return t;let s=Gr(n,r);return{...t,detail:s,provider_message:s}}import{spawnSync as Yk}from"node:child_process";import{readdirSync as zk,readFileSync as Qk}from"node:fs";import{join as Zk}from"node:path";var Ug="ANTIGRAVITY_LS_ADDRESS",jg="ANTIGRAVITY_CSRF_TOKEN",eA="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",tA=["-p","/usage"],rA=(t,e)=>{let r=Yk("agy",tA,{encoding:"utf8",timeout:t,maxBuffer:16777216,env:e,stdio:["ignore","pipe","ignore"]});return{status:r.status,stdout:typeof r.stdout=="string"?r.stdout:"",error:r.error}},nA=async(t,e,r)=>{let n=await fetch(t,{method:"POST",headers:e,body:"{}",signal:AbortSignal.timeout(r)});return{status:n.status,body:await n.text()}},sA=rA,iA=nA;function oA(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function aA(t){let e=t.trim().toLowerCase(),r={"gemini models":"gemini","claude and gpt models":"3p",gemini:"gemini","3p models":"3p","3p":"3p"};return r[e]?r[e]:e.replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function lA(t){let e=t.toLowerCase();return e.includes("weekly")?"weekly":e.includes("five hour")||e.includes("5-hour")||e.includes("5 hour")?"five_hour":e.includes("monthly")||e.includes("month")?"monthly":null}function cA(t){let e={weekly:"weekly",five_hour:"5h",monthly:"monthly"},r=[];for(let n of t.split(/\r?\n/)){let s=n.trim().split(" ").map(l=>l.trim());if(s.length<3||!s[0]||!s[1])continue;let i=lA(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=xe(o/100);r.push(Me({bucket_id:`${aA(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:xe(1-a),remaining_fraction:a,resets_at_iso:s[3]||null,raw_value:o,raw_scale:"remaining_percent"}))}return r.sort((n,s)=>String(n.group_name??"").localeCompare(String(s.group_name??""))||String(n.bucket_id??"").localeCompare(String(s.bucket_id??"")))}function zn(t,e,r){return Fe("agy","provider_unavailable",t,e,"agy_cli_print")}function dA(t,e,r={}){try{let n=sA(Math.max(t,60)*1e3,oA(e));if(je(r,"agy_cli_print",n.stdout??"",[e.ANTIGRAVITY_CSRF_TOKEN]),n.error?.code==="ENOENT")return zn("agy_not_found","the agy CLI is not on PATH",t);if(n.error?.code==="ETIMEDOUT")return zn("cli_timeout","agy -p /usage did not finish in time",t);if(n.error)return zn("cli_failed",n.error.message,t);let s=cA(n.stdout??"");return s.length===0?zn("cli_unparseable",`exit ${n.status??1}; no buckets parsed from CLI output`,t):we("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:s})}catch(n){return zn("cli_failed",n instanceof Error?n.message:String(n),t)}}function uA(t){let e=[],r=new Set,n=(s,i,o)=>{!s||!i||r.has(`${s}\0${i}`)||(r.add(`${s}\0${i}`),e.push([s,i,o]))};n(t[Ug],t[jg],-1);try{for(let s of zk("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of Qk(Zk("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[Ug],i[jg],Number(s))}catch{}}catch{}return e}function fA(t){if(typeof t!="object"||t===null)return null;let e=t.response;if(typeof e!="object"||e===null)return null;let r=e.groups;if(!Array.isArray(r))return null;let n=[];for(let s of r){if(typeof s!="object"||s===null)continue;let i=s,o=typeof i.displayName=="string"?i.displayName:null;if(Array.isArray(i.buckets))for(let a of i.buckets){if(typeof a!="object"||a===null)continue;let l=a,c=ot(l.remainingFraction,"fraction");n.push(Me({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:Pg(l.window),used_fraction:c===null?null:xe(1-c),remaining_fraction:c,resets_at_iso:l.resetTime??null,raw_value:l.remainingFraction??null,raw_scale:"remaining_fraction"}))}}return n.length===0?null:(n.sort((s,i)=>String(s.group_name??"").localeCompare(String(i.group_name??""))||String(s.bucket_id??"").localeCompare(String(i.bucket_id??""))),we("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function mA(t,e,r={}){let n=uA(e);if(n.length===0)return Fe("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let s=[];for(let[i,o,a]of n)try{let l=await iA(`http://${i}${eA}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":o},t*1e3);if(je(r,"agy_connect_rpc",l.body,[o],l.status),l.status===200){let c;try{c=JSON.parse(l.body)}catch{s.push(`pid=${a}: unparseable response`);continue}let d=fA(c);if(d)return d;s.push(`pid=${a}: response had no quota groups`)}else l.status===401||l.status===403?s.push(`pid=${a}: HTTP ${l.status} unauthorized`):s.push(`pid=${a}: HTTP ${l.status}`)}catch(l){s.push(`pid=${a}: ${l instanceof Error?l.message:String(l)}`)}return Fe("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${s.slice(0,5).join("; ")}`,"agy_connect_rpc",n.map(([,i])=>i))}async function Bg(t){let e=dA(t.timeoutSeconds,t.env,t);if(e.status==="ok")return e;let r=await mA(t.timeoutSeconds,t.env,t);return r.status==="ok"?r:Fe("agy","provider_unavailable","cli_and_language_server_unavailable",`cli: ${String(e.reason??e.status)} (${String(e.detail??"no detail")}); connect: ${String(r.reason??r.status)} (${String(r.detail??"no detail")})`,"agy_cli_print")}import{spawnSync as zg}from"node:child_process";import{randomUUID as Xg}from"node:crypto";import{mkdirSync as pA,readFileSync as kc,realpathSync as hA,renameSync as gA,rmSync as Ac,statSync as Hg,writeFileSync as qg}from"node:fs";import{homedir as _A}from"node:os";import{join as Nc}from"node:path";import{setTimeout as yA}from"node:timers/promises";var EA="9d1c250a-e61b-44d9-88ed-5944d1962f5e",TA="https://console.anthropic.com/v1/oauth/token",wA=3e5;function Cc(t){return Nc(t.CLAUDE_CONFIG_DIR??Nc(t.HOME??_A(),".claude"),".credentials.json")}function Rc(t){let e=JSON.parse(kc(t,"utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("invalid credential document");return e}function Lc(t){let e=t.claudeAiOauth;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Gg(t){if(t.CLAUDE_CODE_OAUTH_TOKEN)return{oauth:{accessToken:t.CLAUDE_CODE_OAUTH_TOKEN}};let e=Cc(t);try{let r=Lc(Rc(e));return typeof r?.accessToken=="string"&&r.accessToken?{oauth:r,path:hA(e)}:{error:"not_claude_ai_subscriber"}}catch(r){return r.code==="ENOENT"?{error:t.ANTHROPIC_API_KEY?"not_claude_ai_subscriber":"no_credentials_found"}:{error:"credentials_unreadable"}}}function oo(t){return typeof t.expiresAt=="number"&&Date.now()+wA>=t.expiresAt}function Wg(t,e){return t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken}async function SA(t,e){let r=`${t}.lmctl-refresh.lock`,n=Nc(r,"owner.json"),s=Xg();for(;;){e.throwIfAborted();try{pA(r,{mode:448});try{qg(n,JSON.stringify({pid:process.pid,token:s}),{mode:384})}catch(i){throw Ac(r,{recursive:!0,force:!0}),i}return()=>{try{JSON.parse(kc(n,"utf8")).token===s&&Ac(r,{recursive:!0,force:!0})}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let o=!1;try{let a=JSON.parse(kc(n,"utf8")).pid;if(Number.isInteger(a)&&a>0)try{process.kill(a,0)}catch(l){o=l.code==="ESRCH"}else o=Date.now()-Hg(r).mtimeMs>6e4}catch{try{o=Date.now()-Hg(r).mtimeMs>6e4}catch{continue}}if(o)throw new Error("refresh_lock_stale");await yA(50,void 0,{signal:e})}}}async function Jg(t,e){if(!t.path||typeof t.oauth?.refreshToken!="string"||!t.oauth.refreshToken)throw new Error("no_refresh_token");let r=await SA(t.path,e);try{let n=Lc(Rc(t.path));if(!n||typeof n.accessToken!="string")throw new Error("credentials_changed");if(!Wg(n,t.oauth)&&!oo(n))return n;if(typeof n.refreshToken!="string"||!n.refreshToken)throw new Error("no_refresh_token");let s=await fetch(TA,{method:"POST",headers:{"Content-Type":"application/json"},signal:e,body:JSON.stringify({grant_type:"refresh_token",refresh_token:n.refreshToken,client_id:EA})});if(!s.ok)throw new Error(`refresh_http_${s.status}`);let i=await s.json();if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||i.refresh_token!==void 0&&(typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)))throw new Error("invalid_refresh_response");let o=Math.floor(Date.now()+i.expires_in*1e3);if(!Number.isSafeInteger(o)||o<=Date.now())throw new Error("invalid_refresh_response");let a=Rc(t.path),l=Lc(a);if(!l||!Wg(n,l)){if(l&&typeof l.accessToken=="string"&&!oo(l))return l;throw new Error("credentials_changed")}let c={...l,accessToken:i.access_token,refreshToken:i.refresh_token??n.refreshToken,expiresAt:o,...typeof i.scope=="string"?{scopes:i.scope.split(/\s+/).filter(Boolean)}:{}},d=`${t.path}.${Xg()}.tmp`;try{qg(d,JSON.stringify({...a,claudeAiOauth:c}),{flag:"wx",mode:384}),gA(d,t.path)}finally{Ac(d,{force:!0})}return c}finally{r()}}var vA="https://api.anthropic.com",bA="oauth-2025-04-20",Vg="user:profile";function IA(t){let e=String(t??"").toLowerCase();return e.includes("session")||e.includes("five")||e.includes("5h")?"five_hour":e.includes("week")||e.includes("seven")||e.includes("7d")?"weekly":e.includes("month")||e.includes("30d")?"monthly":"unknown"}var _e={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};function Qg(t){return Object.fromEntries(Object.entries(t).filter(([e])=>e!=="CLAUDECODE"))}function xA(t){try{let e=zg("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:Qg(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function Je(t,e,r,n="claude_oauth_api",s){return Fe("claude",t,e,r,n,void 0,s)}function kA(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function AA(t){if(!t)return;let e=/^([A-Za-z]{3,9})\s+(\d{1,2}),?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?$/i.exec(t.trim());if(!e)return;let r=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"].indexOf(e[1].slice(0,3).toLowerCase());if(r<0)return;let n=Number(e[3]),s=Number(e[4]??0);(e[5]??"").toLowerCase()==="pm"&&n!==12&&(n+=12),(e[5]??"").toLowerCase()==="am"&&n===12&&(n=0);let i=new Date(Date.UTC(new Date().getUTCFullYear(),r,Number(e[2]),n,s));return Number.isFinite(i.getTime())?Math.floor(i.getTime()/1e3):void 0}var NA=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/;function RA(t){let e=[];for(let r of t.split(/\r?\n/)){let n=NA.exec(r.trim());if(!n)continue;let s=n[1].trim(),o=s.toLowerCase()==="session",a=/\(([^)]+)\)/.exec(s)?.[1]?.trim()??s,l=o?"session":a.toLowerCase()==="all models"?"week-all-models":`week-scoped-${a}`,c=o?"five_hour":"weekly";e.push(Me({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:ot(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:AA(n[3])}))}return e.sort((r,n)=>String(r.window_type).localeCompare(String(n.window_type))||String(r.bucket_id).localeCompare(String(n.bucket_id)))}function LA(t){let e={},r;for(let n of t.split(/\r?\n/)){let s=/^Last\s+(\S+)\s*[·-]\s*(\d+)\s+requests?\s*[·-]\s*(\d+)\s+sessions?\s*$/.exec(n.trim());if(s){r={requests:Number(s[2]),sessions:Number(s[3])},e[`window_${s[1].toLowerCase()}`]=r;continue}let i=/^\s+(\d+)%\s+of your usage\s+(.+?)\s*$/.exec(n);if(!i||!r)continue;let o=i[2].toLowerCase(),a=o.includes(">150k context")?"pct_high_context":o.includes("active for 8+ hours")?"pct_long_sessions":o.includes("subagent-heavy")?"pct_subagent_heavy":o.includes("ran in parallel")?"pct_parallel_sessions":void 0;a&&(r[a]=Number(i[1]))}return e}function Kg(t){if(!t||typeof t!="object")return;let e=t,r=e.limit&&typeof e.limit=="object"?e.limit:{},n=e.used&&typeof e.used=="object"?e.used:{},s=r.exponent??n.exponent??2,i=l=>l==null||!Number.isFinite(Number(l))?void 0:(Number(l)/10**Number(s)).toFixed(2),o=ot(e.percent,"percent"),a={limit_usd:i(r.amount_minor),used_usd:i(n.amount_minor),remaining_fraction:o==null?void 0:Math.max(0,1-o),resets_at_iso:e.resets_at};return Object.values(a).every(l=>l==null)?void 0:a}async function Yg(t,e,r,n={}){try{let s=zg("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:Qg(e),maxBuffer:16777216}),i=typeof s.stdout=="string"?s.stdout:"";je(n,"claude_cli_print",i,[t.accessToken,t.refreshToken]);let o=RA(i);if(!o.length)return;let a=LA(i);return we("claude",_e.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:o,...Object.keys(a).length?{characteristics:a}:{}})}catch{return}}async function Zg({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s=Gg(e);if(s.error==="not_claude_ai_subscriber")return Je(_e.notApplicable,s.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(s.error==="no_credentials_found")return Je(_e.unavailable,"credentials_missing",`credentials file not found: ${Cc(e)}`);if(s.error)return Je(_e.expired,"oauth_token_expired_or_invalid",s.error);let i=s.oauth,o=Array.isArray(i.scopes)?i.scopes:[];if(o.length&&!o.includes(Vg))return Je(_e.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${Vg} scope required by the usage endpoint`);let a=new AbortController,l=setTimeout(()=>a.abort(),t*1e3),c,d;try{let m=!1,h=async()=>{try{i=await Jg({...s,oauth:i},a.signal),m=!0}catch(g){let y=g instanceof Error&&/^(no_refresh_token|credentials_changed|invalid_refresh_response|refresh_lock_stale|refresh_http_\d+)$/.test(g.message)?g.message:"refresh_failed";if(y==="refresh_http_429")return Je(_e.throttled,"rate_limited","Claude OAuth refresh was rate limited; try again later");if(y==="refresh_lock_stale")return Je(_e.expired,"oauth_refresh_locked","a previous Claude credential refresh exited without releasing its lock; remove the stale .credentials.json.lmctl-refresh.lock directory before retrying");let S=y==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(y);return Je(S?_e.expired:_e.unavailable,S?"oauth_token_expired_or_invalid":"oauth_refresh_failed",`Claude OAuth refresh failed (${y})${S?"; renew Claude login":"; try again later"}`)}};if(oo(i)){let g=await h();if(g)return g}let T=()=>fetch(`${vA}/api/oauth/usage`,{headers:{Authorization:`Bearer ${i.accessToken}`,"anthropic-beta":bA,"Content-Type":"application/json","User-Agent":xA(e)},signal:a.signal});if(c=await T(),d=await c.text(),je({debug:r,onRawResponse:n},"claude_oauth_api",d,[i.accessToken,i.refreshToken],c.status),c.status===401&&!m&&s.path&&i.refreshToken){let g=await h();if(g)return g;c=await T(),d=await c.text(),je({debug:r,onRawResponse:n},"claude_oauth_api",d,[i.accessToken,i.refreshToken],c.status)}}catch(m){let h=await Yg(i,e,t,{debug:r,onRawResponse:n});return h||Je(_e.unavailable,"request_failed",`${m instanceof Error?m.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(l)}let u=(...m)=>Jr(Je(...m),d,[String(i.accessToken??""),String(i.refreshToken??"")]);if(c.status===401)return u(_e.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(c.status===403)return u(_e.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(c.status===429){let m=kA(c.headers),h=await Yg(i,e,t,{debug:r,onRawResponse:n});return h||u(_e.throttled,"rate_limited",`usage endpoint rate limited${m==null?"":`; retry after ${m}s`}`,"claude_oauth_api",m)}if(c.status!==200)return u(_e.unavailable,`http_${c.status}`,"usage endpoint returned an unexpected status");let f;try{f=JSON.parse(d)}catch{return Je(_e.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!f||typeof f!="object"||Array.isArray(f))return Je(_e.unavailable,"malformed_response","response was not an object");let p=f,_=Array.isArray(p.limits)?p.limits:[],E=_.length?_.flatMap(m=>{if(!m||typeof m!="object")return[];let h=m.kind,T=IA(h==="session"?"session":h),g=m.scope?.model?.display_name,y=h==="session"?"session":h==="weekly_all"?"week-all-models":`week-scoped-${g||h}`;return[Me({bucket_id:y,group_name:h==="session"?"session":"weekly",window_type:T,used_fraction:ot(m.percent,"percent"),resets_at_iso:m.resets_at,raw_value:m.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(m=>{let h=p[m];return!h||typeof h!="object"?[]:[Me({bucket_id:m==="five_hour"?"session":"week-all-models",group_name:m==="five_hour"?"session":"weekly",window_type:m==="five_hour"?"five_hour":"weekly",used_fraction:ot(h.utilization,"percent"),resets_at_iso:h.resets_at,raw_value:h.utilization,raw_scale:"used_percent"})]});return we("claude",_e.ok,{source:"claude_oauth_api",account_id:null,plan_type:i.subscriptionType??i.rateLimitTier??null,ordinary_usage_allowed:null,buckets:E.sort((m,h)=>String(m.window_type).localeCompare(String(h.window_type))||String(m.bucket_id).localeCompare(String(h.bucket_id))),...Kg(p.spend)?{spend_control:Kg(p.spend)}:{}})}import{readFileSync as CA}from"node:fs";import{homedir as OA}from"node:os";import{join as DA}from"node:path";var MA="https://chatgpt.com/backend-api",FA="codex-cli";function Be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function e_(t){let e=typeof t=="number"?t:Number(t);if(!Number.isFinite(e)||e<=0)return"unknown";let r=e/60;return r>=240&&r<=360?"five_hour":r>=9e3&&r<=11500?"weekly":r>=38e3&&r<=46e3?"monthly":"unknown"}function t_(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function PA(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||DA(OA(),".codex","auth.json");try{let r=JSON.parse(CA(e,"utf8")),n=Be(r)&&Be(r.tokens)?r.tokens:void 0,s=n?.access_token,i=n?.account_id;return{token:typeof s=="string"?s:void 0,accountId:typeof i=="string"?i:void 0}}catch{return{}}}function $A(t){if(Be(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function UA(t){let e=[],r=Be(t.rate_limit)?t.rate_limit:{},n=typeof r.allowed=="boolean"?r.allowed:void 0,s=typeof r.limit_reached=="boolean"?r.limit_reached:void 0;for(let o of["primary_window","secondary_window"]){let a=Be(r[o])?r[o]:void 0;if(!a)continue;let l=e_(a.limit_window_seconds);e.push(Me({bucket_id:`codex-${t_(l)}`,group_name:"codex",window_type:l,used_fraction:ot(a.used_percent,"percent"),resets_at:a.reset_at,raw_value:a.used_percent,raw_scale:"used_percent",...n===void 0?{}:{allowed:n},...s===void 0?{}:{limit_reached:s}}))}let i=Array.isArray(t.additional_rate_limits)?t.additional_rate_limits:[];for(let o of i){if(!Be(o))continue;let a=Be(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,d=c||l||"additional",u=typeof a.allowed=="boolean"?a.allowed:void 0,f=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let p of["primary_window","secondary_window"]){let _=Be(a[p])?a[p]:void 0;if(!_)continue;let E=e_(_.limit_window_seconds);e.push(Me({bucket_id:`${d}-${t_(E)}`,group_name:l||d,window_type:E,used_fraction:ot(_.used_percent,"percent"),resets_at:_.reset_at,raw_value:_.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...u===void 0?{}:{allowed:u},...f===void 0?{}:{limit_reached:f}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function jA(t){let e=Be(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=Be(t.spend_control)?t.spend_control:void 0,s=Be(t.credits)?t.credits:void 0;return we("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:UA(t),...s?{credits:$A(s)}:{},...n?{spend_control:n}:{}})}async function r_(t){let{timeoutSeconds:e,env:r,debug:n,onRawResponse:s}=t,i=PA(r);if(!i.token)return we("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let o=new AbortController,a=setTimeout(()=>o.abort(),Math.ceil(e*1e3));try{let l={Authorization:`Bearer ${i.token}`,"User-Agent":FA,"Content-Type":"application/json",Accept:"application/json"};i.accountId&&(l["ChatGPT-Account-Id"]=i.accountId);let c=(r.CODEX_BASE_URL||MA).replace(/\/$/,""),d=await fetch(`${c}/wham/usage`,{headers:l,signal:o.signal}),u=await d.text();je({debug:n,onRawResponse:s},"codex_http",u,[i.token],d.status);let f=(_,E)=>Jr(we("codex",_,E),u,[i.token]);if(d.status===401)return f("auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(d.status===429){let _=d.headers.get("retry-after"),E=_===null?void 0:Number.parseInt(_,10);return f("reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...E!==void 0&&Number.isFinite(E)&&E>=0?{retry_after_seconds:E}:{}})}if(!d.ok)return f("provider_unavailable",{source:"codex_http",reason:`http_${d.status}`,detail:"codex usage endpoint returned an unexpected status"});let p;try{p=JSON.parse(u)}catch(_){return we("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:Gr(String(_),[i.token])})}return Be(p)?jA(p):we("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(l){let c=l instanceof Error?`${l.name}: ${l.message}`:String(l);return we("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:Gr(c,[i.token])})}finally{clearTimeout(a)}}import{createHash as BA,randomUUID as HA}from"node:crypto";import{readFileSync as a_,openSync as WA,fsyncSync as XA,closeSync as qA,mkdirSync as n_,writeFileSync as l_,renameSync as GA,rmSync as JA,rmdirSync as VA,statSync as Oc,utimesSync as KA}from"node:fs";import{homedir as YA}from"node:os";import{basename as zA,dirname as QA,join as ao}from"node:path";import{setTimeout as c_}from"node:timers/promises";var s_="https://api.kimi.com/coding/v1",Dc="https://auth.kimi.com",ZA="17e5f671-d194-4dfb-9706-5516cb48c098",i_=t=>t.trim().replace(/\/+$/,"");function eN(t){let e;try{e=a_(t,"utf8")}catch(s){if(s.code==="ENOENT")return{};throw new Error("config_unreadable")}let r={},n="other";for(let s of e.split(/\r?\n/)){let i=/^\s*\[providers\.(?:"managed:kimi-code"|'managed:kimi-code')(\.oauth)?\]\s*(?:#.*)?$/.exec(s);if(i){n=i[1]?"oauth.":"";continue}if(/^\s*\[/.test(s)){if(s.includes("managed:kimi-code"))throw new Error("config_format_unsupported");n="other";continue}if(n==="other")continue;if(/^\s*oauth\s*=/.test(s))throw new Error("config_format_unsupported");let o=/^\s*(base_url|oauth_host|storage|key)\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*(?:#.*)?$/.exec(s);if(!o&&/^\s*(base_url|oauth_host|storage|key)\s*=/.test(s))throw new Error("config_malformed");if(o)try{r[n+o[1]]=o[2].startsWith('"')?JSON.parse(o[2]):o[2].slice(1,-1)}catch{throw new Error("config_malformed")}}return r}function lo(t){let e;try{e=JSON.parse(a_(t,"utf8"))}catch(r){throw new Error(r.code==="ENOENT"?"credentials_missing":"credentials_malformed")}if(e&&typeof e=="object"&&e.access_token===""&&e.refresh_token==="")throw new Error("credentials_revoked");if(!e||typeof e!="object"||Array.isArray(e)||typeof e.access_token!="string"||!e.access_token.trim())throw new Error("credentials_malformed");return e}function d_(t){let e=t.KIMI_CODE_HOME??ao(t.HOME??YA(),".kimi-code"),r=eN(t.KIMI_CODE_CONFIG_PATH??ao(e,"config.toml")),n=t.KIMI_CODE_BASE_URL!==void 0||t.KIMI_CODE_OAUTH_HOST!==void 0||t.KIMI_OAUTH_HOST!==void 0,s=i_(t.KIMI_CODE_BASE_URL??r.base_url??s_),i=i_(t.KIMI_CODE_OAUTH_HOST??t.KIMI_OAUTH_HOST??(n?Dc:r["oauth.oauth_host"]??Dc)),o=s===s_&&i===Dc?"kimi-code":`kimi-code-env-${BA("sha256").update(JSON.stringify({oauthHost:i,baseUrl:s})).digest("hex").slice(0,16)}`;if(!t.KIMI_CREDENTIALS_PATH&&!n&&r["oauth.key"]===`oauth/${o}`&&r["oauth.storage"]&&r["oauth.storage"]!=="file")throw new Error("credential_storage_unsupported");let a=t.KIMI_CREDENTIALS_PATH??ao(e,"credentials",`${o}.json`),l=lo(a),c=a,d=zA(a,".json");return{home:e,path:c,lockTarget:ao(e,"oauth",d),baseUrl:s,oauthHost:i,token:l}}function co(t){if(typeof t.expires_at!="number")return!1;let e=typeof t.expires_in=="number"?t.expires_in:0;return t.expires_at-Date.now()/1e3<Math.max(300,e*.5)}function o_(t,e){return t.access_token===e.access_token&&t.refresh_token===e.refresh_token&&t.expires_at===e.expires_at&&t.expires_in===e.expires_in}async function tN(t,e){n_(QA(t),{recursive:!0}),l_(t,"",{flag:"a",mode:384});let r=`${t}.lock`;for(;;){if(e.aborted)throw new Error("refresh_locked");try{n_(r);break}catch(o){if(o.code!=="EEXIST")throw new Error("refresh_lock_failed");try{if(Date.now()-Oc(r).mtimeMs>5e3)throw new Error("refresh_lock_stale")}catch(a){if(a.message==="refresh_lock_stale")throw a}try{await c_(50,void 0,{signal:e})}catch{throw new Error("refresh_locked")}}}let n=Oc(r),s=()=>{let o;try{o=Oc(r)}catch{throw new Error("refresh_lock_lost")}if(o.ino!==n.ino||o.dev!==n.dev)throw new Error("refresh_lock_lost")},i=setInterval(()=>{try{s();let o=new Date;KA(r,o,o)}catch{}},1e3);return i.unref(),{assertOwned:s,release(){clearInterval(i);try{s(),VA(r)}catch{}}}}async function u_(t,e){if(typeof t.token.refresh_token!="string"||!t.token.refresh_token)throw new Error("no_refresh_token");let r=await tN(t.lockTarget,e);try{let n=lo(t.path);if(!o_(n,t.token)&&!co(n))return n;if(typeof n.refresh_token!="string"||!n.refresh_token)throw new Error("no_refresh_token");let s;for(let u=0;u<3;u++){try{if(s=await fetch(`${t.oauthHost}/api/oauth/token`,{method:"POST",signal:e,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","User-Agent":"lmctl"},body:new URLSearchParams({client_id:ZA,grant_type:"refresh_token",refresh_token:n.refresh_token})}),![429,500,502,503,504].includes(s.status)||u===2)break;await s.body?.cancel()}catch{if(e.aborted||u===2)throw new Error("refresh_request_failed")}await c_(1e3*2**u,void 0,{signal:e})}if(!s)throw new Error("refresh_request_failed");if(!s.ok){try{let u=lo(t.path);if(u.refresh_token!==n.refresh_token)return u}catch{}throw new Error(`refresh_http_${s.status}`)}let i=await s.json(),o=Number(i?.expires_in);if(!i||typeof i.access_token!="string"||!/^\S+$/.test(i.access_token)||typeof i.refresh_token!="string"||!/^\S+$/.test(i.refresh_token)||!Number.isFinite(o)||o<=0)throw new Error("invalid_refresh_response");let a=Math.floor(Date.now()/1e3)+o;if(!Number.isSafeInteger(a))throw new Error("invalid_refresh_response");r.assertOwned();let l=lo(t.path);if(!o_(l,n)){if(!co(l))return l;throw new Error("credentials_changed")}let c={...l,access_token:i.access_token,refresh_token:i.refresh_token,expires_at:a,expires_in:o,...typeof i.scope=="string"?{scope:i.scope}:{},...typeof i.token_type=="string"?{token_type:i.token_type}:{}},d=`${t.path}.${HA()}.tmp`;try{let u=WA(d,"wx",384);try{l_(u,JSON.stringify(c,null,2)+`
|
|
2177
|
+
`),XA(u)}finally{qA(u)}r.assertOwned(),GA(d,t.path)}finally{JA(d,{force:!0})}return c}finally{r.release()}}function f_(t){let e=o=>{if(typeof o!="number"&&typeof o!="string"||typeof o=="string"&&o.trim()==="")return;let a=Number(o);return Number.isFinite(a)&&a>=0?a:void 0},r=e(t.limit),n=e(t.used),s=e(t.remaining);if(r===void 0||r<=0||n===void 0&&(s===void 0||s>r))return;let i=n??r-s;return{used:i,limit:r,remaining:Math.max(0,r-i)}}async function m_({timeoutSeconds:t,env:e,debug:r,onRawResponse:n}){let s;try{s=d_(e)}catch(E){let m=E instanceof Error&&/^(credentials_missing|credentials_malformed|credentials_revoked|config_unreadable|config_malformed|config_format_unsupported|credential_storage_unsupported)$/.test(E.message)?E.message:"credentials_unreadable";return Fe("kimi",m==="credentials_revoked"?"auth_expired":"provider_unavailable",m,m==="credentials_revoked"?"Kimi login was revoked; run kimi login":m.replaceAll("_"," "),"kimi_http")}let i=s.token,o=new AbortController,a=setTimeout(()=>o.abort(),t*1e3),l,c;try{let E=!1,m=async()=>{i=await u_({...s,token:i},o.signal),E=!0};co(i)&&await m();let h=()=>fetch(`${s.baseUrl}/usages`,{headers:{Authorization:`Bearer ${i.access_token}`,Accept:"application/json"},signal:o.signal});l=await h(),c=await l.text(),je({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status),l.status===401&&!E&&i.refresh_token&&(await m(),l=await h(),c=await l.text(),je({debug:r,onRawResponse:n},"kimi_http",c,[i.access_token,i.refresh_token],l.status))}catch(E){let m=E instanceof Error&&/^(no_refresh_token|credentials_changed|credentials_revoked|invalid_refresh_response|refresh_locked|refresh_lock_stale|refresh_lock_failed|refresh_lock_lost|refresh_request_failed|refresh_http_\d+)$/.test(E.message)?E.message:"request_failed",h=m==="credentials_revoked"||m==="no_refresh_token"||/^refresh_http_(400|401|403)$/.test(m),T=m==="refresh_lock_stale"?"Kimi refresh lock is stale; run the native Kimi CLI to recover its lock, or verify no refresh is active before removing the .lock directory":h?`Kimi credential renewal failed (${m}); run kimi login`:`Kimi quota request failed (${m})`;return Fe("kimi",h?"auth_expired":"provider_unavailable",m,T,"kimi_http")}finally{clearTimeout(a)}let d=(E,m,h)=>Jr(Fe("kimi",E,m,m,"kimi_http",[],h),c,[i.access_token]);if(l.status===401)return d("auth_expired","HTTP 401 from Kimi usage endpoint");if(l.status===403)return d("not_applicable","HTTP 403 from Kimi usage endpoint");if(l.status===429){let E=$g(l.headers);return d("reader_throttled","HTTP 429 from Kimi usage endpoint",E)}if(l.status!==200)return d("provider_unavailable",`HTTP ${l.status} from Kimi usage endpoint`);let u;try{u=JSON.parse(c)}catch{return Fe("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!u||typeof u!="object")return Fe("kimi","provider_unavailable","malformed_response","response was not an object");let f=[],p=new Set;function _(E){let m=String(E.bucket_id),h=m,T=2;for(;p.has(m);)m=`${h}-${T}`,T++;p.add(m),E.bucket_id=m,f.push(Me(E))}if(Array.isArray(u.limits))for(let E of u.limits){if(!E||typeof E!="object")continue;let m=E.window,h=E.detail;if(!m||typeof m!="object"||!h||typeof h!="object")continue;let T=0;if(m.timeUnit==="TIME_UNIT_MINUTE")T=Number(m.duration);else if(m.timeUnit==="TIME_UNIT_HOUR")T=Number(m.duration)*60;else if(m.timeUnit==="TIME_UNIT_DAY")T=Number(m.duration)*1440;else if(m.timeUnit==="TIME_UNIT_WEEK")T=Number(m.duration)*10080;else if(m.timeUnit==="TIME_UNIT_MONTH")T=Number(m.duration)*43200;else continue;let g=Fg(T),y="window";g==="five_hour"&&(y="5h"),g==="weekly"&&(y="weekly"),g==="monthly"&&(y="monthly");let S=f_(h);if(!S)continue;let{used:I,limit:b,remaining:k}=S;_({bucket_id:`kimi-${y}`,window_type:g,used_fraction:xe(I/b),remaining_fraction:xe(k/b),resets_at_iso:h.resetTime,raw_value:I,raw_scale:"count"})}if(u.usage&&typeof u.usage=="object"){let E=f_(u.usage);E&&_({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:xe(E.used/E.limit),remaining_fraction:xe(E.remaining/E.limit),resets_at_iso:u.usage.resetTime,raw_value:E.used,raw_scale:"count"})}if(u.usages&&typeof u.usages=="object"){let E=[{key:"limit_5h",id:"kimi-5h",type:"five_hour"},{key:"limit_7d",id:"kimi-weekly",type:"weekly"},{key:"limit_month_total",id:"kimi-monthly",type:"monthly"},{key:"limit_month_code",id:"kimi-monthly-code",type:"monthly"}];for(let{key:m,id:h,type:T}of E){let g=u.usages[m];if(!g||typeof g!="object"||g.used_ratio==null||g.used_ratio===""||typeof g.used_ratio=="boolean")continue;let y=Number(g.used_ratio);!Number.isFinite(y)||y<0||p.has(h)||(p.add(h),f.push(Me({bucket_id:h,window_type:T,used_fraction:xe(y),resets_at_iso:typeof g.reset_time=="string"&&g.reset_time?g.reset_time:null,raw_value:y,raw_scale:"ratio"})))}}return we("kimi","ok",{source:"kimi_http",buckets:f})}var p_=["all","codex","agy","claude","kimi"],rN=15;async function h_(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let a of e)if(!p_.includes(a))return{status:"error",error:`unknown provider: ${a} (valid targets: ${p_.join(", ")})`,readings:[]};let r=t.timeoutSeconds??rN;if(!Number.isFinite(r)||r<=0)return{status:"error",error:"timeoutSeconds must be a positive finite number",readings:[]};let n=t.env??process.env,s=new Set(e.includes("all")?["codex","agy","claude","kimi"]:e);t.progress?.(`querying ${e.join(" ")} live (timeout ${r}s per provider) ...`);let o=Object.entries({codex:r_,agy:Bg,claude:Zg,kimi:m_}).filter(([a])=>s.has(a)).map(async([,a])=>{let l=[],c=await a({timeoutSeconds:r,env:n,...t.debug?{debug:t.debug}:{},...t.includeRaw?{onRawResponse:d=>l.push(d)}:{}});return t.includeRaw?{...c,raw_responses:l}:c});try{return{status:"ok",readings:(await Promise.all(o)).filter(Boolean)}}catch(a){return{status:"error",error:String(a),readings:[]}}}oa();Wn();Kt();Er();un();qt();Ki();Xs();gs();import{execFile as nN}from"node:child_process";import{mkdtempSync as sN,realpathSync as Pc,rmSync as iN,statSync as v_}from"node:fs";import{tmpdir as b_}from"node:os";import{isAbsolute as $c,join as g_,relative as oN}from"node:path";import{promisify as aN}from"node:util";var lN=aN(nN),cN=[{name:"lmbee_queue_list",category:"Queue Management",signature:"lmbee_queue_list(snapshot_db, team = null, options = null)",description:"Lists queue rows from a temporary lmbee database copy, read directly (no lmbee executable needed).",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"},{name:"options",type:"map",description:`Optional { scope, limit, after_id }: scope "recent" (default) is the newest 30 rows; scope "unfinished" is every genuinely open row (lmauto's listUnfinishedQueue predicate); scope "all" is every row. limit (1-200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:"{ queue: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; each row carries hasAnswer (current, non-superseded answer)"},example:'page = lmbee_queue_list("/tmp/lmbee-copy/state.db", null, {"scope":"unfinished","limit":200});'},{name:"lmbee_queue_get",category:"Queue Management",signature:"lmbee_queue_get(snapshot_db, id)",description:"Gets one queue row from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer queue ID"}],returns:{type:"map",description:"{ queue: row, hasAnswer: boolean } or a queue_not_found error object"},example:'item = lmbee_queue_get("/tmp/lmbee-copy/state.db", 7);'},{name:"lmbee_queue_stats",category:"Queue Management",signature:"lmbee_queue_stats(snapshot_db, team = null)",description:"Reads per-recipient queue counts from a temporary lmbee database copy, without a row window.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"team",type:"string",description:"Optional recipient filter"}],returns:{type:"map",description:"{ stats: [...] } most-stale-first; team_progress-sourced fields (escalationAttemptCount, lastEscalationAttemptTs, quota*) default to 0/null when the snapshot predates that table"},example:'counts = lmbee_queue_stats("/tmp/lmbee-copy/state.db", "worker");'},{name:"lmbee_tasks",category:"Queue Management",signature:"lmbee_tasks(snapshot_db, options = null)",description:"Lists task-ledger rows (lmauto entities: epics, tasks, subtasks) from a temporary lmbee database copy.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:`Optional { scope, status, owner, team, limit, after_id }: scope "recent" (default) is the newest 30 rows and is NOT pageable (limit/after_id require unfinished or all; use a paged scope to traverse completely); scope "unfinished" excludes rows whose normalized status (trim, lowercase, separators to hyphens -- lmauto's normalizeStatus) is done/closed/cancelled, the audit terminal set -- a deliberate bridge choice, since lmauto itself uses done/closed for epic completeness and done-only for dependency satisfaction; scope "all" is every row. status exact-matches the stored value with the ARGUMENT trimmed (lmauto listEntities). owner exact-matches owner_alias; alias-only is a cross-team match -- add team (exact match on the stored canonical team path) to pin one team. limit (1-200, default 200) and after_id page unfinished/all newest-first.`}],returns:{type:"map",description:`{ tasks: [...] } for recent, plus { meta: { next_cursor } } for paged scopes; rows carry id, kind, project, parent_id, title, status, owner_team_path, owner_alias, created_at, updated_at -- updated_at is the entity's own update time, NOT "last activity" (delivery bookkeeping deliberately does not touch it)`},example:'tasks = lmbee_tasks("/tmp/lmbee-copy/state.db", {"scope":"unfinished","owner":"worker","limit":50});'},{name:"lmbee_task_get",category:"Queue Management",signature:"lmbee_task_get(snapshot_db, id)",description:'Gets one task-ledger row with its direct children, so "does this parent still have open children" is a single field.',parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"id",type:"number",description:"Positive integer entity ID"}],returns:{type:"map",description:"{ task, children, open_children } or a task_not_found error object; children is id-ascending and DIRECT only, and open_children counts those direct children whose normalized status is not done/closed/cancelled -- it claims nothing about grandchildren"},example:'t = lmbee_task_get("/tmp/lmbee-copy/state.db", 12);'},{name:"lmbee_cron_list",category:"Queue Management",signature:"lmbee_cron_list(snapshot_db, options = null)",description:"Lists cron jobs from a temporary lmbee database copy. Jobs are operator-created and few, so there is deliberately no paging.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { enabled }: true/false to filter; omitted lists all"}],returns:{type:"map",description:'{ jobs: [...] } by ascending id, with enabled as a real boolean. Two traps: legacy command/enqueue jobs NEVER write cron_runs -- for them "did it run" is last_fired_ts/last_fire_status/last_fire_error on this row; and running_since_ts non-null means a legacy execution is currently claimed'},example:'jobs = lmbee_cron_list("/tmp/lmbee-copy/state.db", {"enabled":true});'},{name:"lmbee_cron_runs",category:"Queue Management",signature:"lmbee_cron_runs(snapshot_db, options = null)",description:"Lists cron run-ledger rows (run-based job kinds: script/session/miniplayer) from a temporary lmbee database copy, newest-first.",parameters:[{name:"snapshot_db",type:"string",description:"Existing database copy in the system temp directory"},{name:"options",type:"map",description:"Optional { job_id, status, limit, after_id }: status is one of pending/running/succeeded/failed/escalated; limit (1-200) defaults to 50 -- the ledger only grows, so page with after_id rather than reading unbounded"}],returns:{type:"map",description:"{ runs: [...], meta: { next_cursor } }. Outcome (status) and execution liveness (execution_state) are SEPARATE: succeeded can coexist with an active execution fence. An empty result does NOT mean a job never ran -- legacy command/enqueue jobs write nothing here; check the job row via lmbee_cron_list. run_token_hash is never returned (lmbee's own public projection)"},example:'runs = lmbee_cron_runs("/tmp/lmbee-copy/state.db", {"job_id":3,"limit":50});'},{name:"lmbee_snapshot",category:"Queue Management",signature:"lmbee_snapshot(source_db)",description:"Creates a WAL-aware temporary database backup, removed when the script ends.",parameters:[{name:"source_db",type:"string",description:"Absolute path to an existing lmbee database"}],returns:{type:"string",description:"Temporary snapshot path for lmbee queue functions"},example:'snapshot = lmbee_snapshot(env("HOME") + "/.lmbee/state.db");'}];function I_(t){if(typeof t!="string"||!t||!$c(t))throw new Error("lmbee: snapshot_db must be an absolute path to a temporary database copy");let e;try{e=Pc(t);let n=v_(e);if(!n.isFile()||n.nlink!==1)throw new Error("not a standalone file")}catch{throw new Error("lmbee: snapshot_db must be an existing temporary database copy")}let r=oN(Pc(b_()),e);if(!r||r===".."||r.startsWith("../")||$c(r))throw new Error("lmbee: snapshot_db must be a temporary database copy inside the system temp directory");return e}function __(t){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error("lmbee: team must be a nonempty string");return t}}function dN(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");return{scope:r,limit:n,afterId:s}}var uN=["id","from_id","to_id","status","created_ts","expects_response","in_reply_to","retracted_ts","escalation_claimed_ts"],fN=["prompt_queue_id","superseded_at"],mN=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],x_=["id","kind","project","parent_id","title","status","owner_team_path","owner_alias","created_at","updated_at"],uo=x_.join(", "),pN="replace(replace(lower(trim(status, char(9, 10, 11, 12, 13, 32, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279))), ' ', '-'), '_', '-')",k_=`${pN} NOT IN ('done', 'closed', 'cancelled')`,A_=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","session_teamfile","session_alias","session_seeded_at","session_generation","enabled","last_checked_ts","last_fired_ts","last_fire_status","last_fire_error","running_systemd_unit","timezone","running_since_ts","created_at","updated_at","revision"],y_=A_.join(", "),N_=["id","job_id","status","execution_state","trigger_kind","config_snapshot","execution_identity","pid","summary","artifacts","escalation_reason","escalation_action","escalation_owner","escalation_resolved_at","escalation_resolution","escalation_resolution_actor","escalation_resolution_note","execution_gone_at","execution_uncertain_reason","execution_confirmation_note","reported_at","created_at","started_at","finished_at","updated_at"],hN=N_.join(", "),gN=new Set(["pending","running","succeeded","failed","escalated"]),_N=`q.status != 'merged'
|
|
2179
2178
|
AND q.retracted_ts IS NULL
|
|
2180
2179
|
AND NOT EXISTS (SELECT 1 FROM answers r WHERE r.prompt_queue_id = q.id)
|
|
2181
|
-
AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`,
|
|
2182
|
-
`)}}function
|
|
2183
|
-
`),null}}function
|
|
2180
|
+
AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`,E_="EXISTS (SELECT 1 FROM answers a WHERE a.prompt_queue_id = q.id AND a.superseded_at IS NULL)";function R_(t,e){let r=t.prepare(`SELECT name FROM pragma_table_info('${e}')`).all();return new Set(r.map(n=>n.name))}function L_(t,e,r){let n=R_(t,e);if(n.size===0)throw new Error(`lmbee: snapshot schema incompatible: missing table '${e}' (expected the lmbee schema; its absence is not an empty result)`);let s=r.filter(i=>!n.has(i));if(s.length>0)throw new Error(`lmbee: snapshot schema incompatible: table '${e}' is missing column(s): ${s.join(", ")}`)}var Mc=[["queue",uN],["answers",fN]],T_=[["entities",x_]],yN=[["cron_jobs",A_]],EN=[["cron_runs",N_]];function TN(t,e){let r=I_(t),n=new mr(r,{readonly:!0,fileMustExist:!0});try{for(let[s,i]of e)L_(n,s,[...i])}catch(s){throw n.close(),s}return n}function w_(t){return{...t,hasAnswer:t.hasAnswer===1}}function wN(t,e,r){let n=[],s=[];e!==void 0&&(n.push("q.to_id = ?"),s.push(e)),r.scope==="unfinished"&&n.push(_N),r.afterId!==void 0&&(n.push("q.id < ?"),s.push(r.afterId));let i=n.length>0?`WHERE ${n.join(" AND ")}`:"";if(r.scope==="recent")return{queue:t.prepare(`SELECT q.*, ${E_} AS hasAnswer FROM queue q ${i} ORDER BY q.id DESC LIMIT 30`).all(...s).map(w_)};let o=t.prepare(`SELECT q.*, ${E_} AS hasAnswer FROM queue q ${i} ORDER BY q.id DESC LIMIT ?`).all(...s,r.limit+1),a=o.length>r.limit;return a&&(o.length=r.limit),{queue:o.map(w_),meta:{next_cursor:a?o[o.length-1].id:null}}}function SN(t,e){let r=t.prepare("SELECT * FROM queue WHERE id = ?").get(e);if(r==null)return{error:{code:"queue_not_found",message:`no queue entry ${e}`}};let n=t.prepare("SELECT 1 AS x FROM answers WHERE prompt_queue_id = ? AND superseded_at IS NULL").get(e);return{queue:r,hasAnswer:n!=null}}function S_(t,e){let r=t-Date.parse(e);return Number.isFinite(r)?r:null}function vN(t,e){let r=Date.now(),n=(f,p)=>e?t.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ? AND to_id = ?`).all(f,e):t.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ?`).all(f),s=f=>{let p=new Map;for(let _ of f){let E=p.get(_.to_id);E?E.push(_.ts):p.set(_.to_id,[_.ts])}return p},i=f=>{let p=f.reduce((_,E)=>_===null||E!==null&&E<_?E:_,null);return p===null?0:S_(r,p)},o=s(n("pending","created_ts")),a=s(n("escalating","escalation_claimed_ts")),l=new Map;if(R_(t,"team_progress").size>0){L_(t,"team_progress",mN);let f=e?t.prepare("SELECT * FROM team_progress WHERE team = ?").all(e):t.prepare("SELECT * FROM team_progress").all();for(let p of f)l.set(p.team,p)}let c=f=>({escalationAttemptCount:f?.escalation_attempt_count??0,lastEscalationAttemptTs:f?.last_escalation_attempt_ts??null,quotaExhaustedLastSeenAgeMs:f?.quota_exhausted_last_seen_ts?S_(r,f.quota_exhausted_last_seen_ts):null,quotaExhaustedMessage:f?.quota_exhausted_message??null}),d=new Set([...o.keys(),...a.keys()]),u=[...d].map(f=>{let p=o.get(f)??[],_=a.get(f)??[];return{toId:f,pendingCount:p.length,oldestPendingAgeMs:p.length>0?i(p):null,escalatingCount:_.length,oldestEscalatingAgeMs:_.length>0?i(_):null,...c(l.get(f))}});for(let f of l.values())d.has(f.team)||f.escalation_attempt_count<=0||u.push({toId:f.team,pendingCount:0,oldestPendingAgeMs:null,escalatingCount:0,oldestEscalatingAgeMs:null,...c(f)});return u.sort((f,p)=>(p.oldestPendingAgeMs??-1)-(f.oldestPendingAgeMs??-1)),{stats:u}}function Fc(t,e){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error(`lmbee: ${e} must be a nonempty string`);return t}}function bN(t){if(t==null)return{scope:"recent",limit:200};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.scope??"recent";if(r!=="recent"&&r!=="unfinished"&&r!=="all")throw new Error("lmbee: scope must be recent, unfinished, or all");let n=e.limit??200;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let s=e.after_id;if(s!==void 0&&(typeof s!="number"||!Number.isSafeInteger(s)||s<=0))throw new Error("lmbee: after_id must be a positive integer");if(r==="recent"&&(e.limit!==void 0||s!==void 0))throw new Error("lmbee: limit and after_id require unfinished or all scope");let i=Fc(e.status,"status")?.trim(),o=Fc(e.owner,"owner"),a=Fc(e.team,"team");return{scope:r,limit:n,afterId:s,status:i,owner:o,team:a}}function IN(t,e){let r=[],n=[];e.scope==="unfinished"&&r.push(k_),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.owner!==void 0&&(r.push("owner_alias = ?"),n.push(e.owner)),e.team!==void 0&&(r.push("owner_team_path = ?"),n.push(e.team)),e.afterId!==void 0&&(r.push("id < ?"),n.push(e.afterId));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"";if(e.scope==="recent")return{tasks:t.prepare(`SELECT ${uo} FROM entities ${s} ORDER BY id DESC LIMIT 30`).all(...n)};let i=t.prepare(`SELECT ${uo} FROM entities ${s} ORDER BY id DESC LIMIT ?`).all(...n,e.limit+1),o=i.length>e.limit;return o&&(i.length=e.limit),{tasks:i,meta:{next_cursor:o?i[i.length-1].id:null}}}function xN(t,e){let r=t.prepare(`SELECT ${uo} FROM entities WHERE id = ?`).get(e);if(r==null)return{error:{code:"task_not_found",message:`no task ${e}`}};let n=t.prepare(`SELECT ${uo} FROM entities WHERE parent_id = ? ORDER BY id ASC`).all(e),s=t.prepare(`SELECT COUNT(*) AS n FROM entities WHERE parent_id = ? AND ${k_}`).get(e);return{task:r,children:n,open_children:s.n}}function kN(t){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t.enabled;if(e!==void 0&&typeof e!="boolean")throw new Error("lmbee: enabled must be a boolean");return{enabled:e}}function AN(t,e){return{jobs:(e.enabled===void 0?t.prepare(`SELECT ${y_} FROM cron_jobs ORDER BY id ASC`).all():t.prepare(`SELECT ${y_} FROM cron_jobs WHERE enabled = ? ORDER BY id ASC`).all(e.enabled?1:0)).map(n=>({...n,enabled:n.enabled===1}))}}function NN(t){if(t==null)return{limit:50};if(typeof t!="object"||Array.isArray(t))throw new Error("lmbee: list options must be a map");let e=t,r=e.job_id;if(r!==void 0&&(typeof r!="number"||!Number.isSafeInteger(r)||r<=0))throw new Error("lmbee: job_id must be a positive integer");let n=e.status;if(n!==void 0&&(typeof n!="string"||!gN.has(n)))throw new Error("lmbee: status must be pending, running, succeeded, failed, or escalated");let s=e.limit??50;if(typeof s!="number"||!Number.isSafeInteger(s)||s<1||s>200)throw new Error("lmbee: limit must be an integer from 1 to 200");let i=e.after_id;if(i!==void 0&&(typeof i!="number"||!Number.isSafeInteger(i)||i<=0))throw new Error("lmbee: after_id must be a positive integer");return{jobId:r,status:n,limit:s,afterId:i}}function RN(t,e){let r=[],n=[];e.jobId!==void 0&&(r.push("job_id = ?"),n.push(e.jobId)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.afterId!==void 0&&(r.push("id < ?"),n.push(e.afterId));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"",i=t.prepare(`SELECT ${hN} FROM cron_runs ${s} ORDER BY id DESC LIMIT ?`).all(...n,e.limit+1),o=i.length>e.limit;return o&&(i.length=e.limit),{runs:i,meta:{next_cursor:o?i[i.length-1].id:null}}}function C_(t,e=()=>{}){let r=(s,i,o)=>{let a=TN(s,i);try{return o(a)}finally{a.close()}},n=async s=>{if(typeof s!="string"||!$c(s))throw new Error("lmbee: source_db must be an absolute path");let i;try{if(i=Pc(s),!v_(i).isFile())throw new Error("not a file")}catch{throw new Error("lmbee: source_db must be an existing database file")}let o=sN(g_(b_(),"lmctl-lmbee-snapshot-")),a=g_(o,"state.db");try{return await lN("sqlite3",["-readonly",i,`.backup "${a.replaceAll('"','""')}"`],{env:t,timeout:12e4,maxBuffer:1048576}),I_(a),e(o),a}catch(l){iN(o,{recursive:!0,force:!0});let c=l;throw c.code==="ENOENT"?new Error("sqlite3 executable not found on PATH"):new Error(`lmbee snapshot failed: ${c.stderr?.trim()||c.message}`)}};return{name:"lmbee",description:"Read-only queue, task-ledger, and cron queries against temporary lmbee database copies",docs:cN,register(s){s.registerFunction("lmbee_queue_list",(i,o,a)=>r(i,Mc,l=>wN(l,__(o),dN(a))),{min:1,max:3}),s.registerFunction("lmbee_queue_get",(i,o)=>{if(typeof o!="number"||!Number.isSafeInteger(o)||o<=0)throw new Error("lmbee: id must be a positive integer");return r(i,Mc,a=>SN(a,o))},2),s.registerFunction("lmbee_queue_stats",(i,o)=>r(i,Mc,a=>vN(a,__(o))),{min:1,max:2}),s.registerFunction("lmbee_tasks",(i,o)=>r(i,T_,a=>IN(a,bN(o))),{min:1,max:2}),s.registerFunction("lmbee_task_get",(i,o)=>{if(typeof o!="number"||!Number.isSafeInteger(o)||o<=0)throw new Error("lmbee: id must be a positive integer");return r(i,T_,a=>xN(a,o))},2),s.registerFunction("lmbee_cron_list",(i,o)=>r(i,yN,a=>AN(a,kN(o))),{min:1,max:2}),s.registerFunction("lmbee_cron_runs",(i,o)=>r(i,EN,a=>RN(a,NN(o))),{min:1,max:2}),s.registerFunction("lmbee_snapshot",n,1)}}}var cr=class{batchHandles=new Map;temporaryDirectories=new Set;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}registerTemporaryDirectory(e){this.temporaryDirectories.add(e)}removeTemporaryDirectories(){for(let e of this.temporaryDirectories)qN(e,{recursive:!0,force:!0}),this.temporaryDirectories.delete(e)}async forceCloseAll(e){try{for(let r of this.getOpenBatches())await X_(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}finally{this.removeTemporaryDirectories()}}};async function JN(t){let e=t.provider.trim().toLowerCase();return Gs(e,hf(),Gi())}async function jc(t,e){try{await G(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)}
|
|
2181
|
+
`)}}function VN(t,e){let r=zi(t,e);if(r.ok)return Qi(r.identity);if(r.reason==="unset")return null;throw new Error(Yi("batch"))}async function KN(t,e){try{let{member:r}=e;return await G(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)}
|
|
2182
|
+
`),null}}function YN(t,e,r,n){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let s=Jt({path:dt(n?.LMCTL_DB)});try{s.finishTrackedInvocation(e,r)}finally{s.close()}}catch{}}async function X_(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 jc(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 G(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)}
|
|
2184
2183
|
`)}}r==="done"&&e.stderr.write(`batch ${xt()}: completed ${t.promptCount}/${t.promptCount} prompts
|
|
2185
|
-
`)}}var Hc=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional 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(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));function sR(t){for(let e of Hc)t.registerFunctionDoc(e)}function K_(t={}){let e=new at;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+`
|
|
2184
|
+
`)}}var Bc=[{name:"lm_batch_open",category:"lmctl Automation",signature:"lm_batch_open(teamfile, alias, batchfile, options = {}); lm_batch_open(member, options = {})",description:"Opens a managed teamfile batch, or a file-free member-map batch using sequential native agent turns. The map form retains session identity without team leases, bundle optimization, or team tracking.",parameters:[{name:"teamfile",type:"string|map",description:"Teamfile path for the legacy form, or a member map for the two-argument form"},{name:"alias",type:"string",description:"Team member alias to target"},{name:"batchfile",type:"string",description:"Legacy form only: source label for tracking; not read by this function"},{name:"options",type:"map",description:"(optional) Teamfile form: promptCount, legacy. Member-map form: permissionMode, idleTimeoutMs, as for lm_agent"}],returns:{type:"map",description:"Batch handle object or null on error"},example:'handle = lm_batch_open("team.lmctl", "reviewer", "prompts.txt", { promptCount: 5 });'},{name:"lm_batch_turn",category:"lmctl Automation",signature:"lm_batch_turn(handle, prompt, index, total)",description:"Executes a single prompt turn within an active batch session, handling heartbeats and status reporting.",parameters:[{name:"handle",type:"map",description:"Active batch handle returned from lm_batch_open"},{name:"prompt",type:"string",description:"Prompt text to execute"},{name:"index",type:"number",description:"1-based prompt index"},{name:"total",type:"number",description:"Total number of prompts in batch"}],returns:{type:"map",description:"{ status: 'ok'|'busy'|'stalled'|'error', reply: string, error: string|null }"},example:'turn = lm_batch_turn(handle, "Summarize this diff", 1, 5);'},{name:"lm_batch_close",category:"lmctl Automation",signature:'lm_batch_close(handle, status = "done", error = null)',description:"Closes an active batch session and finalizes tracked invocations and bundle leases.",parameters:[{name:"handle",type:"map",description:"Active batch handle to close"},{name:"status",type:"string",description:"(optional) Terminal status: 'done', 'cancelled', or 'error' (default: 'done')"},{name:"error",type:"string",description:"(optional) Error message if batch failed"}],returns:{type:"bool",description:"true if successfully closed, false otherwise"},example:'lm_batch_close(handle, "done");'},{name:"lm_prompt",category:"lmctl Automation",signature:"lm_prompt(teamfile, alias, prompt, options = {})",description:"Sends a direct one-shot prompt to a team member and returns the reply.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Target team member alias"},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) Execution options: permissionMode, idleTimeoutMs, messageType"}],returns:{type:"map",description:"{ status, reply, error, message_id, team_chat_log_id }"},example:'res = lm_prompt("team.lmctl", "coder", "Hello agent");'},{name:"lm_agent",category:"lmctl Automation",signature:"lm_agent(member, prompt, options = {})",description:"Prompts a provider directly without a teamfile. Creates a session when sessionid is absent and writes its ID back into member for subsequent turns or explicit persistence.",parameters:[{name:"member",type:"map",description:"Required provider; optional alias, model, effort, sessiondir (default cwd), sessionid. Updated in place with sessionid."},{name:"prompt",type:"string",description:"Prompt text"},{name:"options",type:"map",description:"(optional) permissionMode (yolo or plan), idleTimeoutMs. Fresh agy/pi/dsh sessions require a preliminary seed in yolo mode."}],returns:{type:"map",description:"{ status, reply, error, message_id: null, team_chat_log_id: null }; no team mailbox or log is created"},example:'agent = { provider: "codex" }; res = lm_agent(agent, "Summarize this repository");'},{name:"lm_session_list",category:"lmctl Automation",signature:"lm_session_list(options = {})",description:"Lists native sessions in the current workspace by default. Options: provider, sessiondir, all.",returns:{type:"array",description:"Session maps with provider, sessionid, sessiondir, and modifiedAt."},example:'sessions = lm_session_list({ provider: "codex" });'},{name:"lm_session_delete",category:"lmctl Automation",signature:"lm_session_delete(member, options = {})",description:"Deletes a native session by provider and sessionid. Requires force: true because another process may be using it; refuses active turns in this script engine. A forced cross-process deletion can disrupt that turn.",returns:{type:"map",description:'{ status: "deleted"|"not_found"|"busy"|"error", error: string|null }'},example:"lm_session_delete(agent, { force: true });"},{name:"lm_fanout",category:"lmctl Automation",signature:"lm_fanout(participants, prompts, options = {})",description:"Dispatches a prompt to every participant CONCURRENTLY, over the same path as lm_agent -- for a runtime-sized fan-out that parallel([...]) cannot express, since parallel is a language construct fixed to the call expressions written in the script. Each participant gets its own result in its own array slot; there is no shared accumulator to race on.",parameters:[{name:"participants",type:"array",description:"Array of member maps, each shaped like lm_agent's member argument"},{name:"prompts",type:"string|array",description:"A single string broadcast to every participant, or an array of strings (one per participant, must be the same length as participants)"},{name:"options",type:"map",description:"(optional) Same options as lm_agent (permissionMode, idleTimeoutMs), applied identically to every participant"}],returns:{type:"array",description:"Array of lm_agent-shaped result maps ({ status, reply, error, message_id, team_chat_log_id }), in the SAME order as participants (not first-to-finish order)"},example:'reviewers = [{provider:"codex"}, {provider:"claude"}, {provider:"agy"}]; results = lm_fanout(reviewers, "Review this diff for correctness issues.");'},{name:"lm_seed",category:"lmctl Automation",signature:"lm_seed(teamfile, options = {})",description:"Seeds a real teamfile over the exact same internal path `lmctl seed` takes: seeds only members that lack a sessionid, writes each new sessionid/sessiondir back into the teamfile file, and leaves an already-seeded member untouched. `lmctl seed` itself stays a minimal primitive (one-sentence Lead prompt); a workflow that wants a richer or role-specific preamble supplies it via options.preamble instead of lmctl growing that behavior.",parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to seed"},{name:"options",type:"map",description:'(optional) preamble: a string (replaces the default prompt for whichever alias gets one today -- Lead) or a map keyed by alias, e.g. {"Lead": "...", "Reviewer": "..."} (replaces the default prompt entirely for each matched alias; a non-Lead alias gets no prompt at all unless keyed here)'}],returns:{type:"map",description:'{ status: "ok"|"error" }; progress, warnings and per-member errors are written to stderr, same as lmctl seed'},example:'lm_seed("team.lmctl", { preamble: { Lead: "Use `lmctl prompt` to send a message.", Reviewer: "Wait for a review request from Lead before doing anything." } });'},{name:"lm_terminal",category:"lmctl Automation",signature:"lm_terminal(teamfile, alias)",description:"Opens a tracked team member in its native provider TUI, preserving terminal ownership and inherited stdio. Refuses non-interactive mode.",parameters:[{name:"teamfile",type:"string",description:"Teamfile path"},{name:"alias",type:"string",description:"Member alias"}],returns:{type:"map",description:"{ status, code } after the TUI exits"},example:'lm_terminal("team.lmctl", "Lead");'},{name:"lm_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(value, ...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"value",type:"any",description:"Required first value or message"},{name:"args",type:"any[]",description:"Additional 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(value, ...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"value",type:"any",description:"Required first error detail"},{name:"args",type:"any[]",description:"Additional error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));function zN(t){for(let e of Bc)t.registerFunctionDoc(e)}function q_(t={}){let e=new at;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+`
|
|
2186
2185
|
`),i},{min: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+`
|
|
2187
|
-
`),i},{min:0},{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=
|
|
2188
|
-
`),o},{min:1},{description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(t.env?.LMCTL_NON_INTERACTIVE==="1"||bt(n))throw new Error("prompt_human is disabled in non-interactive mode");if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return
|
|
2186
|
+
`),i},{min:0},{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=Qr(s,i,"printf");return n.stdout.write(o+`
|
|
2187
|
+
`),o},{min:1},{description:"Formats and prints %s, %d, %f and %% with the same width and precision rules as sprintf",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(t.env?.LMCTL_NON_INTERACTIVE==="1"||bt(n))throw new Error("prompt_human is disabled in non-interactive mode");if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return en(s,i,o)}return Zr(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 G_(t,e,r,n=process.env){t.registerFunction("lm_exit",(m=0)=>{let h=Math.floor(Number(m)),T=Number.isFinite(h)&&h>=0&&h<=255?h:1;throw new ke(T)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return e.stderr.write(h+(h.endsWith(`
|
|
2189
2188
|
`)?"":`
|
|
2190
2189
|
`)),h},{min:1},"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...m)=>{let h=m.map(T=>typeof T=="object"?JSON.stringify(T):String(T)).join(" ");return e.stderr.write(`error: ${h}
|
|
2191
|
-
`),r.recordError(h),h},{min:1},"Writes error message to stderr and records it for end-of-run error summary");let s=(m,h=!1)=>{try{let T=
|
|
2192
|
-
`);return!!h?[T.trim()].filter(y=>y.length>0):T.split(/\n\s*\n/u).map(y=>y.trim()).filter(Boolean)}catch(T){throw K(e,`batch: ${T instanceof Error?T.message:String(T)}`),new ke(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 Xe(String(m)).members.map(T=>({alias:T.alias,provider:T.provider,model:T.model,sessionid:T.session,sessiondir:T.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 T=mt(String(m),String(h),e.dal);return{alias:T.alias,provider:T.provider,model:T.model,sessionid:T.sessionid,sessiondir:T.sessiondir,isLead:T.isLead,teamfile:T.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(m,h,T,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 x=h??{};if(typeof x!="object"||Array.isArray(x)||T!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let O={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...m},sourceMember:m,options:{...x},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(O),O}if(typeof h!="string"||typeof T!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let y;try{y=mt(String(m),String(h),e.dal)}catch(x){return K(e,`batch: ${x?.message||String(x)}`),null}let
|
|
2193
|
-
`);try{if(
|
|
2194
|
-
`);try{let J={...
|
|
2195
|
-
`);let
|
|
2196
|
-
`);try{let
|
|
2197
|
-
`)}})}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,T={},g=!1)=>{let y=(
|
|
2198
|
-
`),
|
|
2199
|
-
`);let
|
|
2200
|
-
`);if(!x.success||!x.sessionId)throw new Error(x.error??"lm_agent: provider did not identify the seeded session");
|
|
2201
|
-
`);return R
|
|
2202
|
-
`);let w=l.get(
|
|
2203
|
-
`);else{let N=await Lt(jt()).getSession(
|
|
2190
|
+
`),r.recordError(h),h},{min:1},"Writes error message to stderr and records it for end-of-run error summary");let s=(m,h=!1)=>{try{let T=XN(String(m),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2191
|
+
`);return!!h?[T.trim()].filter(y=>y.length>0):T.split(/\n\s*\n/u).map(y=>y.trim()).filter(Boolean)}catch(T){throw K(e,`batch: ${T instanceof Error?T.message:String(T)}`),new ke(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 Xe(String(m)).members.map(T=>({alias:T.alias,provider:T.provider,model:T.model,sessionid:T.session,sessiondir:T.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 T=mt(String(m),String(h),e.dal);return{alias:T.alias,provider:T.provider,model:T.model,sessionid:T.sessionid,sessiondir:T.sessiondir,isLead:T.isLead,teamfile:T.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(m,h,T,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 x=h??{};if(typeof x!="object"||Array.isArray(x)||T!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let O={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...m},sourceMember:m,options:{...x},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(O),O}if(typeof h!="string"||typeof T!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let y;try{y=mt(String(m),String(h),e.dal)}catch(x){return K(e,`batch: ${x?.message||String(x)}`),null}let S=Number(g?.promptCount??1),b=!!!g?.legacy&&S>1&&await JN(y),k={...e.env??n},v=await KN(e,{member:y,batchfile:String(T),promptCount:S,parentInvocationId:Sr(k.LMCTL_INVOCATION_ID)});v!==null&&(k.LMCTL_INVOCATION_ID=String(v));let w,N,A,R=!1;e.stderr.write(`batch ${xt()}: starting ${S} prompt${S===1?"":"s"} -> ${y.alias} (teamfile=${m} input=${T})
|
|
2192
|
+
`);try{if(b){let M=await G(e,J=>(qs(J,y.teamfile,y.alias),Ss(J,y.teamfile,y.alias)));if(M.busy){let J=M.reason==="in-flight"?`${y.alias} is servicing ${M.inFlight.sender_alias} (${M.inFlight.sender_teamfile}) since ${M.inFlight.started_at} \u2014 wait and retry`:M.source==="terminal-lock"?Xn(M.terminalLock):`${y.alias} is busy (interactive terminal); wait and retry`;return v!==null&&await G(e,P=>{P.finishTrackedInvocation(v,{status:"busy",exit_code:1,error:J,result_summary:"0 prompts completed"})}),K(e,`batch: cannot start bundle: ${J}`),null}let X=await G(e,J=>VN(k,J)),$=await G(e,J=>hr(J,{receiver_teamfile:y.teamfile,receiver_alias:y.alias,sender_teamfile:X?.teamfile??y.teamfile,sender_alias:X?.alias??"operator",ttlMs:Rt(k)}));if(!$.acquired){let J=`${y.alias} is servicing ${$.current.sender_alias} (${$.current.sender_teamfile}) since ${$.current.started_at} \u2014 wait and retry`;return v!==null&&await G(e,P=>{P.finishTrackedInvocation(v,{status:"busy",exit_code:1,error:J,result_summary:"0 prompts completed"})}),K(e,`batch: cannot start bundle: ${J}`),null}w={row:$.lease,leaseId:$.leaseId};let ie=ws(J=>G(e,P=>P.heartbeatAgentInflight(w.row,w.leaseId,J)));A={stop:()=>clearInterval(ie)};let B=wr(e,J=>`batch ${xt()}: opening provider session (${J}s elapsed)
|
|
2193
|
+
`);try{let J={...k};try{let P=await G(e,Q=>Q.getRootTeam(y.teamfile)?.name??null);P!==null&&(J.LMBEE_TEAM_NAME=P)}catch{}N=await zl({provider:y.provider,sessionId:y.sessionid,cwd:y.sessiondir,env:J,...y.model!==void 0?{model:y.model}:{},...y.effort!==void 0?{effort:y.effort}:{},alias:y.alias,isLead:y.isLead,permissionMode:"yolo",holdOpen:ac(e,{teamfile:y.teamfile,alias:y.alias},J)}),R=!0}catch(J){D({event:"persistent_session_open_failed",provider:y.provider,session_id:y.sessionid,error_message:J instanceof Error?J.message:String(J)}),A&&A.stop(),A=void 0,await jc(e,w),w=void 0,R=!1}finally{B.stop()}}let O={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(m),alias:String(h),batchfile:String(T),member:y,promptCount:S,useBundle:R,rootId:v,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:w,bundleSession:N,heartbeatTimer:A,closed:!1,env:k};return r.registerBatch(O),O}catch(x){if(A){try{A.stop()}catch{}A=void 0}if(w){try{await jc(e,w)}catch{}w=void 0}if(N){try{await N.close()}catch{}N=void 0}if(v!==null)try{await G(e,O=>{O.finishTrackedInvocation(v,{status:"error",exit_code:1,error:x?.message||String(x),result_summary:"0 prompts completed"})})}catch{}throw x}},{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,T,g)=>{let y=typeof m=="string"?r.getBatch(m):m?.id?r.getBatch(m.id)??m:void 0;if(!y)throw new Error("Invalid or unmanaged batch handle");if(y.kind==="agent"){if(r.getBatch(y.id)!==y)throw new Error("Invalid or unmanaged batch handle");if(y.closed||y.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(y.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};y.inFlight=!0;try{let k=y.member.sessionid,v=await d(y.member,String(h),y.options);return y.member.sessionid&&y.sourceMember.provider===y.member.provider&&y.sourceMember.sessionid===k&&(y.sourceMember.sessionid=y.member.sessionid),v.status!=="ok"&&(y.failed=!0),{status:v.status,reply:v.reply.replace(/\n+$/u,""),error:v.error}}finally{y.inFlight=!1}}let S=Number(T),I=Number(g);e.stderr.write(`batch ${xt()}: prompt ${S}/${I} -> ${y.member.alias}
|
|
2194
|
+
`);let b=wr(e,k=>`batch ${xt()}: prompt ${S}/${I} still running (${k}s elapsed)
|
|
2195
|
+
`);try{let k=await cc({teamfile:y.member.teamfile,alias:y.member.alias,prompt:String(h),expectedSession:{provider:y.member.provider,sessionid:y.member.sessionid},permissionMode:"yolo",env:{...y.env},messageType:"batch",...y.heldLease!==void 0?{heldLease:y.heldLease}:{},...y.bundleSession!==void 0?{bundleSession:y.bundleSession}:{},io:e,onEvent:w=>{b.poke(),w.kind==="warning"&&e.stderr.write(w.message)}}),v=k.replyText?String(k.replyText).replace(/\n+$/u,""):"";if(k.status!=="ok"){let w=k.status==="stalled"?"provider stalled":k.status==="empty"?"provider returned no content and no observed activity for this turn":k.message,N=`batch: stopped at prompt ${S}/${I} (${S-1} completed): ${w}; later prompts were not sent`;return y.rootFinish={status:k.status==="busy"?"busy":"error",exit_code:1,error:N,result_summary:`${S-1}/${I} prompts completed`},K(e,N),{status:k.status,reply:v,error:N}}return{status:"ok",reply:v,error:null}}catch(k){let v=`batch: stopped at prompt ${S}/${I} (${S-1} completed): ${k instanceof Error?k.message:String(k)}; later prompts were not sent`;return y.rootFinish={status:"error",exit_code:1,error:v,result_summary:`${S-1}/${I} prompts completed`},K(e,v),{status:"error",reply:"",error:v}}finally{b.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(m,h="done",T)=>{let g=typeof m=="string"?r.getBatch(m):m?.id?r.getBatch(m.id)??m:void 0;return g?(await X_(g,e,h==="done"?"done":h==="cancelled"?"cancelled":"error",T),!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 T=m.timeoutSeconds??15;if(typeof T!="number"||!Number.isFinite(T)||T<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return h_({providers:h.length?h:["all"],timeoutSeconds:T,env:e.env??n,progress:g=>{e.stderr.write(`${g}
|
|
2196
|
+
`)}})}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,T={},g=!1)=>{let y=(k,v="",w=null)=>({status:k,reply:v,error:w,message_id:null,team_chat_log_id:null}),S,I=!1,b;try{if(!m||typeof m!="object"||Array.isArray(m))throw new Error("lm_agent: member must be a map");for(let x of["provider","alias","model","effort","sessiondir","sessionid"]){let O=m[x];if(O!=null&&(typeof O!="string"||!O.trim()))throw new Error(`lm_agent: ${x} 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(!T||typeof T!="object"||Array.isArray(T))throw new Error("lm_agent: options must be a map");let k=T.permissionMode??"yolo";if(k!=="yolo"&&k!=="plan")throw new Error("lm_agent: permissionMode must be yolo or plan");if(T.idleTimeoutMs!=null&&(typeof T.idleTimeoutMs!="number"||!Number.isFinite(T.idleTimeoutMs)||T.idleTimeoutMs<0))throw new Error("lm_agent: idleTimeoutMs must be a finite nonnegative number");let v=m.provider,w=m.sessiondir??process.cwd(),N=m.sessionid??"";if(S=N?JSON.stringify([v,N]):void 0,i.has(m)||S!==void 0&&(o.has(S)||!g&&a.has(S)))return y("busy","","lm_agent: session already has an active turn in this engine");i.add(m),S!==void 0&&o.add(S),I=!0,e.stderr.write(`agent ${xt()}: prompting ${m.alias??v}
|
|
2197
|
+
`),b=wr(e,x=>`agent ${xt()}: still running (${x}s elapsed)
|
|
2198
|
+
`);let A=N;if(!A&&["agy","pi","dsh"].includes(v)){if(k!=="yolo")throw new Error(`lm_agent: fresh ${v} sessions require yolo seed; supply sessionid for resume`);let x=await Ql({provider:v,cwd:w,model:m.model,effort:m.effort});for(let O of x.warnings??[])e.stderr.write(`warning: ${O}
|
|
2199
|
+
`);if(!x.success||!x.sessionId)throw new Error(x.error??"lm_agent: provider did not identify the seeded session");A=x.sessionId,m.sessionid=A,S=JSON.stringify([v,A]),o.add(S)}let R=await Hn({provider:v,cwd:w,sessionId:A,prompt:h,model:m.model,effort:m.effort,alias:m.alias,isLead:!1,permissionMode:k,timeoutMs:T.idleTimeoutMs,requireResume:!!A,env:{...e.env??n},onDelta:()=>b?.poke(),onProgress:()=>b?.poke()});for(let x of R.warnings??[])e.stderr.write(`warning: ${x}
|
|
2200
|
+
`);return A&&R.sessionId!==A?y("error","","lm_agent: provider changed session identity during resume"):(R.sessionId&&(m.sessionid=R.sessionId),R.status==="stalled"?y("stalled",R.text,"provider stalled"):R.status==="empty"?y("empty","","lm_agent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):R.sessionId?y("ok",R.text):y("error",R.text,"lm_agent: provider did not return a session ID"))}catch(k){return y("error","",k instanceof Error?k.message:String(k))}finally{b?.stop(),I&&(i.delete(m),S!==void 0&&o.delete(S))}},d=async(m,h,T={},g=!1)=>{let y=await c(m,h,T,g);if(m?.sessionid&&y.status!=="busy"){let S=JSON.stringify([m.provider,m.sessionid]),I=l.get(S)??{lines:[],options:{}};I.lines.push(`You: ${h}`),y.reply&&I.lines.push(`Agent: ${y.reply}`),y.error&&I.lines.push(`${y.status}: ${y.error}`),I.options={...T},l.set(S,I)}return y};t.registerFunction("lm_agent",d,{min:2,max:3},"Prompts an agent described by a map without a teamfile"),t.registerFunction("lm_session_list",async(m={})=>{if(!m||typeof m!="object"||Array.isArray(m)||m.provider!=null&&(typeof m.provider!="string"||!m.provider.trim())||m.sessiondir!=null&&(typeof m.sessiondir!="string"||!m.sessiondir.trim())||m.all!=null&&typeof m.all!="boolean")throw new Error("lm_session_list: expected options map with provider, sessiondir, and all");return(await Zl({provider:m.provider,workspace:m.all?void 0:m.sessiondir??process.cwd()})).map(T=>({provider:T.provider,sessionid:T.sessionId,sessiondir:T.cwd,modifiedAt:T.modifiedAt.toISOString()}))},{min:0,max:1},"Lists native provider sessions"),t.registerFunction("lm_session_delete",async(m,h={})=>{let T=(y,S=null)=>({status:y,error:S});if(!m||typeof m!="object"||Array.isArray(m)||typeof m.provider!="string"||!m.provider.trim()||typeof m.sessionid!="string"||!m.sessionid.trim())return T("error","lm_session_delete: member requires provider and sessionid");if(!h||typeof h!="object"||Array.isArray(h)||h.force!==!0)return T("error","lm_session_delete: force: true is required because cross-process turns cannot be detected");let g=JSON.stringify([m.provider,m.sessionid]);if(i.has(m)||o.has(g)||a.has(g))return T("busy","lm_session_delete: session has an active turn in this engine");o.add(g);try{return await ec(m.provider,m.sessionid)?(l.delete(g),m.sessionid=null,T("deleted")):T("not_found")}catch(y){return T("error",y instanceof Error?y.message:String(y))}finally{o.delete(g)}},{min:1,max:2},"Deletes a native session with explicit cross-process race acceptance");let u=async(m,h,T={})=>{if(!Array.isArray(m))throw new Error("lm_fanout: participants must be an array of member maps");if(m.length===0)return[];let g;if(typeof h=="string")g=m.map(()=>h);else if(Array.isArray(h)){if(h.length!==m.length)throw new Error(`lm_fanout: prompts array length (${h.length}) must match participants length (${m.length})`);for(let y of h)if(typeof y!="string")throw new Error("lm_fanout: every prompts[] entry must be a string");g=h}else throw new Error("lm_fanout: prompts must be a string (broadcast to every participant) or an array of strings (one per participant)");if(!T||typeof T!="object"||Array.isArray(T))throw new Error("lm_fanout: options must be a map");return Promise.all(m.map((y,S)=>d(y,g[S],T)))};t.registerFunction("lm_fanout",u,{min:2,max:3},"Dispatches a prompt to every participant in an array concurrently (runtime-sized, unlike parallel()); returns an array of lm_agent-shaped results in the same order as participants. prompts is a single string broadcast to all, or an array of strings (one per participant, same length).");let f=async(m,h={})=>{if(typeof m!="string"||m.length===0)throw new Error("lm_seed: teamfile must be a nonempty string");if(!h||typeof h!="object"||Array.isArray(h))throw new Error("lm_seed: options must be a map");if(h.preamble!==void 0&&typeof h.preamble!="string"&&(typeof h.preamble!="object"||h.preamble===null||Array.isArray(h.preamble)))throw new Error("lm_seed: options.preamble must be a string or a map keyed by alias");let T=h.preamble!==void 0?{preamble:h.preamble}:{};return{status:await Og(m,e,T)===0?"ok":"error"}};t.registerFunction("lm_seed",f,{min:1,max:2},"Seeds a real teamfile over the exact same path lmctl seed takes; options.preamble overrides the default Lead prompt (string) or per-alias prompts (map)."),t.registerFunction("lm_terminal",async(m,h)=>{if(typeof m!="string"||!m||typeof h!="string"||!h)throw new Error("lm_terminal requires a teamfile and alias");if(bt(e)||n.LMCTL_NON_INTERACTIVE==="1")throw new Error("lm_terminal is disabled in non-interactive mode");let{runTerminal:T}=await Promise.resolve().then(()=>(W_(),H_)),g=await T([m,h],{...e,env:n});return{status:g===0?"ok":"error",code:g}},2,"Opens a tracked member in its native TUI; refuses non-interactive mode.");let p=async m=>{if(typeof m!="string"||m.length===0)throw new Error("lm_lint: teamfile must be a nonempty string");return Cg(m,e)};t.registerFunction("lm_lint",p,1,"Validates a teamfile over the exact same path lmctl lint takes, returning { status, errors, warnings, counts } instead of text to parse.");let _=!1,E=async m=>{let h=m!==null&&typeof m=="object";if(_)throw new Error("prompt_human: another operator prompt is active");_=!0;let T,g;try{let y=e.stdin??process.stdin;if(!h)return await en(m,y,e.stdout);let S={...m};if(Array.isArray(m)||typeof S.provider!="string"||!S.provider.trim()||typeof S.sessionid!="string"||!S.sessionid.trim())return{command:"error",args:["prompt_human: session map requires provider and sessionid; call lm_agent first"]};let I=JSON.stringify([S.provider,S.sessionid]);if(o.has(I))return{command:"busy",args:["Agent turn is still running"]};a.add(I),g=I;let b=y;if(b.destroyed||b.readableEnded)return{command:"eof",args:[]};T=GN({input:b,output:e.stdout,terminal:!!b.isTTY,crlfDelay:1/0});let k=T[Symbol.asyncIterator](),v=!1;T.on("SIGINT",()=>{v=!0,T?.close()}),e.stdout.write(`Session ${S.alias??S.provider} (${S.sessionid})
|
|
2201
|
+
`);let w=l.get(I);if(w)for(let N of w.lines)e.stdout.write(`${N}
|
|
2202
|
+
`);else{let N=await Lt(jt()).getSession(S.sessionid,S.provider);if(!N)return{command:"error",args:["Could not load session history"]};for(let A of N.messages)(A.role==="user"||A.role==="assistant")&&e.stdout.write(`${A.role==="user"?"You":"Agent"}: ${A.content}
|
|
2204
2203
|
`)}for(e.stdout.write(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2205
|
-
`);;){e.stdout.write("You> ");let N=await
|
|
2206
|
-
`),
|
|
2207
|
-
`),{command:
|
|
2204
|
+
`);;){e.stdout.write("You> ");let N=await k.next();if(v)return{command:"cancelled",args:[]};if(N.done)return{command:"eof",args:[]};let A=N.value.trim();if(!A)continue;if(/^\/exit(?:\s|$)/u.test(A)){let x=A.split(/\s+/u).slice(1);return{command:x.shift()??"exit",args:x}}let R=await d(S,N.value,w?.options??{},!0);if(R.reply&&e.stdout.write(`Agent: ${R.reply}
|
|
2205
|
+
`),R.status!=="ok")return e.stdout.write(`${R.status}: ${R.error}
|
|
2206
|
+
`),{command:R.status,args:[R.error??"Agent turn failed"]}}}catch(y){if(!h)throw y;return{command:"error",args:[y instanceof Error?y.message:String(y)]}}finally{T?.close(),g!==void 0&&a.delete(g),_=!1}};t.registerFunction("prompt_human",m=>{if(n.LMCTL_NON_INTERACTIVE==="1"||bt(e))throw new Error("prompt_human is disabled in non-interactive mode");if(!t.isAsyncMode&&(m===null||typeof m!="object")){if(_)throw new Error("prompt_human: another operator prompt is active");return Zr(m)}return E(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,T,g={})=>{try{let y=await cc({teamfile:String(m),alias:String(h),prompt:String(T),permissionMode:g?.permissionMode??"yolo",idleTimeoutMs:g?.idleTimeoutMs,env:{...e.env??n},messageType:g?.messageType,io:e});return{status:y.status,reply:y.replyText??"",error:y.message??null,message_id:y.messageId??null,team_chat_log_id:y.teamChatLogId??null}}catch(y){return{status:"error",reply:"",error:y?.message||String(y),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}var J_={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:Bc,register(t,e){G_(t,e.io,e.registry,e.env)}};function V_(t,e,r=new cr,n=process.env){return t.registerModule(J_,{io:e,registry:r,env:n})}function K_(t,e=[],r=new cr,n=t.env??process.env,s={}){let i=Nu(t,n,s),o=QN(t,e,r,n);for(let[l,c]of Object.entries(i))o.setGlobal(l,c);let a=o.scanAndCheck.bind(o);return o.scanAndCheck=(l,c)=>{let d=a(l,c);return{...d,diagnostics:d.diagnostics.map(u=>({...u,message:Rs(u.message)}))}},o}function QN(t,e=[],r=new cr,n=process.env){let s=q_({scriptArgs:e,io:t,env:n});return V_(s,t,r,n),n.LMCTL_LMBEE_BRIDGE==="1"&&s.registerModule(C_(n,i=>r.registerTemporaryDirectory(i))),s}async function ZN(t,e,r={stdout:process.stdout,stderr:process.stderr},n=process.env,s,i={},o={}){let a=new cr,l=f=>{a.removeTemporaryDirectories();for(let p of a.getOpenBatches()){if(p.kind==="agent"){p.closed=!0;continue}if(p.heartbeatTimer){try{p.heartbeatTimer.stop()}catch{}p.heartbeatTimer=void 0}if(p.heldLease){try{if(r.dal)r.dal.releaseAgentInflight(p.heldLease.row,p.heldLease.leaseId);else{let _=Jt({path:dt(n?.LMCTL_DB)});try{_.releaseAgentInflight(p.heldLease.row,p.heldLease.leaseId)}finally{_.close()}}}catch{}p.heldLease=void 0}p.rootId!==null&&YN(r,p.rootId,{status:"cancelled",signal:f,error:`batch interrupted by ${f}`},n)}process.exit(f==="SIGINT"?130:143)};process.once("SIGINT",l),process.once("SIGTERM",l);let c=!1,d,u=()=>{if(c)return;c=!0;let f=a.getErrors(),p=d?d.getRecordedErrors():[],_=[...f];for(let E of p)_.includes(E)||_.push(E);if(_.length>0){r.stderr.write(`
|
|
2208
2207
|
=== LMScript Error Summary (${_.length} error${_.length===1?"":"s"}) ===
|
|
2209
2208
|
`);for(let E=0;E<_.length;E++)r.stderr.write(` ${E+1}. ${_[E]}
|
|
2210
2209
|
`);r.stderr.write(`==========================================
|
|
2211
|
-
`)}};try{let f=
|
|
2210
|
+
`)}};try{let f=K_(r,e,a,n,o);d=f;for(let[E,m]of Object.entries(i))f.setGlobal(E,m);let p=f.scanAndCheck(t,{file:s});for(let E of p.diagnostics){if(E.severity==="error")continue;let m=E.file?`${E.file}:${E.line}:${E.column}`:`${E.line}:${E.column}`;r.stderr.write(`warning:${m}: ${Rs(E.message)}
|
|
2212
2211
|
`)}let _=await f.runAsync(t,{file:s,stderr:E=>{r.stderr.write(E.endsWith(`
|
|
2213
2212
|
`)?E:`${E}
|
|
2214
|
-
`)}});if(u(),_.exitCode!==void 0)return _.exitCode;if(!_.success){for(let E of _.diagnostics){if(E.severity!=="error")continue;let m=E.file?`${E.file}:${E.line}:${E.column}`:`${E.line}:${E.column}`;r.stderr.write(`error:${m}: ${
|
|
2213
|
+
`)}});if(u(),_.exitCode!==void 0)return _.exitCode;if(!_.success){for(let E of _.diagnostics){if(E.severity!=="error")continue;let m=E.file?`${E.file}:${E.line}:${E.column}`:`${E.line}:${E.column}`;r.stderr.write(`error:${m}: ${Rs(E.message)}
|
|
2215
2214
|
`)}return 1}return a.hasErrors()||_.errors&&_.errors.length>0?1:0}catch(f){return u(),f instanceof ke||f?.name==="LMScriptExit"?f.exitCode:(r.stderr.write(`error: ${f instanceof Error?f.message:String(f)}
|
|
2216
|
-
`),1)}finally{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l),await a.forceCloseAll(r)}}var
|
|
2215
|
+
`),1)}finally{process.removeListener("SIGINT",l),process.removeListener("SIGTERM",l),await a.forceCloseAll(r)}}var eR=`# batchscript.lms - Test-only comparison with procedural lmctl batch
|
|
2217
2216
|
# Arguments: [teamfile, alias, batchfile, flags...]
|
|
2218
2217
|
|
|
2219
2218
|
if (includes(args, "--help") || includes(args, "-h")) {
|
|
@@ -2280,4 +2279,4 @@ for (i = 0; i < len(prompts); i = i + 1) {
|
|
|
2280
2279
|
|
|
2281
2280
|
lm_batch_close(handle, "done");
|
|
2282
2281
|
lm_exit(0);
|
|
2283
|
-
`;export{
|
|
2282
|
+
`;export{eR as BATCH_LMS,Bc as LMCTL_FUNCTION_DOCS,at as LMScript,ke as LMScriptExit,cr as ResourceRegistry,q_ as createBaseScriptEngine,K_ as createLmScriptEngine,J_ as lmctlModule,zN as registerLmctlDocs,G_ as registerLmctlHostFunctions,V_ as registerLmctlModule,ZN as runScriptEngine};
|