@lmctl-ai/lmctl 0.2.21 → 0.2.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +321 -244
- package/dist/cli/schema.sql +79 -0
- package/dist/cli/script.js +196 -119
- package/dist/db/migrate.d.ts +1 -1
- package/dist/script/lmbee-module.d.ts +2 -0
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}var
|
|
3
|
-
`)}catch{}}function
|
|
4
|
-
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function
|
|
5
|
-
`),1;let i=t===Zo?e:[t,...e],o=s.createRuntime();return s.dispatch(i,o)}async function
|
|
6
|
-
`});import{existsSync as
|
|
1
|
+
var VT=Object.create;var Go=Object.defineProperty;var KT=Object.getOwnPropertyDescriptor;var YT=Object.getOwnPropertyNames;var zT=Object.getPrototypeOf,QT=Object.prototype.hasOwnProperty;var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var ZT=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),oe=(t,e)=>{for(var r in e)Go(t,r,{get:e[r],enumerable:!0})},ew=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of YT(e))!QT.call(t,s)&&s!==r&&Go(t,s,{get:()=>e[s],enumerable:!(n=KT(e,s))||n.enumerable});return t};var It=(t,e,r)=>(r=t!=null?VT(zT(t)):{},ew(e||!t||!t.__esModule?Go(r,"default",{value:t,enumerable:!0}):r,t));var hu={};oe(hu,{defaultDbPath:()=>fu,describeStateLocation:()=>Sn,isSlowWslMount:()=>pu,lmctlNextHome:()=>mu,resolveDbPath:()=>pe,warnIfSlowDbPath:()=>Jo});import{platform as du}from"node:os";import{homedir as tw}from"node:os";import{join as uu}from"node:path";function mu(){let t=process.env.LMCTL_HOME;return t!==void 0&&t.length>0?t:uu(tw(),rw)}function fu(){return uu(mu(),nw)}function pe(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:fu()}function Sn(t){return process.env.LMCTL_DB!==void 0&&process.env.LMCTL_DB.length>0?`db: ${t} (overridden by --db/LMCTL_DB)`:`db: ${t}`}function pu(t,e=du()){return e!=="linux"?!1:t.startsWith("/mnt/c/")||t==="/mnt/c"}function Jo(t,e=process.stderr,r=du()){pu(t,r)&&e.write(`warning: DB on /mnt/c is slow; consider moving to ~/.lmctl/state.db (set LMCTL_DB or use --db)
|
|
2
|
+
`)}var rw,nw,ct=k(()=>{"use strict";rw=".lmctl",nw="state.db"});import{readFileSync as Tu,appendFileSync as lw,mkdirSync as cw,existsSync as aM,readdirSync as lM,unlinkSync as cM}from"node:fs";import{join as Ms,dirname as dw}from"node:path";import{homedir as uw}from"node:os";function zo(){return Ms(uw(),".lmctl")}function wu(){jr=!0,process.env.LMCTL_DEBUG="1"}function vu(){return{cliDebug:jr,lmctlDebugEnv:process.env.LMCTL_DEBUG}}function Su(t){jr=t.cliDebug,t.lmctlDebugEnv===void 0?delete process.env.LMCTL_DEBUG:process.env.LMCTL_DEBUG=t.lmctlDebugEnv}function z(){if(jr||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-Eu>=mw&&(yu=hw(),Eu=t),yu}function bu(){return jr||process.env.LMCTL_DEBUG==="1"}function fw(){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 Ie(t,e){if(e?.verbose){if(!jr)return}else if(!e?.always&&!z())return;try{pw();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};lw(Ds,JSON.stringify(r)+`
|
|
3
|
+
`)}catch{}}function pw(){if(!Ds){let e=fw().slice(0,13).replace("T","-");Ds=Ms(zo(),`debug-${e}.log`)}cw(dw(Ds),{recursive:!0})}function Ee(...t){Ie({event:"legacy",msg:t.join(" ")})}function Te(...t){Ie({event:"legacy",msg:t.join(" ")},{verbose:!0})}function L(t){Ie(t,{always:!0})}function hw(){return gw()||_w()}function gw(){try{let t=Tu(Ms(zo(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
4
|
+
`)){let r=e.trim();if(!r||r.startsWith("#"))continue;if(r.startsWith("["))break;let n=/^debug\s*=\s*(.+)$/.exec(r);if(n){let s=n[1].trim().toLowerCase().replace(/^["']|["']$/g,"");return s==="true"||s==="1"}}}catch{}return!1}function _w(){try{let t=Tu(Ms(zo(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var jr,yu,Eu,mw,Ds,V=k(()=>{"use strict";jr=!1,yu=!1,Eu=0,mw=5e3;Ds=null});var Nu={};oe(Nu,{INFRA_CLI_CONTRACT_EXPECTED:()=>$w,INFRA_FLAT_COMMANDS:()=>Ru,INFRA_NAMESPACE_COMMAND:()=>Zo,infraCliEnabled:()=>$s,isInfraCommand:()=>Fs,runInfraCommand:()=>Pw});function $s(t=process.env){return t.LMCTL_INFRA_CLI==="1"||t.LMCTL_INFRA_CLI==="true"}function Fs(t){return Ru.includes(t)||t===Zo}async function Pw(t,e,r,n=Uw){let s;try{s=await n()}catch{return r.stderr.write(Fw),1}if(s.INFRA_CLI_CONTRACT!==1)return r.stderr.write(`lmctl: infra command library contract version ${s.INFRA_CLI_CONTRACT} does not match the version this lmctl build expects (1).
|
|
5
|
+
`),1;let i=t===Zo?e:[t,...e],o=s.createRuntime();return s.dispatch(i,o)}async function Uw(){throw new Error("infra CLI adapter target (lmt) is retired; no successor module currently implements this contract")}var $w,Ru,Zo,Fw,ea=k(()=>{"use strict";$w=1,Ru=["lmchat","lmmail","lmnote","lmsheet","lmtext","lmsound","login","whoami","exec","tell","peers","site"],Zo="auto";Fw=`lmctl: infra commands (site/auto/exec/tell/peers/login/whoami/lmchat/lmmail/lmnote/lmsheet/lmtext/lmsound) are not available in this build.
|
|
6
|
+
`});import{existsSync as jw}from"node:fs";import{createRequire as Bw}from"node:module";function Ww(){return ta===null&&(ta=Bw(import.meta.url)("node:sqlite").DatabaseSync),ta}function ra(t){return t.length===1&&Hw(t[0])?[t[0]]:t}function Hw(t){if(!ia(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ia(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var ta,na,Ps,sa,oa=k(()=>{"use strict";ta=null;na=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!jw(e))throw new Error("unable to open database file");this.name=e,this.handle=new(Ww())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new sa(this.handle.prepare(e))}exec(e){this.handle.exec(e),this.updateTransactionDepth(e)}pragma(e,r){let n=`PRAGMA ${e}`;if(e.includes("=")){this.exec(n);return}let s=this.prepare(n).get();return r?.simple===!0?s===void 0?void 0:Object.values(s)[0]:s}transaction(e){return(...r)=>{if(this.transactionDepth===0){this.exec("BEGIN");try{let s=e(...r);return this.exec("COMMIT"),s}catch(s){throw this.inTransaction&&this.exec("ROLLBACK"),s}}let n=`lmctl_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${n}`);try{let s=e(...r);return this.exec(`RELEASE ${n}`),s}catch(s){throw this.inTransaction&&(this.exec(`ROLLBACK TO ${n}`),this.exec(`RELEASE ${n}`)),s}}}get inTransaction(){return this.transactionDepth>0}close(){this.handle.close()}updateTransactionDepth(e){let r=e.trim().match(/^([A-Za-z]+)/)?.[1]?.toUpperCase();if(r!==void 0){if(r==="BEGIN"||r==="SAVEPOINT"){this.transactionDepth+=1;return}if(r==="COMMIT"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}if(r==="RELEASE"){this.transactionDepth=Math.max(0,this.transactionDepth-1);return}r==="ROLLBACK"&&!/^ROLLBACK\s+TO\b/i.test(e.trim())&&(this.transactionDepth=0)}}},Ps=na,sa=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...ra(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...ra(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...ra(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&ia(e)?Object.values(e):ia(e)?{...e}:e}}});import{createHash as Xw}from"node:crypto";function qw(t,e,r){return Xw("sha256").update(`${t}\0${e}\0${r}`).digest("hex")}function Fe(t,e,r){let n=qw(e.stream_id,e.intentKey??e.event_type,e.observedLastSeq),s=t.prepare(`INSERT INTO message_event (event_id, ts, stream_id, event_type, payload)
|
|
7
7
|
VALUES (?, ?, ?, ?, ?)
|
|
8
|
-
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return r(l),{appended:!0,seq:l,event_id:n}})()}var Us=k(()=>{"use strict"});var Cu={};oe(Cu,{backfillEventLog:()=>aa,rebuildProjections:()=>Lu});import{createHash as
|
|
8
|
+
ON CONFLICT(event_id) DO NOTHING`),i=t.prepare("SELECT seq FROM message_event WHERE event_id = ?");return t.transaction(()=>{let a=s.run(n,e.ts??new Date().toISOString(),e.stream_id,e.event_type,JSON.stringify(e.payload));if(a.changes===0)return{appended:!1,seq:i.get(n).seq,event_id:n};let l=Number(a.lastInsertRowid);return r(l),{appended:!0,seq:l,event_id:n}})()}var Us=k(()=>{"use strict"});var Cu={};oe(Cu,{backfillEventLog:()=>aa,rebuildProjections:()=>Lu});import{createHash as Gw}from"node:crypto";function pr(t,e){return t==null?null:{teamfile:t,alias:e??""}}function Jw(t,e,r){return`lease_${Gw("sha256").update(`${t}\0${e}\0${r}`).digest("hex").slice(0,16)}`}function js(t,e,r,n){r.forEach((s,i)=>{Fe(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 Vw(t){let e=`msg_tcl_${t.id}`,r=pr(t.sender_teamfile,t.sender_alias),n=pr(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:K.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:K.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 Kw(t){let e=`msg_mbx_${t.id}`,r=pr(t.sender_teamfile,t.sender_alias),n=pr(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:K.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:K.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:K.RESPONSE_DELIVERED,ts:t.delivered_at,payload:{...i,message_type:"response",receipt:t.receipt}}),{streamId:e,events:o}}return o.push({event_type:K.CREATE,ts:t.created_at,payload:{...i,message_type:"request",content:t.payload,correlation_status:"legacy-unavailable"}}),o.push({event_type:K.ENQUEUE,ts:t.created_at,payload:{...i,message_type:"request"}}),t.waited_at!==null&&o.push({event_type:K.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:K.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:K.DELIVERED,ts:t.delivered_at,payload:{...i,receipt:t.receipt}}),{streamId:e,events:o}}function Yw(t){let e=`inv_${t.id}`,r=pr(t.target_teamfile,t.target_alias),n={table:"tracked_invocation",id:t.id},s=[{event_type:K.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:K.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:K.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 zw(t){let e=Jw(t.receiver_teamfile,t.receiver_alias,t.started_at),r=pr(t.receiver_teamfile,t.receiver_alias),n=pr(t.sender_teamfile,t.sender_alias);return{streamId:e,events:[{event_type:K.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 Bs(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function aa(t){let e={appended:0,skipped:0},r={team_chat_log:0,agent_mailbox:0,tracked_invocation:0,agent_inflight:0};t.transaction(()=>{if(Bs(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}=Vw(i);js(t,a,l,e),r.team_chat_log+=e.appended+e.skipped-o}if(Bs(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}=Kw(i);js(t,a,l,e),r.agent_mailbox+=e.appended+e.skipped-o}if(Bs(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}=Yw(i);js(t,a,l,e),r.tracked_invocation+=e.appended+e.skipped-o}if(Bs(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}=zw(i);js(t,a,l,e),r.agent_inflight+=e.appended+e.skipped-o}Lu(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 Lu(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);Qw(t,r.seq,r.stream_id,r.event_type,n)}}function ue(t,e,r){let n=t[e];return n!=null?n[r]??null:null}function Qw(t,e,r,n,s){switch(n){case K.ENQUEUE:case K.RESPONSE_ENQUEUE:{let i=n===K.RESPONSE_ENQUEUE;t.prepare(`INSERT INTO message_pending
|
|
9
9
|
(message_id, message_type, in_reply_to, sender_teamfile, sender_alias,
|
|
10
10
|
receiver_teamfile, receiver_alias, lifecycle_state, created_seq, last_seq)
|
|
11
11
|
VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)
|
|
@@ -29,7 +29,7 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
29
29
|
cwd, command, request_message_id, request_payload, holder_pid, holder_host, status, started_at, last_seq)
|
|
30
30
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?)
|
|
31
31
|
ON CONFLICT(invocation_id) DO NOTHING`).run(r,s.kind??"chat",s.origin??"unknown",s.launch_source??"",s.from_identity??"",ue(s,"target","teamfile"),ue(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 K.INVOCATION_FINISH:t.prepare(`UPDATE invocation_state SET status=?, ended_at=?, result_summary=?, error=?, last_seq=?
|
|
32
|
-
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case K.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 K,la=k(()=>{"use strict";Us();K={CREATE:"CREATE",ENQUEUE:"ENQUEUE",DELIVER_CLAIM:"DELIVER_CLAIM",DELIVER_CLAIM_RELEASE:"DELIVER_CLAIM_RELEASE",DELIVERED:"DELIVERED",HANDLED:"HANDLED",WAIT_REGISTER:"WAIT_REGISTER",RESPONSE_CREATE:"RESPONSE_CREATE",RESPONSE_ENQUEUE:"RESPONSE_ENQUEUE",RESPONSE_DELIVERED:"RESPONSE_DELIVERED",INFLIGHT_TAKE:"INFLIGHT_TAKE",INFLIGHT_RELEASE:"INFLIGHT_RELEASE",INFLIGHT_RECLAIM:"INFLIGHT_RECLAIM",TERMINAL_LOCK_TAKE:"TERMINAL_LOCK_TAKE",TERMINAL_LOCK_RELEASE:"TERMINAL_LOCK_RELEASE",TERMINAL_LOCK_EXPIRE:"TERMINAL_LOCK_EXPIRE",INVOCATION_START:"INVOCATION_START",INVOCATION_FINISH:"INVOCATION_FINISH",INVOCATION_NOTIFY_CLAIM:"INVOCATION_NOTIFY_CLAIM"}});var ju={};oe(ju,{CURRENT_USER_VERSION:()=>xt,SchemaSkewError:()=>jt,_resetNewerSchemaWarningForTests:()=>
|
|
32
|
+
WHERE invocation_id=?`).run(s.status??"done",s.ended_at??null,s.result_summary??null,s.error??null,e,r);break;case K.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 K,la=k(()=>{"use strict";Us();K={CREATE:"CREATE",ENQUEUE:"ENQUEUE",DELIVER_CLAIM:"DELIVER_CLAIM",DELIVER_CLAIM_RELEASE:"DELIVER_CLAIM_RELEASE",DELIVERED:"DELIVERED",HANDLED:"HANDLED",WAIT_REGISTER:"WAIT_REGISTER",RESPONSE_CREATE:"RESPONSE_CREATE",RESPONSE_ENQUEUE:"RESPONSE_ENQUEUE",RESPONSE_DELIVERED:"RESPONSE_DELIVERED",INFLIGHT_TAKE:"INFLIGHT_TAKE",INFLIGHT_RELEASE:"INFLIGHT_RELEASE",INFLIGHT_RECLAIM:"INFLIGHT_RECLAIM",TERMINAL_LOCK_TAKE:"TERMINAL_LOCK_TAKE",TERMINAL_LOCK_RELEASE:"TERMINAL_LOCK_RELEASE",TERMINAL_LOCK_EXPIRE:"TERMINAL_LOCK_EXPIRE",INVOCATION_START:"INVOCATION_START",INVOCATION_FINISH:"INVOCATION_FINISH",INVOCATION_NOTIFY_CLAIM:"INVOCATION_NOTIFY_CLAIM"}});var ju={};oe(ju,{CURRENT_USER_VERSION:()=>xt,SchemaSkewError:()=>jt,_resetNewerSchemaWarningForTests:()=>uv,currentSchemaSkew:()=>mv,migrate:()=>bn});import{existsSync as Zw,mkdirSync as ev,readFileSync as Du}from"node:fs";import{randomUUID as tv}from"node:crypto";import{homedir as rv}from"node:os";import{dirname as Mu,join as nv,resolve as $u}from"node:path";import{fileURLToPath as sv,pathToFileURL as iv}from"node:url";function bn(t){t.dbPath!==":memory:"&&ev(Mu(t.dbPath),{recursive:!0});let e=new Ps(t.dbPath);try{e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=Uu(e),n=t.buildVersionForTests??xt;if(r===0)e.exec(Du(Pu,"utf8")),e.pragma(`user_version = ${xt}`);else if(r>n){let s=cv(e,r);if(da={dbVersion:r,buildVersion:n},s>n&&!t.allowSchemaSkew)throw e.close(),new jt(t.dbPath,r,n);return dv(t.dbPath,r,n),e}return av(e,r),lv(e),e}catch(r){try{e.close()}catch{}throw r}}function av(t,e){let r=e;if(r<2&&r!==0&&(t.exec(`
|
|
33
33
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
34
34
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
35
35
|
team_name TEXT NOT NULL,
|
|
@@ -762,7 +762,84 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
762
762
|
value TEXT NOT NULL
|
|
763
763
|
);
|
|
764
764
|
INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '60');
|
|
765
|
-
`),t.pragma("user_version = 61"),r=61}
|
|
765
|
+
`),t.pragma("user_version = 61"),r=61}r<62&&r!==0&&(t.exec(`
|
|
766
|
+
CREATE TABLE IF NOT EXISTS queue(
|
|
767
|
+
id INTEGER PRIMARY KEY,
|
|
768
|
+
from_id TEXT NOT NULL,
|
|
769
|
+
to_id TEXT NOT NULL,
|
|
770
|
+
prompt_file TEXT NOT NULL,
|
|
771
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
772
|
+
created_ts TEXT NOT NULL,
|
|
773
|
+
sent_ts TEXT,
|
|
774
|
+
retrieved_ts TEXT,
|
|
775
|
+
subject_id TEXT,
|
|
776
|
+
dedupe_key TEXT UNIQUE,
|
|
777
|
+
delivered_via_escalation INTEGER NOT NULL DEFAULT 0,
|
|
778
|
+
escalation_claimed_ts TEXT,
|
|
779
|
+
escalation_claim_token TEXT,
|
|
780
|
+
escalation_only INTEGER NOT NULL DEFAULT 0,
|
|
781
|
+
admission_fingerprint TEXT,
|
|
782
|
+
expects_response INTEGER NOT NULL DEFAULT 0,
|
|
783
|
+
to_alias TEXT,
|
|
784
|
+
retracted_ts TEXT,
|
|
785
|
+
retracted_reason TEXT,
|
|
786
|
+
retraction_notice INTEGER NOT NULL DEFAULT 0,
|
|
787
|
+
in_reply_to INTEGER,
|
|
788
|
+
operator_priority INTEGER NOT NULL DEFAULT 0,
|
|
789
|
+
merged_into_id INTEGER
|
|
790
|
+
);
|
|
791
|
+
|
|
792
|
+
CREATE INDEX IF NOT EXISTS idx_queue_to_status ON queue(to_id, status);
|
|
793
|
+
|
|
794
|
+
CREATE TABLE IF NOT EXISTS answers(
|
|
795
|
+
id INTEGER PRIMARY KEY,
|
|
796
|
+
prompt_queue_id INTEGER NOT NULL REFERENCES queue(id),
|
|
797
|
+
answer_text TEXT NOT NULL,
|
|
798
|
+
answered_at TEXT NOT NULL,
|
|
799
|
+
created_at TEXT NOT NULL,
|
|
800
|
+
superseded_at TEXT
|
|
801
|
+
);
|
|
802
|
+
|
|
803
|
+
CREATE INDEX IF NOT EXISTS idx_answers_answered_at ON answers(answered_at);
|
|
804
|
+
|
|
805
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_answers_current ON answers(prompt_queue_id) WHERE superseded_at IS NULL;
|
|
806
|
+
|
|
807
|
+
CREATE TABLE IF NOT EXISTS prompt_tasks(
|
|
808
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
809
|
+
parent_id INTEGER REFERENCES prompt_tasks(id),
|
|
810
|
+
kind TEXT NOT NULL DEFAULT 'task' CHECK(kind IN ('epic', 'task')),
|
|
811
|
+
title TEXT NOT NULL,
|
|
812
|
+
description TEXT NOT NULL DEFAULT '',
|
|
813
|
+
created_at TEXT NOT NULL
|
|
814
|
+
);
|
|
815
|
+
|
|
816
|
+
CREATE INDEX IF NOT EXISTS idx_prompt_tasks_parent ON prompt_tasks(parent_id);
|
|
817
|
+
|
|
818
|
+
CREATE TABLE IF NOT EXISTS task_prompts(
|
|
819
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
820
|
+
task_id INTEGER REFERENCES prompt_tasks(id),
|
|
821
|
+
from_id TEXT NOT NULL,
|
|
822
|
+
to_id TEXT NOT NULL,
|
|
823
|
+
prompt TEXT NOT NULL,
|
|
824
|
+
created_at TEXT NOT NULL,
|
|
825
|
+
retrieved_ts TEXT
|
|
826
|
+
);
|
|
827
|
+
|
|
828
|
+
CREATE INDEX IF NOT EXISTS idx_task_prompts_task ON task_prompts(task_id);
|
|
829
|
+
|
|
830
|
+
CREATE INDEX IF NOT EXISTS idx_task_prompts_to ON task_prompts(to_id, created_at);
|
|
831
|
+
|
|
832
|
+
CREATE TABLE IF NOT EXISTS prompt_task_reassignments(
|
|
833
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
834
|
+
prompt_id INTEGER NOT NULL REFERENCES task_prompts(id),
|
|
835
|
+
from_task_id INTEGER REFERENCES prompt_tasks(id),
|
|
836
|
+
to_task_id INTEGER NOT NULL REFERENCES prompt_tasks(id),
|
|
837
|
+
reassigned_by TEXT NOT NULL,
|
|
838
|
+
reassigned_at TEXT NOT NULL
|
|
839
|
+
);
|
|
840
|
+
|
|
841
|
+
CREATE INDEX IF NOT EXISTS idx_prompt_task_reassignments_prompt ON prompt_task_reassignments(prompt_id);
|
|
842
|
+
`),t.exec("INSERT OR IGNORE INTO schema_meta (key, value) VALUES ('min_reader_version', '61')"),t.pragma("user_version = 62"),r=62),Zw(ov)}function lv(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(tv(),new Date().toISOString())}function G(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function nt(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Ut(t,e){if(!nt(t,e)&&(t.exec(Du(Pu,"utf8")),!nt(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function Ou(t){let e=G(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
766
843
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
767
844
|
CREATE TABLE team_chat_log_v46 (
|
|
768
845
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -791,23 +868,23 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
791
868
|
FROM team_chat_log;
|
|
792
869
|
DROP TABLE team_chat_log;
|
|
793
870
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
794
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function Uu(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function
|
|
871
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function Uu(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function cv(t,e){try{if(!nt(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 dv(t,e,r=xt){ca||(ca=!0,process.stderr.write(`warning: ${t}: state.db is v${e}; this build understands v${r} -- some newer data or features may not be visible, proceeding best-effort. Update: npm install -g @lmctl-ai/lmctl@latest
|
|
795
872
|
`),process.argv.includes("--json")&&process.stderr.write(`${JSON.stringify({schema_skew:{db_version:e,build_version:r,mode:"best_effort"}})}
|
|
796
|
-
`))}function
|
|
873
|
+
`))}function uv(){ca=!1,da=null}function mv(){return da}function fv(){return process.env.LMCTL_DB??nv(rv(),".lmctl","state.db")}var Fu,Pu,ov,xt,jt,ca,da,Ws=k(()=>{"use strict";oa();la();Fu=Mu(sv(import.meta.url)),Pu=$u(Fu,"schema.sql"),ov=$u(Fu,"migrations"),xt=62,jt=class extends Error{dbPath;dbVersion;buildVersion;constructor(e,r,n=xt){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}};ca=!1;da=null;if(process.argv[1]&&(process.argv[1].endsWith("migrate.ts")||process.argv[1].endsWith("migrate.js"))&&import.meta.url===iv(process.argv[1]).href){let t=bn({dbPath:process.argv[2]??fv()});try{process.stdout.write(`migrated user_version=${Uu(t)}
|
|
797
874
|
`)}finally{t.close()}}});function Bu(t){if(t.length===0||!t.startsWith("---"))throw new dt("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
798
|
-
`);if(e[0]!=="---")throw new dt("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 dt(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!
|
|
875
|
+
`);if(e[0]!=="---")throw new dt("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 dt(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!pv.has(c))throw new dt(`unknown frontmatter key "${c}" \u2014 allowed keys: ${Hs.join(", ")}`);r[c]=u}if(n===-1)throw new dt("frontmatter not closed (missing trailing `---` on its own line)");for(let o of Hs)if(r[o]===void 0)throw new dt(`missing required frontmatter key "${o}" \u2014 required: ${Hs.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 Hs,pv,dt,Wu=k(()=>{"use strict";Hs=["title","description","members"],pv=new Set(Hs),dt=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as hv,writeFileSync as $M,renameSync as FM,existsSync as Xu}from"node:fs";import{basename as gv,resolve as Br,dirname as ua}from"node:path";function yv(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 Ev(t){return/^\s*_MEMBER_\s+\S/.test(t)}function Tv(t){return/^\s*_SESSION_\s+\S/.test(t)}function wv(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function fa(t){let e=gv(t);return e.endsWith(".lmctl")?e.slice(0,-6):e}function Ne(t){let e=hv(t,"utf-8"),r=ua(Br(t)),n=pa(e,fa(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 pa(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
799
876
|
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=Bu(i)}catch(l){if(l instanceof dt)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
800
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(
|
|
801
|
-
allowed keys: ${Hu.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!d.alias){s.push(`line ${u}: member line missing required alias: ${c.trim()}`);continue}let m={alias:d.alias,provider:d.provider||"",extra:{}};d.sessionid&&(m.session=d.sessionid),Object.prototype.hasOwnProperty.call(d,"sessiondir")&&(m.sessiondir=d.sessiondir),d.teamfile&&(m.teamfile=d.teamfile),d.model&&(m.model=d.model),d.effort&&(m.effort=d.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function ha(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()===ma.toLowerCase());n.length>1&&r.push({field:ma,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(!Xu(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ne(a),c=Bt(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
|
|
802
|
-
`)}){let n=he(t,
|
|
877
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(Tv(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(wv(c)||!Ev(c))continue;let d=yv(c);for(let f of Object.keys(d))if(!Hu.includes(f))throw new Error(`line ${u}: unknown key "${f}" on _MEMBER_ line: ${c.trim()}
|
|
878
|
+
allowed keys: ${Hu.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}if(!d.alias){s.push(`line ${u}: member line missing required alias: ${c.trim()}`);continue}let m={alias:d.alias,provider:d.provider||"",extra:{}};d.sessionid&&(m.session=d.sessionid),Object.prototype.hasOwnProperty.call(d,"sessiondir")&&(m.sessiondir=d.sessiondir),d.teamfile&&(m.teamfile=d.teamfile),d.model&&(m.model=d.model),d.effort&&(m.effort=d.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function ha(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()===ma.toLowerCase());n.length>1&&r.push({field:ma,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(!Xu(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ne(a),c=Bt(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 _v.has(i.provider)||r.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&r.push({field:i.alias,message:"sessiondir is empty"})}return r}function Bt(t){return t.members.find(e=>e.alias.toLowerCase()===ma.toLowerCase())}function ga(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),!Xu(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Ne(i),l=Bt(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return ga(l,ua(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||ua(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function Xs(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var ma,_v,Hu,kt=k(()=>{"use strict";Wu();ma="Lead",_v=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"]);Hu=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as vv}from"node:crypto";import{existsSync as qu,readFileSync as Gu,realpathSync as Sv}from"node:fs";import{dirname as bv,resolve as Ju}from"node:path";function he(t,e){let r=Ju(t);if(qu(r))return Sv(r);if(e!==void 0){let n=xv(t,r,e);if(n!==null)return n}return r}function Gs(t,e){let r=bv(e),n=pa(t,fa(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Ju(r,s.sessiondir));return n}function Ve(t,e,r=n=>{process.stderr.write(`warning: ${n}
|
|
879
|
+
`)}){let n=he(t,Iv(e)?e:void 0);if(qu(n)){let i=Gu(n,"utf8"),o=Gs(i,n);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(n)===null&&kv(o)&&Rv(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 Iv(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function xv(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);return n===null?null:n.teamfile_path}function kv(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=_a)}function ya(t,e,r){let n=he(e),s=r.members.filter(i=>i.teamfile===void 0&&i.session!==void 0&&i.session.length>=_a);if(s.length!==0)for(let i of t.listRootTeams()){let o,a;try{if(o=he(i.teamfile_path),o===n)continue;a=Gu(o,"utf8")}catch(c){if(Av(c))continue;throw c}let l=Gs(a,o);for(let c of s){let u=l.members.find(d=>d.teamfile===void 0&&d.session===c.session&&(d.session?.length??0)>=_a);if(u!==void 0)throw new qs(`sessionid ownership conflict: ${n}:${c.alias} and ${o}:${u.alias} both use sessionid "${c.session}"`)}}}function Av(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Rv(t,e,r,n,s){try{ya(t,e,r)}catch(o){if(!(o instanceof qs))throw o;s(`${o.message}; skipping automatic registration`);return}let i={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:vv("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(i)}var _a,qs,At=k(()=>{"use strict";kt();_a=5,qs=class extends Error{constructor(e){super(e),this.name="ForeignSessionidOwnershipError"}}});import{randomUUID as Nv}from"node:crypto";import{closeSync as Lv,openSync as Cv,readFileSync as Ku,statSync as Ov,unlinkSync as Ea,writeFileSync as Dv}from"node:fs";function Yu(t,e){return`${t}.seed-${e.toLowerCase()}.lock`}function zu(t){let e;try{e=JSON.parse(Ku(t,"utf8"))}catch(n){return n.code==="ENOENT"?!1:Vu(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 Vu(t);try{return process.kill(r,0),!0}catch(n){return n.code!=="ESRCH"}}function Vu(t){try{return Date.now()-Ov(t).mtimeMs<3e5}catch{return!1}}function Ta(t,e){return zu(Yu(t,e))}function Qu(t,e){let r=Yu(t,e),n=JSON.stringify({pid:process.pid,token:Nv()});for(let s=0;s<2;s+=1)try{let i=Cv(r,"wx");try{Dv(i,n)}catch(o){throw Ea(r),o}finally{Lv(i)}return()=>{try{Ku(r,"utf8")===n&&Ea(r)}catch(o){if(o.code!=="ENOENT")throw o}}}catch(i){if(i.code!=="EEXIST")throw i;if(zu(r))throw new Error(`${e}: seed already in progress; wait for it to finish`);try{Ea(r)}catch(o){if(o.code!=="ENOENT")throw o}}throw new Error(`${e}: could not acquire seed marker`)}var wa=k(()=>{"use strict"});import{existsSync as Mv}from"node:fs";import{dirname as Zu}from"node:path";function Uv(t){return $v.test(t)||Fv.test(t)||Pv.test(t)}function em(t){return Js.test(t)}function Vs(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!r.endsWith(".lmctl")||!Js.test(n)?null:{teamfile:r,alias:n}}function me(t,e,r){if(!t.endsWith(".lmctl"))throw new ne(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl extension).`);if(!em(e))throw new ne(`lmctl: "${e}" is not a valid alias (must match ${Js.source}).`);let n=he(t,r);if(r===void 0&&!Mv(n))throw new ne(`lmctl: teamfile not found: ${t}`);let s;try{s=Ve(n,r)}catch(o){throw new ne(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new ne(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=Xs(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new ne(`lmctl: alias "${e}" not found in ${t}.
|
|
803
880
|
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=ga(i,Zu(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(Ta(n,i.alias))throw new ne(`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=>Ta(n,o.alias))?new ne(`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 ne(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
804
881
|
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??Zu(n),isLead:Bt(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function ut(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=Vs(r);if(o!==null)return n!==void 0&&n!==o.alias?{mode:"error",message:`lmctl ${t.name}: got "${r}" AND second positional "${n}" \u2014 pick one form.`}:{mode:"ai-team",teamfile:o.teamfile,alias:o.alias};if(r.endsWith(".lmctl"))return n!==void 0?em(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${Js.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
805
|
-
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(
|
|
882
|
+
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(Uv(r)){if(n!==void 0)return{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.`};if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: "${r}" is a bare sessionid, but ${t.name} is teamfile-only (a sessionid carries no provider resume incantation).`};let a={mode:"ai-team-raw",sessionid:r};return s.provider!==void 0&&(a.provider=s.provider),a}return n!==void 0?{mode:"error",message:`lmctl ${t.name}: got a second positional "${n}" but "${r}" is not a teamfile path.
|
|
806
883
|
Either drop the second arg, or pass <teamfile>.lmctl as the first arg.`}:{mode:"error",message:`lmctl ${t.name}: can't infer target type from "${r}".
|
|
807
884
|
Expected one of: <path>.lmctl, <path>.lmctl:<alias>, <sessionid>.`}}if(s.session!==void 0){if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: --session (raw mode) is not supported by ${t.name}.`};let o={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(o.provider=s.provider),o}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
808
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ne,
|
|
809
|
-
`,"utf8"),Ke.renameSync(r,t)}catch(n){try{Ke.unlinkSync(r)}catch{}throw n}}function
|
|
810
|
-
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function tm(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function
|
|
885
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var ne,$v,Fv,Pv,Js,We=k(()=>{"use strict";kt();At();wa();ne=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},$v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Fv=/^ses_[A-Za-z0-9_-]+$/,Pv=/^session_[A-Za-z0-9_-]+$/,Js=/^[A-Za-z][A-Za-z0-9_-]*$/});import{existsSync as jv,mkdirSync as Bv,readFileSync as Wv,renameSync as Hv,unlinkSync as Xv,writeFileSync as qv}from"node:fs";import{homedir as rm}from"node:os";import{dirname as In,join as Le,resolve as Gv}from"node:path";function Hr(t,e,r){let n=In(Gv(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())mt(Le(o,".mcp.json"),"mcpServers",[Wt(),Ht()]),a.has("opencode")&&mt(Le(o,".opencode","opencode.json"),"mcp",[nm(),sm()]),a.has("kimi")&&mt(Le(o,".kimi-code","mcp.json"),"mcpServers",[Wt(),Ht()]);for(let o of s)zv(o)}function Vv(t=va??rm()){return Le(t,".copilot","mcp-config.json")}function Kv(t,e){Ke.mkdirSync(In(t),{recursive:!0});let r=Le(In(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ke.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
886
|
+
`,"utf8"),Ke.renameSync(r,t)}catch(n){try{Ke.unlinkSync(r)}catch{}throw n}}function Yv(t,e){Ke.mkdirSync(In(t),{recursive:!0});let r=Le(In(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{Ke.writeFileSync(r,e,"utf8"),Ke.renameSync(r,t)}catch(n){try{Ke.unlinkSync(r)}catch{}throw n}}function mt(t,e,r){try{if(!Ke.existsSync(t))return;let n=JSON.parse(Ke.readFileSync(t,"utf8"));if(!Wr(n)||!Wr(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,Kv(t,n),L({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Wt(){return{name:Ys,shouldRemove:iS}}function nm(){return{name:Ys,shouldRemove:oS}}function Ht(){return{name:Ks,shouldRemove:nS}}function sm(){return{name:Ks,shouldRemove:sS}}function zv(t){let e=va??rm();switch(t){case"copilot":mt(Vv(e),"mcpServers",[Wt(),Ht()]);return;case"claude":mt(Le(e,".claude.json"),"mcpServers",[Wt(),Ht()]);return;case"gemini":mt(Le(e,".gemini","settings.json"),"mcpServers",[Wt(),Ht()]);return;case"qwen":mt(Le(e,".qwen","settings.json"),"mcpServers",[Wt(),Ht()]);return;case"agy":mt(Le(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Wt(),Ht()]);return;case"opencode":mt(Le(e,".config","opencode","opencode.json"),"mcp",[nm(),sm()]);return;case"kimi":mt(Le(va===void 0?process.env.KIMI_CODE_HOME??Le(e,".kimi-code"):Le(e,".kimi-code"),"mcp.json"),"mcpServers",[Wt(),Ht()]);return;case"codex":Qv(Le(e,".codex","config.toml"));return;default:return}}function Qv(t){try{if(!Ke.existsSync(t))return;let e=Ke.readFileSync(t,"utf8"),r=Zv(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=im(l);if(c===null)return;if(c!==void 0){if(tm(c,r)){o=!0,a=c[1],i.add(a);continue}o=!1,a=void 0,s.push(l);continue}if(o){if(/^\s*(?:#.*)?$/.test(l)){s.push(l);continue}a!==void 0&&i.add(a);continue}let u=tS(l);if(u===null)return;if(u!==void 0&&tm(u,r)){i.add(u[1]);continue}s.push(l)}if(i.size===0)return;Yv(t,s.join(`
|
|
887
|
+
`)),L({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function tm(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function Zv(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=im(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=eS(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Ks&&c[1]!==Ys)continue;let u=e.get(c[1])??{};if(c[2]==="command"){let d=om(l);if(d===null)return null;u.command=d}else if(c[2]==="args"){let d=rS(l);if(d===null)return null;u.args=d}e.set(c[1],u)}let n=new Set;for(let[s,i]of e.entries())s===Ks&&lm(i.command,i.args)&&n.add(s),s===Ys&&cm(i.command,i.args)&&n.add(s);return n}function eS(t,e){if(t.startsWith("mcp_servers"))return zs(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=zs(t);return r===null?null:[...e,...r]}function im(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:zs(e[1])}function tS(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 zs(r)}function zs(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 om(t){let e=am(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 rS(t){let e=am(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=>om(s.trim()));return n.some(s=>s===null)?null:n}function am(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 nS(t){return Wr(t)?t.type==="stdio"&&typeof t.command=="string"&&lm(t.command,t.args):!1}function sS(t){return!Wr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&um(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"&&dm(t.command[0],[t.command[1],t.command[2]])}function iS(t){return Wr(t)?t.type==="stdio"&&cm(t.command,t.args):!1}function oS(t){return!Wr(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&mm(t.command[0])&&t.command[1]==="mcp"}function lm(t,e){return um(t)&&fm(e)||dm(t,e)}function cm(t,e){return mm(t)&&fm(e)}function dm(t,e){return aS(t)&&Array.isArray(e)&&e.length===2&&lS(e[0])&&e[1]==="mcp"}function um(t){return typeof t=="string"&&Sa(t)==="lmctl"}function mm(t){return typeof t=="string"&&Sa(t)==="lmctl0"}function aS(t){if(typeof t!="string")return!1;let e=Sa(t).toLowerCase();return e==="node"||e==="node.exe"}function lS(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 Sa(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function fm(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function Wr(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Ks,Ys,Jv,Ke,va,Qs=k(()=>{"use strict";V();Ks="lmctl",Ys="lmctl0",Jv={existsSync:jv,mkdirSync:Bv,readFileSync:Wv,writeFileSync:qv,renameSync:Hv,unlinkSync:Xv},Ke=Jv});function gm(t){let e=pm(t.registry,t.fromTeamfile);if(e===void 0)return Xr(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!hm(e,t.fromAlias))return Xr(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=pm(t.registry,t.toTeamfile);return r===void 0?Xr(`target team is not registered in policy graph: ${t.toTeamfile}`):hm(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Xr(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Xr(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Xr(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function pm(t,e){return t.teams.find(r=>r.teamfile===e)}function hm(t,e){return t.aliases.some(r=>r===e)}function Xr(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var _m=k(()=>{"use strict"});import{basename as cS}from"node:path";function Tm(t,e){let r=new Date(e.now.getTime()-ft()).toISOString(),n=Sm(t,r).filter(f=>!f.sender.teamfile.startsWith("prompt:")),s=fS(e.sender,n),i=pS(e.sender,n);i!==null&&i.teamfile===e.root&&!Em(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(f=>Em(f,o)),c=l.map(f=>f.at).filter(f=>f!==null).sort((f,g)=>g-f)[0]??null,u=c!==null&&e.now.getTime()-c<dS,d=ba(e.sender,n).length;return{stop:l.length>=1&&u&&d>=uS,chain:hS(a)}}function wm(t,e){let r=new Date(e.now.getTime()-ft()).toISOString(),n=Sm(t,r),s=ba(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 ft(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return ym;let r=Number(e);return!Number.isFinite(r)||r<=0?ym:r}function vm(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function mS(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 Sm(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(mS).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function fS(t,e,r={}){let n=new Map;for(let a of e)n.set(hr(a.receiver),a);let s=[{...t,at:null}],i=t,o=new Set([hr(t)]);for(let a=0;a<64;a+=1){let l=n.get(hr(i));if(l===void 0)break;s[0]={...s[0],at:s[0].at??l.at};let c={...l.sender,at:l.at};if(l.sender.teamfile.startsWith("prompt:")&&r.includePromptSender!==!0)break;let u=hr(l.sender);if(o.has(u))break;s.unshift(c),o.add(u),i=l.sender}return s}function ba(t,e){let r=hr(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=hr(l.sender),u=hr(l.receiver);c!==a&&u!==a||(i.includes(l)||i.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return i.sort((o,a)=>o.at-a.at)}function pS(t,e){let r=ba(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Em(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function hr(t){return`${t.teamfile}\0${t.alias}`}function hS(t){return t.map(e=>`${cS(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var dS,uS,ym,xn=k(()=>{"use strict";dS=6e4,uS=2,ym=8*60*60*1e3});function bm(t){return{getAgentInflight:t.prepare("SELECT * FROM agent_inflight WHERE receiver_teamfile = ? AND receiver_alias = ?"),listAgentInflight:t.prepare("SELECT * FROM agent_inflight ORDER BY started_at ASC, receiver_teamfile ASC, receiver_alias ASC"),acquireAgentInflight:t.prepare(`
|
|
811
888
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
812
889
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
813
890
|
ON CONFLICT(receiver_teamfile, receiver_alias) DO UPDATE SET
|
|
@@ -1024,21 +1101,21 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
1024
1101
|
AND started_at = ?
|
|
1025
1102
|
AND last_heartbeat_at IS ?
|
|
1026
1103
|
`)}}function Ye(t){if(t==null)return null;if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(xm,"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")}${xm}`}var xm,Am=k(()=>{"use strict";xm=`
|
|
1027
|
-
...[truncated]`});function Rn(t,e){return JSON.stringify([t,e])}function Rm(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 kn,An,Nm=k(()=>{"use strict";kn="terminal_lock",An="member"});function Ce(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 gr=k(()=>{"use strict"});import{hostname as qr}from"node:os";function Gr(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??
|
|
1104
|
+
...[truncated]`});function Rn(t,e){return JSON.stringify([t,e])}function Rm(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 kn,An,Nm=k(()=>{"use strict";kn="terminal_lock",An="member"});function Ce(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 gr=k(()=>{"use strict"});import{hostname as qr}from"node:os";function Gr(t,e={}){let r=setInterval(()=>{Promise.resolve().then(()=>t(new Date().toISOString())).then(n=>{n||clearInterval(r)}).catch(n=>e.onError?.(n))},e.intervalMs??gS);return r.unref?.(),r}function Xt(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(!Zs(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 qt(t){return t.status!=="running"?null:t.holder_host===qr()&&t.holder_pid!==null&&t.holder_pid>0?Ce(t.holder_pid)?"live":"dead":"unknown"}function pt(t,e,r){let n,s=t.getTerminalLock(e,r);if(s!==null){if(_S(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===qr()?"dead-pid":"stale"}}let i=yS(t,e,r);if(i!==null){if(ES(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===qr())?"dead-pid":"stale"}}let o=t.getAgentInflight(e,r);if(o!==null){let a=new Date(Date.now()-Jr()).toISOString();if(!Zs(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:qr(),reason:o.holder_pid===null?"stale":"dead-pid"}}return n===void 0?{busy:!1}:{busy:!1,reclaimable:n}}function _S(t){if(t.holder_host===qr())return Ce(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=wS():!1}function yS(t,e,r){return t.query(`SELECT id, started_at, last_heartbeat_at, holder_pid, holder_host
|
|
1028
1105
|
FROM tracked_invocation
|
|
1029
1106
|
WHERE target_teamfile = ?
|
|
1030
1107
|
AND target_alias = ?
|
|
1031
1108
|
AND status = 'running'
|
|
1032
1109
|
AND launch_source = 'terminal'
|
|
1033
1110
|
ORDER BY started_at DESC, id DESC
|
|
1034
|
-
LIMIT 1`,e,r)[0]??null}function
|
|
1111
|
+
LIMIT 1`,e,r)[0]??null}function ES(t){return t.holder_pid!==null&&(t.holder_host===null||t.holder_host===qr())?Ce(t.holder_pid):TS(t)}function TS(t){let e=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(e)?Date.now()-e<=Jr():!1}function Zs(t,e){return t.holder_pid===null?t.started_at<e:!Ce(t.holder_pid)}function Jr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return Lm;let r=Number(e);return!Number.isFinite(r)||r<=0?Lm:r}function wS(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return Cm;let r=Number(e);return!Number.isFinite(r)||r<=0?Cm:r}var Lm,Cm,gS,st=k(()=>{"use strict";gr();Lm=8*60*60*1e3,Cm=12e4,gS=3e4});import{randomUUID as vS}from"node:crypto";import{hostname as SS}from"node:os";function Gt(t,e){return{teamfile:t,alias:e}}function Om(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 Ia(t,e){return t===null?null:Gt(t,e??"")}function Rt(t){return`msg_tcl_${t}`}function _r(t){return`inv_${t}`}function Vr(t,e,r){return t.prepare(`SELECT receiver_teamfile, receiver_alias, lease_id, sender_teamfile, sender_alias,
|
|
1035
1112
|
holder_pid, holder_host, started_at, terminal_lock_id,
|
|
1036
1113
|
terminal_invocation_id, currently_handling_message_id,
|
|
1037
1114
|
currently_handling_since, last_seq
|
|
1038
1115
|
FROM agent_state
|
|
1039
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function
|
|
1116
|
+
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r)??null}function IS(t,e,r){if(e===null||r===null)return null;let n=t.prepare(`SELECT currently_handling_message_id, currently_handling_since
|
|
1040
1117
|
FROM agent_state
|
|
1041
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e,r);if(n?.currently_handling_message_id===null||n?.currently_handling_message_id===void 0||n.currently_handling_since===null)return null;let s=Date.parse(n.currently_handling_since);return!Number.isFinite(s)||Date.now()-s>
|
|
1118
|
+
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>bS?null:n.currently_handling_message_id}function xS(t,e,r){let n=IS(t,e,r);return n===null?{}:{causation:{request_message_id:n}}}function xa(t,e,r,n,s=new Date().toISOString()){t.prepare(`INSERT INTO agent_state
|
|
1042
1119
|
(receiver_teamfile, receiver_alias, currently_handling_message_id,
|
|
1043
1120
|
currently_handling_since, last_seq)
|
|
1044
1121
|
VALUES (?, ?, ?, ?, 0)
|
|
@@ -1048,12 +1125,12 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
1048
1125
|
SET currently_handling_message_id = NULL,
|
|
1049
1126
|
currently_handling_since = NULL
|
|
1050
1127
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1051
|
-
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function
|
|
1128
|
+
AND currently_handling_message_id = ?`).run(e,r,n).changes===1}function kS(t,e){let r=e??new Date(Date.now()-Jr()).toISOString();return Zs({holder_pid:t.holder_pid,started_at:t.started_at??""},r)}function AS(t,e,r){return e==="force"||e==="session-idle"?e:r?"force":t.holder_pid!==null&&!Ce(t.holder_pid)?"dead-pid":"stale"}function RS(t){return{sender:Ia(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:t.holder_host,started_at:t.started_at}}function Kr(t,e){if(t!==1)throw new Error(`event projection CAS failed during ${e}`)}function Aa(t,e,r){let n=Rt(e),s=Ia(r.sender_teamfile,r.sender_alias),i=Om(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 Fe(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,...xS(t,r.sender_teamfile,r.sender_alias)}},()=>{xa(t,r.receiver_teamfile,r.receiver_alias,n,r.created_at)}),n}function ei(t,e,r){let n=Rt(e),s={message_id:n,message_type:"request",sender:Ia(r.sender_teamfile,r.sender_alias),receiver:Om(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 Fe(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}},()=>{ka(t,r.receiver_teamfile,r.receiver_alias,n)}),n}function NS(t){return{sender:Gt(t.sender_teamfile,t.sender_alias),holder_pid:t.holder_pid,holder_host:null,started_at:t.started_at}}function Dm(t,e,r,n){let s=t.prepare(`UPDATE agent_state
|
|
1052
1129
|
SET lease_id = NULL, sender_teamfile = NULL, sender_alias = NULL,
|
|
1053
1130
|
holder_pid = NULL, holder_host = NULL, started_at = NULL,
|
|
1054
1131
|
last_heartbeat_at = NULL, last_seq = ?
|
|
1055
1132
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1056
|
-
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Kr(s.changes,n)}function Mm(t,e,r,n,s=null,i=!1){let o=
|
|
1133
|
+
AND lease_id IS ? AND last_seq = ?`).run(r,e.receiver_teamfile,e.receiver_alias,e.lease_id,e.last_seq);Kr(s.changes,n)}function Mm(t,e,r,n,s=null,i=!1){let o=SS();if(r!==null&&n===null)throw new Error("agent inflight takeover is missing a reclaim reason");let a=Vr(t,e.receiver_teamfile,e.receiver_alias);if(a!==null&&a.lease_id!==null){if(!(i||kS(a,s)))throw new Error("event projection rejected INFLIGHT_TAKE: receiver already holds a live lease");let d=AS(a,n,i),m=RS(a),f=a.lease_id;Fe(t,{stream_id:f,event_type:"INFLIGHT_RECLAIM",observedLastSeq:a.last_seq,ts:e.started_at,payload:{receiver:Gt(e.receiver_teamfile,e.receiver_alias),reason:d,previous_holder:m}},g=>Dm(t,a,g,"INFLIGHT_RECLAIM")),a=Vr(t,e.receiver_teamfile,e.receiver_alias)}let l=a?.last_seq??0,c=`lease_${vS()}`;return Fe(t,{stream_id:c,event_type:"INFLIGHT_TAKE",observedLastSeq:l,ts:e.started_at,payload:{lease_id:c,receiver:Gt(e.receiver_teamfile,e.receiver_alias),sender:Gt(e.sender_teamfile,e.sender_alias),holder_pid:e.holder_pid,holder_host:o,started_at:e.started_at}},u=>{if(a===null){t.prepare(`INSERT INTO agent_state
|
|
1057
1134
|
(receiver_teamfile, receiver_alias, lease_id, sender_teamfile,
|
|
1058
1135
|
sender_alias, holder_pid, holder_host, started_at,
|
|
1059
1136
|
last_heartbeat_at, last_seq)
|
|
@@ -1067,7 +1144,7 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
1067
1144
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1068
1145
|
AND lease_id = ?
|
|
1069
1146
|
AND sender_teamfile = ? AND sender_alias = ?
|
|
1070
|
-
AND started_at = ? AND holder_pid IS ?`).run(n,e.receiver_teamfile,e.receiver_alias,r,e.sender_teamfile,e.sender_alias,e.started_at,e.holder_pid).changes===1}function Nn(t,e,r,n){let s=Vr(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||Fe(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:Gt(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:
|
|
1147
|
+
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 Nn(t,e,r,n){let s=Vr(t,e.receiver_teamfile,e.receiver_alias);s===null||s.lease_id===null||Fe(t,{stream_id:s.lease_id,event_type:r,observedLastSeq:s.last_seq,payload:{receiver:Gt(e.receiver_teamfile,e.receiver_alias),...r==="INFLIGHT_RECLAIM"?{reason:n??"stale",previous_holder:NS(e)}:{lease_id:s.lease_id}}},i=>Dm(t,s,i,r))}function Fm(t,e){let r=Vr(t,e.teamfile,e.alias),n=r?.last_seq??0;Fe(t,{stream_id:e.lock_id,event_type:"TERMINAL_LOCK_TAKE",observedLastSeq:n,ts:e.started_at,payload:{receiver:Gt(e.teamfile,e.alias),lock_id:e.lock_id,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at}},s=>{if(r===null){t.prepare(`INSERT INTO agent_state
|
|
1071
1148
|
(receiver_teamfile, receiver_alias, terminal_lock_id, last_seq)
|
|
1072
1149
|
VALUES (?, ?, ?, ?)`).run(e.teamfile,e.alias,e.lock_id,s);return}let i=t.prepare(`UPDATE agent_state SET terminal_lock_id = ?, last_seq = ?
|
|
1073
1150
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
@@ -1091,15 +1168,15 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
1091
1168
|
terminal_invocation_host = NULL,
|
|
1092
1169
|
terminal_invocation_heartbeat_at = NULL, last_seq = ?
|
|
1093
1170
|
WHERE receiver_teamfile = ? AND receiver_alias = ?
|
|
1094
|
-
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);Kr(s.changes,"terminal INVOCATION_FINISH")}var
|
|
1171
|
+
AND terminal_invocation_id = ? AND last_seq = ?`).run(e,n.receiver_teamfile,n.receiver_alias,r,n.last_seq);Kr(s.changes,"terminal INVOCATION_FINISH")}var bS,ti=k(()=>{"use strict";Us();st();gr();bS=60*60*1e3});function Bm(t,e){return t.prepare("SELECT last_seq FROM invocation_state WHERE invocation_id = ?").get(e)??null}function Na(t){return t.launch_source==="terminal"&&t.target_teamfile!==null}function Wm(t,e){let r=_r(e.id),n=e.target_teamfile===null?null:{teamfile:e.target_teamfile,alias:e.target_alias??""},s=e.last_heartbeat_at??e.started_at;Fe(t,{stream_id:r,event_type:LS,observedLastSeq:0,ts:e.started_at,payload:{invocation_id:r,kind:e.kind,origin:e.origin,launch_source:e.launch_source,from_identity:e.from_identity,target:n,root_teamfile:e.root_teamfile,scope_teamfile:e.scope_teamfile,cwd:e.cwd,command:e.command,request_payload:e.request_payload,request_message_id:e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,legacy:{table:"tracked_invocation",id:e.id}}},i=>{t.prepare(`INSERT INTO invocation_state
|
|
1095
1172
|
(invocation_id, kind, origin, launch_source, from_identity, target_teamfile, target_alias,
|
|
1096
1173
|
root_teamfile, cwd, command, request_message_id, request_payload, holder_pid, holder_host,
|
|
1097
1174
|
status, started_at, last_heartbeat_at, last_seq)
|
|
1098
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', ?, ?, ?)`).run(r,e.kind,e.origin,e.launch_source??e.kind,e.from_identity,e.target_teamfile,e.target_alias,e.root_teamfile,e.cwd,e.command,e.team_chat_log_id===null?null:`msg_tcl_${e.team_chat_log_id}`,e.request_payload,e.holder_pid,e.holder_host,e.started_at,e.last_heartbeat_at,i),Na(e)&&Pm(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function ri(t,e){let r=_r(e.id),n=Bm(t,r);return n===null?!1:(Fe(t,{stream_id:r,event_type:
|
|
1175
|
+
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),Na(e)&&Pm(t,i,{invocationId:r,targetTeamfile:e.target_teamfile,targetAlias:e.target_alias??"",holderPid:e.holder_pid,holderHost:e.holder_host,heartbeatAt:s})})}function ri(t,e){let r=_r(e.id),n=Bm(t,r);return n===null?!1:(Fe(t,{stream_id:r,event_type:CS,observedLastSeq:n.last_seq,ts:e.ended_at??e.started_at,payload:{invocation_id:r,status:e.status,ended_at:e.ended_at,exit_code:e.exit_code,signal:e.signal,result_summary:e.result_summary,error:e.error,legacy:{table:"tracked_invocation",id:e.id}}},s=>{if(t.prepare(`UPDATE invocation_state
|
|
1099
1176
|
SET status = ?, ended_at = ?, result_summary = ?, error = ?, last_seq = ?
|
|
1100
|
-
WHERE invocation_id = ? AND last_seq = ?`).run(e.status,e.ended_at,e.result_summary,e.error,s,r,n.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_FINISH for ${r}`);Na(e)&&jm(t,s,r)}),!0)}function Hm(t,e,r,n){let s=_r(e.id),i=Bm(t,s);return i===null?!1:(Fe(t,{stream_id:s,event_type:
|
|
1177
|
+
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}`);Na(e)&&jm(t,s,r)}),!0)}function Hm(t,e,r,n){let s=_r(e.id),i=Bm(t,s);return i===null?!1:(Fe(t,{stream_id:s,event_type:OS,observedLastSeq:i.last_seq,ts:n,payload:{invocation_id:s,notified_by:r,notified_at:n,legacy:{table:"tracked_invocation",id:e.id}}},o=>{if(t.prepare("UPDATE invocation_state SET notified_by = ?, notified_at = ?, last_seq = ? WHERE invocation_id = ? AND last_seq = ?").run(r,n,o,s,i.last_seq).changes!==1)throw new Error(`invocation_state CAS failed during INVOCATION_NOTIFY_CLAIM for ${s}`)}),!0)}function Xm(t,e,r){let n=_r(e.id);t.prepare("UPDATE invocation_state SET last_heartbeat_at = ? WHERE invocation_id = ?").run(r,n),Na(e)&&Um(t,n,r)}function qm(t,e,r){t.prepare("UPDATE invocation_state SET request_payload = ? WHERE invocation_id = ?").run(r,_r(e))}function Gm(t,e,r){t.prepare("UPDATE invocation_state SET request_message_id = ? WHERE invocation_id = ?").run(r,_r(e))}var LS,CS,OS,Jm=k(()=>{"use strict";Us();ti();LS="INVOCATION_START",CS="INVOCATION_FINISH",OS="INVOCATION_NOTIFY_CLAIM"});var DS,MS,I$,Vm,Km,Ym,zm=k(()=>{"use strict";DS="other",MS=["not_enough_information","dont_know","other_work"],I$=new Set([DS,...MS]),Vm="@abort",Km="invalid_decision",Ym="workflow_escalation"});import{randomUUID as Qm}from"node:crypto";import{existsSync as nf,mkdirSync as $S,renameSync as FS,rmdirSync as PS}from"node:fs";import{hostname as La}from"node:os";function Ca(t){return t.provider_resolved??t.provider}function F(){return new Date().toISOString()}function US(t){let e={rootTeams:[],config:[]};if(t===":memory:"||!nf(t))return e;let r;try{r=new Ps(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 jS(t){if(t===":memory:"||!nf(t))return null;let e=`${t}.bak-${Date.now()}-${process.pid}`;for(let r of["","-wal","-shm"]){let n=`${t}${r}`;try{FS(n,`${e}${r}`)}catch{}}return e}function Zm(t,e){let r=e instanceof Error?e.message:String(e);try{let n=US(t),s=jS(t),i=new ni(bn({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${xt} (${r}); started a fresh database instead. Preserved ${n.rootTeams.length} team registration(s) and ${n.config.length} config value(s).`+(s!==null?` Old database backed up at ${s}.
|
|
1101
1178
|
`:`
|
|
1102
|
-
`)),i}catch(n){let s=n instanceof Error?n.message:String(n);throw new Error(`${t}: unusable (${r}), and recovery into a fresh database also failed (${s}). Check that the containing directory is writable, or move the file aside manually and retry.`)}}function ef(t,e){let r;try{return r=bn({dbPath:t,allowSchemaSkew:e}),{dal:new ni(r)}}catch(n){if(n instanceof jt)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
|
|
1179
|
+
`)),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 ef(t,e){let r;try{return r=bn({dbPath:t,allowSchemaSkew:e}),{dal:new ni(r)}}catch(n){if(n instanceof jt)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 XS(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function qS(t){if(t===":memory:")return!0;try{return $S(`${t}${sf}`),!0}catch{return!1}}function GS(t){if(t!==":memory:")try{PS(`${t}${sf}`)}catch{}}function it(t){let e=t.allowSchemaSkew??process.env.LMCTL_ALLOW_SCHEMA_SKEW==="1",r={};for(let n=0;n<BS;n+=1)if(r=ef(t.path,e),r.dal!==void 0)return r.dal;if(r.dbVersion!==void 0&&r.dbVersion>xt){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${xt}) can no longer operate on it (${n}). Update lmctl: npm install -g @lmctl-ai/lmctl@latest`)}for(let n=0;n<WS;n+=1){if(qS(t.path))try{return Zm(t.path,r.cause)}finally{GS(t.path)}XS(HS);let s=ef(t.path,e);if(s.dal!==void 0)return s.dal}return Zm(t.path,r.cause)}function tf(t,e,r){let n=rf(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 rf(c.definition)},a=l=>{let c=i.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...i.slice(c),l].join(" -> ")}`);if(!s.has(l)){i.push(l);try{for(let u of o(l))a(u)}finally{i.pop()}s.add(l)}};a(t)}function rf(t){let e=JS(t),r=e===null?null:VS(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))si(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function JS(t){try{let e=JSON.parse(t);return si(e)?e:null}catch{return null}}function VS(t,e){let r=t[e];return si(r)?r:null}function si(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function KS(t){try{let e=JSON.parse(t);return!si(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 YS(t,e){return t===null?!0:t.holder_host===La()?!Ce(t.holder_pid):t.last_heartbeat<e}function zS(t){return{getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
1103
1180
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
1104
1181
|
VALUES (?, ?, ?, ?, ?)
|
|
1105
1182
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1506,59 +1583,59 @@ var HT=Object.create;var Go=Object.defineProperty;var XT=Object.getOwnPropertyDe
|
|
|
1506
1583
|
response = NULL
|
|
1507
1584
|
WHERE id = ?
|
|
1508
1585
|
AND status = 'running'
|
|
1509
|
-
`),...km(t),...bm(t)}}function JS(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var $S,sf,FS,PS,ni,Jt=k(()=>{"use strict";oa();Ws();Im();Am();Nm();gr();ti();Jm();zm();$S=3,sf=".recovery.lock",FS=20,PS=50;ni=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=GS(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let g=this.getJob(a.id);return{claimed:!1,reason:g?.locked_until!==null&&g?.locked_until!==void 0&&g.locked_until>=i?"locked":"not_claimable",job_id:r,status:g?.status??a.status,locked_by:g?.locked_by??a.locked_by,locked_until:g?.locked_until??a.locked_until}}let f=this.getJob(a.id);return f===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:f}}),this.resumeRunTxn=e.transaction((r,n,s)=>JS("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!==Ym)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Vm&&!a.includes(n))return{resumed:!1,reason:Km};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=Mm(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){tf(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,F()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,F());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){tf(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,F());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,F())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,F());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,F()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,r){return this.stmts.setTriggerCursor.run(r,F(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(F(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,F());return this.stmts.getTeam.get(r.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,F());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,F(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,F());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",F());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,F());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=F(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,F(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,F(),e)??null}closeIssue(e,r,n){let s=F(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,F(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,F(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=F();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Qm(),s=F();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=F(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,F())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??F(),e.dedupe_key??null,e.concurrency_key??null,F());if(r.changes===1)return this.stmts.getJob.get(r.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:F();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,F()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,r){return this.stmts.setJobRun.run(r,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,F()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??F(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,F());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=F(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,F(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(F(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return Aa(this.db,n,e),ei(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 Aa(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}`);ei(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{xa(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>ka(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??F(),n=e.holder_host??La(),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,Ye(e.command),r,e.holder_pid??null,n,s,Ye(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Wm(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(`
|
|
1586
|
+
`),...km(t),...bm(t)}}function QS(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var BS,sf,WS,HS,ni,Jt=k(()=>{"use strict";oa();Ws();Im();Am();Nm();gr();ti();Jm();zm();BS=3,sf=".recovery.lock",WS=20,HS=50;ni=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=zS(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!u)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let d=o(a);if(d.concurrency_key!==null&&(a.concurrency_key_resolved!==d.concurrency_key&&this.stmts.setJobConcurrencyKey.run(d.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(d.concurrency_key,i,a.id)?.count??0)>=Math.max(1,d.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let g=this.getJob(a.id);return{claimed:!1,reason:g?.locked_until!==null&&g?.locked_until!==void 0&&g.locked_until>=i?"locked":"not_claimable",job_id:r,status:g?.status??a.status,locked_by:g?.locked_by??a.locked_by,locked_until:g?.locked_until??a.locked_until}}let f=this.getJob(a.id);return f===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:f}}),this.resumeRunTxn=e.transaction((r,n,s)=>QS("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!==Ym)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let u=JSON.parse(i.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(o=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==Vm&&!a.includes(n))return{resumed:!1,reason:Km};let c={};if(l.pending_escalation_decision!==null)try{let u=JSON.parse(l.pending_escalation_decision);u!==null&&typeof u=="object"&&!Array.isArray(u)&&(c=u)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=this.getAgentInflight(r.receiver_teamfile,r.receiver_alias),i=n.reclaim_observed,o=this.stmts.acquireAgentInflight.get({...r,holder_pid:process.pid,stale_before:n.stale_before??null,force:n.force===!0?1:0,reclaim_observed_sender_teamfile:i?.sender_teamfile??null,reclaim_observed_sender_alias:i?.sender_alias??null,reclaim_observed_started_at:i?.started_at??null,reclaim_observed_holder_pid:typeof i?.holder_pid=="number"?i.holder_pid:null}),a;if(o!==void 0){let l=s===null?null:n.reclaim_reason??(n.force===!0?"force":n.reclaim_observed!==void 0?"dead-pid":"stale"),c=Mm(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){tf(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,F()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,F());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){tf(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,F());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,F())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,F());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,F()),this.stmts.getTriggerInstanceByWorkflowAndId.get(e.workflow_id,e.trigger_id)}listTriggerInstancesForWorkflow(e){return this.stmts.listTriggerInstancesForWorkflow.all(e)}listEnabledTriggerInstances(){return this.stmts.listEnabledTriggerInstances.all()}setTriggerCursor(e,r){return this.stmts.setTriggerCursor.run(r,F(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(F(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,F());return this.stmts.getTeam.get(r.lastInsertRowid)}getTeam(e){return this.stmts.getTeam.get(e)??null}findTeamByName(e){return this.stmts.findTeamByName.get(e)??null}listTeams(){return this.stmts.listTeams.all()}insertTeamMember(e){let r=this.stmts.insertTeamMember.run(e.team_id,e.alias,e.role??"agent",e.provider,e.model??null,e.sessionid??null,e.sessiondir,F());return this.stmts.getTeamMember.get(r.lastInsertRowid)}listTeamMembers(e){return this.stmts.listTeamMembers.all(e)}findTeamMemberByAlias(e,r){return this.stmts.findTeamMemberByAlias.get(e,r)??null}updateTeamMemberSession(e,r){return this.stmts.updateTeamMemberSession.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberState(e,r,n){return this.stmts.setMemberState.run(r,n??null,F(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,F());return this.stmts.getTeamMemberCompanion.get(r.lastInsertRowid)}insertProject(e){let r=this.stmts.insertProject.run(e.name,e.description??null,e.local_path,e.workflow_name,e.team_id,e.default_branch??null,e.intake_config??null,e.test_argv??null,e.test_command??null,e.durable_memory_mode??"folder",F());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,F());return s.changes===1?this.stmts.getProjectWorkflow.get(s.lastInsertRowid):this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r)}getProjectWorkflow(e){return this.stmts.getProjectWorkflow.get(e)??null}listProjectWorkflows(e,r={}){return r.enabled_only===!0?this.stmts.listEnabledProjectWorkflows.all(e):this.stmts.listProjectWorkflows.all(e)}removeProjectWorkflow(e){return this.stmts.removeProjectWorkflow.run(e).changes>0}setProjectWorkflowEnabled(e,r){return this.stmts.setProjectWorkflowEnabled.run(r?1:0,e),this.getProjectWorkflow(e)}createIssue(e){let r=F(),n=this.stmts.createIssue.run(e.project_id,e.title,e.body,e.severity??"medium",e.labels??null,e.ai_test_path??null,e.source_run_id??null,r,r);return this.stmts.getIssue.get(n.lastInsertRowid)}getIssue(e){return this.stmts.getIssue.get(e)??null}listIssues(e,r={}){return this.stmts.listIssuesForProject.all(e).filter(n=>!(r.status!==void 0&&!r.status.includes(n.status)||r.severity!==void 0&&!r.severity.includes(n.severity)||r.ai_test_path!==void 0&&n.ai_test_path!==r.ai_test_path))}claimNextIssue(e,r){return this.stmts.claimNextIssue.get(r,F(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,F(),e)??null}closeIssue(e,r,n){let s=F(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,F(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,F(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=F();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}setWebuiSessionChatbot(e,r){if(this.stmts.setWebuiSessionChatbot.run(r,F(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=Qm(),s=F();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=F(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,F())}getConfigAll(){let e=this.stmts.listConfig.all(),r={};for(let n of e)r[n.key]=n.value;return r}enqueueJob(e){let r=this.stmts.insertJob.run(e.project_id,e.workflow_id_override??null,e.source,e.source_ref??null,e.payload??null,e.priority??0,e.available_at??F(),e.dedupe_key??null,e.concurrency_key??null,F());if(r.changes===1)return this.stmts.getJob.get(r.lastInsertRowid);if(e.dedupe_key===void 0||e.dedupe_key===null)throw new Error("job insert ignored without dedupe key");return this.stmts.findJobByDedupe.get(e.source,e.dedupe_key)}claimNextJob(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=F(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimByIdWithConcurrencyTxn(e.job_id,e.worker_id,n,r,e.evaluator)}releaseJob(e,r,n){let s=r==="queued"||r==="running"?null:F();return this.stmts.releaseJob.run(r,n??null,s,e),this.getJob(e)}getJob(e){return this.stmts.getJob.get(e)??null}findJobBySourceAndDedupe(e,r){return this.stmts.findJobByDedupe.get(e,r)??null}insertRun(e){let r=this.getWorkflow(e.workflow_id);if(r===null)throw new Error(`workflow not found: ${e.workflow_id}`);let n=this.stmts.insertRun.run(e.job_id,e.workflow_id,e.team_id,e.current_state??null,r.active_version_id,e.parent_run_id??null,F()),s=this.stmts.getRun.get(n.lastInsertRowid);return(e.parent_run_id===void 0||e.parent_run_id===null)&&this.stmts.setJobRun.run(s.id,e.job_id),s}setJobRun(e,r){return this.stmts.setJobRun.run(r,e),this.getJob(e)}insertPromptDispatch(e){return this.stmts.insertPromptDispatch.run(e.prompt_id,e.project_id,e.job_id,e.text,e.context_json??null,F()),this.stmts.getPromptDispatch.get(e.prompt_id)}getPromptDispatch(e){return this.stmts.getPromptDispatch.get(e)??null}setPromptDispatchCompleted(e,r){return this.stmts.setPromptDispatchCompleted.run(r??F(),e),this.getPromptDispatch(e)}getWorkspace(e){return this.stmts.getWorkspace.get(e)??null}ensureWorkspace(e={}){let r=e.id??"default";this.stmts.ensureWorkspace.run(r,e.name??"Default workspace",e.idleThresholdMs??6e5,F());let n=this.getWorkspace(r);if(n===null)throw new Error(`workspace ${r} missing after upsert`);return n}listWebProjectsActive(e){return this.stmts.listWebProjectsActive.all(e)}getWebProject(e){return this.stmts.getWebProject.get(e)??null}insertWebProject(e){let r=F(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,F(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(F(),e).changes===1}loadMailboxCursor(e,r){return this.stmts.loadMailboxCursor.get(e,r)??null}saveMailboxCursor(e){this.stmts.saveMailboxCursor.run(e.user_id,e.mailbox_key,e.last_processed_version_id,e.last_processed_seq??null,e.last_processed_at)}addUsage(e){this.stmts.addUsage.run(e.user_id,e.device_id,e.period,e.put,e.get,e.list,e.updated_at)}loadUsage(e,r,n){return this.stmts.loadUsage.get(e,r,n)??null}sumUsageForPeriod(e,r){let n=this.stmts.sumUsageForPeriod.get(e,r);return{put:n?.put??0,get:n?.get??0,list:n?.list??0}}upsertRootTeam(e){this.stmts.upsertRootTeam.run(e.teamfile_path,e.name,e.raw_text,e.raw_sha256,e.registered_at,e.last_seeded_at)}getRootTeam(e){return this.stmts.getRootTeam.get(e)??null}listRootTeams(){return this.stmts.listRootTeams.all()}insertTeamChatLog(e){return this.db.transaction(()=>{let r=this.stmts.insertTeamChatLog.run(e.root_teamfile,e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias,e.message,e.response,e.origin,e.status,e.error_detail,e.truncated,e.message_type??null,e.created_at),n=Number(r.lastInsertRowid);return Aa(this.db,n,e),ei(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 Aa(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}`);ei(this.db,e,r)})()}setCurrentlyHandlingMessage(e,r,n){this.db.transaction(()=>{xa(this.db,e,r,n)})()}clearCurrentlyHandlingMessage(e,r,n){return this.db.transaction(()=>ka(this.db,e,r,n))()}listTeamChatLog(e){return this.stmts.listTeamChatLog.all(e)}listTeamChatLogSinceId(e,r=500){return this.stmts.listTeamChatLogSinceId.all(e,Math.max(1,Math.trunc(r)))}getMaxTeamChatLogId(){return this.stmts.getMaxTeamChatLogId.get()?.max_id??0}loadTeamChatLogCursor(e){return this.stmts.loadTeamChatLogCursor.get(e)??null}saveTeamChatLogCursor(e){this.stmts.saveTeamChatLogCursor.run(e.cursor_key,e.last_pushed_id,e.updated_at)}startTrackedInvocation(e){return this.db.transaction(()=>this.startTrackedInvocationInner(e))()}startTrackedInvocationInner(e){let r=e.started_at??F(),n=e.holder_host??La(),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,Ye(e.command),r,e.holder_pid??null,n,s,Ye(e.meta),e.launch_source??e.kind,e.request_payload??null,e.parent_invocation_id??null),o=this.getTrackedInvocation(Number(i.lastInsertRowid));return Wm(this.db,o),o}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listTrackedInvocationsForTarget(e,r,n={}){let s=["target_teamfile = ?","target_alias = ?"],i=[e,r];n.sinceMs!==void 0&&(s.push("started_at >= ?"),i.push(new Date(n.sinceMs).toISOString())),n.untilMs!==void 0&&(s.push("started_at <= ?"),i.push(new Date(n.untilMs).toISOString()));let o=Math.max(1,Math.trunc(n.limit??200));return this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${s.join(" AND ")} ORDER BY started_at DESC LIMIT ?`).all(...i,o)}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}listRecentlyFinishedTrackedInvocations(e){return this.stmts.listRecentlyFinishedTrackedInvocations.all(e)}listFinishedTrackedInvocationChildren(e,r){if(e.length===0)return[];let n=e.map(()=>"?").join(", ");return this.db.prepare(`
|
|
1510
1587
|
SELECT * FROM tracked_invocation
|
|
1511
1588
|
WHERE parent_invocation_id IN (${n})
|
|
1512
1589
|
AND ended_at IS NOT NULL
|
|
1513
1590
|
AND ended_at >= ?
|
|
1514
1591
|
ORDER BY started_at ASC, id ASC
|
|
1515
1592
|
`).all(...e,r)}finishTrackedInvocation(e,r){return this.db.transaction(()=>{let n=r.ended_at??F();if(this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Ye(r.result_summary),Ye(r.error),r.team_chat_log_id??null,Ye(r.meta),Ye(r.config_warnings),n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return ri(this.db,i),i})()}reclaimTrackedInvocationIfUnchanged(e,r,n){return this.db.transaction(()=>{let s=n.ended_at??F();if(this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Ye(n.result_summary),Ye(n.error),n.team_chat_log_id??null,Ye(n.meta),Ye(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 ri(this.db,o),o})()}heartbeatTrackedInvocation(e,r=F()){return this.db.transaction(()=>{if(this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1)return null;let s=this.getTrackedInvocation(e);return Xm(this.db,s,r),s})()}updateTrackedInvocationRequestPayload(e,r){return this.db.transaction(()=>this.stmts.updateTrackedInvocationRequestPayload.run(r,e).changes!==1?null:(qm(this.db,e,r),this.getTrackedInvocation(e)))()}linkTrackedInvocationMessage(e,r){return this.db.transaction(()=>this.stmts.linkTrackedInvocationChatLog.run(r,e).changes!==1?null:(Gm(this.db,e,Rt(r)),this.getTrackedInvocation(e)))()}abortTrackedInvocationAndTerminalizeMessage(e,r,n){return this.db.transaction(()=>{let s=F();if(this.stmts.abortTrackedInvocationIfUnchanged.run(s,Ye(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 ri(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||ei(this.db,e,{root_teamfile:n.root_teamfile,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,message:n.message,response:null,origin:n.origin,status:"error",error_detail:r,truncated:n.truncated,created_at:F()})}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled', 'aborted')","ended_at IS NOT NULL","notified_by IS NULL"],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));return n.push(s),this.db.prepare(`SELECT * FROM tracked_invocation WHERE ${r.join(" AND ")} ORDER BY ended_at ASC, id ASC LIMIT ?`).all(...n)}claimTrackedInvocationNotification(e,r,n=F()){return this.db.transaction(()=>{if(this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1)return null;let i=this.getTrackedInvocation(e);return Hm(this.db,i,r,n),i})()}listTrackedInvocations(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile)),e.status!==void 0&&(r.push("status = ?"),n.push(e.status)),e.kind!==void 0&&(r.push("kind = ?"),n.push(e.kind)),e.origin!==void 0&&(r.push("origin = ?"),n.push(e.origin));let s=Math.max(1,Math.min(1e3,Math.trunc(e.limit??100)));n.push(s);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}updateTeamChatLogResponse(e,r){this.stmts.updateTeamChatLogResponse.run(r.response,r.status,r.error_detail,r.truncated,e)}getAgentInflight(e,r){return this.stmts.getAgentInflight.get(e,r)??null}listAgentInflight(){return this.stmts.listAgentInflight.all()}tryAcquireAgentInflight(e,r){return this.tryAcquireAgentInflightTxn(e,r)}heartbeatAgentInflight(e,r,n=F()){return this.db.transaction(()=>{let s=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);return s===null||s.sender_teamfile!==e.sender_teamfile||s.sender_alias!==e.sender_alias||s.started_at!==e.started_at?!1:$m(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&&Nn(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&&Nn(this.db,i,"INFLIGHT_RELEASE"),o.changes===1})()}releaseAgentInflight(e,r){this.db.exec("BEGIN IMMEDIATE");try{let n=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(n===null||n.sender_teamfile!==e.sender_teamfile||n.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r!==void 0&&this.db.prepare(`SELECT lease_id FROM agent_state
|
|
1516
|
-
WHERE receiver_teamfile = ? AND receiver_alias = ?`).get(e.receiver_teamfile,e.receiver_alias)?.lease_id!==r)return this.db.exec("COMMIT"),!1;if(n.active_count<=1){let i=this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return i.changes===1&&Nn(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&&(Nn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(kn,Rn(e,r),An);return n===void 0?null:Rm(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Ra(this.db,n,!0),this.stmts.upsertRuntimeState.run(kn,Rn(e.teamfile,e.alias),An,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Fm(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(kn,Rn(e,r),An,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(kn,Rn(e,r),An);return i.changes===1&&Ra(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:XS(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=F()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!qS(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Qm(),holder_pid:process.pid,holder_host:La(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,F(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,F())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,F());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,F(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??F(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,F());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,F()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,F()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,F());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(F(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=F();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??F());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,F())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,F())}}});var gt=VT(Pe=>{"use strict";function ii(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 VS(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function Vt(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 of(t,e,r){let n=" ".repeat(Math.max(0,e-Vt(t)));return r?n+t:t+n}function KS(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 YS(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 zS(t,e,r="\u2026"){if(Vt(t)<=e)return t;let n=Vt(r)>e?"\u2026":r,s=Vt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=Vt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function QS(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 lf(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=QS(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=KS(i);o.headers!==void 0&&ii(o.headers).forEach((a,l)=>{s(l,Vt(a))});for(let a of o.rows.map(ii))a.forEach((l,c)=>{s(c,Vt(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}Pe.measureColumns=lf;function ZS(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 cf(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=ZS(o),u=VS(n),d=YS(l),m=e??lf([{rows:t,headers:r}],{max:a}),f=t.map(ii);r!==void 0&&f.unshift(ii(r));let g=f.map(y=>{let h=y.length-1;for(;h>=0&&y[h]==="";)h--;return y.slice(0,h+1).map((p,_)=>{let T=m[_]||0,E=s&&T>0&&(_!==h||i)?zS(p,T,d):p;return u[_]==="right"?of(E,T,!0):_===h?E:of(E,T,!1)}).join(" ")}).join(`
|
|
1593
|
+
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&&Nn(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&&(Nn(this.db,i,"INFLIGHT_RECLAIM","stale"),s+=1);return s})()}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(kn,Rn(e,r),An);return n===void 0?null:Rm(n.data)}setTerminalLock(e){this.db.transaction(()=>{let n=this.getTerminalLock(e.teamfile,e.alias);n!==null&&n.lock_id!==e.lock_id&&Ra(this.db,n,!0),this.stmts.upsertRuntimeState.run(kn,Rn(e.teamfile,e.alias),An,JSON.stringify(e),e.last_heartbeat),n?.lock_id!==e.lock_id&&Fm(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(kn,Rn(e,r),An,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(kn,Rn(e,r),An);return i.changes===1&&Ra(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:KS(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=F()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!YS(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:Qm(),holder_pid:process.pid,holder_host:La(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,F(),e),this.stmts.getRun.get(e)??null}pauseJob(e){return this.stmts.pauseJob.run(e),this.getJob(e)}resumeRun(e,r){return this.resumeRunTxn(e,r,F())}insertStep(e){let r=this.stmts.insertStep.run(e.run_id,e.parent_step_id??null,e.state_name,e.outcome??null,e.status_detail??null,F());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,F(),e),this.stmts.getStep.get(e)??null}listStepsForRun(e){return this.stmts.listStepsForRun.all(e)}listLatestStepOutcomesByState(e){let r=this.stmts.listLatestStepOutcomesByState.all(e),n={};for(let s of r)n[s.state_name]=s.outcome;return n}insertSubmittedPr(e){let r=this.stmts.insertSubmittedPr.run(e.repo,e.pr_url,e.issue_url??null,e.local_path??null,e.branch??null,e.head_sha??null,e.status??"watching",e.submitted_at??F(),e.last_known_state??null,e.created_by_run_id??null);return this.stmts.getSubmittedPr.get(r.lastInsertRowid)}listSubmittedPrs(e){return e?.status!==void 0?this.stmts.listSubmittedPrsByStatus.all(e.status):this.stmts.listSubmittedPrs.all()}getSubmittedPr(e){return this.stmts.getSubmittedPr.get(e)??null}findSubmittedPrByUrl(e){return this.stmts.findSubmittedPrByUrl.get(e)??null}insertStepArtifact(e){let r=this.stmts.insertStepArtifact.run(e.step_id,e.kind,e.path??null,e.content??null,e.sha??null,e.provider_call_mode??null,F());return this.stmts.getStepArtifact.get(r.lastInsertRowid)}insertExternalObject(e){let n=this.stmts.insertExternalObject.run(e.type,e.provider,e.project_id,e.run_id??null,e.external_id,e.url??null,e.status??null,e.metadata??null,e.last_seen_at??null,F()).changes===1;return{row:this.stmts.findExternalObjectByUnique.get(e.provider,e.type,e.external_id),inserted:n}}insertExternalSignal(e){let r=this.stmts.insertExternalSignal.run(e.object_id,e.kind,e.source??null,e.occurred_at??null,e.payload??null,e.signal_hash??null,null,F()),n=r.changes===1;return{row:e.signal_hash===void 0||e.signal_hash===null?this.stmts.getExternalSignal.get(r.lastInsertRowid):this.stmts.findExternalSignalByUnique.get(e.object_id,e.kind,e.signal_hash),inserted:n}}raiseAttention(e){let r=this.stmts.insertAttention.run(e.kind,e.severity??"warn",e.project_id??null,e.run_id??null,e.external_object_id??null,e.requires_user===!0?1:0,e.payload??null,F());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(F(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=F();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??F());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,F())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,F())}}});var gt=ZT(Pe=>{"use strict";function ii(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 ZS(t){if(t===void 0)return[];if(!Array.isArray(t))throw new TypeError('align must be an array of "left" or "right" per column');return t.map(e=>{if(e!=="left"&&e!=="right")throw new TypeError('align entries must be "left" or "right"');return e})}function Vt(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 of(t,e,r){let n=" ".repeat(Math.max(0,e-Vt(t)));return r?n+t:t+n}function eb(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 tb(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 rb(t,e,r="\u2026"){if(Vt(t)<=e)return t;let n=Vt(r)>e?"\u2026":r,s=Vt(n);if(e<=s)return n;let i="",o=0;for(let a of t){let l=Vt(a);if(o+l>e-s)break;i+=a,o+=l}return`${i}${n}`}function nb(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 lf(t,{max:e}={}){if(!Array.isArray(t))throw new TypeError("grids must be an array of grids");let r=nb(e),n=[],s=(i,o)=>{n[i]=Math.max(n[i]??0,o)};for(let i of t){let o=eb(i);o.headers!==void 0&&ii(o.headers).forEach((a,l)=>{s(l,Vt(a))});for(let a of o.rows.map(ii))a.forEach((l,c)=>{s(c,Vt(l))})}return n.map((i,o)=>{let a=r[o];return a===void 0?i:Math.min(i,a)})}Pe.measureColumns=lf;function sb(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 cf(t,{widths:e,headers:r,align:n,truncate:s=!0,truncateTrailing:i=!1,margin:o,max:a,ellipsis:l}={}){if(!Array.isArray(t))throw new TypeError("rows must be an array of row arrays");if(e!==void 0&&!Array.isArray(e))throw new TypeError("widths must be an array of column widths");if(e!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let c=sb(o),u=ZS(n),d=tb(l),m=e??lf([{rows:t,headers:r}],{max:a}),f=t.map(ii);r!==void 0&&f.unshift(ii(r));let g=f.map(y=>{let h=y.length-1;for(;h>=0&&y[h]==="";)h--;return y.slice(0,h+1).map((p,_)=>{let T=m[_]||0,E=s&&T>0&&(_!==h||i)?rb(p,T,d):p;return u[_]==="right"?of(E,T,!0):_===h?E:of(E,T,!1)}).join(" ")}).join(`
|
|
1517
1594
|
`);return g===""||c===""?g:`${c}${g.split(`
|
|
1518
1595
|
`).join(`
|
|
1519
|
-
${c}`)}`}Pe.renderGrid=cf;function df(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return cf(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function
|
|
1520
|
-
`)}Pe.formatTable=df;Pe.printTable=
|
|
1521
|
-
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}Pe.escapeCell=
|
|
1596
|
+
${c}`)}`}Pe.renderGrid=cf;function df(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a}={}){return cf(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a})}function ib(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a,stream:l=process.stdout}={}){let c=df(t,{headers:e,align:r,truncate:n,truncateTrailing:s,margin:i,max:o,ellipsis:a});c&&l.write(`${c}
|
|
1597
|
+
`)}Pe.formatTable=df;Pe.printTable=ib;function af(t){return t instanceof Date?t.getTime():typeof t=="number"?t:typeof t=="string"&&t.trim()?Date.parse(t):NaN}function ob(t,{now:e=Date.now()}={}){let r=af(e);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=af(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":""}`}Pe.formatRelativeTime=ob;function ab(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`}Pe.formatCount=ab;var Oa=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function lb(t,{maxUnit:e="w",style:r="spaced"}={}){if(typeof t!="number"||!Number.isFinite(t))return"unknown";let n=Oa.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=Oa.slice(n).filter(([d])=>d!=="s");if(a.length===0||s<60)return"<1m";let l=[],c=s,u=!1;for(let[d,m]of a){let f=Math.floor(c/m);if(c-=f*m,f>0&&!u){let g=d==="d"||d==="w"?`${f}${d}`:`${ht(f)}${d}`;l.push({text:g,zero:!1}),u=!0}else u&&l.push({text:`${ht(f)}${d}`,zero:f===0})}for(;l.length>0&&l[l.length-1].zero;)l.pop();return l.map(d=>d.text).join("")}let i=s,o=[];for(let[a,l]of Oa.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(" ")}Pe.formatDuration=lb;function uf(t){return t===void 0?new Date:t instanceof Date?t:typeof t=="number"||typeof t=="string"?new Date(t):new Date(NaN)}function ht(t){return String(t).padStart(2,"0")}function mf(t){let e=uf(t);return Number.isNaN(e.getTime())?"unknown":`${ht(e.getHours())}:${ht(e.getMinutes())}:${ht(e.getSeconds())}`}Pe.formatClock=mf;function cb(t){let e=uf(t);return Number.isNaN(e.getTime())?"unknown":`${`${e.getFullYear()}-${ht(e.getMonth()+1)}-${ht(e.getDate())}`} ${mf(e)}`}Pe.formatLocalTimestamp=cb;function db(t){return typeof t=="number"&&Number.isFinite(t)?`${Math.round(t*100)}%`:"?%"}Pe.formatPercent=db;function ub(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)||Vt(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)}`}Pe.formatBar=ub;function mb(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=`${ht(n)}:${ht(s)}:${ht(e)}`;return r>0?`${r}d ${i}`:i}Pe.formatTimer=mb;function fb(t){return(t==null?"":String(t)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
|
|
1598
|
+
`?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}Pe.escapeCell=fb});async function C(t,e){if(t.dal!==void 0)return e(t.dal);let r=it({path:pe()});try{return await e(r)}finally{r.close()}}function ae(t,e,r=["--json"]){let n=new Set(e),s=new Set(r),i=[],o={};for(let a=0;a<t.length;a+=1){let l=t[a];if(!l.startsWith("--")){i.push(l);continue}if(s.has(l)){o[l]=!0;continue}if(!n.has(l))return{positionals:i,flags:o,error:`unknown flag: ${l}`};let c=t[a+1];if(c===void 0||c.startsWith("--"))return{positionals:i,flags:o,error:`missing value for ${l}`};o[l]=c,a+=1}return{positionals:i,flags:o}}function W(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function X(t,e){return t.flags[e]===!0}function se(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1522
1599
|
`)}function A(t,e){return t.stderr.write(`error: ${e}
|
|
1523
1600
|
`),1}function Ue(){return(0,pf.formatClock)()}function ot(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 ze(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1524
1601
|
`),2}function Kt(t){if(t===void 0)return null;let e=Number.parseInt(t,10);return Number.isInteger(e)&&e>0?e:null}function oi(t){if(t.stdout!==process.stdout||ff)return;ff=!0;let e=r=>{throw r.code==="EPIPE"&&process.exit(0),process.stdout.off("error",e),r};process.stdout.on("error",e)}var pf,ff,ge=k(()=>{"use strict";Jt();pf=It(gt(),1);ct();ff=!1});function Da(t,e){if(qt(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 Yr(t,e,r){let n=t.query(`SELECT id, status, holder_pid, holder_host, started_at, last_heartbeat_at
|
|
1525
1602
|
FROM tracked_invocation
|
|
1526
1603
|
WHERE target_teamfile = ?
|
|
1527
1604
|
AND target_alias = ?
|
|
1528
|
-
AND status = 'running'`,e,r),s=0;for(let i of n)Da(t,i)!==null&&(s+=1);return s}var Ln=k(()=>{"use strict";We();Jt();st()});import{realpathSync as
|
|
1529
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function j(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Qe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var H,xe=k(()=>{"use strict";H=
|
|
1530
|
-
`):"";E&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(E.trimStart())&&!E.trimStart().startsWith("lmctl seed initial connection only.")&&y.push(E)}if(typeof T=="string"){let E=T.trim();if(E.includes("<command-name>")||E.includes("<local-command-")||/^<task-notification>\s*</u.test(E)||E.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(E))continue;u||(u=j(T.trim(),80)),d=j(T.trim(),80),g=void 0,s.push({role:"user",timestamp:_,content:ee(T.trim())})}else if(Array.isArray(T)){for(let E of T)if(E.type==="tool_result"){let S=typeof E.content=="string"?ee(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:_,content:S,toolCallId:E.tool_use_id})}}}if(p.type==="assistant"&&p.message){p.message.stop_reason===null||p.message.stop_reason==="tool_use"?g="in_progress":typeof p.message.stop_reason=="string"&&(g="complete"),p.message.model&&(l=p.message.model);let _=new Date(p.timestamp||0),T=p.message.content;if(Array.isArray(T))for(let E of T)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:_,content:ee(E.text),model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:_,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolInputData:E.input,toolCallId:E.id,model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:_,content:E.thinking})}}if(!i)return null;
|
|
1531
|
-
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=bf(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=bf(i.max);m!==null&&(d.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=d):r.global=d}i={}}for(let d of n){let m=d.trim();if(!m||m.startsWith("#"))continue;let f=
|
|
1532
|
-
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let u=Dn(o).trim(),d=Dn(i).trim();n({success:!1,error:(u||d).slice(0,500)||(c?`terminated by ${c}`:`exit code ${l}`)})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:di,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&&xf(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,r,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:g=>{a+=g,c(),n.onDelta?.(g)},onProgress:g=>{g.kind!=="api_retry"&&c(),n.onProgress?.(g)}},m=this.transportFn(r,d).then(g=>(u(),{...g,status:g.status??"ok"})).catch(g=>{throw u(),o==="external"?new ja("Turn cancelled","external"):g}),f=new Promise(g=>{l=g});return Promise.race([m,f])}runOneShotAgent(e,r,n){let s=kf(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=Af(r.env),c=Lf(s,{shell:!0,cwd:r.cwd,env:we(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m=setTimeout(()=>{d=!0,c.kill()},l),f="",g="";if(c.stdout?.on("data",y=>{let h=y.toString();f+=h,r.onDelta?.(h)}),c.stderr?.on("data",y=>{g+=y.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(m),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",y=>{if(u)return;u=!0,clearTimeout(m);let h=Date.now()-i;d?a(new Error(`Agent command timed out after ${l}ms`)):y===0||y===null?o({text:f.trim(),sessionId:r.sessionId,durationMs:h}):a(new Error(g.trim().slice(0,200)||`Agent command exited with code ${y}`))}),c.on("error",y=>{u||(u=!0,clearTimeout(m),a(y))})})}}});function Fn(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new $n(t,r,e)}var zt,re,Mn,ui,$n,yr=k(()=>{"use strict";zt=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},re=class extends zt{},Mn=class extends zt{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},ui=class extends zt{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},$n=class extends zt{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as Wa from"node:child_process";function
|
|
1605
|
+
AND status = 'running'`,e,r),s=0;for(let i of n)Da(t,i)!==null&&(s+=1);return s}var Ln=k(()=>{"use strict";We();Jt();st()});import{realpathSync as pb}from"node:fs";import{resolve as hb}from"node:path";function Ma(t){let e=hb(t);try{return pb(e)}catch{return e}}var hf=k(()=>{"use strict"});import{platform as gf}from"node:os";function Yt(t){let e=new Cn;for(let r of t)e.registerAdapter(r);return e}var Cn,$a=k(()=>{"use strict";hf();Cn=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=Ma(e.workspace);i=i.filter(a=>Ma(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=gf()==="darwin"||gf()==="win32",r=[];for(let n of this.providers)if(typeof n.getWatchPaths=="function")for(let s of n.getWatchPaths())r.push({provider:n.name,directory:s.directory,recursive:e,filePattern:s.filePattern});return r}async deleteSession(e,r){let n=await this.resolveSession(e,r);return n?n.provider.deleteSession(e):!1}registerAdapter(e){this.adapters.set(e.name,e),this.providers.push({name:e.name,discoverSessions:()=>e.discover(),loadSession:r=>e.load(r),resolveSessionPath:r=>e.resolvePath(r),deleteSession:r=>e.delete(r),getWatchPaths:()=>e.getWatchPaths?.()??[]})}getAdapter(e){return this.adapters.get(e)}getAllAdapters(){return[...this.adapters.values()]}}});import{createReadStream as _f}from"node:fs";import{createInterface as yf}from"node:readline";import{stat as gb}from"node:fs/promises";import{homedir as _b}from"node:os";function Ef(t){try{let e=JSON.parse(t);return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}async function*ce(t){let e=_f(t,{encoding:"utf-8"}),r=yf({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(!s)continue;let i=Ef(s);i!==void 0&&(yield i)}}finally{e.destroy()}}async function He(t,e){let r=[],n=_f(t,{encoding:"utf-8"}),s=yf({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(!o)continue;let a=Ef(o);if(a!==void 0&&r.push(a),r.length>=e)break}}finally{s.close(),n.destroy()}return r}async function de(t){let e=await gb(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function ee(t){return t.replace(/\\n/g,`
|
|
1606
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function j(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Qe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}var H,xe=k(()=>{"use strict";H=_b()});import{readdir as ai,stat as Tf,unlink as yb}from"node:fs/promises";import{join as zr,basename as wf}from"node:path";function Eb(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function Tb(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return ee(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 vf(t){let e=0,r=0,n=0,s=0,i=0,o=0,a,l;for await(let c of ce(t))if(!c.isSidechain){if(c.type==="user"&&!c.isMeta&&c.message){let u=c.message.content;if(typeof u=="string"){if(u.includes("<command-name>")||u.includes("<local-command-"))continue;e++,l=j(u.trim(),80)}}else if(c.type==="assistant"&&c.message){let u=c.message.content;if(Array.isArray(u))for(let m of u)m.type==="text"&&e++;let d=c.message.usage;if(d){let m=d.input_tokens||0,f=d.cache_creation_input_tokens||0,g=d.cache_read_input_tokens||0,y=d.output_tokens||0;r+=m+f+g,n+=g,s+=f,i+=y;let h=m+f+g;h&&(o=h),a={inputTokens:m,cacheWriteInputTokens:f,cachedInputTokens:g,outputTokens:y}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a,lastUserMessage:l}}function wb(t){let e=vb(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 vb(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 li,Sf=k(()=>{"use strict";xe();li=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||zr(H,".claude"),this.projectsDir=zr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await ai(this.projectsDir)}catch{return e}for(let n of r){let s=zr(this.projectsDir,n);if(!(await Tf(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await ai(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=wf(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=zr(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,r){let n=await He(e,50),s=await de(e),i="",o,a,l,c,u,d;for(let f of n)if(!Eb(f.type)&&(!i&&f.cwd&&(i=f.cwd),!o&&f.slug&&(o=f.slug),!a&&f.version&&(a=f.version),!d&&f.timestamp&&(d=new Date(f.timestamp)),f.type==="assistant"&&f.message?.model&&(l=f.message.model),f.type==="user"&&!f.isMeta&&f.message)){let g=f.message.content;if(typeof g=="string"){if(g.includes("<command-name>")||g.includes("<local-command-"))continue;c||(c=j(g.trim(),80)),u=j(g.trim(),80)}}if(!i)return null;let m=await vf(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:m.lastUserMessage??u,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:m.totalCacheWriteInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await de(r),s=[],i="",o,a,l,c,u,d,m,f=e,g,y=[];for await(let p of ce(r))if(p.type!=="file-history-snapshot"&&!p.isSidechain){if(!i&&p.cwd&&(i=p.cwd),!o&&p.slug&&(o=p.slug),!a&&p.version&&(a=p.version),!c&&p.gitBranch&&(c=p.gitBranch),!m&&p.timestamp&&(m=new Date(p.timestamp)),p.sessionId&&(f=p.sessionId),p.type==="system"||p.type==="progress"||p.type==="queue-operation"){s.push({role:"system",timestamp:new Date(p.timestamp||0),content:Tb(p)});continue}if(p.type==="user"&&p.message){if(p.isMeta)continue;let _=new Date(p.timestamp||0),T=p.message.content;if(p.isCompactSummary!==!0&&p.isVisibleInTranscriptOnly!==!0&&p.promptSource!=="system"&&p.toolUseResult===void 0&&p.origin?.kind!=="task-notification"&&p.interruptedMessageId===void 0&&p.interruptedByShutdown!==!0&&p.scheduledTaskId===void 0&&p.scheduledFireId===void 0&&!(Array.isArray(T)&&T.some(E=>E.type==="tool_result"))){let E=typeof T=="string"?T:Array.isArray(T)?T.filter(S=>S.type==="text"&&typeof S.text=="string").map(S=>S.text).join(`
|
|
1607
|
+
`):"";E&&!/^<(?:command-name>|local-command-|task-notification>\s*<|system-reminder>)/u.test(E.trimStart())&&!E.trimStart().startsWith("lmctl seed initial connection only.")&&y.push(E)}if(typeof T=="string"){let E=T.trim();if(E.includes("<command-name>")||E.includes("<local-command-")||/^<task-notification>\s*</u.test(E)||E.startsWith("lmctl seed initial connection only.")||/^<system-reminder>[\s\S]*<\/system-reminder>$/u.test(E))continue;u||(u=j(T.trim(),80)),d=j(T.trim(),80),g=void 0,s.push({role:"user",timestamp:_,content:ee(T.trim())})}else if(Array.isArray(T)){for(let E of T)if(E.type==="tool_result"){let S=typeof E.content=="string"?ee(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:_,content:S,toolCallId:E.tool_use_id})}}}if(p.type==="assistant"&&p.message){p.message.stop_reason===null||p.message.stop_reason==="tool_use"?g="in_progress":typeof p.message.stop_reason=="string"&&(g="complete"),p.message.model&&(l=p.message.model);let _=new Date(p.timestamp||0),T=p.message.content;if(Array.isArray(T))for(let E of T)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:_,content:ee(E.text),model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:_,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolInputData:E.input,toolCallId:E.id,model:p.message.model,...typeof p.message.stop_reason=="string"?{stopReason:p.message.stop_reason}:{}}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:_,content:E.thinking})}}if(!i)return null;wb(s);let h=await vf(r);return{provider:"claude",sessionId:f,slug:o,cwd:i,createdAt:m||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,turnStatus:g,firstUserMessage:u,lastUserMessage:d,messageCount:h.messageCount,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:h.totalCacheWriteInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:s,userPrompts:y}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await yb(r),!0):!1}async resolveSessionFile(e){let r;try{r=await ai(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=zr(this.projectsDir,o);if(!(await Tf(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await ai(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=wf(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:zr(a,u),fileSessionId:d})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await He(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});import{readFileSync as Sb,writeFileSync as dF,mkdirSync as uF}from"node:fs";import{join as bb,dirname as fF}from"node:path";import{homedir as Ib}from"node:os";function kb(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ab(t){let e=t.indexOf("=");if(e===-1)return null;let r=t.slice(0,e).trim(),n=kb(t.slice(e+1).trim());return r?{key:r,value:n}:null}function Rb(t){let e=t.trim();return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1).trim():null}function ci(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function Nb(){return bb(Ib(),".lmctl","config.toml")}function Qr(t){let e=t??Nb(),r;try{r=Sb(e,"utf-8")}catch{return{tools:{}}}return Lb(r)}function bf(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 Lb(t){let e={},r={},n=t.split(`
|
|
1608
|
+
`),s={kind:"none"},i={},o=!1,a={};function l(){if(s.kind==="tool"){let d=e[s.tool]??{};if(s.profile){let m=d.profiles?.[s.profile]??{};i.description&&(m.description=i.description),i.flags!==void 0&&(m.flags=i.flags),d.profiles||(d.profiles={}),d.profiles[s.profile]=m}else i.start&&(d.start=i.start),i.resume&&(d.resume=i.resume),i.agent&&(d.agent=i.agent),i.profile_flag!==void 0&&(d.profile_flag=i.profile_flag);e[s.tool]=d}else if(s.kind==="compact"){let d=s.provider?r.providers?.[s.provider]??{}:r.global??{};if(i.min!==void 0){let m=bf(i.min);m!==null&&(d.min=m)}if(i.max!==void 0){let m=bf(i.max);m!==null&&(d.max=m)}s.provider?(r.providers||(r.providers={}),r.providers[s.provider]=d):r.global=d}i={}}for(let d of n){let m=d.trim();if(!m||m.startsWith("#"))continue;let f=Rb(m);if(f!==null){if(o=!0,l(),f.startsWith("tool.")){let y=".profile.",h=f.indexOf(y);h!==-1?s={kind:"tool",tool:f.slice(5,h),profile:f.slice(h+y.length)}:s={kind:"tool",tool:f.slice(5),profile:null}}else f==="compact"?s={kind:"compact",provider:null}:f.startsWith("compact.")?s={kind:"compact",provider:f.slice(8)}:s={kind:"none"};continue}let g=Ab(m);g&&s.kind!=="none"?i[g.key]=g.value:g&&!o&&(a[g.key]=g.value)}l();let c={tools:e};(r.global||r.providers)&&(c.compact=r);let u=a.site_name;return u!==void 0&&u.length>0&&(c.site_name=u),c}function If(t){return t.site_name??null}function Cb(t,e,r){if(!r)return"";let n=t.tools[e]??Fa[e],s=n?.profiles?.[r]?.flags??Fa[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 xf(t,e){return!!t.tools[e]}function kf(t,e,r,n,s){let i=t.tools[e]??Fa[e],o;if(i?.agent){let l=ci(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=xb[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(u=>u.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let u=c.map(ci).join(" ");o=`printf '%s\\n' ${ci(n)} | ${u}`}else o=c.map(ci).join(" ")}let a=Cb(t,e,s);return a&&(o+=" "+a),o}var Fa,xb,On=k(()=>{"use strict";Fa={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:""}}}},xb={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 Af(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 Rf=k(()=>{"use strict"});var Ob,J,di,Oe=k(()=>{"use strict";Ob="ACK: waiting for explicit lmctl task.",J=`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: ${Ob}`,di=`send this exact lmctl seed instruction: "${J}"`});import{existsSync as Db}from"node:fs";function Nf(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&&!Db(e);if(!r&&!n)return t;L({event:"claude_execpath_sanitized",reason:r?"wrong_platform_exe":"missing_file",value:e,platform:process.platform});let s={...t};return delete s.CLAUDE_CODE_EXECPATH,s}function Zr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function $b(t,e){return e===void 0||e.length===0?t:{...t??process.env,[Pa]:e}}function we(t,e,r,n="chat"){return{...$b(Zr(t,e),r),[Mb]:n}}var Pa,Mb,_t=k(()=>{"use strict";V();Pa="LMCTL_SELF_SESSIONID",Mb="LMCTL_LAUNCH_SOURCE"});function Dn(t){return t.replace(/\x1b\[[0-9;]*[a-zA-Z]/g,"")}var Ua=k(()=>{"use strict"});import{spawn as Lf}from"node:child_process";import{mkdirSync as Fb}from"node:fs";var ja,te,Xe=k(()=>{"use strict";On();Rf();Oe();_t();Ua();ja=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},te=class t{name;capabilities;injection;provider;binary;seedArgs;seedTimeoutMs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedTimeoutMs=e.seedTimeoutMs??6e4,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===J?r:n)}turnOptsFor(e){return e}seed(e,r){return Fb(e,{recursive:!0}),new Promise(n=>{let s;try{s=Lf(this.binary,this.seedArgsFor(r),{cwd:e,env:Zr(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}
|
|
1609
|
+
`:this.seedStdin;a&&s.stdin?.write(a),s.stdin?.end(),s.on("exit",(l,c)=>{if(l===0&&!c)n({success:!0});else{let u=Dn(o).trim(),d=Dn(i).trim();n({success:!1,error:(u||d).slice(0,500)||(c?`terminated by ${c}`:`exit code ${l}`)})}}),s.on("error",l=>{n({success:!1,error:l.message})})})}resumeCommand(e,r){return this.resumeTemplate.replace(/\{\{session_id\}\}/g,e)}startCommand(e){return this.startTemplate}manualSeedHint(e){return{launchCommand:`cd ${e} && ${this.binary}`,postLaunchNote:di,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&&xf(n.userConfig,this.name)){let i=n.userConfig.tools[this.name];if(i?.agent)return this.runOneShotAgent(e,n,i.agent)}let s=n.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return s<=0&&!n.signal?this.transportFn(e,{...n,binary:this.binary}):this.withTimeouts(s,e,n)}withTimeouts(e,r,n){let s=new AbortController,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:g=>{a+=g,c(),n.onDelta?.(g)},onProgress:g=>{g.kind!=="api_retry"&&c(),n.onProgress?.(g)}},m=this.transportFn(r,d).then(g=>(u(),{...g,status:g.status??"ok"})).catch(g=>{throw u(),o==="external"?new ja("Turn cancelled","external"):g}),f=new Promise(g=>{l=g});return Promise.race([m,f])}runOneShotAgent(e,r,n){let s=kf(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=Af(r.env),c=Lf(s,{shell:!0,cwd:r.cwd,env:we(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,m=setTimeout(()=>{d=!0,c.kill()},l),f="",g="";if(c.stdout?.on("data",y=>{let h=y.toString();f+=h,r.onDelta?.(h)}),c.stderr?.on("data",y=>{g+=y.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(m),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",y=>{if(u)return;u=!0,clearTimeout(m);let h=Date.now()-i;d?a(new Error(`Agent command timed out after ${l}ms`)):y===0||y===null?o({text:f.trim(),sessionId:r.sessionId,durationMs:h}):a(new Error(g.trim().slice(0,200)||`Agent command exited with code ${y}`))}),c.on("error",y=>{u||(u=!0,clearTimeout(m),a(y))})})}}});function Fn(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new $n(t,r,e)}var zt,re,Mn,ui,$n,yr=k(()=>{"use strict";zt=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},re=class extends zt{},Mn=class extends zt{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},ui=class extends zt{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},$n=class extends zt{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as Wa from"node:child_process";function Ub(t){if(typeof Wa.spawnSync=="function")try{Wa.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function Cf(t){return t.exitCode!==null||t.signalCode!==null}function Ba(t,e){return Cf(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 ie(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??Ub;if(Cf(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await Ba(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 Ba(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await Ba(t,Pb)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var Pb,Pn=k(()=>{"use strict";Pb=1e3});function Of(t){z()&&Ie({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function Qt(t,e){let r=Bb[t];if(r)return r[e]??r.yolo}function Hb(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 ke(t,e,r="yolo"){if(Wb.has(t)){Of(`YOLO ${t} [mode=${r}]: ${t==="codex"?`JSON-RPC params (approvalPolicy=never, sandbox=${r==="plan"?"read-only":"danger-full-access"})`:t==="opencode"?".opencode/opencode.json (permission=allow)":t==="kimi"?`ACP session/set_config_option (configId=mode, value=${r==="plan"?"plan":"auto"})`:t==="dsh"?"DSH_PERMISSION_MODE=danger-full-access env var on the sidecar spawn \u2014 no argv flag":t==="hermes"?"HERMES_YOLO_MODE=1 shell gate + ACP session/set_mode (modeId=dont_ask) edit gate":t==="pi"?"no tool-permission prompts exist in pi by design \u2014 nothing to bypass":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?Qt(t,"plan"):jb[t];if(!n){let s=`unknown provider "${t}" \u2014 YOLO contract not configured. Add an entry to YOLO_FLAGS in src/providers/yolo-contract.ts before spawning this provider.`;throw L({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new re(s)}if(!Hb(e,n)){let s=n.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw L({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new re(i)}Of(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var jb,Bb,Wb,Nt=k(()=>{"use strict";yr();V();jb={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},Bb={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"]}};Wb=new Set(["codex","opencode","kimi","dsh","hermes","pi"])});async function fi(t,e,r){if(typeof t=="boolean")return t;let n,s;try{return await Promise.race([t,new Promise(i=>{n=setTimeout(()=>i(Ha),e),n.unref?.(),r!==void 0&&(s=()=>i(Ha),r.addEventListener("abort",s,{once:!0}))})])}finally{n!==void 0&&clearTimeout(n),s!==void 0&&r?.removeEventListener("abort",s)}}function Zt(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();Vb(t,e,s,n).catch(()=>{n({startedMs:s,held:!1,reason:"check-error"})})}async function Vb(t,e,r,n){let s=t.pollMs??Xb,i=t.maxHoldMs??mi,o=t.settleMs??qb,a=t.backgroundGraceMs??Gb,l=!1,c=null,u=d=>n({startedMs:r,held:l,reason:d});for(;;){if(e.isAborted())return u("aborted");if(e.hasChildExited())return u("child-exited");let d=i-(Date.now()-r);if(d<=0)return u("max-hold");let m;try{m=await fi(t.hasOutstandingWork(),d,e.signal)}catch{return u("check-error")}if(m===Ha)return u(e.isAborted()||e.signal?.aborted===!0?"aborted":"max-hold");if(m)c=null;else{if(!l&&e.wasBackgroundJobLaunched?.()===!0&&Date.now()-r<a){let y=a-(Date.now()-r);await new Promise(h=>setTimeout(h,Math.max(0,Math.min(s,Jb,y))).unref?.());continue}if(!l||o<=0)return u("cleared");c===null&&(c=Date.now(),Te(`${e.label}: dispatched work cleared \u2014 settling ${o}ms before closing stdin`));let g=Math.max(c,e.lastEventAtMs());if(!e.isTurnInFlight()&&Date.now()-g>=o)return u("cleared")}if(l||(l=!0,t.onHold?.(),Te(`${e.label}: deferring stdin close \u2014 outstanding dispatched work (poll ${s}ms)`)),Date.now()-r>=i)return L({event:"transport_hold_open_max_wait",provider:e.label,elapsed_ms:Date.now()-r}),u("max-hold");let f=Math.max(0,Math.min(s,i-(Date.now()-r)));await new Promise(g=>setTimeout(g,f).unref?.())}}var Xb,mi,qb,Gb,Jb,Ha,pi=k(()=>{"use strict";V();Xb=2e3,mi=8*60*60*1e3,qb=5e3,Gb=1e3,Jb=50,Ha=Symbol("check-timed-out")});function Df(t){if(t.length===0)return"";if(t.length===1)return t[0];let e=[];for(let r=0;r<t.length;r++)r===0?e.push(t[r]):e.push(`
|
|
1533
1610
|
|
|
1534
1611
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1535
1612
|
|
|
1536
|
-
`+t[r]);return e.join("")}function hi(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=Mf(e),i=Df(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 Mf(t){let e=[],r=0,n=0,s="",i=!1,o;for(let a of t){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(r+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=c);let u=a.session_id;if(typeof u=="string"&&u&&(s=u),a.is_error===!0){i=!0;let d=a.errors,m=Array.isArray(d)?d.filter(g=>typeof g=="string").join("; "):void 0,f=typeof a.subtype=="string"?a.subtype:"unknown";o=m&&m.length>0?m:`result subtype=${f} (no error detail provided)`}}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s,isError:i,errorMessage:o}}var Xa=k(()=>{"use strict"});import{spawn as Ff}from"node:child_process";import{existsSync as Pf}from"node:fs";import{join as gi}from"node:path";import{readdir as
|
|
1613
|
+
`+t[r]);return e.join("")}function hi(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=Mf(e),i=Df(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 Mf(t){let e=[],r=0,n=0,s="",i=!1,o;for(let a of t){e.push(a.result||"");let l=a.duration_ms;typeof l=="number"&&Number.isFinite(l)&&(r+=l);let c=a.num_turns;typeof c=="number"&&Number.isFinite(c)&&(n=c);let u=a.session_id;if(typeof u=="string"&&u&&(s=u),a.is_error===!0){i=!0;let d=a.errors,m=Array.isArray(d)?d.filter(g=>typeof g=="string").join("; "):void 0,f=typeof a.subtype=="string"?a.subtype:"unknown";o=m&&m.length>0?m:`result subtype=${f} (no error detail provided)`}}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s,isError:i,errorMessage:o}}var Xa=k(()=>{"use strict"});import{spawn as Ff}from"node:child_process";import{existsSync as Pf}from"node:fs";import{join as gi}from"node:path";import{readdir as Kb}from"node:fs/promises";function Uf(){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 jf(){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 Bf(t){let r=t.message?.content;return Array.isArray(r)?r.some(n=>n?.type==="tool_use"):!1}function zb(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1537
1614
|
One possible cause: the provider stream ended before a complete response was delivered; for Claude Code this can appear as "API Error: Stream idle timeout - partial response received".`;return e?`Original provider error:
|
|
1538
1615
|
${e}
|
|
1539
1616
|
|
|
1540
|
-
${r}`:r}function Wf(t){let e=t.tool||"claude",r=t.binaryPath||
|
|
1541
|
-
`);d=Y.pop()||"";for(let Cs of Y)fr(Cs)});let bt="";c.stderr?.on("data",D=>{bt+=D.toString()}),c.on("error",D=>{L({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:D.message}),n(new re(`Failed to spawn ${o}: ${D.message}`,{cause:D}))}),c.on("exit",D=>{if(m=!0,I(),R(),u)return;d.trim()&&fr(d);let Y=be.finalize();Y?.isError?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:Y.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${Y.errorMessage??"unknown error"}`))):Y?(Te(`stream-json: result ${Y.result.slice(0,80)}${Y.result.length>80?"...":""} (${Y.durationMs}ms)`),r({result:Y.result,sessionId:Y.sessionId,durationMs:Y.durationMs,numTurns:Y.numTurns,exitCode:D})):E!==null&&S==="text_done"&&h.trim().length>0?(L({event:"transport_stall_finalized",provider:i,reason:E,text_len:h.length}),r({result:h,sessionId:p||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:D,warnings:[E]})):E!==null&&S==="tool_use_silence"?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:D,stderr_tail:bt.slice(0,500)}),n(new Error(`${E} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(e.sessionId?` (session=${e.sessionId})`:"")))):(L({event:"transport_error",provider:i,error_class:"Error",reason:E!==null?"provider_stalled_no_content":"provider_no_result",exit_code:D,stderr_tail:bt.slice(0,500)}),n(new Error(E!==null?`${E} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):
|
|
1542
|
-
`),Te(`stream-json: prompt sent (${t.length} chars)`)})}function
|
|
1543
|
-
`);D=B.pop()||"";for(let fe of B)vn(fe)}),i.on("error",O=>{if(c=new re(`Failed to spawn ${r}: ${O.message}`,{cause:O}),L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:O.message}),Z(c),w!==null){let B=w;w=null,a.turnActive=!1,B.reject(c)}}),i.on("exit",O=>{a.exited=!0,a.exitCode=O,I(),R(),D.trim()&&vn(D),Z(a.exited&&!Q?new Error(`stream-json bundle: ${e} exited (code ${String(O)}) before its init event`):void 0);let B=w;B!==null&&(w=null,a.turnActive=!1,B.aborted||(y!==null&&h==="text_done"&&d.trim().length>0?(L({event:"transport_stall_finalized",provider:e,reason:y,text_len:d.length}),B.resolve({result:d,sessionId:m||t.sessionId||"",durationMs:Date.now()-B.startMs,numTurns:1,warnings:[y]})):y!==null&&h==="tool_use_silence"?(L({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:O,stderr_tail:u.slice(0,500)}),B.reject(new Error(`${y} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")))):(L({event:"transport_error",provider:e,error_class:"Error",reason:y!==null?"provider_stalled_no_content":"provider_no_result",exit_code:O,stderr_tail:u.slice(0,500)}),B.reject(x()))));for(let fe of b.splice(0))fe()});try{t.sessionId&&await $f(e,t.sessionId,t.sessionFileRoots),await fr}catch(O){let B=c??(O instanceof Error?O:new Error(String(O))),fe=t.closeTimeoutMs??2e3;throw await ie(i,{softDelayMs:Math.min(1e3,fe),killDelayMs:Math.min(1e3,fe)}).catch(()=>{}),B}let Xo=O=>new Promise(B=>{setTimeout(B,O).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(O,B={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw x();if(w!==null)throw new Error(`stream-json bundle session (${e}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);let fe=()=>(a.closed=!0,ie(i).catch(()=>{}),new Error("Aborted"));if(B.signal?.aborted)throw fe();if(t.sessionId&&(await $f(e,t.sessionId,t.sessionFileRoots),a.exited))throw x();if(B.signal?.aborted)throw fe();return d="",f=!1,g=!1,y=null,h=null,p=null,new Promise((Ur,Os)=>{let qo={processor:hi({onText:cu=>{d+=cu,B.onText?.(cu)}}),resolve:Ur,reject:Os,startMs:Date.now(),aborted:!1,onEventForward:B.onEvent};w=qo,a.turnActive=!0;let
|
|
1544
|
-
`),Te(`stream-json bundle: prompt sent (${O.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(O=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),O()},label:e})}):i.stdin?.end(),!a.exited)){let O=t.closeTimeoutMs??2e3;await Promise.race([v(),Xo(O)]),a.exited||await ie(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),a.closing}}}var
|
|
1617
|
+
${r}`:r}function Wf(t){let e=t.tool||"claude",r=t.binaryPath||Yb[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=Qt(e,s)??Qb[e]??["--dangerously-skip-permissions"];if(n.push(...i),ke(e,n,s),t.cwd&&!Pf(t.cwd))throw L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`,elapsed_ms:0}),new re(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});let o=we(t.env,t.cwd,t.sessionId);return{tool:e,binary:r,args:n,spawnEnv:e==="claude"?Nf(o):o}}function Hf(t,e){return new Promise((r,n)=>{let s=Date.now(),i,o,a,l;try{({tool:i,binary:o,args:a,spawnEnv:l}=Wf(e))}catch(D){return n(D instanceof Error?D:new Error(String(D)))}let c=Ff(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:l});c.stdin?.on("error",D=>{Te(`stream-json: stdin pipe error, ignored (exit handler reports): ${D.message}`)});let u=!1;if(e.signal){if(e.signal.aborted)return u=!0,L({event:"transport_abort",provider:i,phase:"pre_spawn"}),ie(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,L({event:"transport_abort",provider:i}),ie(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let d="",m=!1,f=!1,g=0,y=!1,h="",p="",_,T,E=null,S=null,w=!1,b=!1,v=Uf(),x=jf();function I(){_!==void 0&&(clearTimeout(_),_=void 0)}function R(){T!==void 0&&(clearTimeout(T),T=void 0)}let M=null;function N(){return m||u||be.sawResult()}function $(D){return D==="text_done"?v:x}async function q(D){if(D==="text_done"?_=void 0:T=void 0,N()||E!==null)return;M??=Date.now();let Y=$(D);if(e.holdOpen){let vn=(e.holdOpen.maxHoldMs??mi)-(Date.now()-M),Xo=vn>0?await fi(Promise.resolve(e.holdOpen.hasOutstandingWork()).catch(()=>!1),vn,e.signal):!1;if(N()||(D==="text_done"?_!==void 0:T!==void 0))return;if(Xo===!0){L({event:"transport_stall_grace_deferred",provider:i,grace_kind:D,grace_ms:Y,reason:"outstanding_dispatched_work"}),Q(D);return}}S=D,E=D==="text_done"?`${i} finished responding but never emitted its closing result event (${Y}ms of silence after its last message)`:`${i} went silent mid-turn and never emitted its closing result event (${Y}ms of silence)`,L({event:"transport_stall_grace_fired",provider:i,grace_kind:D,grace_ms:Y}),ie(c).catch(()=>{})}function Q(D){let Y=setTimeout(()=>{q(D)},$(D));Y.unref?.(),D==="text_done"?(I(),_=Y):(R(),T=Y)}let be=hi({onEvent:D=>{g=Date.now(),y=D.type!=="result",D.type==="system"&&D.subtype==="init"&&(p=D.session_id||p),D.type==="assistant"?(w=!Bf(D),b=w&&D.message?.stop_reason==="pause_turn"):(D.type==="result"||D.type==="user")&&(w=!1,b=!1),I(),i==="claude"&&w&&!b&&!be.sawResult()&&Q("text_done"),R(),i==="claude"&&!be.sawResult()&&Q("tool_use_silence"),e.onEvent?.(D)},onText:D=>{h+=D,e.onText?.(D)}});function ye(){f||(f=!0,Zt(e.holdOpen,{isAborted:()=>u,hasChildExited:()=>m,isTurnInFlight:()=>y,lastEventAtMs:()=>g,closeStdin:()=>{c.stdin?.end()},signal:e.signal,label:e.tool||"claude"}))}function fr(D){let Y=be.sawResult();be.processLine(D),!Y&&be.sawResult()&&ye()}c.stdout?.on("data",D=>{d+=D.toString();let Y=d.split(`
|
|
1618
|
+
`);d=Y.pop()||"";for(let Cs of Y)fr(Cs)});let bt="";c.stderr?.on("data",D=>{bt+=D.toString()}),c.on("error",D=>{L({event:"transport_error",provider:i,error_class:"TransportConnectionError",error_message:D.message}),n(new re(`Failed to spawn ${o}: ${D.message}`,{cause:D}))}),c.on("exit",D=>{if(m=!0,I(),R(),u)return;d.trim()&&fr(d);let Y=be.finalize();Y?.isError?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_result_error",error_message:Y.errorMessage}),n(new Error(`${i} reported an error for this turn (no assistant output)`+(e.sessionId?` \u2014 session=${e.sessionId}`:"")+`: ${Y.errorMessage??"unknown error"}`))):Y?(Te(`stream-json: result ${Y.result.slice(0,80)}${Y.result.length>80?"...":""} (${Y.durationMs}ms)`),r({result:Y.result,sessionId:Y.sessionId,durationMs:Y.durationMs,numTurns:Y.numTurns,exitCode:D})):E!==null&&S==="text_done"&&h.trim().length>0?(L({event:"transport_stall_finalized",provider:i,reason:E,text_len:h.length}),r({result:h,sessionId:p||e.sessionId||"",durationMs:Date.now()-s,numTurns:1,exitCode:D,warnings:[E]})):E!==null&&S==="tool_use_silence"?(L({event:"transport_error",provider:i,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:D,stderr_tail:bt.slice(0,500)}),n(new Error(`${E} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(e.sessionId?` (session=${e.sessionId})`:"")))):(L({event:"transport_error",provider:i,error_class:"Error",reason:E!==null?"provider_stalled_no_content":"provider_no_result",exit_code:D,stderr_tail:bt.slice(0,500)}),n(new Error(E!==null?`${E} \u2014 and produced no usable content to fall back on`+(e.sessionId?` (session=${e.sessionId})`:""):zb({tool:i,exitCode:D,stderr:bt}))))});let Z=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(Z+`
|
|
1619
|
+
`),Te(`stream-json: prompt sent (${t.length} chars)`)})}function Zb(t){return t==="qwen"?[gi(H,".qwen","projects")]:[gi(H,".claude","projects")]}async function $f(t,e,r){let n=r??Zb(t),s=null;for(let a of n){let l;try{l=await Kb(a)}catch{continue}for(let c of l){for(let u of[gi(a,c,`${e}.jsonl`),gi(a,c,"chats",`${e}.jsonl`)])if(Pf(u)){s=u;break}if(s!==null)break}if(s!==null)break}if(s===null)throw new Error(`stream-json bundle: no session file for session "${e}" under ${n.join(", ")} \u2014 the session must exist on disk before a bundle can resume it`);let o=(await He(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 Xf(t){let{tool:e,binary:r,args:n,spawnEnv:s}=Wf(t),i=Ff(r,n,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:s}),o=Date.now();i.stdin?.on("error",O=>{Te(`stream-json bundle: stdin pipe error, ignored (exit handler reports): ${O.message}`)});let a={exited:!1,exitCode:null,lastEventAtMs:0,turnActive:!1,completedTurns:0,closed:!1,closing:null},l=t.sessionId||"",c=null,u="";i.stderr?.on("data",O=>{u+=O.toString()});let d="",m="",f=!1,g=!1,y=null,h=null,p=null,_,T,E=Uf(),S=jf(),w=null,b=[],v=()=>a.exited?Promise.resolve():new Promise(O=>{b.push(O)}),x=()=>new Error(`stream-json bundle process (${e}) exited${a.exitCode!==null?` with code ${a.exitCode}`:""} after ${a.completedTurns} completed prompt(s); the bundle cannot continue`);function I(){_!==void 0&&(clearTimeout(_),_=void 0)}function R(){T!==void 0&&(clearTimeout(T),T=void 0)}function M(){return a.exited||w===null||w.aborted||w.processor.sawResult()}function N(O){return O==="text_done"?E:S}async function $(O){if(O==="text_done"?_=void 0:T=void 0,M()||y!==null)return;p??=Date.now();let B=N(O);if(t.holdOpen){let Ur=(t.holdOpen.maxHoldMs??mi)-(Date.now()-p),Os=Ur>0?await fi(Promise.resolve(t.holdOpen.hasOutstandingWork()).catch(()=>!1),Ur,void 0):!1;if(M()||(O==="text_done"?_!==void 0:T!==void 0))return;if(Os===!0){L({event:"transport_stall_grace_deferred",provider:e,grace_kind:O,grace_ms:B,reason:"outstanding_dispatched_work"}),q(O);return}}h=O,y=O==="text_done"?`${e} finished responding but never emitted its closing result event (${B}ms of silence after its last message)`:`${e} went silent mid-turn and never emitted its closing result event (${B}ms of silence)`,L({event:"transport_stall_grace_fired",provider:e,grace_kind:O,grace_ms:B}),ie(i).catch(()=>{})}function q(O){let B=setTimeout(()=>{$(O)},N(O));B.unref?.(),O==="text_done"?(I(),_=B):(R(),T=B)}let Q=!1,be,ye,fr=new Promise((O,B)=>{be=O,ye=B});fr.catch(()=>{});let bt=setTimeout(()=>{Q||(Q=!0,ye(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);bt.unref?.();function Z(O){Q||(Q=!0,clearTimeout(bt),O?ye(O):be())}let D="";function Y(O){if(a.lastEventAtMs=Date.now(),O.type==="system"&&O.subtype==="init"){if(m=O.session_id||m,t.sessionId&&typeof O.session_id=="string"&&O.session_id.length>0&&O.session_id!==t.sessionId){let fe=new Error(`stream-json bundle: provider resumed a different session (init reported "${O.session_id}", expected "${t.sessionId}")`);Z(fe),ie(i).catch(()=>{});return}Z()}let B=w?.processor.sawResult()??!0;O.type==="assistant"?(f=!Bf(O),g=f&&O.message?.stop_reason==="pause_turn"):(O.type==="result"||O.type==="user")&&(f=!1,g=!1),I(),e==="claude"&&a.turnActive&&f&&!g&&!B&&q("text_done"),R(),e==="claude"&&a.turnActive&&!B&&q("tool_use_silence")}function Cs(){let O=w;if(O===null)return;let B=O.processor.finalize();if(B!==null){if(w=null,a.turnActive=!1,I(),R(),B.isError){L({event:"transport_error",provider:e,error_class:"Error",reason:"provider_result_error",error_message:B.errorMessage}),O.reject(new Error(`${e} reported an error for this turn (no assistant output)`+(t.sessionId?` \u2014 session=${t.sessionId}`:"")+`: ${B.errorMessage??"unknown error"}`));return}a.completedTurns+=1,l=B.sessionId||l,Te(`stream-json bundle: result ${B.result.slice(0,80)}${B.result.length>80?"...":""} (${B.durationMs}ms)`),O.resolve({result:B.result,sessionId:B.sessionId||l,durationMs:B.durationMs,numTurns:B.numTurns})}}function vn(O){if(!O.trim())return;let B;try{B=JSON.parse(O)}catch{return}Y(B);let fe=w;if(fe!==null){let Ur=fe.processor.sawResult();fe.processor.processLine(O),fe.onEventForward?.(B),!Ur&&fe.processor.sawResult()&&Cs()}}i.stdout?.on("data",O=>{D+=O.toString();let B=D.split(`
|
|
1620
|
+
`);D=B.pop()||"";for(let fe of B)vn(fe)}),i.on("error",O=>{if(c=new re(`Failed to spawn ${r}: ${O.message}`,{cause:O}),L({event:"transport_error",provider:e,error_class:"TransportConnectionError",error_message:O.message}),Z(c),w!==null){let B=w;w=null,a.turnActive=!1,B.reject(c)}}),i.on("exit",O=>{a.exited=!0,a.exitCode=O,I(),R(),D.trim()&&vn(D),Z(a.exited&&!Q?new Error(`stream-json bundle: ${e} exited (code ${String(O)}) before its init event`):void 0);let B=w;B!==null&&(w=null,a.turnActive=!1,B.aborted||(y!==null&&h==="text_done"&&d.trim().length>0?(L({event:"transport_stall_finalized",provider:e,reason:y,text_len:d.length}),B.resolve({result:d,sessionId:m||t.sessionId||"",durationMs:Date.now()-B.startMs,numTurns:1,warnings:[y]})):y!==null&&h==="tool_use_silence"?(L({event:"transport_error",provider:e,error_class:"Error",reason:"provider_stalled_mid_turn",exit_code:O,stderr_tail:u.slice(0,500)}),B.reject(new Error(`${y} \u2014 a tool call was still in flight, so any streamed text is incomplete mid-turn narration, not a real answer`+(t.sessionId?` (session=${t.sessionId})`:"")))):(L({event:"transport_error",provider:e,error_class:"Error",reason:y!==null?"provider_stalled_no_content":"provider_no_result",exit_code:O,stderr_tail:u.slice(0,500)}),B.reject(x()))));for(let fe of b.splice(0))fe()});try{t.sessionId&&await $f(e,t.sessionId,t.sessionFileRoots),await fr}catch(O){let B=c??(O instanceof Error?O:new Error(String(O))),fe=t.closeTimeoutMs??2e3;throw await ie(i,{softDelayMs:Math.min(1e3,fe),killDelayMs:Math.min(1e3,fe)}).catch(()=>{}),B}let Xo=O=>new Promise(B=>{setTimeout(B,O).unref?.()});return{tool:e,get sessionId(){return l},get completedTurns(){return a.completedTurns},async sendTurn(O,B={}){if(a.closed||a.closing!==null)throw new Error(`stream-json bundle session (${e}) is closed`);if(a.exited)throw x();if(w!==null)throw new Error(`stream-json bundle session (${e}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);let fe=()=>(a.closed=!0,ie(i).catch(()=>{}),new Error("Aborted"));if(B.signal?.aborted)throw fe();if(t.sessionId&&(await $f(e,t.sessionId,t.sessionFileRoots),a.exited))throw x();if(B.signal?.aborted)throw fe();return d="",f=!1,g=!1,y=null,h=null,p=null,new Promise((Ur,Os)=>{let qo={processor:hi({onText:cu=>{d+=cu,B.onText?.(cu)}}),resolve:Ur,reject:Os,startMs:Date.now(),aborted:!1,onEventForward:B.onEvent};w=qo,a.turnActive=!0;let GT=()=>{qo.aborted=!0,L({event:"transport_abort",provider:e}),a.closed=!0,ie(i).catch(()=>{}),w===qo&&(w=null,a.turnActive=!1),Os(new Error("Aborted"))};B.signal?.addEventListener("abort",GT,{once:!0});let JT=JSON.stringify({type:"user",message:{role:"user",content:O}});i.stdin?.write(`${JT}
|
|
1621
|
+
`),Te(`stream-json bundle: prompt sent (${O.length} chars)`)})},close(){return a.closing!==null||(a.closing=(async()=>{if(a.closed=!0,!a.exited&&(t.holdOpen!==void 0?await new Promise(O=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>a.exited,isTurnInFlight:()=>a.turnActive,lastEventAtMs:()=>a.lastEventAtMs,closeStdin:()=>{i.stdin?.end(),O()},label:e})}):i.stdin?.end(),!a.exited)){let O=t.closeTimeoutMs??2e3;await Promise.race([v(),Xo(O)]),a.exited||await ie(i,{stdinEnd:!1,softDelayMs:Math.min(1e3,O),killDelayMs:Math.min(1e3,O)}).catch(()=>{})}})()),a.closing}}}var Yb,Qb,qa=k(()=>{"use strict";yr();Pn();Nt();V();pi();_t();Xa();xe();Xa();Yb={claude:"claude",qwen:"qwen"};Qb={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function _i(t={}){return[]}var Ga=k(()=>{"use strict"});function Ja(t){return t==="plan"?"read-only":"danger-full-access"}function qf(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function yi(){return{agentItems:new Map,resultText:""}}function en(t,e,r,n){let s=t.method;if(!s)return!1;let i=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=typeof o.phase=="string"?o.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(o.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let o=i?.delta||"",a=typeof i?.itemId=="string"?i.itemId:void 0;if(!o)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=o),r?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,r?.(o)),!0}if(s==="item/completed"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=e.agentItems.get(o.id);if(a){if(a.phase!=="commentary"){let l=typeof o.text=="string"?o.text:a.buffer;if(n&&typeof o.text=="string"&&o.text!==a.buffer){let c=typeof i?.threadId=="string"?i.threadId:void 0,u=typeof i?.turnId=="string"?i.turnId:void 0;n({itemId:o.id,threadId:c,turnId:u,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function Ei(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function Gf(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 Ti(){return{pendingCodexError:null}}function wi(t,e){let r=Gf(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function vi(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 Va=k(()=>{"use strict"});import{spawn as Jf}from"node:child_process";import{createInterface as Vf}from"node:readline";import{existsSync as eI,readFileSync as tI}from"node:fs";import{fileURLToPath as rI}from"node:url";function Kf(){return qf(nI)}function er(t,e){Te(`[codex:${t}] ${JSON.stringify(e)}`)}function sI(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1545
1622
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1546
1623
|
${e}
|
|
1547
1624
|
|
|
1548
|
-
${r}`:r}function Yf(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?_i():[];r.push(...s),z()&&Ee(JSON.stringify({event:"codex_mcp_inject",alias:t.alias??null,isLead:n,injected:s.length>0}));let i=t.permissionMode??"yolo",o=Ja(i);if(ke("codex",r,i),t.cwd&&!
|
|
1625
|
+
${r}`:r}function Yf(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?_i():[];r.push(...s),z()&&Ee(JSON.stringify({event:"codex_mcp_inject",alias:t.alias??null,isLead:n,injected:s.length>0}));let i=t.permissionMode??"yolo",o=Ja(i);if(ke("codex",r,i),t.cwd&&!eI(t.cwd))throw L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${t.cwd}`}),new re(`sessiondir missing: ${t.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:e,codexArgs:r,sandbox:o,permissionMode:i,spawnEnv:we(t.env,t.cwd,t.threadId)}}function zf(t,e){return new Promise((r,n)=>{let s,i,o;try{({binary:s,codexArgs:i,sandbox:o}=Yf(e))}catch(w){return n(w instanceof Error?w:new Error(String(w)))}let a=Jf(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:we(e.env,e.cwd,e.threadId)}),l=!1;if(e.signal){if(e.signal.aborted)return l=!0,L({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),ie(a).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{l=!0,L({event:"transport_abort",provider:"codex"}),ie(a).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let c=Vf({input:a.stdout}),u=new Map,d=1,m=e.threadId||"",f="",g=!1,y=!1,h=Date.now(),p=yi(),_=Ti();function T(w,b={}){return new Promise((v,x)=>{let I=d++;u.set(I,{resolve:v,reject:x});let R=JSON.stringify({jsonrpc:"2.0",id:I,method:w,params:b});a.stdin?.write(R+`
|
|
1549
1626
|
`)})}function E(w,b={}){let v=JSON.stringify({jsonrpc:"2.0",method:w,params:b});a.stdin?.write(v+`
|
|
1550
|
-
`)}c.on("line",w=>{let b;try{b=JSON.parse(w)}catch{return}if(typeof b.id=="number"&&u.has(b.id)){let I=u.get(b.id);if(u.delete(b.id),b.error){let R=b.error,M=typeof R?.message=="string"&&R.message.length>0?R.message:JSON.stringify(b.error);I.reject(Fn(`codex app-server error: ${M}`,R))}else I.resolve(b);e.onEvent?.(b);return}let v=b.method;if(!v){e.onEvent?.(b);return}if(v==="thread/started"){let R=b.params?.thread;R?.id&&(m=R.id)}let x=z()?I=>{er("item.text/buffer-mismatch",{itemId:I.itemId,threadId:I.threadId??null,turnId:I.turnId??null,expectedFromItemText:I.expectedFromItemText,gotFromBuffer:I.gotFromBuffer,expectedLen:I.expectedFromItemText.length,gotLen:I.gotFromBuffer.length})}:void 0;if(v==="turn/started"){let I=b.params,R=I?.turn;R?.id&&(f=R.id),en(b,p,e.onDelta,x),z()&&er("turn/started",{params:I??null})}if(z()&&(v==="item/started"||v==="item/completed")){let I=b.params;I?.item?.type==="agentMessage"&&er(v,{params:I??null})}if(v==="item/started"||v==="item/agentMessage/delta"||v==="item/completed"){if(v==="item/agentMessage/delta"){let I=b.params;z()&&er("agentMessage/delta",{params:I??null})}en(b,p,e.onDelta,x)}if(v==="turn/completed"){let I=b.params;if(z())for(let[M,N]of p.agentItems.entries())N.buffer&&er("turn/completed/unflushed-item",{itemId:M,phase:N.phase,bufferLen:N.buffer.length});Ei(p),z()&&er("turn/completed",{params:I??null});let R=vi(b,_);R.shouldReject?(z()&&er("turn/completed/terminal-reject",{message:R.turnError.message}),y=!0,g=!0,a.stdin?.end(),n(R.turnError)):(g=!0,a.stdin?.end())}if(v==="error"){let I=wi(b,_);if(z()){let R=b.params,M=R?.error,N=typeof M?.message=="string"?M.message:"(no message)";er(I.willRetry?"error/retry":"error/terminal-deferred",{message:N,willRetry:I.willRetry,params:R??null})}}e.onEvent?.(b)});let S="";a.stderr?.on("data",w=>{S+=w.toString()}),a.on("error",w=>{L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:w.message}),n(new re(`Failed to spawn codex app-server: ${w.message}`,{cause:w}))}),a.on("exit",w=>{if(!l&&!y){if(g){r({result:p.resultText,threadId:m,turnId:f,durationMs:Date.now()-h,exitCode:w});return}if(_.pendingCodexError){n(_.pendingCodexError);return}L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:w,stderr_tail:S.slice(0,500)}),n(new Error(
|
|
1627
|
+
`)}c.on("line",w=>{let b;try{b=JSON.parse(w)}catch{return}if(typeof b.id=="number"&&u.has(b.id)){let I=u.get(b.id);if(u.delete(b.id),b.error){let R=b.error,M=typeof R?.message=="string"&&R.message.length>0?R.message:JSON.stringify(b.error);I.reject(Fn(`codex app-server error: ${M}`,R))}else I.resolve(b);e.onEvent?.(b);return}let v=b.method;if(!v){e.onEvent?.(b);return}if(v==="thread/started"){let R=b.params?.thread;R?.id&&(m=R.id)}let x=z()?I=>{er("item.text/buffer-mismatch",{itemId:I.itemId,threadId:I.threadId??null,turnId:I.turnId??null,expectedFromItemText:I.expectedFromItemText,gotFromBuffer:I.gotFromBuffer,expectedLen:I.expectedFromItemText.length,gotLen:I.gotFromBuffer.length})}:void 0;if(v==="turn/started"){let I=b.params,R=I?.turn;R?.id&&(f=R.id),en(b,p,e.onDelta,x),z()&&er("turn/started",{params:I??null})}if(z()&&(v==="item/started"||v==="item/completed")){let I=b.params;I?.item?.type==="agentMessage"&&er(v,{params:I??null})}if(v==="item/started"||v==="item/agentMessage/delta"||v==="item/completed"){if(v==="item/agentMessage/delta"){let I=b.params;z()&&er("agentMessage/delta",{params:I??null})}en(b,p,e.onDelta,x)}if(v==="turn/completed"){let I=b.params;if(z())for(let[M,N]of p.agentItems.entries())N.buffer&&er("turn/completed/unflushed-item",{itemId:M,phase:N.phase,bufferLen:N.buffer.length});Ei(p),z()&&er("turn/completed",{params:I??null});let R=vi(b,_);R.shouldReject?(z()&&er("turn/completed/terminal-reject",{message:R.turnError.message}),y=!0,g=!0,a.stdin?.end(),n(R.turnError)):(g=!0,a.stdin?.end())}if(v==="error"){let I=wi(b,_);if(z()){let R=b.params,M=R?.error,N=typeof M?.message=="string"?M.message:"(no message)";er(I.willRetry?"error/retry":"error/terminal-deferred",{message:N,willRetry:I.willRetry,params:R??null})}}e.onEvent?.(b)});let S="";a.stderr?.on("data",w=>{S+=w.toString()}),a.on("error",w=>{L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:w.message}),n(new re(`Failed to spawn codex app-server: ${w.message}`,{cause:w}))}),a.on("exit",w=>{if(!l&&!y){if(g){r({result:p.resultText,threadId:m,turnId:f,durationMs:Date.now()-h,exitCode:w});return}if(_.pendingCodexError){n(_.pendingCodexError);return}L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:w,stderr_tail:S.slice(0,500)}),n(new Error(sI({exitCode:w,stderr:S})))}}),(async()=>{try{if(await T("initialize",Kf()),E("initialized",{}),e.threadId)try{let w=T("thread/resume",{threadId:e.threadId,sandbox:o,approvalPolicy:"never",...e.model?{model:e.model}:{}}),b=new Promise((v,x)=>setTimeout(()=>x(new Error("resume timeout")),3e4));await Promise.race([w,b]),m=e.threadId}catch(w){process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1551
1628
|
`),L({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:w instanceof Error?w.message:String(w)});let v=(await T("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;v?.id&&(m=v.id)}else{let b=(await T("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:o,...e.model?{model:e.model}:{}})).result?.thread;b?.id&&(m=b.id)}await T("turn/start",{threadId:m,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(w){ie(a).catch(()=>{}),n(w instanceof Error?w:new Error(String(w)))}})()})}async function Qf(t){let{binary:e,codexArgs:r,sandbox:n}=Yf(t),s=Jf(e,r,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:we(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",S=>{c+=S.toString()});let u=Vf({input:s.stdout}),d=new Map,m=1;function f(S,w={}){return new Promise((b,v)=>{let x=m++;d.set(x,{resolve:b,reject:v});let I=JSON.stringify({jsonrpc:"2.0",id:x,method:S,params:w});s.stdin?.write(I+`
|
|
1552
1629
|
`)})}function g(S,w={}){let b=JSON.stringify({jsonrpc:"2.0",method:S,params:w});s.stdin?.write(b+`
|
|
1553
|
-
`)}let y=[],h=()=>o.exited?Promise.resolve():new Promise(S=>{y.push(S)}),p=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),_=null;function T(S){let w=_;w===null||w.settled||(w.settled=!0,_=null,S&&w.reject(S))}u.on("line",S=>{let w;try{w=JSON.parse(S)}catch{return}if(typeof w.id=="number"&&d.has(w.id)){let x=d.get(w.id);if(d.delete(w.id),w.error){let I=w.error,R=typeof I?.message=="string"&&I.message.length>0?I.message:JSON.stringify(w.error);x.reject(Fn(`codex app-server error: ${R}`,I))}else x.resolve(w);_?.onEvent?.(w);return}let b=w.method;if(!b){_?.onEvent?.(w);return}if(b==="thread/started"){let I=w.params?.thread;I?.id&&(a=I.id)}let v=_;if(b==="turn/started"&&v!==null){let I=w.params?.turn;I?.id&&(v.turnId=I.id),en(w,v.agentState,v.onDelta,void 0)}if(v!==null&&(b==="item/started"||b==="item/agentMessage/delta"||b==="item/completed")&&en(w,v.agentState,v.onDelta,void 0),b==="turn/completed"&&v!==null&&!v.settled){Ei(v.agentState);let x=vi(w,v.turnState);v.settled=!0,_=null,x.shouldReject?v.reject(x.turnError):(o.completedTurns+=1,v.resolve({text:v.agentState.resultText,sessionId:a,turnId:v.turnId,durationMs:Date.now()-v.startMs}))}b==="error"&&v!==null&&wi(w,v.turnState),v?.onEvent?.(w)}),s.on("error",S=>{l=new re(`Failed to spawn codex app-server: ${S.message}`,{cause:S}),L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:S.message});for(let w of d.values())w.reject(l);d.clear(),T(l)}),s.on("exit",S=>{o.exited=!0,o.exitCode=S;let w=p();for(let v of d.values())v.reject(w);d.clear();let b=_;b!==null&&!b.settled&&(b.settled=!0,_=null,b.turnState.pendingCodexError?b.reject(b.turnState.pendingCodexError):(L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:c.slice(0,500)}),b.reject(w)));for(let v of y.splice(0))v()});try{if(await f("initialize",Kf()),g("initialized",{}),t.threadId){let S;try{S=await f("thread/resume",{threadId:t.threadId,sandbox:n,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(b){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${b instanceof Error?b.message:String(b)} (the thread/start fallback is disabled in bundle mode)`)}let w=S.result?.thread;if(typeof w?.id=="string"&&w.id.length>0){if(w.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${w.id}"`);a=w.id}}else{let w=(await f("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:n,...t.model?{model:t.model}:{}})).result?.thread;w?.id&&(a=w.id)}}catch(S){let w=l??(S instanceof Error?S:new Error(String(S))),b=t.closeTimeoutMs??2e3;throw await ie(s,{softDelayMs:Math.min(1e3,b),killDelayMs:Math.min(1e3,b)}).catch(()=>{}),w}let E=S=>new Promise(w=>{setTimeout(w,S).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(S,w={}){if(o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw p();if(_!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(w.signal?.aborted)throw new Error("Aborted");return new Promise((b,v)=>{let x={agentState:yi(),turnState:Ti(),resolve:b,reject:v,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};_=x;let I=()=>{x.settled||(x.settled=!0,_=null,x.turnId&&f("turn/interrupt",{threadId:a,turnId:x.turnId}).catch(()=>{}),v(new Error("Aborted")))};w.signal?.addEventListener("abort",I,{once:!0}),f("turn/start",{threadId:a,input:[{type:"text",text:S}],...t.model?{model:t.model}:{}}).catch(R=>{x.settled||(x.settled=!0,_=null,w.signal?.removeEventListener("abort",I),v(o.exited?p():R instanceof Error?R:new Error(String(R))))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,!o.exited&&(t.holdOpen!==void 0?await new Promise(S=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>_!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),S()},label:"codex"})}):s.stdin?.end(),!o.exited)){let S=t.closeTimeoutMs??2e3;await Promise.race([h(),E(S)]),o.exited||await ie(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})}})()),o.closing}}}var
|
|
1630
|
+
`)}let y=[],h=()=>o.exited?Promise.resolve():new Promise(S=>{y.push(S)}),p=()=>new Error(`codex bundle process exited${o.exitCode!==null?` with code ${o.exitCode}`:""} after ${o.completedTurns} completed prompt(s); the bundle cannot continue`),_=null;function T(S){let w=_;w===null||w.settled||(w.settled=!0,_=null,S&&w.reject(S))}u.on("line",S=>{let w;try{w=JSON.parse(S)}catch{return}if(typeof w.id=="number"&&d.has(w.id)){let x=d.get(w.id);if(d.delete(w.id),w.error){let I=w.error,R=typeof I?.message=="string"&&I.message.length>0?I.message:JSON.stringify(w.error);x.reject(Fn(`codex app-server error: ${R}`,I))}else x.resolve(w);_?.onEvent?.(w);return}let b=w.method;if(!b){_?.onEvent?.(w);return}if(b==="thread/started"){let I=w.params?.thread;I?.id&&(a=I.id)}let v=_;if(b==="turn/started"&&v!==null){let I=w.params?.turn;I?.id&&(v.turnId=I.id),en(w,v.agentState,v.onDelta,void 0)}if(v!==null&&(b==="item/started"||b==="item/agentMessage/delta"||b==="item/completed")&&en(w,v.agentState,v.onDelta,void 0),b==="turn/completed"&&v!==null&&!v.settled){Ei(v.agentState);let x=vi(w,v.turnState);v.settled=!0,_=null,x.shouldReject?v.reject(x.turnError):(o.completedTurns+=1,v.resolve({text:v.agentState.resultText,sessionId:a,turnId:v.turnId,durationMs:Date.now()-v.startMs}))}b==="error"&&v!==null&&wi(w,v.turnState),v?.onEvent?.(w)}),s.on("error",S=>{l=new re(`Failed to spawn codex app-server: ${S.message}`,{cause:S}),L({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:S.message});for(let w of d.values())w.reject(l);d.clear(),T(l)}),s.on("exit",S=>{o.exited=!0,o.exitCode=S;let w=p();for(let v of d.values())v.reject(w);d.clear();let b=_;b!==null&&!b.settled&&(b.settled=!0,_=null,b.turnState.pendingCodexError?b.reject(b.turnState.pendingCodexError):(L({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:S,stderr_tail:c.slice(0,500)}),b.reject(w)));for(let v of y.splice(0))v()});try{if(await f("initialize",Kf()),g("initialized",{}),t.threadId){let S;try{S=await f("thread/resume",{threadId:t.threadId,sandbox:n,approvalPolicy:"never",...t.model?{model:t.model}:{}})}catch(b){throw new Error(`Cannot resume codex thread ${t.threadId} for a bundle: ${b instanceof Error?b.message:String(b)} (the thread/start fallback is disabled in bundle mode)`)}let w=S.result?.thread;if(typeof w?.id=="string"&&w.id.length>0){if(w.id!==t.threadId)throw new Error(`codex thread/resume did not return the requested thread id: expected "${t.threadId}", received "${w.id}"`);a=w.id}}else{let w=(await f("thread/start",{cwd:t.cwd,approvalPolicy:"never",sandbox:n,...t.model?{model:t.model}:{}})).result?.thread;w?.id&&(a=w.id)}}catch(S){let w=l??(S instanceof Error?S:new Error(String(S))),b=t.closeTimeoutMs??2e3;throw await ie(s,{softDelayMs:Math.min(1e3,b),killDelayMs:Math.min(1e3,b)}).catch(()=>{}),w}let E=S=>new Promise(w=>{setTimeout(w,S).unref?.()});return{provider:"codex",get sessionId(){return a},get completedTurns(){return o.completedTurns},async sendTurn(S,w={}){if(o.closed||o.closing!==null)throw new Error("codex bundle session is closed");if(o.exited)throw p();if(_!==null)throw new Error("codex bundle session has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending");if(w.signal?.aborted)throw new Error("Aborted");return new Promise((b,v)=>{let x={agentState:yi(),turnState:Ti(),resolve:b,reject:v,startMs:Date.now(),turnId:"",onDelta:w.onDelta,onEvent:w.onEvent,settled:!1};_=x;let I=()=>{x.settled||(x.settled=!0,_=null,x.turnId&&f("turn/interrupt",{threadId:a,turnId:x.turnId}).catch(()=>{}),v(new Error("Aborted")))};w.signal?.addEventListener("abort",I,{once:!0}),f("turn/start",{threadId:a,input:[{type:"text",text:S}],...t.model?{model:t.model}:{}}).catch(R=>{x.settled||(x.settled=!0,_=null,w.signal?.removeEventListener("abort",I),v(o.exited?p():R instanceof Error?R:new Error(String(R))))})})},close(){return o.closing!==null||(o.closing=(async()=>{if(o.closed=!0,!o.exited&&(t.holdOpen!==void 0?await new Promise(S=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>o.exited,isTurnInFlight:()=>_!==null,lastEventAtMs:()=>i,closeStdin:()=>{s.stdin?.end(),S()},label:"codex"})}):s.stdin?.end(),!o.exited)){let S=t.closeTimeoutMs??2e3;await Promise.race([h(),E(S)]),o.exited||await ie(s,{stdinEnd:!1,softDelayMs:Math.min(1e3,S),killDelayMs:Math.min(1e3,S)}).catch(()=>{})}})()),o.closing}}}var nI,Zf=k(()=>{"use strict";V();V();yr();Pn();pi();Nt();Ga();V();_t();Va();Va();nI=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(tI(rI(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});function Si(t){let e=[...t.matchAll(iI)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return ep(t.slice(n).trimStart())}return ep(dI(t.replace(oI,"")))}function dI(t){let e=aI.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(lI)];if(n.length<2)return t;let s=n[0],i=(s.index??0)+s[0].length;return r.slice(i).trimStart()}function ep(t){let e=[...t.matchAll(cI)];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 tr(t,e=""){let r=t.result;return typeof r?.sessionId=="string"&&r.sessionId.length>0?r.sessionId:e}function rp(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function bi(t={}){let e="",r="",n="",s=!1,i=!1,o=!1,a=t.isolateResult??(t.tool==="gemini"?Si: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=rp(c),s=!0,i=!1,l()},cancelTurn(){r="",n="",i=!1},processMessage(c){if(c.method!=="session/update")return!1;let d=c.params?.update,m=d?.sessionUpdate;if(typeof m!="string"||(i&&uI.has(m)&&(o=!0),m!=="agent_message_chunk"))return!1;let f=d?.content,g=typeof f?.text=="string"?f.text:"";return g&&i&&(r+=g,t.onDelta?.(g)),!0},finalize(){return s?l():null}}}var tp,iI,oI,aI,lI,cI,uI,Un=k(()=>{"use strict";tp="(?:png|jpe?g|webp|heic|pdf)",iI=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${tp}\\s*`,"gi"),oI=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${tp}\\s*`,"i"),aI=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,lI=/^STANCE:\s+\S+\s*$/gim,cI=/\[Thought:\s*true\]\s*/gi;uI=new Set(["agent_message_chunk","agent_thought_chunk","tool_call","tool_call_update","plan"])});import{createInterface as mI}from"node:readline";function jn(t,e){let r=mI({input:t.stdout}),n=new Map,s=(o,a={})=>new Promise((l,c)=>{let u=fI++;n.set(u,{resolve:l,reject:c});let d=JSON.stringify({jsonrpc:"2.0",id:u,method:o,params:a});Ie({event:"acp_send",direction:"SEND",provider:e.provider,method:o,id:u,params:a}),t.stdin?.write(`${d}
|
|
1554
1631
|
`)}),i=(o,a={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:o,params:a})}
|
|
1555
1632
|
`)};return r.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(Ie({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let u=a.error,d=typeof u?.message=="string"&&u.message.length>0?u.message:JSON.stringify(a.error);c.reject(Fn(`ACP RPC error: ${d}`,u))}else c.resolve(a);return}let l=a.method;if(l){if(typeof a.id=="number"){L({event:"acp_unhandled_request",provider:e.provider,method:l,id:a.id,params:a.params});let c=JSON.stringify({jsonrpc:"2.0",id:a.id,error:{code:-32601,message:`Method not found: ${l} (lmctl does not implement server-side ACP methods)`}});Ie({event:"acp_send",direction:"SEND",provider:e.provider,replyTo:a.id,error:"method not found"}),t.stdin?.write(`${c}
|
|
1556
|
-
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new re("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var
|
|
1633
|
+
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new re("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}var fI,Ka=k(()=>{"use strict";V();yr();fI=1});import{readFileSync as pI,readdirSync as np}from"node:fs";import{join as Ii}from"node:path";function sp(t,e){let r=e.GEMINI_DIR??process.env.GEMINI_DIR??Ii(H,".gemini"),n=Ii(r,"tmp"),s;try{s=np(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=Ii(n,a,"chats"),c;try{c=np(l)}catch{continue}for(let u of c){if(!u.endsWith(".json"))continue;let d;try{d=pI(Ii(l,u),"utf8").slice(0,8192)}catch{continue}if(d.includes(i)||d.includes(o))return}}throw new Error(`gemini bundle: no session "${t}" in the gemini chats store (${n}) \u2014 the session must exist on disk before a bundle can resume it`)}var Bn,ip=k(()=>{"use strict";Un();xe();Nt();Bn={name:"gemini",binary:"gemini",baseArgs:["--acp","-y","--skip-trust"],argv(t){let e=[...Bn.baseArgs];if(t.permissionMode==="plan"){let r=Qt("gemini","plan"),n=Qt("gemini","yolo");e=e.filter(s=>!(n??[]).includes(s)),r&&e.push(...r)}return t.model&&e.push("--model",t.model),e},isolateResult:Si,sessionIdentity:{verifyLoadedSession:t=>{sp(t.requestedSessionId,t.env)},recheckSession:t=>{sp(t.requestedSessionId,t.env)}}}});import{existsSync as hI,readFileSync as gI}from"node:fs";import{join as Ya}from"node:path";function op(t,e){let r=e.COPILOT_HOME??process.env.COPILOT_HOME??Ya(H,".copilot"),n=Ya(r,"session-state",t),s=Ya(n,"workspace.yaml");if(!hI(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=gI(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 Wn,ap=k(()=>{"use strict";V();xe();Wn={name:"copilot",binary:"copilot",baseArgs:["--acp","--yolo"],argv(t){return t.permissionMode==="plan"&&(process.stderr.write(`[acp] copilot has no plan-mode flag in --acp mode; --permission-mode plan is not honored (running yolo). See src/providers/yolo-contract.ts.
|
|
1557
1634
|
`),L({event:"acp_plan_mode_unsupported",provider:"copilot",requested_mode:"plan",effective_mode:"yolo"})),t.model&&(process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${t.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1558
|
-
`),L({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...Wn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{op(t.requestedSessionId,t.env)},recheckSession:t=>{op(t.requestedSessionId,t.env)}}}});import{existsSync as dp,mkdirSync as
|
|
1559
|
-
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function fp(t,e={}){let r=Hn(t,".opencode"),n=Hn(r,"opencode.json");if(!dp(n)){
|
|
1635
|
+
`),L({event:"acp_model_unsupported",provider:"copilot",model:t.model})),[...Wn.baseArgs]},yoloAssertion:"always-yolo",sessionIdentity:{verifyLoadedSession:t=>{op(t.requestedSessionId,t.env)},recheckSession:t=>{op(t.requestedSessionId,t.env)}}}});import{existsSync as dp,mkdirSync as _I,readFileSync as up,writeFileSync as lp}from"node:fs";import{join as Hn,resolve as yI}from"node:path";function mp(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 za(t,e,r={existsSync:dp,readFileSync:up}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=yI(e,s.sessiondir??e);for(let o of EI(i)){let a=TI(o,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(mp(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 EI(t){return[Hn(t,".opencode","opencode.jsonc"),Hn(t,"opencode.jsonc"),Hn(t,"opencode.json")]}function TI(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(wI(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function wI(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]!==`
|
|
1636
|
+
`;)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 fp(t,e={}){let r=Hn(t,".opencode"),n=Hn(r,"opencode.json");if(!dp(n)){_I(r,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return lp(n,o+`
|
|
1560
1637
|
`,"utf-8"),!0}let s;try{s=JSON.parse(up(n,"utf-8"))}catch{return console.log(cp.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(cp.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),mp(s.permission)||L({event:"opencode_yolo_override",provider:"opencode",config_path:n,user_permission:s.permission,message:`opencode.json has a user-set 'permission' value other than 'allow' \u2014 lmctl's YOLO contract is NOT in effect; turns may hang waiting on permission prompts. Set permission: "allow" or remove the key to restore YOLO.`}),i&&lp(n,JSON.stringify(s,null,2)+`
|
|
1561
|
-
`,"utf-8"),i}var cp,Qa=k(()=>{"use strict";V();cp={yellow:t=>t}});import{existsSync as el,readdirSync as
|
|
1638
|
+
`,"utf-8"),i}var cp,Qa=k(()=>{"use strict";V();cp={yellow:t=>t}});import{existsSync as el,readdirSync as vI,statSync as pp}from"node:fs";import{join as rr}from"node:path";import{createRequire as SI}from"node:module";function tl(){return Za===null&&(Za=SI(import.meta.url)("node:sqlite").DatabaseSync),Za}function hp(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalCacheWriteInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function gp(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 _p(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 yp(){let t=process.env.XDG_DATA_HOME||rr(H,".local","share"),e=process.env.XDG_CONFIG_HOME||rr(H,".config");return[rr(t,"opencode","opencode.db"),rr(e,"opencode","opencode.db")]}function bI(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let t=process.env.XDG_DATA_HOME||rr(H,".local","share"),e=rr(t,"lmplayer"),r=rr(e,"opencode-local.db"),n=[r];try{let s=vI(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>rr(e,i)).filter(i=>i!==r).sort((i,o)=>{try{return pp(o).mtimeMs-pp(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function II(t){return t==="lmplayer"?bI():yp()}function rl(t,e){let r=e?.dbPath!==void 0?[e.dbPath]:yp();for(let n of r){if(!el(n))continue;let s=new(tl())(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 Za,tn,xi=k(()=>{"use strict";xe();V();Za=null;tn=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=II(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>el(e))}openDb(e){if(!el(e))return null;let r=new(tl())(e,{open:!0,readOnly:!0});return r.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),r}async discoverSessions(){let e=[];for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1562
1639
|
s.time_created, s.time_updated
|
|
1563
1640
|
FROM session s
|
|
1564
1641
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",u=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
@@ -1572,73 +1649,73 @@ ${r}`:r}function Yf(t){let e=t.binaryPath||"codex",r=["app-server","--listen","s
|
|
|
1572
1649
|
WHERE s.id LIKE ?
|
|
1573
1650
|
ORDER BY s.time_updated DESC
|
|
1574
1651
|
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function Xn(t){return{id:t.id,onFailure:"non-fatal",applies:e=>t.value(e)!==void 0,run:async e=>{await e.sendRpc("session/set_config_option",{sessionId:e.sessionId,configId:t.configId,value:t.value(e)})},describeFailure:(e,r)=>{let n=t.value(e),s=r instanceof Error?r.message:String(r);return{event:"acp_config_option_failed",fields:{config_id:t.configId,value:n,error_message:s},stderrLine:`[acp] set_config_option(${t.configId}=${n}) failed: ${s}
|
|
1575
|
-
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var nl=k(()=>{"use strict"});import{spawn as
|
|
1652
|
+
`,warning:`${t.provider} ignored ${t.configId}=${n}: ${s}`,message:s}},successLog:e=>`acp: set_config_option(${t.configId}=${t.value(e)}) ok`}}var nl=k(()=>{"use strict"});import{spawn as xI}from"node:child_process";import{resolve as Ep}from"node:path";function qn(t){let e;try{e=xI(t.binaryPath??Er.binary,[...Er.baseArgs],{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:we(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=jn(e,{provider:"opencode"}),n=t.timeoutMs??5e3;return new Promise(s=>{let i=!1,o=(u,d=!0)=>{if(!i){if(i=!0,clearTimeout(c),e.removeListener("error",a),e.removeListener("exit",l),r.close(),!d){s(u);return}ie(e,{softDelayMs:100,killDelayMs:100}).finally(()=>s(u))}},a=u=>{o({status:"unavailable",reason:"spawn",error:u.message},!1)},l=(u,d)=>{o({status:"unavailable",reason:"handshake",error:`opencode ACP exited before verification (code=${String(u)}, signal=${String(d)})`},!1)};e.once("error",a),e.once("exit",l);let c=setTimeout(()=>{o({status:"unavailable",reason:"timeout"})},n);(async()=>{try{await r.sendRpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r.sendNotification("notifications/initialized");let u=await r.sendRpc("session/new",{cwd:t.cwd,mcpServers:[]}),d=tr(u);try{await r.sendRpc("session/set_config_option",{sessionId:d,configId:"model",value:t.model})}catch(m){o({status:"rejected",option:"model",value:t.model,error:m instanceof Error?m.message:String(m)});return}if(t.effort!==void 0)try{await r.sendRpc("session/set_config_option",{sessionId:d,configId:"effort",value:t.effort})}catch(m){o({status:"rejected",option:"effort",value:t.effort,error:m instanceof Error?m.message:String(m)});return}o({status:"verified"})}catch(u){o({status:"unavailable",reason:"handshake",error:u instanceof Error?u.message:String(u)})}})()})}var Er,sl=k(()=>{"use strict";V();Qa();xi();Un();_t();Pn();Ka();nl();Er={name:"opencode",binary:"opencode",baseArgs:["acp"],argv:()=>[...Er.baseArgs],preSpawn(t){try{fp(t.cwd)}catch(e){L({event:"opencode_config_install_failed",cwd:t.cwd,error_message:e instanceof Error?e.message:String(e)})}},sessionSetup:[Xn({id:"model",provider:"opencode",configId:"model",value:t=>t.model}),Xn({id:"effort",provider:"opencode",configId:"effort",value:t=>t.effort})],probe:qn,sessionIdentity:{verifyLoadedSession:t=>{let e=rl(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(Ep(e.directory)!==Ep(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(rl(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 kI}from"node:fs";import{readdir as AI}from"node:fs/promises";import{join as il,resolve as RI}from"node:path";function wp(t){let e=NI.exec(t);return e?e[0]:null}function LI(t){if(!t.includes("notifications/initialized"))return t;let e=t.split(/\r?\n/),r=[];for(let n=0;n<e.length;n++){let s=e[n];if(s.includes("Error handling notification")&&s.includes("notifications/initialized")){let i=[s],o=n;for(;o+1<e.length&&i.length<8&&(o++,i.push(e[o]),e[o].trim()!=="}"););let a=i.join(`
|
|
1576
1653
|
`);if(/\bcode:\s*-32601\b/.test(a)&&/Method not found[^]*notifications\/initialized/.test(a)){n=o;continue}}r.push(s)}return r.join(`
|
|
1577
|
-
`)}async function Tp(t,e){let r=
|
|
1578
|
-
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function Vn(t){return
|
|
1654
|
+
`)}async function Tp(t,e){let r=RI(e.KIMI_CODE_HOME??process.env.KIMI_CODE_HOME??il(H,".kimi-code")),n=il(r,"sessions"),s;try{s=await AI(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()&&kI(il(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 NI,ol,Gn,al=k(()=>{"use strict";V();xe();nl();NI=/runtime\s+\S+\s+does not exist in workspace\s+\S+/;ol=t=>t.permissionMode==="plan"?"plan":"auto";Gn={name:"kimi",binary:"kimi",baseArgs:["acp"],argv:()=>[...Gn.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:ol(t)})},describeFailure:(t,e)=>{let r=ol(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=${ol(t)}) ok`},Xn({id:"model",provider:"kimi",configId:"model",value:t=>t.model})],onExitFinalization(t){let e=wp(t.result);e!==null&&L({event:"kimi_runtime_dead",provider:"kimi",session_id:t.sessionId,matched_text:e})},filterExpectedStderr:LI,sessionIdentity:{verifyLoadedSession:async t=>{await Tp(t.requestedSessionId,t.env)},recheckSession:async t=>{await Tp(t.requestedSessionId,t.env)}}}});var Jn,vp=k(()=>{"use strict";Jn={name:"hermes",binary:"hermes",baseArgs:["acp"],argv(t){if(t.permissionMode==="plan")throw new Error('provider "hermes" does not support --permission-mode plan');return[...Jn.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}
|
|
1655
|
+
`,message:`Cannot set Hermes ACP model to ${String(t.model)}: ${r}`}},successLog:t=>`acp: set_model(modelId=${String(t.model)}) ok`}],sessionIdentity:{verifyLoadedSession:()=>{}}}});function Vn(t){return CI[t]}var CI,OI,Sp=k(()=>{"use strict";ip();ap();sl();al();vp();CI={gemini:Bn,copilot:Wn,opencode:Er,kimi:Gn,hermes:Jn};OI={gemini:{binary:Bn.binary,args:Bn.baseArgs},copilot:{binary:Wn.binary,args:Wn.baseArgs},opencode:{binary:Er.binary,args:Er.baseArgs},kimi:{binary:Gn.binary,args:Gn.baseArgs},hermes:{binary:Jn.binary,args:Jn.baseArgs}}});import{spawn as bp}from"node:child_process";import{existsSync as DI}from"node:fs";function Ip(t,e){let r=Vn(t)?.modeVocabulary;if(!r)throw new re(`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 re(`provider "${t}" has no ACP mode "${e}" (known: ${r.known.join(", ")}).`);if(!r.selectable.includes(e))throw new re(`provider "${t}" ACP mode "${e}" is not selectable by lmctl (selectable: ${r.selectable.join(", ")}).`)}function MI(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1579
1656
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1580
1657
|
${e}
|
|
1581
1658
|
|
|
1582
|
-
${r}`:r}function
|
|
1583
|
-
`),L({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=tr(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=tr(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=tr(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=tr(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function Np(t,e){let r=Vn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{Ip(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:v=>{o.push(v)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=Ap(r,e,a))}catch(v){return s(v instanceof Error?v:new Error(String(v)))}let d=bp(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),f=!1,g=!1,y=0,h=!1,p=!1;if(e.signal){if(e.signal.aborted)return f=!0,L({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ie(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{f=!0,L({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ie(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let _=e.sessionId||"",T=bi({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});T.setSessionId(_);let E=jn(d,{provider:e.tool,onEvent:v=>{y=Date.now(),xp(v)&&(p=!0),e.onEvent?.(v)},onNotification:v=>{y=Date.now(),T.processMessage(v)}}),{sendRpc:S,sendNotification:w}=E,b="";d.stderr?.on("data",v=>{b+=v.toString()}),d.on("error",v=>{E.close(v),L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:v.message,elapsed_ms:Date.now()-m}),s(new re(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${v.message}`,{cause:v}))}),d.on("exit",v=>{if(g=!0,E.close(new re(`ACP process exited with code ${String(v)}`)),f)return;let x=T.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:v}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-m,stopReason:x.stopReason,exitCode:v,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let I=LI(e.tool,b);L({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:v,stderr_tail:I.slice(0,500),elapsed_ms:Date.now()-m}),s(new Error(NI({tool:e.tool,exitCode:v,stderr:I})))}}),(async()=>{try{let v=await Rp({sendRpc:S,sendNotification:w,opts:e,outputProcessor:T});_=v.sessionId;let x=v.sessionResponse;await kp(r,a,{sessionId:_,response:x},S),T.beginTurn(),h=!0,Te(`acp: prompt sent (${t.length} chars)`);let I=await S("session/prompt",{sessionId:_,prompt:[{type:"text",text:t}]}),R=T.completeTurn(I);h=!1,Te(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),Zt(e.holdOpen,{isAborted:()=>f,hasChildExited:()=>g,isTurnInFlight:()=>h,lastEventAtMs:()=>y,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>p})}catch(v){ie(d).catch(()=>{}),s(v instanceof Error?v:new Error(String(v)))}})()})}async function Lp(t){let e=Vn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&Ip(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}=Ap(e,t,i),c=bp(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m=t.sessionId||"",f=null,g="";c.stderr?.on("data",v=>{g+=v.toString()});let y,h,p=bi({tool:t.tool,onDelta:v=>y?.(v),...e.isolateResult?{isolateResult:e.isolateResult}:{}});p.setSessionId(m);let _=jn(c,{provider:t.tool,onEvent:v=>{d.lastEventAtMs=Date.now(),xp(v)&&(d.backgroundJobLaunched=!0),h?.(v)},onNotification:v=>{d.lastEventAtMs=Date.now(),p.processMessage(v)}}),T=()=>new Error(`ACP bundle process (${t.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),E=[],S=()=>d.exited?Promise.resolve():new Promise(v=>{E.push(v)}),w=null;c.on("error",v=>{f=new re(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${v.message}`,{cause:v}),L({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:v.message,elapsed_ms:Date.now()-u}),_.close(v)}),c.on("exit",v=>{if(d.exited=!0,d.exitCode=v,_.close(new re(`ACP process exited with code ${String(v)}`)),!d.telemetryFired){d.telemetryFired=!0;let x=p.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:v})}if(w!==null){let x=w;w=null,x(T())}for(let x of E.splice(0))x()});try{let v=await Rp({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:p,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});m=v.sessionId,await kp(e,i,{sessionId:v.sessionId,response:v.sessionResponse},_.sendRpc)}catch(v){let x=f??(v instanceof Error?v:new Error(String(v)));throw ie(c).catch(()=>{}),x}let b=v=>new Promise(x=>{setTimeout(x,v).unref?.()});return{tool:t.tool,get sessionId(){return m},get completedTurns(){return d.completedTurns},async sendTurn(v,x={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw T();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:m,cwd:t.cwd,env:l}),d.exited)throw T();if(x.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,y=x.onDelta,h=x.onEvent;let I=Date.now();try{p.beginTurn(),Te(`acp: bundle prompt sent (${v.length} chars)`);let R=await new Promise(($,q)=>{w=q;let Q=()=>{p.cancelTurn(),_.sendNotification("session/cancel",{sessionId:m}),q(new Error("Aborted"))},be=x.signal;be?.addEventListener("abort",Q,{once:!0}),_.sendRpc("session/prompt",{sessionId:m,prompt:[{type:"text",text:v}]}).then(ye=>{be?.removeEventListener("abort",Q),$(ye)},ye=>{be?.removeEventListener("abort",Q),q(ye instanceof Error?ye:new Error(String(ye)))})});w=null;let M=p.completeTurn(R);d.turnInFlight=!1,d.completedTurns+=1,Te(`acp: bundle result received (${M.result.length} chars, stopReason=${M.stopReason})`);let N=s&&n.length>0?[...n]:void 0;return s=!1,{result:M.result,sessionId:M.sessionId,stopReason:M.stopReason,durationMs:Date.now()-I,sawActivity:M.sawActivity,...N!==void 0?{warnings:N}:{}}}catch(R){throw w=null,p.cancelTurn(),d.turnInFlight=!1,d.exited?T():R}finally{y=void 0,h=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(x=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let v=t.closeTimeoutMs??2e3;await Promise.race([S(),b(v)]),d.exited||await ie(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{})})()),d.closing}}}var ll=k(()=>{"use strict";V();yr();Pn();pi();Nt();V();_t();Un();Ka();Sp();al();sl();Un()});function le(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Dp(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=CI){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 OI(){let t=new Map;return(e,r)=>{DI(e,Dp(t,r))}}function DI(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 u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(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,u="";c&&(typeof c.command=="string"?u=c.command:typeof c.file_path=="string"?u=c.file_path:typeof c.path=="string"?u=c.path:typeof c.pattern=="string"?u=c.pattern:typeof c.url=="string"?u=c.url:u=le(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:le(u),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,u,d=i.content;if(typeof d=="string")u=`${d.split(`
|
|
1659
|
+
${r}`:r}function $I(t,e){return Vn(t)?.filterExpectedStderr?.(e)??e}function xp(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 kp(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&&Te(s.successLog(i))}catch(o){let a=s.describeFailure(i,o);if(L({event:a.event,provider:t.name,...a.fields}),a.stderrLine&&process.stderr.write(a.stderrLine),a.warning&&e.warnings.push(a.warning),s.onFailure==="fail-closed")throw new Error(a.message)}}}function Ap(t,e,r){let n=we(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(ke(e.tool,i,o),e.cwd&&!DI(e.cwd))throw L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),new re(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})});return{binary:s,spawnArgs:i,spawnEnv:n}}async function Rp(t){let{sendRpc:e,sendNotification:r,opts:n,outputProcessor:s}=t,i=t.strictSessionIdentity===!0;await e("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r("notifications/initialized");let o=n.sessionId||"",a;if(n.sessionId){let l;try{l=await e("session/load",{sessionId:n.sessionId,cwd:n.cwd,mcpServers:[]})}catch(c){if(i||n.requireResume)throw new Error(`Cannot resume session ${n.sessionId} via ACP: ${c instanceof Error?c.message:String(c)}`);process.stderr.write(`[acp] session/load failed for ${n.sessionId}, creating new session
|
|
1660
|
+
`),L({event:"acp_session_resume_fallback",provider:n.tool,session_id:n.sessionId,error_message:c instanceof Error?c.message:String(c)});let u=await e("session/new",{cwd:n.cwd,mcpServers:[]});return o=tr(u),s.setSessionId(o),{sessionId:o,sessionResponse:u}}if(i){let c=tr(l);if(c!==""&&c!==n.sessionId)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received "${c}"`);if(c===""){if(t.verifyLoadResponse===void 0)throw new Error(`ACP session/load did not return the requested session id: expected "${n.sessionId}", received none`);await t.verifyLoadResponse(l)}o=n.sessionId}else o=tr(l,n.sessionId);a=l,s.setSessionId(o)}else{let l=await e("session/new",{cwd:n.cwd,mcpServers:[]});o=tr(l),a=l,s.setSessionId(o)}return{sessionId:o,sessionResponse:a}}function Np(t,e){let r=Vn(e.tool);if(!r)return Promise.reject(new Error(`No ACP config for tool "${e.tool}"`));if(e.acpMode!==void 0)try{Ip(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:v=>{o.push(v)}}},l,c,u;try{({binary:l,spawnArgs:c,spawnEnv:u}=Ap(r,e,a))}catch(v){return s(v instanceof Error?v:new Error(String(v)))}let d=bp(l,c,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:u}),m=Date.now(),f=!1,g=!1,y=0,h=!1,p=!1;if(e.signal){if(e.signal.aborted)return f=!0,L({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),ie(d).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{f=!0,L({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-m}),ie(d).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let _=e.sessionId||"",T=bi({tool:e.tool,onDelta:e.onDelta,...r.isolateResult?{isolateResult:r.isolateResult}:{}});T.setSessionId(_);let E=jn(d,{provider:e.tool,onEvent:v=>{y=Date.now(),xp(v)&&(p=!0),e.onEvent?.(v)},onNotification:v=>{y=Date.now(),T.processMessage(v)}}),{sendRpc:S,sendNotification:w}=E,b="";d.stderr?.on("data",v=>{b+=v.toString()}),d.on("error",v=>{E.close(v),L({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:v.message,elapsed_ms:Date.now()-m}),s(new re(`Failed to spawn ${r.binary} ${r.baseArgs.join(" ")}: ${v.message}`,{cause:v}))}),d.on("exit",v=>{if(g=!0,E.close(new re(`ACP process exited with code ${String(v)}`)),f)return;let x=T.finalize();if(x!==null)r.onExitFinalization?.({...a,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:v}),n({result:x.result,sessionId:x.sessionId,durationMs:Date.now()-m,stopReason:x.stopReason,exitCode:v,sawActivity:x.sawActivity,...o.length>0?{warnings:o}:{}});else{let I=$I(e.tool,b);L({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:v,stderr_tail:I.slice(0,500),elapsed_ms:Date.now()-m}),s(new Error(MI({tool:e.tool,exitCode:v,stderr:I})))}}),(async()=>{try{let v=await Rp({sendRpc:S,sendNotification:w,opts:e,outputProcessor:T});_=v.sessionId;let x=v.sessionResponse;await kp(r,a,{sessionId:_,response:x},S),T.beginTurn(),h=!0,Te(`acp: prompt sent (${t.length} chars)`);let I=await S("session/prompt",{sessionId:_,prompt:[{type:"text",text:t}]}),R=T.completeTurn(I);h=!1,Te(`acp: result received (${R.result.length} chars, stopReason=${R.stopReason})`),Zt(e.holdOpen,{isAborted:()=>f,hasChildExited:()=>g,isTurnInFlight:()=>h,lastEventAtMs:()=>y,closeStdin:()=>{d.stdin?.end()},signal:e.signal,label:e.tool,wasBackgroundJobLaunched:()=>p})}catch(v){ie(d).catch(()=>{}),s(v instanceof Error?v:new Error(String(v)))}})()})}async function Lp(t){let e=Vn(t.tool);if(!e)throw new Error(`No ACP config for tool "${t.tool}"`);t.acpMode!==void 0&&Ip(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}=Ap(e,t,i),c=bp(o,a,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:l}),u=Date.now(),d={exited:!1,exitCode:null,lastEventAtMs:0,turnInFlight:!1,backgroundJobLaunched:!1,completedTurns:0,closed:!1,closing:null,telemetryFired:!1},m=t.sessionId||"",f=null,g="";c.stderr?.on("data",v=>{g+=v.toString()});let y,h,p=bi({tool:t.tool,onDelta:v=>y?.(v),...e.isolateResult?{isolateResult:e.isolateResult}:{}});p.setSessionId(m);let _=jn(c,{provider:t.tool,onEvent:v=>{d.lastEventAtMs=Date.now(),xp(v)&&(d.backgroundJobLaunched=!0),h?.(v)},onNotification:v=>{d.lastEventAtMs=Date.now(),p.processMessage(v)}}),T=()=>new Error(`ACP bundle process (${t.tool}) exited${d.exitCode!==null?` with code ${d.exitCode}`:""} after ${d.completedTurns} completed prompt(s); the bundle cannot continue`),E=[],S=()=>d.exited?Promise.resolve():new Promise(v=>{E.push(v)}),w=null;c.on("error",v=>{f=new re(`Failed to spawn ${e.binary} ${e.baseArgs.join(" ")}: ${v.message}`,{cause:v}),L({event:"transport_error",provider:t.tool,error_class:"TransportConnectionError",error_message:v.message,elapsed_ms:Date.now()-u}),_.close(v)}),c.on("exit",v=>{if(d.exited=!0,d.exitCode=v,_.close(new re(`ACP process exited with code ${String(v)}`)),!d.telemetryFired){d.telemetryFired=!0;let x=p.finalize();x!==null&&e.onExitFinalization?.({...i,sessionId:x.sessionId,result:x.result,stopReason:x.stopReason,exitCode:v})}if(w!==null){let x=w;w=null,x(T())}for(let x of E.splice(0))x()});try{let v=await Rp({sendRpc:_.sendRpc,sendNotification:_.sendNotification,opts:t,outputProcessor:p,strictSessionIdentity:!0,verifyLoadResponse:e.sessionIdentity===void 0?void 0:async x=>e.sessionIdentity.verifyLoadedSession({...i,requestedSessionId:t.sessionId,loadResponse:x,cwd:t.cwd,env:l})});m=v.sessionId,await kp(e,i,{sessionId:v.sessionId,response:v.sessionResponse},_.sendRpc)}catch(v){let x=f??(v instanceof Error?v:new Error(String(v)));throw ie(c).catch(()=>{}),x}let b=v=>new Promise(x=>{setTimeout(x,v).unref?.()});return{tool:t.tool,get sessionId(){return m},get completedTurns(){return d.completedTurns},async sendTurn(v,x={}){if(d.closed||d.closing!==null)throw new Error(`ACP bundle session (${t.tool}) is closed`);if(d.exited)throw T();if(d.turnInFlight)throw new Error(`ACP bundle session (${t.tool}) has a turn still in flight \u2014 a stalled turn poisons the bundle; close it instead of sending`);if(x.signal?.aborted)throw new Error("Aborted");if(e.sessionIdentity?.recheckSession!==void 0){if(await e.sessionIdentity.recheckSession({requestedSessionId:m,cwd:t.cwd,env:l}),d.exited)throw T();if(x.signal?.aborted)throw new Error("Aborted")}d.turnInFlight=!0,y=x.onDelta,h=x.onEvent;let I=Date.now();try{p.beginTurn(),Te(`acp: bundle prompt sent (${v.length} chars)`);let R=await new Promise(($,q)=>{w=q;let Q=()=>{p.cancelTurn(),_.sendNotification("session/cancel",{sessionId:m}),q(new Error("Aborted"))},be=x.signal;be?.addEventListener("abort",Q,{once:!0}),_.sendRpc("session/prompt",{sessionId:m,prompt:[{type:"text",text:v}]}).then(ye=>{be?.removeEventListener("abort",Q),$(ye)},ye=>{be?.removeEventListener("abort",Q),q(ye instanceof Error?ye:new Error(String(ye)))})});w=null;let M=p.completeTurn(R);d.turnInFlight=!1,d.completedTurns+=1,Te(`acp: bundle result received (${M.result.length} chars, stopReason=${M.stopReason})`);let N=s&&n.length>0?[...n]:void 0;return s=!1,{result:M.result,sessionId:M.sessionId,stopReason:M.stopReason,durationMs:Date.now()-I,sawActivity:M.sawActivity,...N!==void 0?{warnings:N}:{}}}catch(R){throw w=null,p.cancelTurn(),d.turnInFlight=!1,d.exited?T():R}finally{y=void 0,h=void 0}},close(){return d.closing!==null||(d.closing=(async()=>{if(d.closed=!0,d.exited||(t.holdOpen!==void 0?await new Promise(x=>{Zt(t.holdOpen,{isAborted:()=>!1,hasChildExited:()=>d.exited,isTurnInFlight:()=>d.turnInFlight,lastEventAtMs:()=>d.lastEventAtMs,closeStdin:()=>{c.stdin?.end(),x()},label:t.tool,wasBackgroundJobLaunched:()=>d.backgroundJobLaunched})}):c.stdin?.end(),d.exited))return;let v=t.closeTimeoutMs??2e3;await Promise.race([S(),b(v)]),d.exited||await ie(c,{stdinEnd:!1,softDelayMs:Math.min(1e3,v),killDelayMs:Math.min(1e3,v)}).catch(()=>{})})()),d.closing}}}var ll=k(()=>{"use strict";V();yr();Pn();pi();Nt();V();_t();Un();Ka();Sp();al();sl();Un()});function le(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function Dp(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=FI){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 PI(){let t=new Map;return(e,r)=>{UI(e,Dp(t,r))}}function UI(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 u=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:u});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(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,u="";c&&(typeof c.command=="string"?u=c.command:typeof c.file_path=="string"?u=c.file_path:typeof c.path=="string"?u=c.path:typeof c.pattern=="string"?u=c.pattern:typeof c.url=="string"?u=c.url:u=le(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:le(u),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,u,d=i.content;if(typeof d=="string")u=`${d.split(`
|
|
1584
1661
|
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let m=d.map(f=>typeof f=="object"&&f&&"text"in f?f.text:"").filter(Boolean).join("");m&&(u=`${m.split(`
|
|
1585
|
-
`).length} lines, ${m.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function ki(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?
|
|
1662
|
+
`).length} lines, ${m.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function ki(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?PI():void 0;if(e.bundleSession!==void 0){let i=e.bundleSession;if(i.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${i.provider}", turn targets "${r}"`);let o=await i.sendTurn(t,{onDelta:e.onDelta,onEvent:n?a=>n(a,e.onProgress):void 0,signal:e.signal});return{text:o.text,sessionId:o.sessionId,durationMs:o.durationMs,...o.warnings!==void 0&&o.warnings.length>0?{warnings:o.warnings}:{}}}let s=await Hf(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 Ai(t){let e=t.binary==="qwen"?"qwen":"claude",r=await Xf({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs,sessionFileRoots:t.sessionFileRoots});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s={}){let i=await r.sendTurn(n,{onText:s.onDelta,onEvent:s.onEvent,signal:s.signal});return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>r.close()}}function jI(){let t=new Map;return(e,r)=>{BI(e,Dp(t,r))}}function BI(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:"",u=c?`running\u2026 ${le(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:i})}}function Cp(t,e){if(e!==void 0)return t===""&&!e?"empty":void 0}async function yt(t,e){let r=e.acpTool||e.binary,n=e.onProgress?jI():void 0;if(e.bundleSession!==void 0){let a=e.bundleSession;if(a.provider!==r)throw new Error(`bundle session provider mismatch: session serves "${a.provider}", turn targets "${r}"`);let l=await a.sendTurn(t,{onDelta:e.onDelta,onEvent:n?c=>n(c,e.onProgress):void 0,signal:e.signal});return{text:l.text,sessionId:l.sessionId,durationMs:l.durationMs,stopReason:l.stopReason,...Cp(l.text,l.sawActivity)!==void 0?{status:"empty"}:{},...l.warnings!==void 0?{warnings:l.warnings}:{}}}let s=[];if(e.model&&r==="copilot"){let a="copilot --acp does not implement per-session model selection";Ie({event:"model_ignored",provider:r,model:e.model,reason:a}),s.push(`copilot ignored model=${e.model}: ${a}`)}let i=await Np(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,...Cp(i.result,i.sawActivity)!==void 0?{status:"empty"}:{},...o.length>0?{warnings:o}:{}}}async function Et(t){let e=t.acpTool||t.binary,r=await Lp({tool:e,sessionId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,effort:t.effort,alias:t.alias,permissionMode:t.permissionMode,acpMode:t.acpMode,requireResume:!0,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:e,get sessionId(){return r.sessionId},get completedTurns(){return r.completedTurns},async sendTurn(n,s){let i=await r.sendTurn(n,s);return{text:i.result,sessionId:i.sessionId,durationMs:i.durationMs,stopReason:i.stopReason,...i.warnings!==void 0?{warnings:i.warnings}:{}}},close:()=>r.close()}}function Op(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 u=s.exitCode,d=s.status||"",m=typeof s.durationMs=="number"?s.durationMs:void 0,f=typeof u=="number"?`exit ${u}`:d||"done",g=[];typeof u=="number"?g.push(`exit ${u}`):d&&g.push(d),typeof m=="number"&&g.push(`${Math.round(m/1e3)}s`),e({kind:"tool_result",summary:g.join(", ")||"done",status:f,elapsedMs:m,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(o){let l=s.changes,c=Array.isArray(l)?l.map(u=>u.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary: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 u=s.status||"done";e({kind:"tool_result",summary:u,status:u,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary: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(`
|
|
1586
1663
|
`).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(`
|
|
1587
|
-
`).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 Mp(t,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>Op(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await zf(t,{threadId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?n=>Op(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function $p(t){let e=await Qf({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var
|
|
1588
|
-
`);try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1589
|
-
`);v.includes("user.text")&&x&&(!b.id||!h.has(b.id))&&(_(x,"metadata"),b.id&&h.add(b.id))}for(let x of b.content)if(x.type==="input_text"&&typeof x.text=="string"&&x.text){let I=x.text.trim();c||(c=j(I,80)),u=j(I,80),Yn(s,g,{role:"user",timestamp:w,content:ee(I)})}continue}if(b.role==="assistant"&&b.content){for(let v of b.content)v.type==="output_text"&&typeof v.text=="string"&&v.text&&Yn(s,g,{role:"assistant",timestamp:w,content:ee(v.text),model:a});continue}if(b.role!=="user"&&b.role!=="assistant"&&b.content){for(let v of b.content)(v.type==="input_text"||v.type==="output_text")&&typeof v.text=="string"&&v.text&&Yn(s,g,{role:"system",timestamp:w,content:ee(v.text.trim())});continue}}if(b.type==="function_call"){s.push({role:"tool_use",timestamp:w,content:b.name||"unknown tool",toolName:b.name,toolInput:b.arguments!==void 0?ee(rn(b.arguments)):void 0,toolInputData:
|
|
1590
|
-
`);v.trim()&&Yn(s,g,{role:"thinking",timestamp:w,content:ee(v)});continue}}if(S.type==="event_msg"&&S.payload&&(S.payload.type==="task_started"?(T(),f="in_progress"):S.payload.type==="task_complete"?f="complete":S.payload.type==="turn_aborted"&&(f="aborted"),S.payload.type==="user_message"&&typeof S.payload.message=="string"&&_(S.payload.message,"event"),S.payload.type==="agent_reasoning")){let b=S.payload.message||S.payload.text;b&&Yn(s,g,{role:"thinking",timestamp:w,content:ee(b)})}}if(!i)return null;T();let E=await jp(r);return{provider:"codex",sessionId:d,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:m,turnStatus:f,firstUserMessage:c,lastUserMessage:u,messageCount:E.messageCount,filePath:r,totalInputTokens:E.totalInputTokens||void 0,totalCachedInputTokens:E.totalCachedInputTokens||void 0,totalOutputTokens:E.totalOutputTokens||void 0,totalReasoningOutputTokens:E.totalReasoningOutputTokens||void 0,lastInputTokens:E.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:E.lastTokenUsage,modelContextWindow:E.modelContextWindow,messages:s,userPrompts:y}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await
|
|
1664
|
+
`).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 Mp(t,e){if(e.bundleSession!==void 0){let n=e.bundleSession;if(n.provider!=="codex")throw new Error(`bundle session provider mismatch: session serves "${n.provider}", turn targets "codex"`);let s=await n.sendTurn(t,{onDelta:e.onDelta,onEvent:e.onProgress?i=>Op(i,e.onProgress):void 0,signal:e.signal});return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}}let r=await zf(t,{threadId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,alias:e.alias,isLead:e.isLead,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:e.onProgress?n=>Op(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}async function $p(t){let e=await Qf({threadId:t.sessionId,cwd:t.cwd,env:t.env,binaryPath:t.progPath,model:t.model,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,closeTimeoutMs:t.closeTimeoutMs});return{provider:"codex",get sessionId(){return e.sessionId},get completedTurns(){return e.completedTurns},async sendTurn(r,n){let s=await e.sendTurn(r,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs}},close:()=>e.close()}}var FI,Lt=k(()=>{"use strict";qa();qa();Zf();ll();V();FI=256});import{join as Fp}from"node:path";function dl(t){return new cl(t)}var cl,ul=k(()=>{"use strict";Sf();Xe();xe();Lt();Oe();cl=class extends te{claudeDir;constructor(e){super({provider:new li(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",J,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:ki}),this.claudeDir=e?.claudeDir??Fp(H,".claude")}openSession(e){return Ai({...e,binary:"claude",sessionFileRoots:e.sessionFileRoots??[Fp(this.claudeDir,"projects")]})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as WI,stat as Pp,unlink as HI}from"node:fs/promises";import{join as Kn,basename as XI}from"node:path";function qI(t,e,r){return`${t}|${e.toISOString()}|${r}`}function Yn(t,e,r){let n=qI(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function Up(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function GI(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 rn(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 rn(r)}).filter(r=>r.length>0).join(`
|
|
1665
|
+
`);try{return JSON.stringify(t)}catch{return String(t)}}function JI(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 VI(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 jp(t){let e=0,r=0,n=0,s=0,i=0,o,a,l;for await(let c of ce(t)){if(c.type==="event_msg"&&c.payload?.type==="user_message"){let u=c.payload.message||c.payload.text;u&&(l=j(u.trim(),80))}if(c.type==="response_item"&&c.payload){let u=c.payload;if(u.type==="message"&&u.role==="user"&&u.content)for(let d of u.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&(e++,l=j(d.text.trim(),80));else if(u.type==="message"&&u.role==="assistant"&&u.content)for(let d of u.content)d.type==="output_text"&&typeof d.text=="string"&&d.text&&e++}if(c.payload&&typeof c.payload.model_context_window=="number"&&(a=c.payload.model_context_window),c.type==="event_msg"&&c.payload?.type==="token_count"&&c.payload.info?.total_token_usage){let u=c.payload.info.total_token_usage;r=u.input_tokens??r,n=u.cached_input_tokens??u.cache_read_input_tokens??n,s=u.output_tokens??s,i=u.reasoning_output_tokens??i;let d=GI(c.payload.info.last_token_usage);d&&(o=d),typeof c.payload.info.model_context_window=="number"&&(a=c.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:r,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:i,lastTokenUsage:o,modelContextWindow:a,lastUserMessage:l}}var Ri,Bp=k(()=>{"use strict";xe();Ri=class{name="codex";codexDirs;constructor(e={}){let r=[Kn(H,".codex"),Kn(H,".code")];if(e.codexDirs&&e.codexDirs.length>0){this.codexDirs=[...new Set(e.codexDirs)];return}let n=[e.codexDir||r[0],e.codeDir||r[1]];this.codexDirs=[...new Set(n)]}getWatchPaths(){return this.codexDirs.map(e=>({directory:Kn(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=Kn(r,"sessions");try{await Pp(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 WI(e)}catch{return r}for(let s of n){let i=Kn(e,s),o=await Pp(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=XI(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 He(e,30),n=await de(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,u,d,m;for(let g of r){if(g.type==="session_meta"&&g.payload&&(g.payload.id&&(s=g.payload.id),g.payload.cwd&&(i=g.payload.cwd),g.payload.cli_version&&(o=g.payload.cli_version),g.payload.timestamp&&(l=new Date(g.payload.timestamp)),g.payload.originator&&(d=g.payload.originator),g.payload.source&&(m=g.payload.source)),g.type==="turn_context"&&g.payload&&(g.payload.model&&(a=g.payload.model),!i&&g.payload.cwd&&(i=g.payload.cwd)),g.type==="event_msg"&&g.payload?.type==="user_message"){let y=g.payload.message||g.payload.text;y&&(c||(c=j(y.trim(),80)),u=j(y.trim(),80))}if(g.type==="response_item"&&g.payload?.type==="message"&&g.payload.role==="user"&&g.payload.content){let y=g.payload.content.find(h=>h.type==="input_text"&&typeof h.text=="string"&&h.text);typeof y?.text=="string"&&(c||(c=j(y.text.trim(),80)),u=j(y.text.trim(),80))}}if(!i)return null;let f=await jp(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:Up(d,m),firstUserMessage:c,lastUserMessage:f.lastUserMessage??u,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCachedInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,totalReasoningOutputTokens:f.totalReasoningOutputTokens||void 0,lastInputTokens:f.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:f.lastTokenUsage,modelContextWindow:f.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await de(r),s=[],i="",o,a,l,c,u,d=e,m,f,g=new Set,y=[],h=new Set,p=[],_=(S,w)=>{let b=p.find(v=>!v.mirrored&&v.source!==w&&v.text===S);b?b.mirrored=!0:p.push({text:S,source:w,mirrored:!1})},T=()=>{y.push(...p.map(S=>S.text)),p=[]};for await(let S of ce(r)){let w=S.timestamp?new Date(S.timestamp):new Date;if(S.type==="session_meta"&&S.payload){S.payload.id&&(d=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)),m=Up(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 v=b.internal_chat_message_metadata_passthrough?.content_item_kinds;if(Array.isArray(v)){let x=b.content.filter((I,R)=>v[R]==="user.text"&&typeof I.text=="string").map(I=>I.text).join(`
|
|
1666
|
+
`);v.includes("user.text")&&x&&(!b.id||!h.has(b.id))&&(_(x,"metadata"),b.id&&h.add(b.id))}for(let x of b.content)if(x.type==="input_text"&&typeof x.text=="string"&&x.text){let I=x.text.trim();c||(c=j(I,80)),u=j(I,80),Yn(s,g,{role:"user",timestamp:w,content:ee(I)})}continue}if(b.role==="assistant"&&b.content){for(let v of b.content)v.type==="output_text"&&typeof v.text=="string"&&v.text&&Yn(s,g,{role:"assistant",timestamp:w,content:ee(v.text),model:a});continue}if(b.role!=="user"&&b.role!=="assistant"&&b.content){for(let v of b.content)(v.type==="input_text"||v.type==="output_text")&&typeof v.text=="string"&&v.text&&Yn(s,g,{role:"system",timestamp:w,content:ee(v.text.trim())});continue}}if(b.type==="function_call"){s.push({role:"tool_use",timestamp:w,content:b.name||"unknown tool",toolName:b.name,toolInput:b.arguments!==void 0?ee(rn(b.arguments)):void 0,toolInputData:JI(b.arguments),toolCallId:b.call_id});continue}if(b.type==="function_call_output"){s.push({role:"tool_result",timestamp:w,content:ee(rn(b.output)),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call"){s.push({role:"tool_use",timestamp:w,content:b.name||"unknown tool",toolName:b.name,toolInput:b.input!==void 0?ee(rn(b.input)):void 0,toolInputData:VI(b.name,b.input),toolCallId:b.call_id});continue}if(b.type==="custom_tool_call_output"){s.push({role:"tool_result",timestamp:w,content:ee(rn(b.output)),toolCallId:b.call_id});continue}if(b.type==="reasoning"&&b.summary){let v=b.summary.map(x=>rn(x.text)).join(`
|
|
1667
|
+
`);v.trim()&&Yn(s,g,{role:"thinking",timestamp:w,content:ee(v)});continue}}if(S.type==="event_msg"&&S.payload&&(S.payload.type==="task_started"?(T(),f="in_progress"):S.payload.type==="task_complete"?f="complete":S.payload.type==="turn_aborted"&&(f="aborted"),S.payload.type==="user_message"&&typeof S.payload.message=="string"&&_(S.payload.message,"event"),S.payload.type==="agent_reasoning")){let b=S.payload.message||S.payload.text;b&&Yn(s,g,{role:"thinking",timestamp:w,content:ee(b)})}}if(!i)return null;T();let E=await jp(r);return{provider:"codex",sessionId:d,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:m,turnStatus:f,firstUserMessage:c,lastUserMessage:u,messageCount:E.messageCount,filePath:r,totalInputTokens:E.totalInputTokens||void 0,totalCachedInputTokens:E.totalCachedInputTokens||void 0,totalOutputTokens:E.totalOutputTokens||void 0,totalReasoningOutputTokens:E.totalReasoningOutputTokens||void 0,lastInputTokens:E.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:E.lastTokenUsage,modelContextWindow:E.modelContextWindow,messages:s,userPrompts:y}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await HI(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 He(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 pl(t){return new fl(t)}var ml,fl,hl=k(()=>{"use strict";Bp();Xe();Lt();Oe();ml="gpt-5.6-sol",fl=class extends te{constructor(e){super({provider:new Ri(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append"},binary:"codex",seedArgs:["exec","--dangerously-bypass-approvals-and-sandbox","--skip-git-repo-check","-"],seedStdin:`${J}
|
|
1591
1668
|
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Mp})}openSession(e){return $p({...e,model:e.model??ml})}seedArgsFor(e){let r=super.seedArgsFor(e),n=e?.model??ml;return[...r.slice(0,-1),"--model",n,r[r.length-1]]}turnOptsFor(e){return e.model?e:{...e,model:ml}}}});function zn(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 Ni(t){let e=zn(t);if(e==="unknown")throw new Error("gemini session content matches neither known format (old .json with messages[] or new .jsonl with kind metadata)");if(e==="json"){let a=JSON.parse(t);return{sessionId:a.sessionId,projectHash:a.projectHash,startTime:a.startTime,lastUpdated:a.lastUpdated,kind:a.kind,messages:Array.isArray(a.messages)?a.messages:[]}}let r=t.split(`
|
|
1592
|
-
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let u=c;if(typeof u.id=="string"){let d=o.get(u.id);d?
|
|
1669
|
+
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let u=c;if(typeof u.id=="string"){let d=o.get(u.id);d?KI(d,u):(i.push(u),o.set(u.id,u))}else i.push(u)}}return{sessionId:typeof s.sessionId=="string"?s.sessionId:void 0,projectHash:typeof s.projectHash=="string"?s.projectHash:void 0,startTime:typeof s.startTime=="string"?s.startTime:void 0,lastUpdated:typeof s.lastUpdated=="string"?s.lastUpdated:void 0,kind:typeof s.kind=="string"?s.kind:void 0,messages:i}}function KI(t,e){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="tokens"&&Wp(t.tokens)&&Wp(n)){t.tokens={...t.tokens,...n};continue}t[r]=n}}function Wp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Hp(t,e){if(e==="json")return JSON.stringify(t,null,2);let{messages:r,...n}=t,s=[JSON.stringify(n)];for(let i of r)s.push(JSON.stringify(i));return s.join(`
|
|
1593
1670
|
`)+`
|
|
1594
|
-
`}var gl=k(()=>{"use strict"});import{createHash as
|
|
1595
|
-
`).trim();b&&i.push({role:"thinking",timestamp:Tr(w.timestamp,_),content:ee(b)})}i.push({role:"assistant",timestamp:_,content:E,model:p.model});continue}let S=T?`[${T}] `:"";i.push({role:"system",timestamp:_,content:`${S}${E}`.trim()})}let g=Tr(n.startTime,s.createdAt),y=Tr(n.lastUpdated,s.modifiedAt),h=Gp(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:g,modifiedAt:y,model:f,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await de(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,u,d=0;for(let f of s)if(qp(f.type)){d++;let g=_l(f.content).trim();g&&(l||(l=j(ee(g),80)),c=j(ee(g),80))}else yl(f.type)&&(d++,f.model&&(u=f.model));let m=Gp(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Tr(r.startTime,n.createdAt),modifiedAt:Tr(r.lastUpdated,n.modifiedAt),model:u,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async readSessionFile(e){let r=await Xp(e,"utf-8");if(zn(r)==="unknown")return L({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.slice(0,120),message:`gemini session file at ${e} matches neither old (.json with messages[]) nor new (.jsonl with kind metadata) format. Skipping; lmctl ls / audit / stats will not see this session.`}),null;try{return Ni(r)}catch{return null}}extractSessionIdFromFilename(e){let r=
|
|
1596
|
-
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:di,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=
|
|
1597
|
-
`)){let n=r.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function wr(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function
|
|
1598
|
-
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;r.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function
|
|
1599
|
-
`).trim():""}function nh(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function
|
|
1600
|
-
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return vr(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 Zp(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=vr(this.sessionsDir,s.name),o;try{o=await Zp(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=vr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Qp(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:Rl(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:vr(r,"state.json"),wirePath:vr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!th(e)||
|
|
1671
|
+
`}var gl=k(()=>{"use strict"});import{createHash as YI}from"node:crypto";import{readdir as Qn,readFile as Xp,stat as Li,unlink as zI}from"node:fs/promises";import{join as qe,basename as QI,dirname as ZI}from"node:path";import{cwd as ex}from"node:process";function _l(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function qp(t){return t==="user"}function yl(t){return t==="gemini"||t==="assistant"}function Tr(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function tx(t){return`${t.sessionId}\0${t.cwd}`}function rx(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 Ci(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function Gp(t){let e=0,r=0,n=0,s=0,i=0,o;for(let a of t){if(!yl(a.type)||!a.tokens)continue;let l=Ci(a.tokens.input),c=Ci(a.tokens.cached),u=Math.max(l-c,0),d=Ci(a.tokens.output),m=Ci(a.tokens.thoughts);e+=l,r+=c,n+=d,s+=m,i=l,o={inputTokens:u,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:d,reasoningOutputTokens:m,totalTokens:l+d+m}}return{totalInputTokens:e,totalCachedInputTokens:r,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function nx(t){return YI("sha256").update(t).digest("hex")}function Zn(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=ZI(r);if(n===r)break;r=n}}var Oi,Jp=k(()=>{"use strict";xe();gl();V();Oi=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||qe(H,".gemini");this.geminiProjectsFile=qe(r,"projects.json"),this.geminiTmpDir=qe(r,"tmp");let n=e.claudeDir||qe(H,".claude");this.claudeProjectsDir=qe(n,"projects");let s=[qe(H,".codex"),qe(H,".code")],i=e.codexDirs&&e.codexDirs.length>0?e.codexDirs:[e.codexDir||s[0],e.codeDir||s[1]];this.codexSessionDirs=[...new Set(i)].map(o=>qe(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=tx(s),o=r.get(i);r.set(i,o?rx(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 de(r),i=[],o=[],a=n.messages||[],l=n.sessionId||this.extractSessionIdFromFilename(r),c=n.projectHash||"",u=await this.resolveWorkspace(c),d,m,f;for(let p of a){let _=Tr(p.timestamp),T=p.type,E=ee(_l(p.content));if(qp(T)){let w=_l(p.content);w&&o.push(w);let b=E.trim();b&&(d||(d=j(b,80)),m=j(b,80)),i.push({role:"user",timestamp:_,content:b||E});continue}if(yl(T)){p.model&&(f=p.model);for(let w of p.thoughts||[]){let b=[w.subject,w.description].filter(Boolean).join(`
|
|
1672
|
+
`).trim();b&&i.push({role:"thinking",timestamp:Tr(w.timestamp,_),content:ee(b)})}i.push({role:"assistant",timestamp:_,content:E,model:p.model});continue}let S=T?`[${T}] `:"";i.push({role:"system",timestamp:_,content:`${S}${E}`.trim()})}let g=Tr(n.startTime,s.createdAt),y=Tr(n.lastUpdated,s.modifiedAt),h=Gp(a);return{provider:"gemini",sessionId:l,cwd:u,createdAt:g,modifiedAt:y,model:f,startCommand:"gemini",firstUserMessage:d,lastUserMessage:m,messageCount:i.filter(p=>p.role==="user"||p.role==="assistant").length,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i,userPrompts:o}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await de(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,u,d=0;for(let f of s)if(qp(f.type)){d++;let g=_l(f.content).trim();g&&(l||(l=j(ee(g),80)),c=j(ee(g),80))}else yl(f.type)&&(d++,f.model&&(u=f.model));let m=Gp(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Tr(r.startTime,n.createdAt),modifiedAt:Tr(r.lastUpdated,n.modifiedAt),model:u,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastInputTokens||void 0,lastTokenUsage:m.lastTokenUsage}}async readSessionFile(e){let r=await Xp(e,"utf-8");if(zn(r)==="unknown")return L({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.slice(0,120),message:`gemini session file at ${e} matches neither old (.json with messages[]) nor new (.jsonl with kind metadata) format. Skipping; lmctl ls / audit / stats will not see this session.`}),null;try{return Ni(r)}catch{return null}}extractSessionIdFromFilename(e){let r=QI(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 Qn(this.geminiTmpDir)}catch{return e}for(let n of r){let s=qe(this.geminiTmpDir,n,"chats");if(!(await Li(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Qn(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(qe(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await zI(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){let i=await this.readSessionFile(s).catch(()=>null),o=this.extractSessionIdFromFilename(s),a=i?.sessionId||o,l=a===e||a.startsWith(e),c=o===e||o.startsWith(e)||o.length>=8&&e.startsWith(o);if(!l&&!c)continue;let u=await de(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:Tr(i?.lastUpdated,u.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;Zn(e,ex());for(let n of this.extraWorkspacePaths)Zn(e,n);for(let n of await this.collectGeminiProjectPaths())Zn(e,n);for(let n of await this.collectCodexCwds())Zn(e,n);for(let n of await this.collectClaudeCwds())Zn(e,n);let r=new Map;for(let n of e)r.set(nx(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await Xp(this.geminiProjectsFile,"utf-8")}catch{return[]}try{let n=JSON.parse(e).projects;return!n||typeof n!="object"||Array.isArray(n)?[]:Object.keys(n)}catch{return[]}}async collectCodexCwds(){let e=new Set;for(let r of this.codexSessionDirs){let n=await this.findJsonlFiles(r);for(let s of n){let o=(await He(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await Qn(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=qe(this.claudeProjectsDir,n);if(!(await Li(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await Qn(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=qe(s,a),u=(await He(l,1).catch(()=>[]))[0]?.cwd;u&&e.add(u)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await Li(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await Qn(e)}catch{return r}for(let i of s){let o=qe(e,i),a=await Li(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 sx,writeFileSync as ix,mkdirSync as ox}from"node:fs";import{join as ax,dirname as lx}from"node:path";import{randomUUID as cx}from"node:crypto";function Tl(t){return new El(t)}var El,wl=k(()=>{"use strict";Jp();Xe();Lt();Oe();gl();El=class extends te{geminiDir;constructor(e){super({provider:new Oi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!0,forkSupport:"automatic",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",J,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>yt(r,{...n,acpTool:"gemini"})}),this.geminiDir=e?.geminiDir}openSession(e){return Et({...e,env:this.geminiDir!==void 0?{...e.env??process.env,GEMINI_DIR:this.geminiDir}:e.env,binary:"gemini",acpTool:"gemini"})}forkHint(e){return["Gemini fork: copies the session file with a new ID.","The forked session has the same conversation history","but diverges from that point forward."].join(`
|
|
1673
|
+
`)}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:di,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=sx(n,"utf-8"),i=zn(s),o=Ni(s),a=cx();o.sessionId=a,o.kind="main";let l=lx(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=i==="jsonl"?".jsonl":".json",d=`session-${c}-${a.slice(0,8)}${u}`,m=ax(l,d);return ox(l,{recursive:!0}),ix(m,Hp(o,i),"utf-8"),{success:!0,sessionId:a,filePath:m}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as Vp,readFile as dx,rm as ux,stat as nn}from"node:fs/promises";import{basename as mx,join as at}from"node:path";function fx(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 vl(){return{shutdownTotals:null,assistantOutputSum:0}}function Yp(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=fx(e.data?.modelMetrics);r&&(t.shutdownTotals=r)}}function Kp(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 px(t){let e={};for(let r of t.split(`
|
|
1674
|
+
`)){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 wr(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function hx(t){let e=0,r=vl(),n;for await(let s of ce(t)){if(s.type==="user.message"){e++;let i=(s.data?.content||"").trim();i&&(n=j(i,80))}else s.type==="assistant.message"&&(s.data?.content||"").trim()&&e++;Yp(r,s)}return{messageCount:e,tokens:r,lastUserMessage:n}}function gx(t){let e=_x(t),r=new Map;for(let n of t){if(n.role!=="tool_use"||n.toolCallId===void 0)continue;if(n.toolName==="bash"){let l=e.get(n.toolCallId),u=[l?.content,l?.toolDetailedContent].filter(m=>typeof m=="string").join(`
|
|
1675
|
+
`).match(/<command (?:started in (?:detached )?background with|with) shellId:\s*([^>\s]+)/i)?.[1];if(u===void 0)continue;let d=`copilot-shell:${u}:${n.toolCallId}`;r.set(u,d),n.backgroundTaskId=d,l!==void 0&&(l.backgroundTaskId=d);continue}if(!["read_bash","write_bash","stop_bash"].includes(n.toolName??""))continue;let s=n.toolInputData?.shellId;if(typeof s!="string"&&typeof s!="number")continue;let i=String(s),o=r.get(i);if(o===void 0)continue;n.backgroundTaskId=o;let a=e.get(n.toolCallId);a!==void 0&&(a.backgroundTaskId=o)}}function _x(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 Di,zp=k(()=>{"use strict";xe();Di=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||at(H,".copilot");this.sessionStateDir=at(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Vp(this.sessionStateDir)}catch{return e}for(let n of r){let s=at(this.sessionStateDir,n);if((await nn(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=at(r,"events.jsonl"),i=await nn(s).catch(()=>null),o=i?s:at(r,"workspace.yaml"),a=await de(i?s:r),l=[],c=[],u=n?.cwd||"(unknown workspace)",d,m,f,g,y,h,p=n?.id||mx(r)||e,_=vl();if(i)for await(let T of ce(s)){let E=wr(T.timestamp)||a.modifiedAt;if(Yp(_,T),T.type==="session.start"&&T.data){T.data.sessionId&&(p=T.data.sessionId),T.data.copilotVersion&&(m=T.data.copilotVersion),T.data.startTime&&(h=wr(T.data.startTime)),T.data.selectedModel&&(d=T.data.selectedModel),T.data.context&&(T.data.context.cwd&&(u=T.data.context.cwd),T.data.context.branch&&(f=T.data.context.branch));continue}if(T.type==="session.model_change"&&T.data?.newModel){d=T.data.newModel;continue}if(T.type==="user.message"&&T.data){let S=T.data.content||"";S&&c.push(S);let w=S.trim();w&&(g||(g=j(w,80)),y=j(w,80)),l.push({role:"user",timestamp:E,content:ee(w||S)});continue}if(T.type==="assistant.message"&&T.data){let S=(T.data.content||"").trim();if(S&&l.push({role:"assistant",timestamp:E,content:ee(S),model:d}),T.data.toolRequests)for(let w of T.data.toolRequests)l.push({role:"tool_use",timestamp:E,content:w.name||"unknown tool",toolName:w.name,toolInput:w.arguments?JSON.stringify(w.arguments,null,2):void 0,toolInputData:Qe(w.arguments),toolCallId:w.toolCallId});continue}if(T.type==="tool.execution_complete"&&T.data){let S=T.data.result?.content||"",w=T.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:E,content:ee(S),toolDetailedContent:w?ee(w):void 0,toolCallId:T.data.toolCallId});continue}if(T.type==="assistant.reasoning"&&T.data?.content){l.push({role:"thinking",timestamp:E,content:ee(T.data.content)});continue}if(T.type==="session.error"||T.type==="session.warning"||T.type==="session.info"||T.type==="system.message"){let S=T.data?.message||"";S.trim()&&l.push({role:"system",timestamp:E,content:ee(S)});continue}}if(!g){let T=(n?.summary||"").trim();T&&(g=j(T,80))}return gx(l),{provider:"copilot",sessionId:p,cwd:u,createdAt:h??wr(n?.created_at)??a.createdAt,modifiedAt:wr(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",gitBranch:f,firstUserMessage:g,lastUserMessage:y,messageCount:l.filter(T=>T.role==="user"||T.role==="assistant").length,filePath:o,...Kp(_),messages:l,userPrompts:c}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=at(e,"events.jsonl"),i=await nn(s).catch(()=>null),o=i?s:at(e,"workspace.yaml"),a=await de(i?s:e),l=i?await He(s,20):[],c=n?.id||r,u=n?.cwd||"(unknown workspace)",d,m,f,g,y;for(let p of l)if(p.type==="session.start"&&p.data&&(p.data.sessionId&&(c=p.data.sessionId),p.data.copilotVersion&&(m=p.data.copilotVersion),p.data.startTime&&(f=wr(p.data.startTime)),p.data.selectedModel&&(d=p.data.selectedModel),p.data.context?.cwd&&(u=p.data.context.cwd)),p.type==="session.model_change"&&p.data?.newModel&&(d||(d=p.data.newModel)),p.type==="user.message"&&p.data){let _=(p.data.content||"").trim();_&&(g||(g=j(_,80)),y=j(_,80))}if(!g){let p=(n?.summary||"").trim();p&&(g=j(p,80))}let h=i?await hx(s):{messageCount:0,tokens:vl()};return{provider:"copilot",sessionId:c,cwd:u,createdAt:f??wr(n?.created_at)??a.createdAt,modifiedAt:wr(n?.updated_at)??a.modifiedAt,model:d,cliVersion:m,startCommand:"copilot",firstUserMessage:g,lastUserMessage:h.lastUserMessage??y,messageCount:h.messageCount,filePath:o,...Kp(h.tokens)}}async readWorkspaceYaml(e){let r=at(e,"workspace.yaml");try{let n=await dx(r,"utf-8");return px(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await ux(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await Vp(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=at(this.sessionStateDir,e);if((await nn(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=at(this.sessionStateDir,s);(await nn(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=at(this.sessionStateDir,s);if(!(await nn(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 bl(t){return new Sl(t)}var Sl,Il=k(()=>{"use strict";zp();Xe();Lt();V();Oe();Sl=class extends te{copilotDir;constructor(e){super({provider:new Di(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",J,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>yt(r,{...n,acpTool:"copilot"})}),this.copilotDir=e?.copilotDir}openSession(e){return Et({...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 Ie({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});function kl(){return new xl}var xl,Al=k(()=>{"use strict";xi();Xe();Lt();Oe();xl=class extends te{constructor(){super({provider:new tn,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",J],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>yt(e,{...r,acpTool:"opencode"})})}openSession(e){return Et({...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??J),r}}});import{appendFile as yx,mkdir as Ex,readFile as Qp,readdir as Zp,rm as Tx,stat as eh}from"node:fs/promises";import{basename as wx,dirname as vx,isAbsolute as th,join as vr,relative as Sx,resolve as Rl}from"node:path";function Nl(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}function kx(t){return typeof t=="number"?new Date(t):Nl(t)??new Date(0)}function rh(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(`
|
|
1676
|
+
`).trim():""}function nh(t){if(t!==void 0)try{return JSON.stringify(t)}catch{return String(t)}}function Ax(t){return t&&typeof t=="object"&&"output"in t&&typeof t.output=="string"?t.output:nh(t)??""}function Rx(t){let e=Nx(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 Nx(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 bx,Ix,xx,Mi,sh=k(()=>{"use strict";xe();bx="1.4",Ix="1.5",xx=new Set([bx,Ix]),Mi=class{name="kimi";homeDir;sessionsDir;constructor(e){this.homeDir=Rl(e?.kimiHome??process.env.KIMI_CODE_HOME??vr(H,".kimi-code")),this.sessionsDir=vr(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 Tx(r.sessionDir,{recursive:!0,force:!0}),await Ex(vx(this.indexPath()),{recursive:!0,mode:448}),await yx(this.indexPath(),`${JSON.stringify({sessionId:r.sessionId,deleted:!0})}
|
|
1677
|
+
`,"utf-8"),!0):!1}getWatchPaths(){return[{directory:this.sessionsDir,filePattern:/wire\.jsonl$/}]}indexPath(){return vr(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 Zp(this.sessionsDir,{withFileTypes:!0})}catch{return[...r.values()]}for(let s of n){if(!s.isDirectory())continue;let i=vr(this.sessionsDir,s.name),o;try{o=await Zp(i,{withFileTypes:!0})}catch{continue}for(let a of o){if(!a.isDirectory()||r.has(a.name))continue;let l=vr(i,a.name);r.set(a.name,this.filesFor(a.name,l))}}return[...r.values()]}async readIndex(){let e;try{e=await Qp(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:Rl(s.sessionDir),workDir:s.workDir})}catch{}return r}filesFor(e,r,n){return{sessionId:e,sessionDir:r,statePath:vr(r,"state.json"),wirePath:vr(r,"agents","main","wire.jsonl"),indexedWorkDir:n}}validSessionDir(e,r){if(!th(e)||wx(e)!==r)return!1;let n=Sx(this.sessionsDir,Rl(e));return n!==""&&n!==".."&&!n.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&!th(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 Qp(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 eh(e.wirePath)}catch{return null}let s=await eh(e.statePath).catch(()=>n),i=await this.parseWire(e.wirePath),o=Nl(r.createdAt)??s.birthtime,a=Nl(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?j(r.lastPrompt.trim(),80):void 0),messageCount:i.messageCount,filePath:e.wirePath,filePaths:[e.statePath,e.wirePath],totalInputTokens:i.totalInputTokens,totalCachedInputTokens:i.totalCachedInputTokens,totalCacheWriteInputTokens:i.totalCacheWriteInputTokens,totalOutputTokens:i.totalOutputTokens,lastInputTokens:i.lastInputTokens,lastTokenUsage:i.lastTokenUsage}}async parseWire(e){let r=[],n=[],s=new Set,i=!0,o,a,l,c=0,u=0,d=0,m=0,f=!1,g=0,y,h;for await(let p of ce(e)){let _=kx(p.time??p.created_at);if(i&&(i=!1,p.type==="metadata"&&!xx.has(p.protocol_version))){let E=`Kimi transcript wire protocol version ${JSON.stringify(p.protocol_version)} is not supported by this lmctl version.`;return{messages:[{role:"system",timestamp:_,content:E}],userPrompts:[],messageCount:1,firstUserMessage:E,lastUserMessage:E}}if((p.type==="config.update"||p.type==="profile.bind")&&p.modelAlias&&(o=p.modelAlias),p.type==="usage.record"){p.model&&(o=p.model),f||=p.usage!==void 0;let E=p.usage?.inputOther??0,S=p.usage?.inputCacheRead??0,w=p.usage?.inputCacheCreation??0,b=p.usage?.output??0;c+=E,u+=S,d+=w,m+=b,p.usageScope==="turn"&&(y=E+S+w,h={inputTokens:E,cachedInputTokens:S,cacheWriteInputTokens:w,outputTokens:b,totalTokens:y+b});continue}if(p.type==="turn.prompt"&&p.origin?.kind==="user"){let E=rh(p.input);E&&((!p.promptId||!s.has(p.promptId))&&(n.push(E),p.promptId&&s.add(p.promptId)),a??=j(E,80),l=j(E,80),r.push({role:"user",timestamp:_,content:E}),g++);continue}if(p.type==="turn.steer"){let E=rh(p.input);E&&(r.push({role:"system",timestamp:_,content:E}),g++);continue}if(p.type!=="context.append_loop_event"||!p.event)continue;let T=p.event;T.type==="content.part"&&T.part?.type==="text"&&T.part.text?(r.push({role:"assistant",timestamp:_,content:T.part.text,model:o}),g++):T.type==="content.part"&&T.part?.type==="think"&&T.part.think?r.push({role:"thinking",timestamp:_,content:T.part.think,model:o}):T.type==="tool.call"?r.push({role:"tool_use",timestamp:_,content:T.name??"tool",toolName:T.name,toolInput:nh(T.args),toolInputData:Qe(T.args),toolCallId:T.toolCallId,model:o}):T.type==="tool.result"&&r.push({role:"tool_result",timestamp:_,content:Ax(T.result),toolCallId:T.toolCallId,model:o})}return Rx(r),{messages:r,userPrompts:n,messageCount:g,model:o,firstUserMessage:a,lastUserMessage:l,totalInputTokens:f?c:void 0,totalCachedInputTokens:f?u:void 0,totalCacheWriteInputTokens:f?d:void 0,totalOutputTokens:f?m:void 0,lastInputTokens:y,lastTokenUsage:h}}}});function Cl(t){return new Ll(t)}var Ll,Ol=k(()=>{"use strict";sh();Xe();Lt();Oe();Ll=class extends te{kimiHome;constructor(e){super({provider:new Mi(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Kimi supports skills through ~/.kimi-code/skills and --skills-dir."},binary:"kimi",seedArgs:["-p",J,"--output-format","stream-json"],resumeTemplate:"kimi --session {{session_id}} --auto",startTemplate:"kimi --auto",transport:(r,n)=>yt(r,{...n,acpTool:"kimi"})}),this.kimiHome=e?.kimiHome}openSession(e){return Et({...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??J,"--output-format","stream-json"),r}}});import{spawn as Lx}from"node:child_process";import{mkdirSync as Cx}from"node:fs";function Ml(t){return new Dl(t)}async function Ox(t,e){let r=Date.now(),n=ih({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});ke("lmplayer",n,e.permissionMode??"yolo");let s=await ah(e.binary,n,{cwd:e.cwd,env:we(e.env,e.cwd,e.sessionId),signal:e.signal,onText:i=>{e.onProgress?.({kind:"text",summary:i.slice(0,120)}),e.onDelta?.(i)}});if(s.code!==0&&s.code!==null)throw new Error(oh(s));return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function ih(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(...Qt("lmplayer",t.permissionMode)??[]),e.push("--",t.prompt),e}function oh(t){if(t.error)return t.error;let e=Dn(t.stderr).trim();return e?e.slice(0,500):`exit code ${t.code}`}function ah(t,e,r){return new Promise((n,s)=>{let i;try{i=Lx(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(y){s(y);return}let o="",a="",l="",c,u,d,m=[],f=!1,g=y=>{let h=y.trim();if(!h)return;let p;try{p=JSON.parse(h)}catch{m.push(y),r.onText?.(y);return}if(!sn(p))return;let _=$i(p,!1);c===void 0&&_!==void 0&&(c=_),u=$i(p,!0)??u;let T=Dx(p);T!==void 0&&(d=T);let E=lh(p);E&&(m.push(E),r.onText?.(E))};i.stdout?.on("data",y=>{let h=y.toString("utf8");o+=h,l+=h;let p=l.indexOf(`
|
|
1601
1678
|
`);for(;p>=0;){let _=l.slice(0,p);l=l.slice(p+1),g(_),p=l.indexOf(`
|
|
1602
|
-
`)}}),i.stderr?.on("data",y=>{a+=y.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",y=>{f||(f=!0,l.length>0&&g(l),n({code:y,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",y=>{f||(f=!0,s(y))})})}function
|
|
1679
|
+
`)}}),i.stderr?.on("data",y=>{a+=y.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",y=>{f||(f=!0,l.length>0&&g(l),n({code:y,stdout:o,stderr:a,sessionId:c??u,text:m.join(""),error:d}))}),i.on("error",y=>{f||(f=!0,s(y))})})}function Dx(t){let e=t.error;if(typeof e=="string"&&e.length>0)return e;if(sn(e)){let r=e.data;if(sn(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 lh(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(sn(r)){let n=lh(r);if(n)return n}}}function $i(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(sn(r)){let n=$i(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(sn(s)){let i=$i(s,e);if(i!==void 0)return i}}}function sn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Dl,$l=k(()=>{"use strict";xi();Xe();Oe();Nt();_t();Ua();Dl=class extends te{constructor(e){super({provider:new tn({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none"},binary:"lmplayer",seedArgs:["run","--format","json","--dangerously-skip-permissions",J],resumeTemplate:"lmplayer tui --session {{session_id}}",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:Ox})}seedArgsFor(e){return ih({prompt:e?.prompt??J,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){Cx(e,{recursive:!0});let n=this.seedArgsFor(r);ke("lmplayer",n);try{let s=await ah(this.binary,n,{cwd:e,env:Zr(void 0,e)});return s.code!==0&&s.code!==null?{success:!1,error:oh(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 "${J}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as Fi,readFile as Mx,rm as $x}from"node:fs/promises";import{basename as ch,join as nr}from"node:path";function Fx(){return{observed:!1,totalInputTokens:0,totalCachedInputTokens:0,totalOutputTokens:0,totalReasoningOutputTokens:0}}function es(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function Px(t,e){if(!e)return;t.observed=!0;let r=es(e.promptTokenCount),n=es(e.cachedContentTokenCount),s=es(e.candidatesTokenCount),i=es(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:es(e.totalTokenCount)||r+s}}function Ux(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 dh(t){return t.type==="user"||t.message?.role==="user"}function uh(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function mh(t){let e=t.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(r=>r.type==="text").map(r=>r.text||"").join(`
|
|
1603
1680
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1604
|
-
`):"":""}function fh(t){return t.model||t.message?.model}function Mx(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:hh(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function ts(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 $x(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return ts(e.output??e.error??t)}return ts(t)}function hh(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function ph(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:ts(t.args,!0),toolInputData:Qe(t.args),toolCallId:t.id,model:r}}var Pi,gh=k(()=>{"use strict";xe();Pi=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||nr(H,".qwen")}async discoverSessions(){let e=nr(this.baseDir,"projects"),r;try{r=await Fi(e)}catch{return[]}let n=[];for(let s of r){let i=nr(e,s,"chats"),o;try{o=await Fi(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=nr(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await de(e),i="(unknown)",o,a,l,c,u=0;for await(let d of ce(e)){if(n=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),dh(d)){let m=mh(d).trim();m&&(l||(l=j(m,80)),c=j(m,80),u++)}if(uh(d)){let m=fh(d);m&&(o=m),u+=Mx(d)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=ch(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await de(e),s="(unknown)",i,o,a,l,c,u,d=[],m=Cx();for await(let f of ce(e)){if(Ox(m,f.usageMetadata),f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let g=f.message,y=f.timestamp?new Date(f.timestamp):n.modifiedAt;if(f.type==="tool_result"){let h=hh(f).filter(p=>p.functionResponse!==void 0);h.length===0&&f.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:y,content:ts(f.toolCallResult.resultDisplay??f.toolCallResult.error??f.toolCallResult.status)??"tool result",toolCallId:f.toolCallResult.callId});for(let p of h){let _=p.functionResponse,T=$x(_.response),E=ts(f.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:y,content:E??T??f.toolCallResult?.status??"tool result",toolName:_.name,toolCallId:f.toolCallResult?.callId??_.id,...T!==void 0?{toolDetailedContent:T}:{}})}}else if(dh(f)){let h=mh(f);h.trim()&&(c||(c=j(h.trim(),80)),u=j(h.trim(),80)),d.push({role:"user",timestamp:y,content:h})}else if(uh(f)){let h=fh(f);if(h&&(i=h),Array.isArray(g.content))for(let p of g.content)p.type==="text"&&p.text?d.push({role:"assistant",timestamp:y,content:p.text,model:h}):p.type==="thinking"&&p.thinking?d.push({role:"thinking",timestamp:y,content:p.thinking}):p.functionCall&&d.push(ph(p.functionCall,y,h));else if(typeof g.content=="string")d.push({role:"assistant",timestamp:y,content:g.content,model:h});else if(Array.isArray(g.parts))for(let p of g.parts)if(p.thought||p.type==="thinking"){let _=p.thinking||p.text;_&&d.push({role:"thinking",timestamp:y,content:_})}else p.functionCall?d.push(ph(p.functionCall,y,h)):p.text&&d.push({role:"assistant",timestamp:y,content:p.text,model:h})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...Dx(m),messages:d}}async resolveSessionPath(e){let r=nr(this.baseDir,"projects");try{let n=await Fi(r),s=[];for(let i of n){let o=nr(r,i,"chats",`${e}.jsonl`);try{return await Nx(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=nr(r,i,"chats"),a;try{a=await Fi(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;ch(l,".jsonl").startsWith(e)&&s.push(nr(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 Lx(r),!0}catch{return!1}}}});function Pl(){return new Fl}var Fl,Ul=k(()=>{"use strict";gh();Xe();Lt();Oe();Fl=class extends te{constructor(){super({provider:new Pi,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",J,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:ki})}openSession(e){return Ai({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as _h,readFile as yh,rm as Eh,stat as Th}from"node:fs/promises";import{basename as jl,join as Tt}from"node:path";import{fileURLToPath as Fx}from"node:url";async function Px(t){let e=await Promise.all(t.map(r=>de(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 Ux(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function wh(t){return t.type==="USER_INPUT"}function vh(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function jx(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function Sh(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function bh(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 Bx(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function Wx(t){for await(let e of ce(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=Hx(s);if(i)return i}let n=Xx(e.content);if(n)return n}return null}function Hx(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 Xx(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function qx(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 Gx(t,e){let r=new Set;for(let n of e){let s=Jx(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 Jx(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:zx(r.event.content);if(n!==void 0)return Ih(t.filter(i=>!e.has(i)&&Qx(i)===n),r.event.step_index);let s=Yx(r.event);if(s!==void 0)return Ih(t.filter(i=>!e.has(i)&&Vx(i.name,r.event.type)&&kh(Kx(i))===s),r.event.step_index)}function Ih(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 Vx(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 Kx(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function Yx(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]),kh(e)}function kh(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return Fx(e)}catch{return}}function zx(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function Qx(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 xh(t){if(t.endsWith(".db"))return jl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ui,Ah=k(()=>{"use strict";xe();Ui=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Tt(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Tt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Tt(this.baseDir,"conversations"),r;try{r=await _h(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=jl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Tt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Tt(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 Th(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await Px([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of ce(n)){let m=bh(d.content);if(m&&(a=m),wh(d)){let f=Sh(d.content).trim();f&&(l||(l=j(f,80)),c=j(f,80)),u++}else vh(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=xh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let m of ce(i)){let f=Ux(m.created_at,s.modifiedAt),g=bh(m.content);if(g&&(a=g),wh(m)){let y=Sh(m.content),h=y.trim();h&&(l||(l=j(h,80)),c=j(h,80)),o.push({role:"user",timestamp:f,content:y});continue}if(Array.isArray(m.tool_calls))for(let y of m.tool_calls){let h=y.name||"tool",p=Bx(y.args),_=Qe(y.args),T={role:"tool_use",timestamp:f,content:p,toolName:h,toolInput:p,toolInputData:_};o.push(T),u.push({name:h,stepIndex:m.step_index,input:_,message:T})}if(vh(m)&&m.content)o.push({role:"assistant",timestamp:f,content:m.content,model:a});else if(jx(m)&&m.content){let y=qx(m,n),h=y===void 0?null:await this.readTaskLog(n,y),p={role:"tool_result",timestamp:h?.modifiedAt??f,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:y,...h===null?{}:{toolDetailedContent:h.content}};o.push(p),d.push({event:m,message:p})}m.thinking&&o.push({role:"thinking",timestamp:f,content:m.thinking})}return Gx(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await Th(r),r}catch{}let n=Tt(this.baseDir,"conversations");try{let s=[];for(let i of await _h(n)){if(!i.endsWith(".db"))continue;jl(i,".db").startsWith(e)&&s.push(Tt(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=xh(r);return n?(await Eh(this.conversationPath(n),{force:!0}),await Eh(Tt(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 Wx(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Tt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await yh(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=Tt(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([yh(n,"utf8"),de(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as Zx}from"node:child_process";import{StringDecoder as Rh}from"node:string_decoder";function ji(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 ek(t.label,r.binary,s,{cwd:r.cwd,env:we(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function ek(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=Zx(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new Rh("utf8"),u=new Rh("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,f)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let g=f?`signal ${f}`:`exit code ${m}`,y=l.trim()||a.trim();i(new Error(`${t} failed (${g})${y?`: ${y}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}var Bl=k(()=>{"use strict";_t()});import{randomUUID as tk}from"node:crypto";function Hl(t){return new Wl(t)}function nk(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Wl,rk,Xl=k(()=>{"use strict";Ah();Xe();Oe();Nt();Bl();Wl=class extends te{constructor(e){super({provider:new Ui(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",J,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:rk})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${tk()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1605
|
-
${r?.prompt??J}`}),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}`}}},
|
|
1606
|
-
`))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=sr(this.sessionsDir,e,r,"session.jsonl.zstd");return Ch(n,s,Lh(n))}}});import{spawn as
|
|
1607
|
-
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function
|
|
1681
|
+
`):"":""}function fh(t){return t.model||t.message?.model}function jx(t){let e=t.message?.content;return typeof e=="string"?e.length>0?1:0:hh(t).filter(r=>!r.thought&&r.type!=="thinking"&&typeof r.text=="string"&&r.text.length>0).length}function ts(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 Bx(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t;return ts(e.output??e.error??t)}return ts(t)}function hh(t){return Array.isArray(t.message?.content)?t.message.content:t.message?.parts??[]}function ph(t,e,r){let n=t.name||"tool";return{role:"tool_use",timestamp:e,content:n,toolName:n,toolInput:ts(t.args,!0),toolInputData:Qe(t.args),toolCallId:t.id,model:r}}var Pi,gh=k(()=>{"use strict";xe();Pi=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||nr(H,".qwen")}async discoverSessions(){let e=nr(this.baseDir,"projects"),r;try{r=await Fi(e)}catch{return[]}let n=[];for(let s of r){let i=nr(e,s,"chats"),o;try{o=await Fi(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=nr(i,a);try{let u=await this.extractSummary(c,l);u&&n.push(u)}catch{}}}return n}async extractSummary(e,r){let n=!1,s=await de(e),i="(unknown)",o,a,l,c,u=0;for await(let d of ce(e)){if(n=!0,d.cwd&&(i=d.cwd,d.version&&(a=d.version)),d.type==="system"&&d.cwd&&(i=d.cwd,d.version&&(a=d.version),d.model&&(o=d.model)),dh(d)){let m=mh(d).trim();m&&(l||(l=j(m,80)),c=j(m,80),u++)}if(uh(d)){let m=fh(d);m&&(o=m),u+=jx(d)}}return n?{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e}:null}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=ch(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await de(e),s="(unknown)",i,o,a,l,c,u,d=[],m=Fx();for await(let f of ce(e)){if(Px(m,f.usageMetadata),f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let g=f.message,y=f.timestamp?new Date(f.timestamp):n.modifiedAt;if(f.type==="tool_result"){let h=hh(f).filter(p=>p.functionResponse!==void 0);h.length===0&&f.toolCallResult?.callId&&d.push({role:"tool_result",timestamp:y,content:ts(f.toolCallResult.resultDisplay??f.toolCallResult.error??f.toolCallResult.status)??"tool result",toolCallId:f.toolCallResult.callId});for(let p of h){let _=p.functionResponse,T=Bx(_.response),E=ts(f.toolCallResult?.resultDisplay);d.push({role:"tool_result",timestamp:y,content:E??T??f.toolCallResult?.status??"tool result",toolName:_.name,toolCallId:f.toolCallResult?.callId??_.id,...T!==void 0?{toolDetailedContent:T}:{}})}}else if(dh(f)){let h=mh(f);h.trim()&&(c||(c=j(h.trim(),80)),u=j(h.trim(),80)),d.push({role:"user",timestamp:y,content:h})}else if(uh(f)){let h=fh(f);if(h&&(i=h),Array.isArray(g.content))for(let p of g.content)p.type==="text"&&p.text?d.push({role:"assistant",timestamp:y,content:p.text,model:h}):p.type==="thinking"&&p.thinking?d.push({role:"thinking",timestamp:y,content:p.thinking}):p.functionCall&&d.push(ph(p.functionCall,y,h));else if(typeof g.content=="string")d.push({role:"assistant",timestamp:y,content:g.content,model:h});else if(Array.isArray(g.parts))for(let p of g.parts)if(p.thought||p.type==="thinking"){let _=p.thinking||p.text;_&&d.push({role:"thinking",timestamp:y,content:_})}else p.functionCall?d.push(ph(p.functionCall,y,h)):p.text&&d.push({role:"assistant",timestamp:y,content:p.text,model:h})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:u,messageCount:d.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...Ux(m),messages:d}}async resolveSessionPath(e){let r=nr(this.baseDir,"projects");try{let n=await Fi(r),s=[];for(let i of n){let o=nr(r,i,"chats",`${e}.jsonl`);try{return await Mx(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=nr(r,i,"chats"),a;try{a=await Fi(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;ch(l,".jsonl").startsWith(e)&&s.push(nr(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 $x(r),!0}catch{return!1}}}});function Pl(){return new Fl}var Fl,Ul=k(()=>{"use strict";gh();Xe();Lt();Oe();Fl=class extends te{constructor(){super({provider:new Pi,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",J,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:ki})}openSession(e){return Ai({...e,binary:"qwen"})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as _h,readFile as yh,rm as Eh,stat as Th}from"node:fs/promises";import{basename as jl,join as Tt}from"node:path";import{fileURLToPath as Wx}from"node:url";async function Hx(t){let e=await Promise.all(t.map(r=>de(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 Xx(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function wh(t){return t.type==="USER_INPUT"}function vh(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function qx(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function Sh(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function bh(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 Gx(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function Jx(t){for await(let e of ce(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=Vx(s);if(i)return i}let n=Kx(e.content);if(n)return n}return null}function Vx(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 Kx(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function Yx(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 zx(t,e){let r=new Set;for(let n of e){let s=Qx(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 Qx(t,e,r){let n=r.message.backgroundTaskId===void 0?void 0:rk(r.event.content);if(n!==void 0)return Ih(t.filter(i=>!e.has(i)&&nk(i)===n),r.event.step_index);let s=tk(r.event);if(s!==void 0)return Ih(t.filter(i=>!e.has(i)&&Zx(i.name,r.event.type)&&kh(ek(i))===s),r.event.step_index)}function Ih(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 Zx(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 ek(t){let e=t.name==="view_file"?t.input?.AbsolutePath:t.input?.TargetFile;return typeof e=="string"?e:void 0}function tk(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]),kh(e)}function kh(t){if(!t)return;let e=t.trim().replace(/^`|`$/g,"");if(!e.startsWith("file://"))return e;try{return Wx(e)}catch{return}}function rk(t){if(t)return/Task Description:\s*([^\n]+)/.exec(t)?.[1]?.trim()}function nk(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 xh(t){if(t.endsWith(".db"))return jl(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Ui,Ah=k(()=>{"use strict";xe();Ui=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Tt(H,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Tt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Tt(this.baseDir,"conversations"),r;try{r=await _h(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=jl(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Tt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e,r){return Tt(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 Th(r),r}catch{}return null}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await Hx([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,u=0;if(n)for await(let d of ce(n)){let m=bh(d.content);if(m&&(a=m),wh(d)){let f=Sh(d.content).trim();f&&(l||(l=j(f,80)),c=j(f,80)),u++}else vh(d)&&d.content&&u++}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=xh(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage,u=[],d=[];if(i)for await(let m of ce(i)){let f=Xx(m.created_at,s.modifiedAt),g=bh(m.content);if(g&&(a=g),wh(m)){let y=Sh(m.content),h=y.trim();h&&(l||(l=j(h,80)),c=j(h,80)),o.push({role:"user",timestamp:f,content:y});continue}if(Array.isArray(m.tool_calls))for(let y of m.tool_calls){let h=y.name||"tool",p=Gx(y.args),_=Qe(y.args),T={role:"tool_use",timestamp:f,content:p,toolName:h,toolInput:p,toolInputData:_};o.push(T),u.push({name:h,stepIndex:m.step_index,input:_,message:T})}if(vh(m)&&m.content)o.push({role:"assistant",timestamp:f,content:m.content,model:a});else if(qx(m)&&m.content){let y=Yx(m,n),h=y===void 0?null:await this.readTaskLog(n,y),p={role:"tool_result",timestamp:h?.modifiedAt??f,content:m.content,toolName:m.type?.toLowerCase(),backgroundTaskId:y,...h===null?{}:{toolDetailedContent:h.content}};o.push(p),d.push({event:m,message:p})}m.thinking&&o.push({role:"thinking",timestamp:f,content:m.thinking})}return zx(u,d),{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.filter(m=>m.role==="user"||m.role==="assistant").length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await Th(r),r}catch{}let n=Tt(this.baseDir,"conversations");try{let s=[];for(let i of await _h(n)){if(!i.endsWith(".db"))continue;jl(i,".db").startsWith(e)&&s.push(Tt(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=xh(r);return n?(await Eh(this.conversationPath(n),{force:!0}),await Eh(Tt(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 Jx(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Tt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await yh(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=Tt(this.baseDir,"brain",e,".system_generated","tasks",`${r}.log`);try{let[s,i]=await Promise.all([yh(n,"utf8"),de(n)]);return{content:s,modifiedAt:i.modifiedAt}}catch{return null}}}});import{spawn as sk}from"node:child_process";import{StringDecoder as Rh}from"node:string_decoder";function ji(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 ik(t.label,r.binary,s,{cwd:r.cwd,env:we(r.env,r.cwd,r.sessionId),signal:r.signal});return r.onProgress?.({kind:"system",summary:`${t.label} -p one-shot completed`}),{text:i.trimEnd(),sessionId:r.sessionId,durationMs:Date.now()-n}}}function ik(t,e,r,n){return new Promise((s,i)=>{if(n.signal?.aborted){i(new Error(`${t} turn aborted`));return}let o;try{o=sk(e,r,{cwd:n.cwd,env:n.env,stdio:["ignore","pipe","pipe"]})}catch(m){i(m);return}let a="",l="",c=new Rh("utf8"),u=new Rh("utf8");o.stdout?.on("data",m=>{a+=c.write(m)}),o.stderr?.on("data",m=>{l+=u.write(m)});let d=()=>{o.kill("SIGTERM"),i(new Error(`${t} turn aborted`))};o.on("error",m=>{n.signal?.removeEventListener("abort",d),i(m)}),o.on("close",(m,f)=>{if(n.signal?.removeEventListener("abort",d),a+=c.end(),l+=u.end(),m===0){s({stdout:a,stderr:l});return}let g=f?`signal ${f}`:`exit code ${m}`,y=l.trim()||a.trim();i(new Error(`${t} failed (${g})${y?`: ${y}`:""}`))}),n.signal?.aborted?d():n.signal?.addEventListener("abort",d,{once:!0})})}var Bl=k(()=>{"use strict";_t()});import{randomUUID as ok}from"node:crypto";function Hl(t){return new Wl(t)}function lk(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var Wl,ak,Xl=k(()=>{"use strict";Ah();Xe();Oe();Nt();Bl();Wl=class extends te{constructor(e){super({provider:new Ui(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",J,"--dangerously-skip-permissions","--print-timeout","2m"],seedTimeoutMs:13e4,resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:ak})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}async seed(e,r){let n=`[lmctl-seed:${ok()}]`,s=await super.seed(e,{...r,prompt:`${n}
|
|
1682
|
+
${r?.prompt??J}`}),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}`}}},ak=ji({label:"agy",buildArgs:(t,e)=>{let r=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",lk(e.timeoutMs)];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>ke("agy",t,e.permissionMode??"yolo")})});import ck from"node:zlib";function yk(t,e){return t[e]===uk&&t[e+1]===mk&&t[e+2]===fk&&t[e+3]===pk}function Nh(t,e){return(t[e]&240)===80&&t[e+1]===hk&&t[e+2]===gk&&t[e+3]===_k}function Ek(t,e){if(Nh(t,e))return e+8>t.length?void 0:8+t.readUInt32LE(e+4);if(!yk(t,e))return;let r=e+4;if(r+1>t.length)return;let n=t[r];r+=1;let s=n>>6,i=(n&32)!==0,o=(n&4)!==0,a=n&3;i||(r+=1),r+=[0,1,2,4][a];let l=s===0?i?1:0:[2,4,8][s-1];if(r+=l,!(r>t.length)){for(;;){if(r+3>t.length)return;let c=t[r]|t[r+1]<<8|t[r+2]<<16,u=(c&1)!==0,d=c>>1&3,m=c>>3;if(r+=3,d===3||(r+=d===1?1:m,r>t.length))return;if(u)break}if(o&&(r+=4),!(r>t.length))return r-e}}function Tk(t){let e=[],r=0;for(;r+4<=t.length;){let n=Ek(t,r);if(n===void 0||n<=0)break;e.push(t.subarray(r,r+n)),r+=n}return e}function Bi(t){let e=[];for(let r of Tk(t))Nh(r,0)||e.push(dk(r).toString("utf8"));return e.join("")}var dk,uk,mk,fk,pk,hk,gk,_k,ql=k(()=>{"use strict";dk=ck.zstdDecompressSync,uk=40,mk=181,fk=47,pk=253,hk=42,gk=77,_k=24});import{readdir as Gl,rm as wk,stat as vk}from"node:fs/promises";import{join as sr}from"node:path";function Sk(t){return"--"+t.replace(/^\/+|\/+$/g,"").replace(/\//g,"-")+"--"}function Jl(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 bk(t){if(!Array.isArray(t))return[];let e=[];for(let r of t)r&&typeof r=="object"&&r.type==="reasoning"&&typeof r.text=="string"&&e.push(r.text);return e}function Lh(t){let e=[];for(let r of t){let n=r.data??{},s=r.time?new Date(r.time):new Date(0);if(r.type==="user/message"){let i=n;if(i.source?.kind!==void 0&&i.source.kind!=="user")continue;e.push({role:"user",timestamp:s,content:Jl(i.content)})}else if(r.type==="assistant/message"){let i=n.message;for(let o of bk(i?.content))e.push({role:"thinking",timestamp:s,content:o});e.push({role:"assistant",timestamp:s,content:Jl(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:Jl(a?.content??i.message?.content),toolCallId:a?.toolCallId??i.message?.source?.callId})}}return e}function Ik(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r.type==="turn/end")return r.data?.reason?.kind==="completed"?"complete":"aborted";if(r.type==="turn/start")return"in_progress"}}function Ch(t,e,r){let n=t.find(f=>f.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 f of t)if(f.type==="request/header"){let g=f.data?.header;g?.config?.model&&(a=g.config.model)}let l=t.map(f=>f.time).filter(f=>typeof f=="number"),c=s.createdAt??i?.createdAt,u=c?new Date(c):new Date(0),d=l.length>0?new Date(Math.max(...l)):u,m=r.filter(f=>f.role==="user");return{provider:"dsh",sessionId:o,cwd:s.cwd??i?.cwd??"",createdAt:u,modifiedAt:d,model:a,firstUserMessage:m[0]?.content,lastUserMessage:m.at(-1)?.content,messageCount:r.filter(f=>f.role==="user"||f.role==="assistant").length,filePath:e,...xk(t)}}function xk(t){let e=!1,r=0,n=0,s=0,i=0,o,a;for(let l of t){if(l.type!=="assistant/message")continue;let c=l.data?.usage;if(!c)continue;e=!0;let u=Wi(c.inputTokens),d=Wi(c.cacheReadTokens),m=Wi(c.outputTokens),f=Wi(c.reasoningTokens);r+=u,n+=d,s+=m,i+=f,o=u+d,a={inputTokens:u,cachedInputTokens:d,outputTokens:m,reasoningOutputTokens:f,totalTokens:u+d+m}}return{totalInputTokens:e?r:void 0,totalCachedInputTokens:e?n:void 0,totalOutputTokens:e?s:void 0,totalReasoningOutputTokens:e?i:void 0,lastInputTokens:o,lastTokenUsage:a}}function Wi(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}var Hi,Oh=k(()=>{"use strict";xe();ql();Hi=class{name="dsh";sessionsDir;constructor(e={}){let r=e.dshHome||sr(H,".dsh");this.sessionsDir=sr(r,"sessions")}async discoverSessions(){let e=[],r;try{r=await Gl(this.sessionsDir)}catch{return[]}for(let n of r){let s;try{s=await Gl(sr(this.sessionsDir,n))}catch{continue}for(let i of s)if(i.startsWith("session-"))try{let o=await this.readSummary(n,i);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.findSessionDir(e);if(!r)return null;let n=await this.readRecords(r.cwdDir,r.sessionDir);if(n.length===0)return null;let s=Lh(n),i=Ch(n,r.filePath,s);return i?{...i,turnStatus:Ik(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 wk(sr(this.sessionsDir,r.cwdDir,r.sessionDir),{recursive:!0,force:!0}),!0):!1}sessionFilePath(e,r){return sr(this.sessionsDir,Sk(e),r,"session.jsonl.zstd")}async findSessionDir(e){let r;try{r=await Gl(this.sessionsDir)}catch{return null}for(let n of r){let s=e,i=sr(this.sessionsDir,n,s,"session.jsonl.zstd");try{return await vk(i),{cwdDir:n,sessionDir:s,filePath:i}}catch{}}return null}async readRecords(e,r){let{readFile:n}=await import("node:fs/promises"),s=sr(this.sessionsDir,e,r,"session.jsonl.zstd"),i=await n(s),o=Bi(i),a=[];for(let l of o.split(`
|
|
1683
|
+
`))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=sr(this.sessionsDir,e,r,"session.jsonl.zstd");return Ch(n,s,Lh(n))}}});import{spawn as kk}from"node:child_process";async function Xi(t,e=r=>Vl.spawn(r)){if(ir){let r=await ir.catch(()=>{});if(r?.alive)return r;ir=void 0}return ir=e(t),ir}async function rs(){if(!ir)return;(await ir.catch(()=>{}))?.shutdown(),ir=void 0}var Ak,Dh,on,Vl,ir,Mh=k(()=>{"use strict";Ak=/dsh web:\s*(https?:\/\/\S+)/,Dh=2e4,on=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)}},Vl=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 on(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 on(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 on(e,"malformed response: HTTP 200 but body is not a well-formed {result:{ok,\u2026}} envelope");if(o.ok===!1)throw new on(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=kk("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 ${Dh}ms (stdout: ${o.slice(0,500)}; stderr: ${a.slice(0,500)})`)))},Dh);s.stdout?.on("data",c=>{if(o+=c.toString(),i)return;let u=Ak.exec(o);u&&(i=!0,clearTimeout(l),r(new t(u[1],s)))}),s.stderr?.on("data",c=>{a+=c.toString()}),s.on("error",c=>{i||(i=!0,clearTimeout(l),n(c))}),s.on("exit",(c,u)=>{if(i)return;i=!0,clearTimeout(l);let d=u?`signal ${u}`:`exit code ${c}`;n(new Error(`dsh web exited before reporting a boot URL (${d}): ${a.slice(0,500)}`))})})}}});import{randomUUID as Rk}from"node:crypto";import{existsSync as $h}from"node:fs";import{readFile as Nk,mkdir as Lk}from"node:fs/promises";function Ql(t){return new zl(t)}function Yl(t){return{...t,DSH_PERMISSION_MODE:t.DSH_PERMISSION_MODE??"danger-full-access"}}function Ok(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 qi(t){return t instanceof Error?t.message:String(t)}async function Dk(t){let e=await Fh(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 Fh(t){let e;try{e=await Nk(t)}catch{return[]}let r=Bi(e),n=[];for(let s of r.split(`
|
|
1684
|
+
`))if(s.trim())try{let i=JSON.parse(s);i!==null&&typeof i=="object"&&!Array.isArray(i)&&n.push(i)}catch{}return n}function Mk(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 Ck,Kl,zl,Zl=k(()=>{"use strict";Xe();Oh();ql();Mh();Oe();Nt();Ck=500,Kl=8*60*60*1e3;zl=class extends te{dshProvider;constructor(e){let r=new Hi(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"dsh has no in-session leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"dsh",seedArgs:[],resumeTemplate:"dsh web --no-open --port 0 # continuity is via the RPC sidecar, not a resume flag",startTemplate:"dsh web --no-open --port 0",transport:(n,s)=>this.dshPromptTurn(n,s)}),this.dshProvider=r}manualSeedHint(e){return{launchCommand:`cd ${e} && dsh web`,postLaunchNote:"dsh has no interactive terminal session to seed into \u2014 continuity lives in the web profile's session store, not a TTY. Boot the sidecar with the command above, open the printed http:// URL, and start a session rooted at this directory in the web UI; lmctl's managed sidecar can then cold-resume it by id (cross-profile session sharing is verified). Send lmctl's seed instruction there, wait for the reply, then find the new session id with the ls command below and register it manually.",lsCommand:`lmctl ls --provider dsh --sessiondir ${e}`}}async seed(e,r){await Lk(e,{recursive:!0});let n=`session-${Rk()}`,s=Yl(process.env);ke("dsh",[],"yolo");try{let i;try{i=await Xi(s)}catch(a){return{success:!1,error:`dsh sidecar failed to start: ${qi(a)}`}}try{await i.rpc("session.create",{sessionId:n,cwd:e})}catch(a){return{success:!1,error:`session.create failed: ${qi(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: ${qi(a)}`}}let o=r?.prompt??J;try{await this.promptAndWait(i,e,n,o,Kl)}catch(a){return{success:!1,error:`seed turn failed: ${qi(a)}`}}return{success:!0,sessionId:n}}finally{await rs()}}async dshPromptTurn(e,r){let n=Date.now();if(r.bundleSession!==void 0){let o=r.bundleSession;if(o.provider!=="dsh")throw new Error(`bundle session provider mismatch: session serves "${o.provider}", turn targets "dsh"`);let a=await o.sendTurn(e,{signal:r.signal});return{text:a.text,sessionId:a.sessionId,durationMs:a.durationMs,...a.warnings!==void 0?{warnings:a.warnings}:{}}}let s=Yl(r.env??process.env);ke("dsh",[],r.permissionMode??"yolo");let i;try{let o=await Xi(s);r.model&&(await o.rpc("session.selectModel",{sessionId:r.sessionId,provider:"deepseek-official",model:r.model}),r.onProgress?.({kind:"system",summary:`dsh model set to ${r.model}`})),r.onProgress?.({kind:"system",summary:"dsh session.prompt sent"}),i=await this.promptAndWait(o,r.cwd,r.sessionId,e,r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:Kl)}finally{await rs()}return r.onProgress?.({kind:"system",summary:"dsh turn completed"}),{text:i,sessionId:r.sessionId,durationMs:Date.now()-n}}async openSession(e){let r=Yl(e.env??process.env);ke("dsh",[],e.permissionMode??"yolo");let n=await Xi(r),s=this.dshProvider.sessionFilePath(e.cwd,e.sessionId);if(!$h(s))throw await rs(),new Error(`dsh bundle: session file does not exist for session "${e.sessionId}" (${s}) \u2014 the session must exist before a bundle can resume it`);e.model&&await n.rpc("session.selectModel",{sessionId:e.sessionId,provider:"deepseek-official",model:e.model});let i=e.sessionId,o=this,a=0,l=!1,c=null,u=!1,d=!1,m=async()=>{d||(d=!0,await rs())};return{provider:"dsh",sessionId:i,get completedTurns(){return a},async sendTurn(f,g={}){if(l||c!==null)throw new Error("dsh bundle session is closed");if(u)throw new Error("dsh bundle session has a turn still in flight");if(g.signal?.aborted)throw new Error("Aborted");if(!$h(s))throw new Error(`dsh bundle: session file for session "${i}" disappeared mid-bundle \u2014 identity re-check failed (external re-seed?)`);u=!0;let y=Date.now();try{let h=o.promptAndWait(n,e.cwd,i,f,Kl,g.signal);h.catch(()=>{});let p=await Promise.race([h,new Promise((_,T)=>{g.signal?.addEventListener("abort",()=>{(async()=>{l=!0,await m()})().finally(()=>T(new Error("Aborted")))},{once:!0})})]);return a+=1,{text:p,sessionId:i,durationMs:Date.now()-y}}finally{u=!1}},close(){return c!==null||(c=(async()=>{l=!0,await m()})()),c}}}async promptAndWait(e,r,n,s,i,o){let a=this.dshProvider.sessionFilePath(r,n),l=await Dk(a);await e.rpc("session.prompt",{sessionId:n,mode:"queue",content:[{type:"text",text:s}]});let c=Date.now()+i;for(;;){if(o?.aborted)throw new Error("Aborted");let u=await Fh(a),d=u.find(m=>m.type==="turn/end"&&(m.seq??-1)>l);if(d){let m=d.data?.reason,f=[...u].reverse().find(y=>y.type==="assistant/message"),g=f?Mk(f):"";if(m?.kind!=="completed"&&!g)throw new Error(Ok(m));return g}if(Date.now()>c)throw new Error(`dsh turn timed out after ${i}ms waiting for turn/end`);await new Promise(m=>setTimeout(m,Ck))}}}});import{existsSync as $k}from"node:fs";import{join as Wh,resolve as Fk}from"node:path";import{createRequire as Pk}from"node:module";function Uk(){return ec===null&&(ec=Pk(import.meta.url)("node:sqlite").DatabaseSync),ec}function tc(t={}){return Fk(t.hermesHome?.trim()||process.env.HERMES_HOME?.trim()||Wh(H,".hermes"))}function jk(t={}){return Wh(tc(t),"state.db")}function ns(t){let e=typeof t=="number"&&Number.isFinite(t)?t:0;return new Date(e*1e3)}function je(t){return typeof t=="string"&&t.length>0?t:void 0}function Bk(t){if(!t)return{};try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function jh(t){return je(t.cwd)??je(Bk(t.model_config).cwd)??"(unknown)"}function Wk(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function Hk(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 Bh(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 ec,Ph,Uh,Gi,Hh=k(()=>{"use strict";xe();V();ec=null;Ph="acp";Uh=`id, source, model, model_config, started_at,
|
|
1608
1685
|
last_activity_at, message_count, input_tokens, output_tokens,
|
|
1609
|
-
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;Gi=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=
|
|
1686
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens, cwd, title`;Gi=class{name="hermes";dbPath;busyTimeoutMs;discoverLimit;constructor(e){this.dbPath=jk(e),this.busyTimeoutMs=e?.busyTimeoutMs??5e3,this.discoverLimit=e?.discoverLimit??200}get stateDbPath(){return this.dbPath}openDb(){if(!$k(this.dbPath))return null;let e=null;try{return e=new(Uk())(this.dbPath,{open:!0,readOnly:!0}),e.exec(`PRAGMA busy_timeout = ${this.busyTimeoutMs}`),e}catch(r){return e?.close(),L({event:"hermes_store_unavailable",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),null}}selectSessionRow(e,r){return e.prepare(`SELECT ${Uh} FROM sessions WHERE id = ? AND source = ?`).get(r,Ph)??null}async discoverSessions(){let e=this.openDb();if(!e)return[];try{let r=e.prepare(`SELECT ${Uh} FROM sessions
|
|
1610
1687
|
WHERE source = ?
|
|
1611
1688
|
ORDER BY COALESCE(last_activity_at, started_at) DESC
|
|
1612
1689
|
LIMIT ?`).all(Ph,this.discoverLimit),n=[];for(let s of r){let i=this.previewTexts(e,s.id);n.push({provider:this.name,sessionId:s.id,slug:je(s.title),cwd:jh(s),createdAt:ns(s.started_at),modifiedAt:ns(s.last_activity_at??s.started_at),model:je(s.model),startCommand:this.name,firstUserMessage:i.first,lastUserMessage:i.last,messageCount:s.message_count??0,filePath:this.dbPath,...Bh(s)})}return n}catch(r){return L({event:"hermes_discover_sessions_failed",provider:this.name,db_path:this.dbPath,error_message:r instanceof Error?r.message:String(r)}),[]}finally{e.close()}}activeMessageRows(e,r){let n=new Set(e.prepare("PRAGMA table_info(messages)").all().map(a=>a.name)),i=`id, session_id, role, content, tool_call_id, tool_calls, tool_name,
|
|
1613
1690
|
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 = ?
|
|
1614
|
-
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?j(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let u=ns(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=j(d,80)),l=j(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:je(c.tool_call_id),toolName:je(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:je(n.model),stopReason:je(c.finish_reason)});for(let m of Fk(c.tool_calls)){let f=Pk(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:je(m.function?.name)??"tool_call",toolName:je(m.function?.name),toolCallId:je(m.call_id)??je(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Qe(f)})}}return{provider:this.name,sessionId:n.id,slug:je(n.title),cwd:jh(n),createdAt:ns(n.started_at),modifiedAt:ns(n.last_activity_at??n.started_at),model:je(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Bh(n),messages:i,userPrompts:o}}catch(n){return L({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as Uk}from"node:fs/promises";function Bk(t){return jk.test(t)}function Xh(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return Wk}function nc(t){return new rc(t)}var jk,Wk,rc,sc=k(()=>{"use strict";Xe();Hh();Lt();Oe();V();jk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Wk="dont_ask";rc=class extends te{hermesProvider;hermesHome;constructor(e){let r=new Gi(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(n,s)=>yt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Xh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=tc(e)}async openSession(e){return Et({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Xh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Uk(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??J,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return Bk(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as qh,rm as Hk,stat as Xk}from"node:fs/promises";import{join as ic}from"node:path";function oc(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 Gh(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Ji,Jh=k(()=>{"use strict";xe();Ji=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||ic(H,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await qh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=ic(this.baseDir,n);try{if(!(await Xk(s)).isDirectory())continue;for(let i of await qh(s))i.endsWith(".jsonl")&&r.push(ic(s,i))}catch{}}return r}async readHeader(e){for await(let r of ce(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await de(e),s,i,o,a=0,l=0,c=0,u=0,d=0,m=0,f=0,g;for await(let y of ce(e)){if(y.type==="model_change"&&y.provider&&y.modelId){s=`${y.provider}/${y.modelId}`;continue}if(y.type!=="message"||!y.message)continue;let h=y.message;if(h.provider&&h.model&&(s=`${h.provider}/${h.model}`),h.role==="user"){let p=oc(h).trim();p&&(i||(i=j(p,80)),o=j(p,80)),a++}else if(h.role==="assistant"){a++;let p=h.usage;p&&(l+=p.input??0,c+=p.cacheRead??0,u+=p.cacheWrite??0,d+=p.output??0,m+=p.reasoning??0,f=p.input??0,g={inputTokens:p.input,cachedInputTokens:p.cacheRead,cacheWriteInputTokens:p.cacheWrite,outputTokens:p.output,reasoningOutputTokens:p.reasoning,totalTokens:p.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:f,lastTokenUsage:g}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of ce(r)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:oc(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:Gh(c.arguments),toolName:c.name??"tool",toolInput:Gh(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:oc(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 Hk(r,{force:!0}),!0):!1}}});function lc(t){return new ac(t)}var ac,qk,cc=k(()=>{"use strict";Jh();Xe();Oe();Nt();Bl();ac=class extends te{constructor(e){super({provider:new Ji(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",J],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:qk})}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}`}}},qk=ji({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>ke("pi",t,e.permissionMode??"yolo")})});import{createHash as Gk}from"node:crypto";import{existsSync as Jk,mkdirSync as uc,readFileSync as Vk,renameSync as Kk,rmdirSync as tg,statSync as Yk,writeFileSync as zk}from"node:fs";import{dirname as hc,join as Vh,resolve as dc}from"node:path";function Qk(t){return Gk("sha256").update(t).digest("hex").slice(0,8)}function Zk(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function eA(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 rg(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Vi(t){return Math.max(1,Math.ceil(t.length/4))}function ln(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return dc(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Vh(hc(dc(r)),".lmctl-claude-mock","sessions.json"):Vh(dc(t),".lmctl-claude-mock","sessions.json")}function Kh(){return{schemaVersion:1,sessions:{}}}function ss(t){if(!Jk(t))return Kh();try{let e=JSON.parse(Vk(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=mc(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Kh()}}function ng(t,e){uc(hc(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;zk(r,`${JSON.stringify(e,null,2)}
|
|
1615
|
-
`,"utf8"),Kk(r,t)}function nA(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function sA(t){let e=`${t}.lock`;uc(hc(t),{recursive:!0});let r=Date.now()+Yh;for(;;)try{return uc(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Yk(e).mtimeMs>tA){try{tg(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${Yh}ms: ${e}`);nA(rA)}}function iA(t){try{tg(t)}catch{}}function sg(t,e){let r=sA(t);try{return e()}finally{iA(r)}}function oA(t){return{...t,timestamp:t.timestamp.toISOString()}}function aA(t){return{...t,timestamp:new Date(t.timestamp)}}function lA(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(oA)}}function ig(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(aA)}}function Ki(t,e=process.cwd()){let r=an.get(t);if(r!==void 0)return r;let s=ss(ln(e)).sessions[t];if(s===void 0)return;let i=ig(s);return an.set(i.sessionId,i),i}function zh(t){an.set(t.sessionId,t);let e=ln(t.cwd);sg(e,()=>{let r=ss(e);r.sessions[t.sessionId]=lA({...t,filePath:e}),ng(e,r)})}function cA(t,e=process.cwd()){let r=ln(e);return sg(r,()=>{let n=ss(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],ng(r,n)),s})}function dA(){let t=ss(ln()),e=Object.values(t.sessions).map(ig);for(let r of e)an.set(r.sessionId,r);return e}function mc(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Qh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=mc(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=mc(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Zh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function uA(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Qh(r[t]??r[rg(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Qh(n[s]);if(i!==void 0)return i}}}function eg(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 gc(){return new pc}var an,tA,rA,Yh,fc,pc,_c=k(()=>{"use strict";an=new Map;tA=5e3,rA=15,Yh=1e4;fc=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of dA())e.set(r.sessionId,r);for(let r of an.values())e.set(r.sessionId,r);return[...e.values()].map(eg)}async loadSession(e){let r=Ki(e);return r===void 0?null:{...eg(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Ki(e)?.filePath??null}async deleteSession(e){let r=an.delete(e),n=cA(e);return r||n}},pc=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new fc;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=Zk(eA(e,r)),s=`mock-${n}-${Qk(`${e}:${n}`)}`,i=new Date,o=ln(e),a=Ki(s,e),l=r?.prompt??"ClaudeMock seed",c=Vi(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=Vi("ACK: ClaudeMock seeded"),zh(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Ki(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=ss(ln(r.cwd)),a=uA(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Zh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${rg(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+=Vi(e),s.totalOutputTokens+=Vi(c),zh(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Zh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function or(t){let e=[dl({claudeDir:t?.claudeDir}),pl({codexDir:t?.codexDir,codeDir:t?.codeDir}),Tl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),bl({copilotDir:t?.copilotDir}),kl(),Cl({kimiHome:t?.kimiHome}),Ml({lmplayerDbPath:t?.lmplayerDbPath}),Pl(),Hl({agyDir:t?.agyDir}),Ql({dshHome:t?.dshHome}),nc({hermesHome:t?.hermesHome}),lc({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(gc()),e}var yc=k(()=>{"use strict";ul();hl();wl();Il();Al();Ol();$l();Ul();Xl();Zl();sc();cc();_c();ul();hl();wl();Il();Al();Ol();$l();Ul();Xl();Zl();sc();cc();_c()});var Sr,cn,og=k(()=>{"use strict";Sr=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],cn=["agy","pi","lmplayer"]});var vc={};oe(vc,{BUNDLE_CAPABLE_PROVIDERS:()=>Sr,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>cn,ProviderRegistry:()=>Cn,TransportConnectionError:()=>re,TransportError:()=>zt,TransportJsonError:()=>ui,TransportProcessError:()=>Mn,TransportRpcError:()=>$n,_resetDefaultRegistryForTests:()=>mA,bundleSupportedProviders:()=>dn,chat:()=>Ir,countTokens:()=>pA,createAdapterRegistry:()=>Yt,createAllAdapters:()=>or,deleteSession:()=>wc,listSessions:()=>os,openBundleSession:()=>is,seed:()=>Tc});function br(){return Yi===null&&(Yi=Yt(or())),Yi}function mA(){Yi=null}function Ec(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function Ir(t){let e=t.registry??br(),r=Ec(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function dn(t){return(t??br()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function is(t){let e=t.registry??br(),r=Ec(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${dn(e).join(", ")})`);return r.openSession(t)}async function Tc(t){let e=t.registry??br(),r=Ec(e,t.provider),n=await ag(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 ag(e,t.provider,t.cwd),a=fA(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 ag(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 fA(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 os(t={}){return(t.registry??br()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function wc(t,e,r=br()){return r.deleteSession(e,t)}async function pA(t){let r=await(t.registry??br()).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 Yi,Ct=k(()=>{"use strict";$a();yc();$a();yc();og();yr();Yi=null});function zi(t){return gA.has(t)}function bc(){return Sc===null&&(Sc=Yt(or())),Sc}function Ic(t,e,r={}){if(!zi(t))return null;try{let n=bc().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?_i({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?hA[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,...lg[t]??[]]}catch{return null}}function dg(t,e,r={}){let n=Ic(t,e,r);return n===null?null:n.join(" ")}function Re(t,e){return bc().getSession(t,e)}async function un(t){return(await bc().resolveSessions(t)).map(r=>r.provider.name)}var lg,hA,gA,cg,Sc,ar=k(()=>{"use strict";Ct();Ga();lg={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:[]},hA={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]},gA=new Set(Object.keys(lg)),cg=/^[\w.:-]+$/;Sc=null});function _A(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return ug;let r=Number(e);return!Number.isFinite(r)||r<=0?ug:r}async function yA(t,e,r){try{let n=me(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 un(s);if(c.length!==1)return null;i=c[0]}let o=await Re(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 mg(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??_A(),o=await yA(t,r,n),a=o!==null&&o>=i;return a&&L({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var ug,fg=k(()=>{"use strict";V();ar();We();ug=36e5});function EA(t){return t===null?null:Ce(t)?"live":"dead"}function xc(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:EA(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function TA(t){return(0,pg.formatDuration)(t)}function kc(t){let e=[];return t.idle_ms!==null&&e.push(`active ${TA(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var pg,hg=k(()=>{"use strict";gr();pg=It(gt(),1)});import{randomUUID as wA}from"node:crypto";import{hostname as gg,networkInterfaces as vA}from"node:os";function _g(t){let e=(t.now??new Date).toISOString();return{lock_id:wA(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??gg(),holder_ips:t.ips??kA(),started_at:e,last_heartbeat:e}}function yg(t=process.env){return Eg(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,SA)}function IA(t=process.env){return Eg(t.LMCTL_TERMINAL_LOCK_STALE_MS,bA)}function Ac(t,e={}){let r=e.now??new Date,n=e.localHost??gg(),s=e.staleMs??IA();if(t.holder_host===n)return(e.isProcessAlive??xA)(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 xr(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function Eg(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 xA(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 kA(){let t=new Set;for(let e of Object.values(vA()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var SA,bA,as=k(()=>{"use strict";SA=15e3,bA=12e4});function AA(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
1691
|
+
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?j(a.content,80):void 0});return{first:n,last:s}}catch{return{}}}async loadSession(e){let r=this.openDb();if(!r)return null;try{let n=this.selectSessionRow(r,e);if(!n)return null;let s=this.activeMessageRows(r,e),i=[],o=[],a,l;for(let c of s){let u=ns(c.timestamp),d=c.content??"";if(c.role==="user"){d&&c._compressed_summary!==1&&c.display_kind!=="hidden"&&o.push(d),d.length>0&&(a||(a=j(d,80)),l=j(d,80)),i.push({role:"user",timestamp:u,content:d||"(empty)"});continue}if(c.role==="tool"){i.push({role:"tool_result",timestamp:u,content:d,toolCallId:je(c.tool_call_id),toolName:je(c.tool_name)});continue}d.length>0&&i.push({role:"assistant",timestamp:u,content:d,model:je(n.model),stopReason:je(c.finish_reason)});for(let m of Wk(c.tool_calls)){let f=Hk(m.function?.arguments);i.push({role:"tool_use",timestamp:u,content:je(m.function?.name)??"tool_call",toolName:je(m.function?.name),toolCallId:je(m.call_id)??je(m.id),toolInput:typeof m.function?.arguments=="string"?m.function.arguments:JSON.stringify(m.function?.arguments??{}),toolInputData:Qe(f)})}}return{provider:this.name,sessionId:n.id,slug:je(n.title),cwd:jh(n),createdAt:ns(n.started_at),modifiedAt:ns(n.last_activity_at??n.started_at),model:je(n.model),startCommand:this.name,firstUserMessage:a,lastUserMessage:l,messageCount:n.message_count??i.length,filePath:this.dbPath,...Bh(n),messages:i,userPrompts:o}}catch(n){return L({event:"hermes_load_session_failed",provider:this.name,session_id:e,db_path:this.dbPath,error_message:n instanceof Error?n.message:String(n)}),null}finally{r.close()}}async resolveSessionPath(e){let r=this.openDb();if(!r)return null;try{return this.selectSessionRow(r,e)?this.dbPath:null}catch{return null}finally{r.close()}}async deleteSession(e){return!1}}});import{mkdir as Xk}from"node:fs/promises";function Gk(t){return qk.test(t)}function Xh(t){if(t==="plan")throw new Error(`provider "hermes" does not support --permission-mode plan: Hermes's ACP mode ladder (default/accept_edits/dont_ask) governs file edits only and has no plan-equivalent, so lmctl refuses rather than silently running the member with edit auto-approval.`);return Jk}function nc(t){return new rc(t)}var qk,Jk,rc,sc=k(()=>{"use strict";Xe();Hh();Lt();Oe();V();qk=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;Jk="dont_ask";rc=class extends te{hermesProvider;hermesHome;constructor(e){let r=new Gi(e);super({provider:r,capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append",leaderSetupHint:"Hermes has no provider-side leader-injection mechanism; the seed prompt carries lmctl's leader instructions."},binary:"hermes",seedArgs:[],resumeTemplate:"hermes --yolo --resume {{session_id}}",startTemplate:"hermes",transport:async(n,s)=>yt(n,{...s,requireResume:s.requireResume??!!s.sessionId,env:{...s.env??process.env,HERMES_HOME:this.hermesHome},acpTool:"hermes",acpMode:Xh(s.permissionMode)})}),this.hermesProvider=r,this.hermesHome=tc(e)}async openSession(e){return Et({...e,env:{...e.env??process.env,HERMES_HOME:this.hermesHome},binary:"hermes",acpTool:"hermes",acpMode:Xh(e.permissionMode)})}get stateDbPath(){return this.hermesProvider.stateDbPath}async seed(e,r){await Xk(e,{recursive:!0});let n=[];if(r?.effort){let i="hermes has no ACP-level effort surface";L({event:"hermes_effort_ignored",provider:this.name,effort:r.effort,reason:i}),n.push(`hermes seed ignored effort=${r.effort}: ${i}`)}let s;try{s=await this.sendTurn(r?.prompt??J,{sessionId:"",cwd:e,model:r?.model})}catch(i){return{success:!1,error:`hermes ACP seed failed: ${i instanceof Error?i.message:String(i)}`}}return Gk(s.sessionId)?(n.push(...s.warnings??[]),{success:!0,sessionId:s.sessionId,...n.length>0?{warnings:n}:{}}):(L({event:"hermes_seed_contract_violation",provider:this.name,session_id:s.sessionId,reason:"session/new did not return a UUID session id"}),{success:!1,error:`hermes ACP session/new did not return a UUID session id (got ${JSON.stringify(s.sessionId)})`})}}});import{readdir as qh,rm as Vk,stat as Kk}from"node:fs/promises";import{join as ic}from"node:path";function oc(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 Gh(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}var Ji,Jh=k(()=>{"use strict";xe();Ji=class{name="pi";baseDir;constructor(e={}){this.baseDir=e.piDir||ic(H,".pi","agent","sessions")}getWatchPaths(){return[{directory:this.baseDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[];for(let r of await this.listSessionFiles())try{let n=await this.extractSummary(r);n&&e.push(n)}catch{}return e}async listSessionFiles(){let e;try{e=await qh(this.baseDir)}catch{return[]}let r=[];for(let n of e){let s=ic(this.baseDir,n);try{if(!(await Kk(s)).isDirectory())continue;for(let i of await qh(s))i.endsWith(".jsonl")&&r.push(ic(s,i))}catch{}}return r}async readHeader(e){for await(let r of ce(e))return r.type==="session"?r:null;return null}async extractSummary(e){let r=await this.readHeader(e);if(!r)return null;let n=await de(e),s,i,o,a=0,l=0,c=0,u=0,d=0,m=0,f=0,g;for await(let y of ce(e)){if(y.type==="model_change"&&y.provider&&y.modelId){s=`${y.provider}/${y.modelId}`;continue}if(y.type!=="message"||!y.message)continue;let h=y.message;if(h.provider&&h.model&&(s=`${h.provider}/${h.model}`),h.role==="user"){let p=oc(h).trim();p&&(i||(i=j(p,80)),o=j(p,80)),a++}else if(h.role==="assistant"){a++;let p=h.usage;p&&(l+=p.input??0,c+=p.cacheRead??0,u+=p.cacheWrite??0,d+=p.output??0,m+=p.reasoning??0,f=p.input??0,g={inputTokens:p.input,cachedInputTokens:p.cacheRead,cacheWriteInputTokens:p.cacheWrite,outputTokens:p.output,reasoningOutputTokens:p.reasoning,totalTokens:p.totalTokens})}}return{provider:"pi",sessionId:r.id,cwd:r.cwd??"(unknown)",createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:s,startCommand:"pi",firstUserMessage:i,lastUserMessage:o,messageCount:a,filePath:e,totalInputTokens:l,totalCachedInputTokens:c,totalCacheWriteInputTokens:u,totalOutputTokens:d,totalReasoningOutputTokens:m,lastInputTokens:f,lastTokenUsage:g}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=await this.extractSummary(r);if(!n)return null;let s=[],i=n.model;for await(let o of ce(r)){if(o.type==="model_change"&&o.provider&&o.modelId){i=`${o.provider}/${o.modelId}`;continue}if(o.type!=="message"||!o.message)continue;let a=o.message;a.provider&&a.model&&(i=`${a.provider}/${a.model}`);let l=a.timestamp?new Date(a.timestamp):n.modifiedAt;if(a.role==="user")s.push({role:"user",timestamp:l,content:oc(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:Gh(c.arguments),toolName:c.name??"tool",toolInput:Gh(c.arguments),toolInputData:c.arguments,toolCallId:c.id});else a.role==="toolResult"&&s.push({role:"tool_result",timestamp:l,content:oc(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 Vk(r,{force:!0}),!0):!1}}});function lc(t){return new ac(t)}var ac,Yk,cc=k(()=>{"use strict";Jh();Xe();Oe();Nt();Bl();ac=class extends te{constructor(e){super({provider:new Ji(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"pi uses one-shot print turns; no streaming events are available."},binary:"pi",seedArgs:["-p",J],resumeTemplate:"pi --session {{session_id}}",startTemplate:"pi",transport:Yk})}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}`}}},Yk=ji({label:"pi",buildArgs:(t,e)=>{let r=["--session",e.sessionId,"-p",t];return e.model&&r.push("--model",e.model),r},assertArgs:(t,e)=>ke("pi",t,e.permissionMode??"yolo")})});import{createHash as zk}from"node:crypto";import{existsSync as Qk,mkdirSync as uc,readFileSync as Zk,renameSync as eA,rmdirSync as tg,statSync as tA,writeFileSync as rA}from"node:fs";import{dirname as hc,join as Vh,resolve as dc}from"node:path";function nA(t){return zk("sha256").update(t).digest("hex").slice(0,8)}function sA(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function iA(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 rg(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Vi(t){return Math.max(1,Math.ceil(t.length/4))}function ln(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return dc(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?Vh(hc(dc(r)),".lmctl-claude-mock","sessions.json"):Vh(dc(t),".lmctl-claude-mock","sessions.json")}function Kh(){return{schemaVersion:1,sessions:{}}}function ss(t){if(!Qk(t))return Kh();try{let e=JSON.parse(Zk(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=mc(e.defaultDelayMs);return{schemaVersion:1,sessions:r,...i!==void 0?{defaultDelayMs:i}:{},...n!==void 0?{script:n}:{},...s!==void 0?{scriptContains:s}:{}}}catch{return Kh()}}function ng(t,e){uc(hc(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;rA(r,`${JSON.stringify(e,null,2)}
|
|
1692
|
+
`,"utf8"),eA(r,t)}function lA(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function cA(t){let e=`${t}.lock`;uc(hc(t),{recursive:!0});let r=Date.now()+Yh;for(;;)try{return uc(e),e}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-tA(e).mtimeMs>oA){try{tg(e)}catch{}continue}}catch{continue}if(Date.now()>=r)throw new Error(`ClaudeMock store lock timeout after ${Yh}ms: ${e}`);lA(aA)}}function dA(t){try{tg(t)}catch{}}function sg(t,e){let r=cA(t);try{return e()}finally{dA(r)}}function uA(t){return{...t,timestamp:t.timestamp.toISOString()}}function mA(t){return{...t,timestamp:new Date(t.timestamp)}}function fA(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(uA)}}function ig(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(mA)}}function Ki(t,e=process.cwd()){let r=an.get(t);if(r!==void 0)return r;let s=ss(ln(e)).sessions[t];if(s===void 0)return;let i=ig(s);return an.set(i.sessionId,i),i}function zh(t){an.set(t.sessionId,t);let e=ln(t.cwd);sg(e,()=>{let r=ss(e);r.sessions[t.sessionId]=fA({...t,filePath:e}),ng(e,r)})}function pA(t,e=process.cwd()){let r=ln(e);return sg(r,()=>{let n=ss(r),s=n.sessions[t]!==void 0;return s&&(delete n.sessions[t],ng(r,n)),s})}function hA(){let t=ss(ln()),e=Object.values(t.sessions).map(ig);for(let r of e)an.set(r.sessionId,r);return e}function mc(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Qh(t){if(typeof t=="string")return{kind:"success",text:t};if(t!==void 0&&typeof t.text=="string"&&typeof t.error!="string"){let e=mc(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=mc(t.delayMs);return{kind:"error",error:t.error,...e!==void 0?{delayMs:e}:{}}}}async function Zh(t){t!==void 0&&t>0&&await new Promise(e=>setTimeout(e,t))}function gA(t,e){let{script:r,scriptContains:n}=e;if(r!==void 0){let s=Qh(r[t]??r[rg(t)]);if(s!==void 0)return s}if(n!==void 0){for(let s of Object.keys(n))if(t.includes(s)){let i=Qh(n[s]);if(i!==void 0)return i}}}function eg(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 gc(){return new pc}var an,oA,aA,Yh,fc,pc,_c=k(()=>{"use strict";an=new Map;oA=5e3,aA=15,Yh=1e4;fc=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of hA())e.set(r.sessionId,r);for(let r of an.values())e.set(r.sessionId,r);return[...e.values()].map(eg)}async loadSession(e){let r=Ki(e);return r===void 0?null:{...eg(r),messages:r.messages.slice()}}async resolveSessionPath(e){return Ki(e)?.filePath??null}async deleteSession(e){let r=an.delete(e),n=pA(e);return r||n}},pc=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new fc;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=sA(iA(e,r)),s=`mock-${n}-${nA(`${e}:${n}`)}`,i=new Date,o=ln(e),a=Ki(s,e),l=r?.prompt??"ClaudeMock seed",c=Vi(l),u={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return u.messages.push({role:"user",timestamp:i,content:l}),u.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),u.totalInputTokens+=c,u.totalOutputTokens+=Vi("ACK: ClaudeMock seeded"),zh(u),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=Ki(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=ss(ln(r.cwd)),a=gA(e,o),l=a?.delayMs??o.defaultDelayMs;if(a?.kind==="error")throw await Zh(l),new Error(a.error);let c=a?.kind==="success"?a.text:`ClaudeMock ack: ${rg(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+=Vi(e),s.totalOutputTokens+=Vi(c),zh(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),await Zh(l),{text:c,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function or(t){let e=[dl({claudeDir:t?.claudeDir}),pl({codexDir:t?.codexDir,codeDir:t?.codeDir}),Tl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),bl({copilotDir:t?.copilotDir}),kl(),Cl({kimiHome:t?.kimiHome}),Ml({lmplayerDbPath:t?.lmplayerDbPath}),Pl(),Hl({agyDir:t?.agyDir}),Ql({dshHome:t?.dshHome}),nc({hermesHome:t?.hermesHome}),lc({piDir:t?.piDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(gc()),e}var yc=k(()=>{"use strict";ul();hl();wl();Il();Al();Ol();$l();Ul();Xl();Zl();sc();cc();_c();ul();hl();wl();Il();Al();Ol();$l();Ul();Xl();Zl();sc();cc();_c()});var Sr,cn,og=k(()=>{"use strict";Sr=["claude","qwen","codex","dsh","gemini","copilot","opencode","kimi","hermes"],cn=["agy","pi","lmplayer"]});var vc={};oe(vc,{BUNDLE_CAPABLE_PROVIDERS:()=>Sr,BUNDLE_NEVER_CAPABLE_PROVIDERS:()=>cn,ProviderRegistry:()=>Cn,TransportConnectionError:()=>re,TransportError:()=>zt,TransportJsonError:()=>ui,TransportProcessError:()=>Mn,TransportRpcError:()=>$n,_resetDefaultRegistryForTests:()=>_A,bundleSupportedProviders:()=>dn,chat:()=>Ir,countTokens:()=>EA,createAdapterRegistry:()=>Yt,createAllAdapters:()=>or,deleteSession:()=>wc,listSessions:()=>os,openBundleSession:()=>is,seed:()=>Tc});function br(){return Yi===null&&(Yi=Yt(or())),Yi}function _A(){Yi=null}function Ec(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function Ir(t){let e=t.registry??br(),r=Ec(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode,holdOpen:t.holdOpen,requireResume:t.requireResume,bundleSession:t.bundleSession},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs,...s.warnings!==void 0?{warnings:s.warnings}:{}}}function dn(t){return(t??br()).getAllAdapters().filter(r=>r.openSession!==void 0).map(r=>r.name)}async function is(t){let e=t.registry??br(),r=Ec(e,t.provider);if(r.openSession===void 0)throw new Error(`provider "${t.provider}" does not support bundle sessions in this version (supported: ${dn(e).join(", ")})`);return r.openSession(t)}async function Tc(t){let e=t.registry??br(),r=Ec(e,t.provider),n=await ag(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 ag(e,t.provider,t.cwd),a=yA(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 ag(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 yA(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 os(t={}){return(t.registry??br()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function wc(t,e,r=br()){return r.deleteSession(e,t)}async function EA(t){let r=await(t.registry??br()).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 Yi,Ct=k(()=>{"use strict";$a();yc();$a();yc();og();yr();Yi=null});function zi(t){return wA.has(t)}function bc(){return Sc===null&&(Sc=Yt(or())),Sc}function Ic(t,e,r={}){if(!zi(t))return null;try{let n=bc().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?_i({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?TA[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,...lg[t]??[]]}catch{return null}}function dg(t,e,r={}){let n=Ic(t,e,r);return n===null?null:n.join(" ")}function Re(t,e){return bc().getSession(t,e)}async function un(t){return(await bc().resolveSessions(t)).map(r=>r.provider.name)}var lg,TA,wA,cg,Sc,ar=k(()=>{"use strict";Ct();Ga();lg={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:[]},TA={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]},wA=new Set(Object.keys(lg)),cg=/^[\w.:-]+$/;Sc=null});function vA(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return ug;let r=Number(e);return!Number.isFinite(r)||r<=0?ug:r}async function SA(t,e,r){try{let n=me(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 un(s);if(c.length!==1)return null;i=c[0]}let o=await Re(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 mg(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??vA(),o=await SA(t,r,n),a=o!==null&&o>=i;return a&&L({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var ug,fg=k(()=>{"use strict";V();ar();We();ug=36e5});function bA(t){return t===null?null:Ce(t)?"live":"dead"}function xc(t){let e=t.nowMs??Date.now(),r=Date.parse(t.since);return{holder_pid:t.holderPid,holder_liveness:bA(t.holderPid),since:t.since,idle_ms:Number.isFinite(r)?Math.max(0,e-r):null}}function IA(t){return(0,pg.formatDuration)(t)}function kc(t){let e=[];return t.idle_ms!==null&&e.push(`active ${IA(t.idle_ms)}`),e.push(`since ${t.since}`),e.push(t.holder_pid===null?"holder_pid=unavailable":`holder_pid=${t.holder_pid}, ${t.holder_liveness}`),`(${e.join("; ")})`}var pg,hg=k(()=>{"use strict";gr();pg=It(gt(),1)});import{randomUUID as xA}from"node:crypto";import{hostname as gg,networkInterfaces as kA}from"node:os";function _g(t){let e=(t.now??new Date).toISOString();return{lock_id:xA(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??gg(),holder_ips:t.ips??CA(),started_at:e,last_heartbeat:e}}function yg(t=process.env){return Eg(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,AA)}function NA(t=process.env){return Eg(t.LMCTL_TERMINAL_LOCK_STALE_MS,RA)}function Ac(t,e={}){let r=e.now??new Date,n=e.localHost??gg(),s=e.staleMs??NA();if(t.holder_host===n)return(e.isProcessAlive??LA)(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 xr(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function Eg(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 LA(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 CA(){let t=new Set;for(let e of Object.values(kA()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var AA,RA,as=k(()=>{"use strict";AA=15e3,RA=12e4});function OA(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
1616
1693
|
manually, outside a member session that lmctl started. Running lmctl this way is
|
|
1617
1694
|
not officially supported.
|
|
1618
1695
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Ot(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
1619
1696
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
1620
1697
|
Consulted ${Sn(pe())}
|
|
1621
1698
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Tg(t){return`unknown option --from
|
|
1622
|
-
${
|
|
1623
|
-
`)}function
|
|
1624
|
-
`});let _=t.env??process.env,T=await C(r,N=>N.getRootTeam(h)?.name??null);T!==null&&(_.LMBEE_TEAM_NAME=T),i=await FA(r,{receiverTeamfile:f,receiverAlias:m.alias,sender:y,rootTeamfile:h,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:g.origin,parentInvocationId:Kt(_.LMCTL_INVOCATION_ID)}),o=BA(r,i),i!==null&&(_.LMCTL_INVOCATION_ID=String(i));try{Hr(r,Ne(f),f)}catch{}n={root_teamfile:h,sender_teamfile:y?.teamfile??null,sender_alias:y?.alias??null,receiver_teamfile:f,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:g.origin,message_type:t.messageType??null,policy:p};let E=await kg(r,f,m.alias);if(E!==null){let N=xr(E);return kr(i,n,t.prompt,N,"unavailable"),u=Nc(N,null),{status:"busy",message:N,teamChatLogId:null}}let S=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,q=>{let Q=q.getAgentInflight(f,m.alias);return Q===null||Q.sender_teamfile!==N.row.sender_teamfile||Q.sender_alias!==N.row.sender_alias||Q.started_at!==N.row.started_at||Q.holder_pid!==process.pid?!1:q.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let q=`bundle lease lost for ${m.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return kr(i,n,t.prompt,q,"unavailable"),u=ds(q,null),{status:"error",errorKind:"provider",message:q,teamChatLogId:null,messageId:null}}}else{let N=await DA(r,f,m.alias);if(N.busy){let $=await MA(r,f,m.alias);return $+=await $A(r,f,m.alias),kr(i,n,t.prompt,$,"unavailable"),u=Nc($,null),{status:"busy",message:$,teamChatLogId:null}}S=N.idleReclaim}if(y!==null&&y.teamfile!==f){let N=await C(r,$=>Tm($,{root:h,sender:y,receiverTeamfile:f,receiverAlias:m.alias,now:new Date}));if(N.stop){let $=vm(N.chain);return kr(i,n,t.prompt,$,"cycle"),u=ds($,null),{status:"error",errorKind:"cycle",message:$,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await KA(r,{receiver_teamfile:f,receiver_alias:m.alias,sender_teamfile:y?.teamfile??f,sender_alias:y?.alias??"operator",...S?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let $=Ag(f,m.alias,N.current);return $+=` ${kc(xc({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,kr(i,n,t.prompt,$,"unavailable"),u=Nc($,null),{status:"busy",message:$,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=Gr($=>C(r,q=>q.heartbeatAgentInflight(s.row,s.leaseId,$)),{intervalMs:Ig,onError:$=>{z()&&Ee(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:$ instanceof Error?$.message:String($)}))}})}let w=await wg({sender:y??{teamfile:f,alias:"operator"},receiver:{teamfile:f,alias:m.alias,provider:m.provider,sessionId:m.sessionid,cwd:m.sessiondir,...m.model!==void 0?{model:m.model}:{},...m.effort!==void 0?{effort:m.effort}:{},...m.isLead!==void 0?{isLead:m.isLead}:{}},newMessage:t.prompt,newMessageFrom:y===null?"operator":`${y.teamfile}:${y.alias}`,io:r,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:N=>e({kind:"delta",chunk:N}),onProgress:N=>e({kind:"progress",alias:m.alias,event:N}),onPromptBuilt:async N=>{d=N,l===null&&(l=await zA(r,{...n,message:N}),l!==null&&(t.onAccepted?.(Rt(l)),i!==null&&await jA(r,i,l))),i!==null&&await UA(r,i,N)}});d=w.prompt;let b=w.status==="stalled",v=w.status==="empty",x=null,I=b?`provider stalled${w.stalledAfterMs!==void 0?` after ${w.stalledAfterMs}ms`:""}`:v?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":w.status==="error"?w.error??w.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=b||v||w.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await bg(r,l,{...n,message:d,response:w.receipt,status:R,error_detail:I}),c=!0,x=l):x=await ZA(r,{...n,message:d,response:w.receipt,status:R,error_detail:I});let M=w.status!=="error"?w.warnings:void 0;if(b||v){let N=I;kr(i,n,d,N,"error"),u=ds(N,x,w.receipt,M)}else u=WA(w.receipt,x,M);return{status:b?"stalled":v?"empty":"ok",replyText:w.receipt,wroteDelta:w.wroteDelta,teamChatLogId:x,messageId:x===null?null:Rt(x),durationMs:w.durationMs}}catch(m){let f=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await bg(r,l,{...n,message:d,response:null,status:"error",error_detail:f}),c=!0),kr(i,n,d,f,"error"),u=ds(f,l),{status:"error",errorKind:m instanceof ne?"target":"provider",message:f,teamChatLogId:l,messageId:l===null?null:Rt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await QA(r,n,Rt(l)),s!==null&&await YA(r,s.row,s.leaseId),i!==null&&await PA(r,i,u??ds("chat turn exited without a terminal outcome",null))}}function OA(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function DA(t,e,r){let n=await C(t,i=>(Yr(i,e,r),pt(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>mg(i,n,e,r));return{busy:!s,idleReclaim:s}}async function MA(t,e,r){let n=await kg(t,e,r);if(n!==null)return xr(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?Ag(e,r,s):`${r} is busy; wait and retry`}async function $A(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${kc(xc({holderPid:n.holder_pid,since:n.started_at}))}`}async function FA(t,e){try{return(await C(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:HA(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return z()&&Ee(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function PA(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function UA(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function jA(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function BA(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&Ee(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Ig);return r.unref?.(),r}function xg(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function WA(t,e,r){return{status:"done",result_summary:us(t),error:null,team_chat_log_id:e,...xg(r)}}function Nc(t,e){return{status:"busy",result_summary:us(t),error:t,team_chat_log_id:e}}function ds(t,e,r,n){return{status:"error",result_summary:us(r===void 0?t:r),error:t,team_chat_log_id:e,...xg(n)}}function us(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function HA(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function XA(t,e){let r=mn(e,t);if(r.ok)return{sender:Dt(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Ot("chat"))}async function qA(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>he(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>wm(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function GA(t,e){return await C(t,r=>gm({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:JA(r,e.sender.teamfile,e.receiverTeamfile)}))}function JA(t,e,r){return{teams:[e,r].map(s=>VA(s,t))}}function VA(t,e){let r=Ve(t,e),n=Bt(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function KA(t,e){return await C(t,r=>{let n=z(),s=Xt(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:ft(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Ee(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:Sg(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Ee(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:Sg(s.current)})),{acquired:!1,current:s.current})})}async function kg(t,e,r){return await C(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(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 Sg(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 YA(t,e,r){try{await C(t,n=>{n.releaseAgentInflight(e,r)})}catch(n){t.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
1625
|
-
`)}}function Ag(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
|
|
1699
|
+
${OA(t)}`}function mn(t,e){let r=Rc(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function Rc(t,e){let r=t[Pa];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=Ve(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===r&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var fn=k(()=>{"use strict";_t();ct();At()});function Dt(t){let e=Vs(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var ls=k(()=>{"use strict";We()});function cs(t,e,r){let n=`${e.teamfile}:${e.alias}`,s=null,i=()=>t.dal!==void 0?t.dal:(s===null&&(s=it({path:pe()})),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&&Ce(a.holder_pid)),pollMs:DA,settleMs:MA,maxHoldMs:Jr(r),onHold:()=>L({event:"delivery_hold_open_started",receiver:n}),onRelease:a=>{o(),!(!a.held&&a.reason==="cleared")&&L({event:"delivery_hold_open_released",receiver:n,elapsed_ms:a.elapsedMs,held:a.held,reason:a.reason})}}}async function wg(t){let e=$A(t.newMessage,{newMessageFrom:t.newMessageFrom??FA(t.sender)});if(e.length===0)throw new Error(`no message to deliver for ${t.sender.teamfile}:${t.sender.alias} -> ${t.receiver.teamfile}:${t.receiver.alias}`);let r=!1,n=z(),s=0,i=0,o=0,a={provider:t.receiver.provider,sessionId:t.receiver.sessionId,cwd:t.receiver.cwd,prompt:e,permissionMode:t.permissionMode,env:t.env,onDelta:c=>{r=!0,n&&(s+=1,o=Buffer.byteLength(c,"utf8"),i+=o),t.onDelta?.(c)},onProgress:c=>t.onProgress?.(c)};t.receiver.model!==void 0&&(a.model=t.receiver.model),t.receiver.effort!==void 0&&(a.effort=t.receiver.effort),a.alias=t.receiver.alias,a.isLead=t.receiver.isLead,t.idleTimeoutMs!==void 0&&(a.timeoutMs=t.idleTimeoutMs),t.requireResume!==void 0&&(a.requireResume=t.requireResume),t.bundleSession!==void 0&&(a.bundleSession=t.bundleSession),a.holdOpen=cs(t.io,t.receiver,t.env),await t.onPromptBuilt?.(e);let l=await Ir(a);if(t.requireResume&&l.sessionId!==t.receiver.sessionId)throw new Error(`provider session changed: expected ${t.receiver.sessionId}, received ${l.sessionId??"(missing)"}`);return n&&Ee(JSON.stringify({event:"chat_return",alias:t.receiver.alias,provider:t.receiver.provider,streamed:r,blockCount:s,streamedBytes:i,resultTextBytes:Buffer.byteLength(l.text,"utf8"),lastChunkBytes:o,tailPreview:l.text.slice(-200)})),l.status==="stalled"?{status:"stalled",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,stalledAfterMs:l.stalledAfterMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:l.status==="empty"?{status:"empty",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}:{status:"ok",receipt:l.text,prompt:e,wroteDelta:r,durationMs:l.durationMs,...l.warnings!==void 0?{warnings:l.warnings}:{}}}function $A(t,e={}){return[`--- new prompt (from ${e.newMessageFrom??"operator"}) ---`,t].join(`
|
|
1700
|
+
`)}function FA(t){return`${t.teamfile}:${t.alias}`}var TW,DA,MA,Qi=k(()=>{"use strict";Ct();V();Jt();ct();gr();st();TW=60*60*1e3,DA=2e3,MA=5e3});async function Ar(t){let e=t.onEvent??(()=>{}),r=PA(t.io,e),n=null,s=null,i=null,o,a,l=null,c=!1,u=null,d=t.prompt;try{let m=await C(r,N=>me(t.teamfile,t.alias,N));if(t.expectedSession!==void 0&&(m.provider!==t.expectedSession.provider||m.sessionid!==t.expectedSession.sessionid))throw new ne(`session changed for ${m.alias}; expected ${t.expectedSession.provider}:${t.expectedSession.sessionid}, found ${m.provider}:${m.sessionid}`);let f=m.teamfile,g=await C(r,N=>KA(N,t.env??process.env)),y=g.sender,h=await YA(r,{explicitRoot:t.rootFlag,sender:y,receiverTeamfile:f,operatorOrigin:g.origin==="operator"}),p=y===null?null:await zA(r,{rootTeamfile:h,sender:y,receiverTeamfile:f,receiverAlias:m.alias});p!==null&&!p.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${p.reason}
|
|
1701
|
+
`});let _=t.env??process.env,T=await C(r,N=>N.getRootTeam(h)?.name??null);T!==null&&(_.LMBEE_TEAM_NAME=T),i=await WA(r,{receiverTeamfile:f,receiverAlias:m.alias,sender:y,rootTeamfile:h,provider:m.provider,model:m.model,sessionId:m.sessionid,cwd:m.sessiondir,prompt:t.prompt,origin:g.origin,parentInvocationId:Kt(_.LMCTL_INVOCATION_ID)}),o=GA(r,i),i!==null&&(_.LMCTL_INVOCATION_ID=String(i));try{Hr(r,Ne(f),f)}catch{}n={root_teamfile:h,sender_teamfile:y?.teamfile??null,sender_alias:y?.alias??null,receiver_teamfile:f,receiver_alias:m.alias,receiver_provider:m.provider,receiver_session_id:m.sessionid,origin:g.origin,message_type:t.messageType??null,policy:p};let E=await kg(r,f,m.alias);if(E!==null){let N=xr(E);return kr(i,n,t.prompt,N,"unavailable"),u=Nc(N,null),{status:"busy",message:N,teamChatLogId:null}}let S=!1;if(t.heldLease!==void 0){let N=t.heldLease;if(!await C(r,q=>{let Q=q.getAgentInflight(f,m.alias);return Q===null||Q.sender_teamfile!==N.row.sender_teamfile||Q.sender_alias!==N.row.sender_alias||Q.started_at!==N.row.started_at||Q.holder_pid!==process.pid?!1:q.heartbeatAgentInflight(N.row,N.leaseId,new Date().toISOString())})){let q=`bundle lease lost for ${m.alias}: this batch no longer holds the in-flight lease (reclaimed or taken over); aborting before this prompt instead of dispatching unsynchronized`;return kr(i,n,t.prompt,q,"unavailable"),u=ds(q,null),{status:"error",errorKind:"provider",message:q,teamChatLogId:null,messageId:null}}}else{let N=await UA(r,f,m.alias);if(N.busy){let $=await jA(r,f,m.alias);return $+=await BA(r,f,m.alias),kr(i,n,t.prompt,$,"unavailable"),u=Nc($,null),{status:"busy",message:$,teamChatLogId:null}}S=N.idleReclaim}if(y!==null&&y.teamfile!==f){let N=await C(r,$=>Tm($,{root:h,sender:y,receiverTeamfile:f,receiverAlias:m.alias,now:new Date}));if(N.stop){let $=vm(N.chain);return kr(i,n,t.prompt,$,"cycle"),u=ds($,null),{status:"error",errorKind:"cycle",message:$,teamChatLogId:null,messageId:null}}}if(t.heldLease===void 0){let N=await eR(r,{receiver_teamfile:f,receiver_alias:m.alias,sender_teamfile:y?.teamfile??f,sender_alias:y?.alias??"operator",...S?{force:!0,reclaimReason:"session-idle"}:{}});if(!N.acquired){let $=Ag(f,m.alias,N.current);return $+=` ${kc(xc({holderPid:N.current.holder_pid,since:N.current.started_at}))}`,kr(i,n,t.prompt,$,"unavailable"),u=Nc($,null),{status:"busy",message:$,teamChatLogId:null}}s={row:N.lease,leaseId:N.leaseId},a=Gr($=>C(r,q=>q.heartbeatAgentInflight(s.row,s.leaseId,$)),{intervalMs:Ig,onError:$=>{z()&&Ee(JSON.stringify({event:"agent_inflight_heartbeat_error",receiver:{teamfile:s.row.receiver_teamfile,alias:s.row.receiver_alias},error:$ instanceof Error?$.message:String($)}))}})}let w=await wg({sender:y??{teamfile:f,alias:"operator"},receiver:{teamfile:f,alias:m.alias,provider:m.provider,sessionId:m.sessionid,cwd:m.sessiondir,...m.model!==void 0?{model:m.model}:{},...m.effort!==void 0?{effort:m.effort}:{},...m.isLead!==void 0?{isLead:m.isLead}:{}},newMessage:t.prompt,newMessageFrom:y===null?"operator":`${y.teamfile}:${y.alias}`,io:r,permissionMode:t.permissionMode,...t.expectedSession!==void 0?{requireResume:!0}:{},...t.bundleSession!==void 0?{bundleSession:t.bundleSession}:{},env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:N=>e({kind:"delta",chunk:N}),onProgress:N=>e({kind:"progress",alias:m.alias,event:N}),onPromptBuilt:async N=>{d=N,l===null&&(l=await rR(r,{...n,message:N}),l!==null&&(t.onAccepted?.(Rt(l)),i!==null&&await qA(r,i,l))),i!==null&&await XA(r,i,N)}});d=w.prompt;let b=w.status==="stalled",v=w.status==="empty",x=null,I=b?`provider stalled${w.stalledAfterMs!==void 0?` after ${w.stalledAfterMs}ms`:""}`:v?"provider returned no content and no observed activity for this turn -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error":w.status==="error"?w.error??w.receipt:n.policy?.outOfPolicy===!0?n.policy.reason:null,R=b||v||w.status==="error"?"error":n.policy?.outOfPolicy===!0?"out_of_policy":"ok";l!==null?(await bg(r,l,{...n,message:d,response:w.receipt,status:R,error_detail:I}),c=!0,x=l):x=await sR(r,{...n,message:d,response:w.receipt,status:R,error_detail:I});let M=w.status!=="error"?w.warnings:void 0;if(b||v){let N=I;kr(i,n,d,N,"error"),u=ds(N,x,w.receipt,M)}else u=JA(w.receipt,x,M);return{status:b?"stalled":v?"empty":"ok",replyText:w.receipt,wroteDelta:w.wroteDelta,teamChatLogId:x,messageId:x===null?null:Rt(x),durationMs:w.durationMs}}catch(m){let f=m instanceof Error?m.message:String(m);return l!==null&&!c&&n!==null&&(await bg(r,l,{...n,message:d,response:null,status:"error",error_detail:f}),c=!0),kr(i,n,d,f,"error"),u=ds(f,l),{status:"error",errorKind:m instanceof ne?"target":"provider",message:f,teamChatLogId:l,messageId:l===null?null:Rt(l)}}finally{o!==void 0&&clearInterval(o),a!==void 0&&clearInterval(a),l!==null&&await nR(r,n,Rt(l)),s!==null&&await tR(r,s.row,s.leaseId),i!==null&&await HA(r,i,u??ds("chat turn exited without a terminal outcome",null))}}function PA(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function UA(t,e,r){let n=await C(t,i=>(Yr(i,e,r),pt(i,e,r)));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await C(t,i=>mg(i,n,e,r));return{busy:!s,idleReclaim:s}}async function jA(t,e,r){let n=await kg(t,e,r);if(n!==null)return xr(n);let s=await C(t,i=>i.getAgentInflight(e,r));return s!==null?Ag(e,r,s):`${r} is busy; wait and retry`}async function BA(t,e,r){let n=await C(t,s=>s.getAgentInflight(e,r));return n===null?"":` ${kc(xc({holderPid:n.holder_pid,since:n.started_at}))}`}async function WA(t,e){try{return(await C(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:VA(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return z()&&Ee(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function HA(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function XA(t,e,r){try{await C(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function qA(t,e,r){try{await C(t,n=>{n.linkTrackedInvocationMessage(e,r)})}catch(n){z()&&Ee(JSON.stringify({event:"tracked_invocation_message_link_error",id:e,team_chat_log_id:r,error:n instanceof Error?n.message:String(n)}))}}function GA(t,e){if(e===null)return;let r=setInterval(()=>{C(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{z()&&Ee(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},Ig);return r.unref?.(),r}function xg(t){return t!==void 0&&t.length>0?{config_warnings:JSON.stringify(t)}:{}}function JA(t,e,r){return{status:"done",result_summary:us(t),error:null,team_chat_log_id:e,...xg(r)}}function Nc(t,e){return{status:"busy",result_summary:us(t),error:t,team_chat_log_id:e}}function ds(t,e,r,n){return{status:"error",result_summary:us(r===void 0?t:r),error:t,team_chat_log_id:e,...xg(n)}}function us(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function VA(t,e,r){return`lmctl prompt ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function KA(t,e){let r=mn(e,t);if(r.ok)return{sender:Dt(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Ot("chat"))}async function YA(t,e){if(e.explicitRoot!==void 0)return await C(t,n=>he(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await C(t,n=>wm(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function zA(t,e){return await C(t,r=>gm({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:QA(r,e.sender.teamfile,e.receiverTeamfile)}))}function QA(t,e,r){return{teams:[e,r].map(s=>ZA(s,t))}}function ZA(t,e){let r=Ve(t,e),n=Bt(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function eR(t,e){return await C(t,r=>{let n=z(),s=Xt(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:ft(),...e.force===!0?{force:!0}:{},...e.reclaimReason===void 0?{}:{reclaimReason:e.reclaimReason}});return s.acquired?(n&&Ee(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:Sg(s.previous)}})),{acquired:!0,lease:s.lease,leaseId:s.leaseId}):(n&&Ee(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:Sg(s.current)})),{acquired:!1,current:s.current})})}async function kg(t,e,r){return await C(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(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 Sg(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 tR(t,e,r){try{await C(t,n=>{n.releaseAgentInflight(e,r)})}catch(n){t.stderr.write(`warning: failed to release chat in-flight slot: ${n instanceof Error?n.message:String(n)}
|
|
1702
|
+
`)}}function Ag(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 rR(t,e){let r=ms(e.message);try{return await C(t,n=>n.beginTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:null,origin:e.origin,status:"running",error_detail:null,truncated:r.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(n){return t.stderr.write(`warning: failed to begin chat log: ${n instanceof Error?n.message:String(n)}
|
|
1626
1703
|
`),null}}async function bg(t,e,r){let n=ms(r.message),s=r.response===null?null:ms(r.response);try{await C(t,i=>i.finishTeamChatLog(e,{root_teamfile:r.root_teamfile,sender_teamfile:r.sender_teamfile,sender_alias:r.sender_alias,receiver_teamfile:r.receiver_teamfile,receiver_alias:r.receiver_alias,receiver_provider:r.receiver_provider,receiver_session_id:r.receiver_session_id,provider_prompt:r.message,message:n.text,response:s?.text??null,origin:r.origin,status:r.status,error_detail:r.error_detail,truncated:n.truncated||s?.truncated?1:0,created_at:new Date().toISOString()}))}catch(i){t.stderr.write(`warning: failed to finish chat log ${e}: ${i instanceof Error?i.message:String(i)}
|
|
1627
|
-
`)}}async function
|
|
1628
|
-
`)}}async function
|
|
1629
|
-
`),null}}function kr(t,e,r,n,s){t!==null||e===null||L({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:us(r)})}function ms(t){return t.length<=vg?{text:t,truncated:!1}:{text:t.slice(0,vg),truncated:!0}}var vg,Ig,Zi=k(()=>{"use strict";We();kt();Qs();_m();At();xn();V();ge();st();Ln();fg();hg();as();fn();ls();Qi();ti();vg=256*1024,Ig=3e4});var Lg={};oe(Lg,{runBatch:()=>
|
|
1630
|
-
`);if(l=a?[_.trim()].filter(T=>T.length>0):_.split(/\n\s*\n/u).map(T=>T.trim()).filter(Boolean),l.length===0)return A(e,`batch: ${i}: no prompts found`);c=me(n,s,e.dal)}catch(_){return A(e,`batch: ${_ instanceof Error?_.message:String(_)}`)}let u=!o&&l.length>1&&await
|
|
1631
|
-
`);try{return u?await
|
|
1704
|
+
`)}}async function nR(t,e,r){if(e!==null)try{await C(t,n=>{n.clearCurrentlyHandlingMessage(e.receiver_teamfile,e.receiver_alias,r)})}catch(n){t.stderr.write(`warning: failed to clear chat causal pointer: ${n instanceof Error?n.message:String(n)}
|
|
1705
|
+
`)}}async function sR(t,e){let r=ms(e.message),n=e.response===null?null:ms(e.response);try{return await C(t,s=>s.insertTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,receiver_provider:e.receiver_provider,receiver_session_id:e.receiver_session_id,provider_prompt:e.message,message:r.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,message_type:e.message_type??null,created_at:new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
1706
|
+
`),null}}function kr(t,e,r,n,s){t!==null||e===null||L({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:us(r)})}function ms(t){return t.length<=vg?{text:t,truncated:!1}:{text:t.slice(0,vg),truncated:!0}}var vg,Ig,Zi=k(()=>{"use strict";We();kt();Qs();_m();At();xn();V();ge();st();Ln();fg();hg();as();fn();ls();Qi();ti();vg=256*1024,Ig=3e4});var Lg={};oe(Lg,{runBatch:()=>oR});import{readFileSync as iR}from"node:fs";async function oR(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(Rg),0;let r=ae(t,[],["--legacy","--single"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==3)return A(e,Rg.trimEnd());let[n,s,i]=r.positionals,o=r.flags["--legacy"]===!0,a=r.flags["--single"]===!0,l,c;try{let _=iR(i,"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
1707
|
+
`);if(l=a?[_.trim()].filter(T=>T.length>0):_.split(/\n\s*\n/u).map(T=>T.trim()).filter(Boolean),l.length===0)return A(e,`batch: ${i}: no prompts found`);c=me(n,s,e.dal)}catch(_){return A(e,`batch: ${_ instanceof Error?_.message:String(_)}`)}let u=!o&&l.length>1&&await cR(c),d={...e.env??process.env},m=await dR(e,{member:c,batchfile:i,promptCount:l.length,parentInvocationId:Kt(d.LMCTL_INVOCATION_ID)}),f={status:"error",error:"batch exited without a terminal outcome"},g=_=>{f=_},y=_=>{m!==null&&(mR(e,m,{status:"cancelled",signal:_,error:`batch interrupted by ${_}`}),process.exit(_==="SIGINT"?130:143))},h=()=>y("SIGINT"),p=()=>y("SIGTERM");m!==null&&(d.LMCTL_INVOCATION_ID=String(m),process.once("SIGINT",h),process.once("SIGTERM",p)),e.stderr.write(`batch ${Ue()}: starting ${l.length} prompt${l.length===1?"":"s"} -> ${c.alias} (teamfile=${n} input=${i})
|
|
1708
|
+
`);try{return u?await aR(e,{member:c,prompts:l,env:d,setRootFinish:g,teamfile:n,batchfile:i}):await Lc(e,{member:c,prompts:l,env:d,setRootFinish:g,teamfile:n,batchfile:i})}finally{m!==null&&(process.removeListener("SIGINT",h),process.removeListener("SIGTERM",p),await uR(e,m,f))}}async function Lc(t,e){let{member:r,prompts:n,env:s}=e;for(let[i,o]of n.entries()){t.stderr.write(`batch ${Ue()}: prompt ${i+1}/${n.length} -> ${r.alias}
|
|
1632
1709
|
`);let a=ot(t,l=>`batch ${Ue()}: prompt ${i+1}/${n.length} still running (${l}s elapsed)
|
|
1633
1710
|
`);try{let l=await Ar({teamfile:r.teamfile,alias:r.alias,prompt:o,expectedSession:{provider:r.provider,sessionid:r.sessionid},permissionMode:"yolo",env:{...s},messageType:"batch",...e.heldLease!==void 0?{heldLease:e.heldLease}:{},...e.bundleSession!==void 0?{bundleSession:e.bundleSession}:{},io:t,onEvent:c=>{a.poke(),c.kind==="warning"&&t.stderr.write(c.message)}});if((l.status==="ok"||l.status==="stalled"||l.status==="empty")&&l.replyText&&t.stdout.write(`${l.replyText}${l.replyText.endsWith(`
|
|
1634
1711
|
`)?"":`
|
|
1635
1712
|
`}
|
|
1636
1713
|
`),l.status!=="ok"){let c=l.status==="stalled"?"provider stalled":l.status==="empty"?"provider returned no content and no observed activity for this turn":l.message,u=`batch: stopped at prompt ${i+1}/${n.length} (${i} completed): ${c}; later prompts were not sent`;return e.setRootFinish({status:l.status==="busy"?"busy":"error",exit_code:1,error:u,result_summary:`${i}/${n.length} prompts completed`}),A(t,u)}}catch(l){let c=`batch: stopped at prompt ${i+1}/${n.length} (${i} completed): ${l instanceof Error?l.message:String(l)}; later prompts were not sent`;return e.setRootFinish({status:"error",exit_code:1,error:c,result_summary:`${i}/${n.length} prompts completed`}),A(t,c)}finally{a.stop()}}return t.stderr.write(`batch ${Ue()}: completed ${n.length}/${n.length} prompts
|
|
1637
|
-
`),e.setRootFinish({status:"done",exit_code:0,result_summary:`batch completed ${n.length}/${n.length} prompts`}),0}async function
|
|
1714
|
+
`),e.setRootFinish({status:"done",exit_code:0,result_summary:`batch completed ${n.length}/${n.length} prompts`}),0}async function aR(t,e){let{member:r,prompts:n,env:s}=e,i=await C(t,m=>(Yr(m,r.teamfile,r.alias),pt(m,r.teamfile,r.alias)));if(i.busy){let m=i.reason==="in-flight"?`${r.alias} is servicing ${i.inFlight.sender_alias} (${i.inFlight.sender_teamfile}) since ${i.inFlight.started_at} \u2014 wait and retry`:i.source==="terminal-lock"?xr(i.terminalLock):`${r.alias} is busy (interactive terminal); wait and retry`;return e.setRootFinish({status:"busy",exit_code:1,error:m,result_summary:"0 prompts completed"}),A(t,`batch: cannot start bundle: ${m}`)}let o=await C(t,m=>lR(s,m)),a=await C(t,m=>Xt(m,{receiver_teamfile:r.teamfile,receiver_alias:r.alias,sender_teamfile:o?.teamfile??r.teamfile,sender_alias:o?.alias??"operator",ttlMs:ft()}));if(!a.acquired){let m=`${r.alias} is servicing ${a.current.sender_alias} (${a.current.sender_teamfile}) since ${a.current.started_at} \u2014 wait and retry`;return e.setRootFinish({status:"busy",exit_code:1,error:m,result_summary:"0 prompts completed"}),A(t,`batch: cannot start bundle: ${m}`)}let l={row:a.lease,leaseId:a.leaseId},c=Gr(m=>C(t,f=>f.heartbeatAgentInflight(l.row,l.leaseId,m))),u,d=ot(t,m=>`batch ${Ue()}: opening provider session (${m}s elapsed)
|
|
1638
1715
|
`);try{let m={...s};try{let f=await C(t,g=>g.getRootTeam(r.teamfile)?.name??null);f!==null&&(m.LMBEE_TEAM_NAME=f)}catch{}u=await is({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,env:m,...r.model!==void 0?{model:r.model}:{},...r.effort!==void 0?{effort:r.effort}:{},alias:r.alias,isLead:r.isLead,permissionMode:"yolo",holdOpen:cs(t,{teamfile:r.teamfile,alias:r.alias},m)})}catch{return clearInterval(c),await Ng(t,l),Lc(t,{member:r,prompts:n,env:s,setRootFinish:e.setRootFinish,teamfile:e.teamfile,batchfile:e.batchfile})}finally{d.stop()}try{return await Lc(t,{member:r,prompts:n,env:s,setRootFinish:e.setRootFinish,teamfile:e.teamfile,batchfile:e.batchfile,heldLease:l,bundleSession:u})}finally{await u.close(),clearInterval(c),await Ng(t,l)}}async function Ng(t,e){try{await C(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
1639
|
-
`)}}function
|
|
1640
|
-
`),null}}async function
|
|
1641
|
-
`)}}function
|
|
1716
|
+
`)}}function lR(t,e){let r=mn(t,e);if(r.ok)return Dt(r.identity);if(r.reason==="unset")return null;throw new Error(Ot("batch"))}async function cR(t){let e=t.provider.trim().toLowerCase();return cn.includes(e)||Qr().tools[e]?.agent!==void 0||!Sr.includes(e)?!1:dn().includes(e)}async function dR(t,e){try{let{member:r}=e;return await C(t,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:r.teamfile,from_identity:`${r.teamfile}:batch`,target_teamfile:r.teamfile,target_alias:r.alias,root_teamfile:r.teamfile,cwd:r.sessiondir,command:`lmctl batch ${r.teamfile} ${r.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:r.provider,sessionid:r.sessionid,...r.model!==void 0?{model:r.model}:{}})}).id)}catch(r){return t.stderr.write(`warning: failed to start batch root invocation: ${r instanceof Error?r.message:String(r)}
|
|
1717
|
+
`),null}}async function uR(t,e,r){try{await C(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){t.stderr.write(`warning: failed to finish batch root invocation: ${n instanceof Error?n.message:String(n)}
|
|
1718
|
+
`)}}function mR(t,e,r){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let n=it({path:pe()});try{n.finishTrackedInvocation(e,r)}finally{n.close()}}catch{}}var Rg,Cg=k(()=>{"use strict";Zi();ge();ct();We();Jt();st();Ln();xn();as();fn();ls();On();Qi();Ct();Rg=`usage: lmctl batch <teamfile> <alias> <batchfile> [--legacy] [--single]
|
|
1642
1719
|
|
|
1643
1720
|
Send blank-line-separated paragraphs as prompts, one completed turn at a
|
|
1644
1721
|
time, to the same existing member session. Accepts export --prompt-only
|
|
@@ -1665,7 +1742,7 @@ lease) -- the pre-bundle behavior -- as an opt-out while bundle is new.
|
|
|
1665
1742
|
--single sends the WHOLE file as ONE prompt: blank lines are content, not
|
|
1666
1743
|
separators. A single prompt (one paragraph, or --single) never bundles and
|
|
1667
1744
|
never takes a batch-level lease -- one plain turn.
|
|
1668
|
-
`});import{spawn as Og,spawnSync as Oc}from"node:child_process";import{randomUUID as
|
|
1745
|
+
`});import{spawn as Og,spawnSync as Oc}from"node:child_process";import{randomUUID as fR}from"node:crypto";import{tmpdir as pR}from"node:os";import*as U from"node:fs";import*as _e from"node:path";import*as jg from"node:readline";import{fileURLToPath as Bg}from"node:url";function Wg(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(`
|
|
1669
1746
|
`),i=String(t.line),o=t.line-1,a=s[o]??"",l=" | ",c=` ${i.padStart(4," ")} | `,u=" ".repeat(Math.max(0,t.column-1));return`[${t.severity.toUpperCase()} at ${r}] ${t.message}
|
|
1670
1747
|
`+l+`
|
|
1671
1748
|
${c}${a}
|
|
@@ -1697,11 +1774,11 @@ try {
|
|
|
1697
1774
|
} finally {
|
|
1698
1775
|
clearTimeout(timer);
|
|
1699
1776
|
}
|
|
1700
|
-
`,n=Oc(process.execPath,["--input-type=module","-e",r,t],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:Dc+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
|
|
1777
|
+
`,n=Oc(process.execPath,["--input-type=module","-e",r,t],{encoding:"utf8",shell:!1,timeout:35e3,maxBuffer:Dc+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 hR(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>Dc)throw await s.cancel().catch(()=>{}),r.abort(),new Error("response exceeds 10 MiB limit");o.push(l.value)}return Buffer.concat(o).toString("utf-8")}catch(i){if(r.abort(),s)try{await s.cancel().catch(()=>{})}catch{}throw i.name==="AbortError"?new Error("urlget() request timed out"):new Error(`urlget() failed: ${i?.message||String(i)}`)}finally{clearTimeout(n)}}function no(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 qg(t){let e=String(t);return e.length>0&&/^[a-zA-Z0-9_./@=-]+$/.test(e)?e:"'"+e.replace(/'/g,"'\\''")+"'"}function Gg(t,e=6e4){if(!Number.isSafeInteger(e)||e<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");let r=performance.now(),n;if(Array.isArray(t)){if(t.length===0)throw new Error("system() argv array must not be empty");let u=String(t[0]),d=t.slice(1).map(String);n=Oc(u,d,{shell:!1,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"})}else n=Oc(t,{shell:!0,encoding:"utf-8",timeout:e>0?e:void 0,maxBuffer:10*1024*1024,killSignal:"SIGKILL"});let s=Math.max(0,Math.round(performance.now()-r)),i=typeof n.pid=="number"?n.pid:null;if(n.error){if(n.error.code==="ETIMEDOUT"){let u=n.stdout!=null?String(n.stdout):"",d=n.stderr!=null?String(n.stderr):"";return no(u,d,null,n.signal||"SIGKILL",!0,s,i)}throw n.error}let o=n.stdout!=null?String(n.stdout):"",a=n.stderr!=null?String(n.stderr):"",l=n.status!==null?n.status:null,c=n.signal!==null?String(n.signal):null;return no(o,a,l,c,!1,s,i)}function Jg(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 T=String(t[0]),E=t.slice(1).map(String);o=Og(T,E,{shell:!1,detached:i,stdio:["ignore","pipe","pipe"]})}else o=Og(t,{shell:!0,detached:i,stdio:["ignore","pipe","pipe"]});ro.add(o);let a="",l="",c=null,u=null,d=0,m=!1,f=!1,g,y=!1,h,p=()=>{if(y)return;y=!0,ro.delete(o),h&&clearTimeout(h);try{o.stdout?.destroy(),o.stderr?.destroy()}catch{}let T=Math.max(0,Math.round(performance.now()-s)),E=typeof o.pid=="number"?o.pid:null;if(g){n(g);return}if(f){r(no(a,l,null,u||"SIGKILL",!0,T,E));return}r(no(a,l,c,u,!1,T,E))};e>0&&(h=setTimeout(()=>{f=!0,u="SIGKILL";try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}p()},e));let _=10*1024*1024;o.stdout?.setEncoding("utf-8"),o.stderr?.setEncoding("utf-8"),o.stdout?.on("data",T=>{let E=Buffer.byteLength(T,"utf-8");if(d+E>_){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1701
1778
|
`)?`
|
|
1702
1779
|
`:"")+"system() output exceeds 10 MiB limit",g=new Error("system() output exceeds 10 MiB limit"),p()}return}d+=E,a+=T}),o.stderr?.on("data",T=>{let E=Buffer.byteLength(T,"utf-8");if(d+E>_){if(!m){m=!0;try{if(i&&o.pid)try{process.kill(-o.pid,"SIGKILL")}catch{o.kill("SIGKILL")}else o.kill("SIGKILL")}catch{}l+=(l&&!l.endsWith(`
|
|
1703
1780
|
`)?`
|
|
1704
|
-
`:"")+"system() output exceeds 10 MiB limit",g=new Error("system() output exceeds 10 MiB limit"),p()}return}d+=E,l+=T}),o.on("error",T=>{g||(g=T)}),o.on("close",(T,E)=>{T!==null?(c=T,u=null):(c=null,u=E?String(E):null),p()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function
|
|
1781
|
+
`:"")+"system() output exceeds 10 MiB limit",g=new Error("system() output exceeds 10 MiB limit"),p()}return}d+=E,l+=T}),o.on("error",T=>{g||(g=T)}),o.on("close",(T,E)=>{T!==null?(c=T,u=null):(c=null,u=E?String(E):null),p()})}catch(i){n(i instanceof Error?i:new Error(String(i)))}})}function gR(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 _s(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===`
|
|
1705
1782
|
`)return r.endsWith("\r")&&(r=r.slice(0,-1)),r;r+=s}}catch{return null}}function ys(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=jg.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 Dg(t,e=!0,r=","){Hg(r);let n=[],s=[],i="",o=!1,a=!1,l=!1;for(let d=0;d<t.length;d++){let m=t[d],f=t[d+1];if(l=!0,o)m==='"'?f==='"'?(i+='"',d++):(o=!1,a=!0):i+=m;else{if(a&&m!==r&&m!=="\r"&&m!==`
|
|
1706
1783
|
`)throw new Error("Invalid CSV: unexpected character after closing quote");if(m==='"'){if(i.length>0)throw new Error("Invalid CSV: quote inside unquoted field");o=!0}else m===r?(a=!1,s.push(i),i=""):m==="\r"?(f===`
|
|
1707
1784
|
`&&d++,s.push(i),n.push(s),s=[],i="",a=!1,l=!1):m===`
|
|
@@ -1709,7 +1786,7 @@ try {
|
|
|
1709
1786
|
`);if(typeof r=="object"&&r!==null){let n=Object.keys(r),s=n.map(o=>to(o,e)).join(e),i=t.map(o=>n.map(a=>to(wt(o,a)??"",e)).join(e));return[s,...i].join(`
|
|
1710
1787
|
`)}return t.map(n=>to(n,e)).join(`
|
|
1711
1788
|
`)}function to(t,e){let r=t==null?"":String(t);return r===""||r.includes(e)||r.includes('"')||r.includes(`
|
|
1712
|
-
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}function Mc(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)Mc(s,e);else n&&typeof n=="object"&&Mc(n,e)}}}function
|
|
1789
|
+
`)||r.includes("\r")?`"${r.replaceAll('"','""')}"`:r}function Mc(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)Mc(s,e);else n&&typeof n=="object"&&Mc(n,e)}}}function yR(){if(!Cc){let e=new ps(_R,"<std>").tokenize(),n=new hs(e,"<std>").parse();for(let s of n.statements)s.kind==="FunctionDeclStmt"&&(s.isStdlib=!0);Cc=n}return{kind:"Program",statements:[...Cc.statements],line:1,column:1,file:"<std>"}}function ER(t,e={}){let r=e.file||"<main>",n=e.baseDir||(e.file?_e.dirname(_e.resolve(e.file)):process.cwd()),s=new Map,i=new Set;function o(h,p){if(e.moduleResolver)return e.moduleResolver(h,p).path;let _=n;p&&p!=="<main>"&&p!=="<std>"&&(_=_e.dirname(p));let T=_e.resolve(_,h);try{return U.realpathSync(T)}catch{return T}}function a(h,p){let _,T;if(e.moduleResolver){let v=e.moduleResolver(h,p);_=v.path,T=v.source}else{if(_=o(h,p),s.has(_))return s.get(_);if(i.has(_))return{kind:"Program",statements:[],line:1,column:1,file:_};try{T=U.readFileSync(_,"utf-8")}catch(v){throw new P(`Cannot resolve import '${h}': ${v?.message||String(v)}`,1,1,"PARSER",p)}}if(s.has(_))return s.get(_);if(i.has(_))return{kind:"Program",statements:[],line:1,column:1,file:_};i.add(_);let S=new ps(T,_).tokenize(),b=new hs(S,_).parse();for(let v of b.statements)if(v.kind!=="FunctionDeclStmt"&&v.kind!=="ImportStmt")throw new P(`Library '${_}' cannot contain top-level executable statements; libraries must only declare functions. Found '${v.kind}'.`,v.line,v.column,"CHECKER",_);for(let v of b.statements)v.kind==="ImportStmt"&&a(v.path,_);return i.delete(_),s.set(_,b),b}let c=new ps(t,r).tokenize(),d=new hs(c,r).parse(),m=r!=="<main>"?o(r):"<main>";s.set(m,d);for(let h of d.statements)h.kind==="ImportStmt"&&a(h.path,r);let f=[];if(!e.noStdlib){let h=yR();for(let p of h.statements)p.kind==="FunctionDeclStmt"&&f.push(p)}for(let[h,p]of s.entries())if(h!==m)for(let _ of p.statements)_.kind==="FunctionDeclStmt"&&f.push(_);for(let h of d.statements)h.kind!=="ImportStmt"&&f.push(h);let g={kind:"Program",statements:f,line:d.line,column:d.column,file:r},y=Array.from(s.keys());return{program:g,loadedFiles:y}}function SR(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 Pg(t,e){let r=new Date(t),n=(s,i=2)=>String(s).padStart(i,"0");return String(e).replace(/%[YmdHMS%]/g,s=>{switch(s){case"%Y":return String(r.getFullYear());case"%m":return n(r.getMonth()+1);case"%d":return n(r.getDate());case"%H":return n(r.getHours());case"%M":return n(r.getMinutes());case"%S":return n(r.getSeconds());case"%%":return"%";default:return s}})}function gs(t,e){let r=0,n=s=>typeof s=="object"&&s!==null?JSON.stringify(s):String(s);return String(t).replace(/%[sdf%]/g,s=>{if(s==="%%")return"%";let i=e[r++];return s==="%d"?String(Math.trunc(Number(i))):s==="%f"?String(Number(i)):n(i)})}async function bR(){console.log("================================================="),console.log(" LMScript Verification & Full Feature Test Suite "),console.log(`=================================================
|
|
1713
1790
|
`);let t=new ur,e=!0;console.log("Test Suite 1: Functions, Recursion, and Control Flow");let n=t.run(`
|
|
1714
1791
|
fn factorial(n) {
|
|
1715
1792
|
if (n <= 1) {
|
|
@@ -1936,7 +2013,7 @@ try {
|
|
|
1936
2013
|
assert(res1 == "a" && res2 == "b" && res3 == "c", "parallel results must match return values");
|
|
1937
2014
|
`);return p.success?(console.log(p.output.map(_=>" [out] "+_).join(`
|
|
1938
2015
|
`)),console.log(` -> Passed!
|
|
1939
|
-
`)):(console.error(" -> Failed:",p.diagnostics),e=!1),e}async function
|
|
2016
|
+
`)):(console.error(" -> Failed:",p.diagnostics),e=!1),e}async function IR(){let t=process.argv.slice(2);if(t.length===0||t.length===1&&t[0]==="--test"){await bR()||(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:_e.resolve(t[0]),o=s?t[1]:U.readFileSync(i,"utf-8"),a=new ur,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(Wg(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 P,Ge,Dc,ro,eo,Fg,ps,hs,_R,Cc,Rr,$c,pn,lr,cr,hn,lt,so,Fc,io,TR,wR,vR,ur,Ug,Pc=k(()=>{"use strict";P=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}},Ge=class extends Error{isControlFlow=!0;exitCode;constructor(e=0){super(`LMScript exited with code ${e}`),this.name="LMScriptExit",this.exitCode=e}};Dc=10*1024*1024;ro=new Set,eo=1e3;process.on("exit",()=>{for(let t of ro)try{process.platform!=="win32"&&t.pid?process.kill(-t.pid,"SIGKILL"):t.kill("SIGKILL")}catch{}ro.clear()});Fg={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"},ps=class{source;length;file;pos=0;line=1;column=1;constructor(e,r){this.source=e,this.length=e.length,this.file=r}tokenize(){let e=[];for(;this.pos<this.length&&(this.skipWhitespaceAndComments(),!(this.pos>=this.length));){let r=this.line,n=this.column,s=this.peek();if(this.isDigit(s)||s==="."&&this.isDigit(this.peekNext())){e.push(this.readNumber(r,n));continue}if(s==='"'||s==="'"){e.push(this.readString(s,r,n));continue}if(s==="<"&&this.peekNext()==="<"){let i=this.tryReadHeredoc(r,n);if(i){e.push(i);continue}}if(this.isAlpha(s)){e.push(this.readIdentifier(r,n));continue}switch(this.advance(),s){case".":e.push({type:"DOT",value:".",line:r,column:n});break;case":":e.push({type:"COLON",value:":",line:r,column:n});break;case"(":e.push({type:"LPAREN",value:"(",line:r,column:n});break;case")":e.push({type:"RPAREN",value:")",line:r,column:n});break;case"{":e.push({type:"LBRACE",value:"{",line:r,column:n});break;case"}":e.push({type:"RBRACE",value:"}",line:r,column:n});break;case"[":e.push({type:"LBRACKET",value:"[",line:r,column:n});break;case"]":e.push({type:"RBRACKET",value:"]",line:r,column:n});break;case",":e.push({type:"COMMA",value:",",line:r,column:n});break;case";":e.push({type:"SEMICOLON",value:";",line:r,column:n});break;case"+":e.push({type:"PLUS",value:"+",line:r,column:n});break;case"-":e.push({type:"MINUS",value:"-",line:r,column:n});break;case"*":e.push({type:"STAR",value:"*",line:r,column:n});break;case"/":e.push({type:"SLASH",value:"/",line:r,column:n});break;case"%":e.push({type:"PERCENT",value:"%",line:r,column:n});break;case"=":this.match("=")?e.push({type:"EQUAL",value:"==",line:r,column:n}):e.push({type:"ASSIGN",value:"=",line:r,column:n});break;case"!":this.match("=")?e.push({type:"NOT_EQUAL",value:"!=",line:r,column:n}):e.push({type:"NOT",value:"!",line:r,column:n});break;case"<":this.match("=")?e.push({type:"LESS_EQUAL",value:"<=",line:r,column:n}):e.push({type:"LESS",value:"<",line:r,column:n});break;case">":this.match("=")?e.push({type:"GREATER_EQUAL",value:">=",line:r,column:n}):e.push({type:"GREATER",value:">",line:r,column:n});break;case"&":if(this.match("&"))e.push({type:"AND",value:"&&",line:r,column:n});else throw new P("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 P("Unexpected character '|'. Did you mean '||'?",r,n,"LEXER",this.file);break;default:throw new P(`Unexpected character: '${s}'`,r,n,"LEXER",this.file)}}return e.push({type:"EOF",value:"",line:this.line,column:this.column}),e}peek(){return this.source[this.pos]||""}peekNext(){return this.source[this.pos+1]||""}advance(){let e=this.source[this.pos++];return e===`
|
|
1940
2017
|
`?(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===`
|
|
1941
2018
|
`)this.advance();else if(e==="/"&&this.peekNext()==="/"||e==="#")for(;this.pos<this.length&&this.peek()!==`
|
|
1942
2019
|
`;)this.advance();else if(e==="/"&&this.peekNext()==="*"){let r=this.line,n=this.column;this.advance(),this.advance();let s=!1;for(;this.pos<this.length;){if(this.peek()==="*"&&this.peekNext()==="/"){this.advance(),this.advance(),s=!0;break}this.advance()}if(!s)throw new P("Unterminated block comment",r,n,"LEXER",this.file)}else break}}readNumber(e,r){let n="";for(;this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peekNext()))for(n+=this.advance();this.pos<this.length&&this.isDigit(this.peek());)n+=this.advance();return{type:"NUMBER",value:n,literal:parseFloat(n),line:e,column:r}}readString(e,r,n){this.advance();let s="";for(;this.pos<this.length&&this.peek()!==e;){if(this.peek()===`
|
|
@@ -1947,7 +2024,7 @@ try {
|
|
|
1947
2024
|
`;)c++;let u=this.source.slice(l,c),d=u===`${s};`;if(u===s||d){let g=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1948
2025
|
`?2:this.source[c]===`
|
|
1949
2026
|
`||this.source[c]==="\r"?1:0,y=this.source.slice(a,l),p=s.length+(d?0:g);for(let _=0;_<p;_++)this.advance();return{type:"STRING",value:y,literal:y,line:e,column:r}}let m=this.source[c]==="\r"&&this.source[c+1]===`
|
|
1950
|
-
`?2:c<this.length?1:0,f=c+m-this.pos;for(let g=0;g<f;g++)this.advance()}throw new P(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(Fg,n)?Fg[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}}};hs=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&&Mc(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 P("'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 P?r:new P(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new P("'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 P("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new P("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 P("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new P("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new P("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 P("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 P(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new P(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},mR=`# LMScript Standard Library (std.lms)
|
|
2027
|
+
`?2:c<this.length?1:0,f=c+m-this.pos;for(let g=0;g<f;g++)this.advance()}throw new P(`Unterminated heredoc; expected closing marker '${s}'`,e,r,"LEXER",this.file)}readIdentifier(e,r){let n="";for(;this.pos<this.length&&this.isAlphaNumeric(this.peek());)n+=this.advance();let s=Object.hasOwn(Fg,n)?Fg[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}}};hs=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&&Mc(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 P("'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 P?r:new P(r instanceof Error?r.message:String(r),this.peek().line,this.peek().column,"PARSER",this.file)}}parseImportStmt(){let e=this.previous(),r=this.consume("STRING","Expected file path string after 'import'");return this.consumeOptionalSemicolon(),{kind:"ImportStmt",path:r.value,line:e.line,column:e.column,file:this.file}}parseFunctionDecl(){let e=this.previous(),r=this.consume("IDENTIFIER","Expected function name after 'fn'");this.consume("LPAREN","Expected '(' after function name");let n=[];if(!this.check("RPAREN"))do{let i=this.consume("IDENTIFIER","Expected parameter name");n.push(i.value)}while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after parameters"),this.consume("LBRACE","Expected '{' before function body");let s=this.parseBlockBody(this.previous());return{kind:"FunctionDeclStmt",name:r.value,params:n,body:s,line:e.line,column:e.column}}parseVarDecl(){let e=this.previous();if(this.match("LPAREN","LBRACKET")){let s=this.previous().type==="LPAREN"?"RPAREN":"RBRACKET",i=[];if(!this.check(s))do{let a=this.consume("IDENTIFIER","Expected variable name in destructuring");i.push(a.value)}while(this.match("COMMA"));this.consume(s,`Expected '${s==="RPAREN"?")":"]"}' after variable list`),this.consume("ASSIGN","Expected '=' after destructuring variable list");let o=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"TupleVarDeclStmt",names:i,initializer:o,line:e.line,column:e.column}}let r=this.consume("IDENTIFIER","Expected variable name after 'let'"),n;return this.match("ASSIGN")&&(n=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"VarDeclStmt",name:r.value,initializer:n,line:e.line,column:e.column}}parseStatement(){if(this.match("IMPORT"))throw new P("'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 P("Invalid 'sync' statement target; expected variable assignment ('sync a = ...'), member/index assignment ('sync obj.k = ...'), or container mutation call ('sync push(arr, ...)').",e.line,e.column,"PARSER",this.file)}parseIfStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'if'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after if condition");let n=this.parseStatement(),s;return this.match("ELSE")&&(s=this.parseStatement()),{kind:"IfStmt",condition:r,thenBranch:n,elseBranch:s,line:e.line,column:e.column}}parseWhileStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'while'");let r=this.parseExpression();this.consume("RPAREN","Expected ')' after while condition");let n=this.parseStatement();return{kind:"WhileStmt",condition:r,body:n,line:e.line,column:e.column}}parseForStatement(){let e=this.previous();this.consume("LPAREN","Expected '(' after 'for'");let r;if(this.match("SEMICOLON"))r=void 0;else if(this.match("LET"))r=this.parseVarDecl();else{let o=this.parseExpression();this.consume("SEMICOLON","Expected ';' after for-loop initializer"),r={kind:"ExprStmt",expr:o,line:o.line,column:o.column}}let n;this.check("SEMICOLON")||(n=this.parseExpression()),this.consume("SEMICOLON","Expected ';' after for-loop condition");let s;this.check("RPAREN")||(s=this.parseExpression()),this.consume("RPAREN","Expected ')' after for clauses");let i=this.parseStatement();return{kind:"ForStmt",init:r,condition:n,update:s,body:i,line:e.line,column:e.column}}parseReturnStatement(){let e=this.previous(),r;return!this.check("SEMICOLON")&&!this.check("RBRACE")&&!this.isAtEnd()&&(r=this.parseExpression()),this.consumeOptionalSemicolon(),{kind:"ReturnStmt",value:r,line:e.line,column:e.column}}parseBreakStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"BreakStmt",line:e.line,column:e.column}}parseContinueStatement(){let e=this.previous();return this.consumeOptionalSemicolon(),{kind:"ContinueStmt",line:e.line,column:e.column}}parseBlockBody(e){let r=[];for(;!this.check("RBRACE")&&!this.isAtEnd();)r.push(this.parseDeclaration());return this.consume("RBRACE","Expected '}' after block"),{kind:"BlockStmt",statements:r,line:e.line,column:e.column}}parseExpressionStatement(){let e=this.parseExpression();return this.consumeOptionalSemicolon(),{kind:"ExprStmt",expr:e,line:e.line,column:e.column}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseLogicalOr();if(this.match("ASSIGN")){let r=this.previous(),n=this.parseAssignment();if(e.kind==="IdentifierExpr")return{kind:"AssignExpr",target:e.name,value:n,line:r.line,column:r.column};if(e.kind==="IndexExpr")return{kind:"IndexAssignExpr",target:e.target,index:e.index,value:n,line:r.line,column:r.column};if(e.kind==="TupleExpr"||e.kind==="ArrayExpr"){let s=[];for(let i of e.elements){if(i.kind!=="IdentifierExpr")throw new P("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 P("Invalid assignment target",e.line,e.column,"PARSER",this.file)}return e}parseLogicalOr(){let e=this.parseLogicalAnd();for(;this.match("OR");){let r=this.previous(),n=this.parseLogicalAnd();e={kind:"BinaryExpr",operator:"||",left:e,right:n,line:r.line,column:r.column}}return e}parseLogicalAnd(){let e=this.parseEquality();for(;this.match("AND");){let r=this.previous(),n=this.parseEquality();e={kind:"BinaryExpr",operator:"&&",left:e,right:n,line:r.line,column:r.column}}return e}parseEquality(){let e=this.parseRelational();for(;this.match("EQUAL","NOT_EQUAL");){let r=this.previous(),n=r.type==="EQUAL"?"==":"!=",s=this.parseRelational();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseRelational(){let e=this.parseAdditive();for(;this.match("LESS","LESS_EQUAL","GREATER","GREATER_EQUAL");){let r=this.previous(),n=r.type==="LESS"?"<":r.type==="LESS_EQUAL"?"<=":r.type==="GREATER"?">":">=",s=this.parseAdditive();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseAdditive(){let e=this.parseMultiplicative();for(;this.match("PLUS","MINUS");){let r=this.previous(),n=r.type==="PLUS"?"+":"-",s=this.parseMultiplicative();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseMultiplicative(){let e=this.parseUnary();for(;this.match("STAR","SLASH","PERCENT");){let r=this.previous(),n=r.type==="STAR"?"*":r.type==="SLASH"?"/":"%",s=this.parseUnary();e={kind:"BinaryExpr",operator:n,left:e,right:s,line:r.line,column:r.column}}return e}parseUnary(){if(this.match("NOT","MINUS")){let e=this.previous(),r=e.type==="NOT"?"!":"-",n=this.parseUnary();return{kind:"UnaryExpr",operator:r,operand:n,line:e.line,column:e.column}}return this.parseCallAndIndex()}parseCallAndIndex(){let e=this.parsePrimary();for(;;)if(this.match("LPAREN")){if(e.kind!=="IdentifierExpr")throw new P("Only identifiers can be called directly as functions",e.line,e.column,"PARSER",this.file);let r=[];if(!this.check("RPAREN"))do r.push(this.parseExpression());while(this.match("COMMA"));this.consume("RPAREN","Expected ')' after function arguments"),e={kind:"CallExpr",callee:e.name,args:r,line:e.line,column:e.column}}else if(this.match("LBRACKET")){let r=this.parseExpression();this.consume("RBRACKET","Expected ']' after index expression"),e={kind:"IndexExpr",target:e,index:r,line:e.line,column:e.column}}else if(this.match("DOT")){let r=this.consume("IDENTIFIER","Expected property name after '.'");e={kind:"IndexExpr",target:e,index:{kind:"LiteralExpr",value:r.value,line:r.line,column:r.column},line:r.line,column:r.column}}else break;return e}parsePrimary(){let e=this.peek();if(this.match("NUMBER","STRING","TRUE","FALSE","NULL"))return{kind:"LiteralExpr",value:this.previous().literal,line:e.line,column:e.column};if(this.match("PARALLEL")){let r=this.previous();this.consume("LPAREN","Expected '(' after 'parallel'"),this.consume("LBRACKET","Expected '[' starting array of function calls in 'parallel([ ... ])'");let n=[];if(!this.check("RBRACKET"))do{let s=this.parseExpression();if(s.kind!=="CallExpr")throw new P("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 P("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 P(`Unexpected token '${e.value||e.type}' in expression`,e.line,e.column,"PARSER",this.file)}match(...e){for(let r of e)if(this.check(r))return this.advance(),!0;return!1}check(e){return this.isAtEnd()?!1:this.peek().type===e}advance(){return this.isAtEnd()||this.current++,this.previous()}isAtEnd(){return this.peek().type==="EOF"}peek(){return this.tokens[this.current]}previous(){return this.tokens[this.current-1]}consume(e,r){if(this.check(e))return this.advance();let n=this.peek();throw new P(r,n.line,n.column,"PARSER",this.file)}consumeOptionalSemicolon(){this.check("SEMICOLON")&&this.advance()}},_R=`# LMScript Standard Library (std.lms)
|
|
1951
2028
|
|
|
1952
2029
|
# String Utilities
|
|
1953
2030
|
fn is_blank(s) {
|
|
@@ -2047,32 +2124,32 @@ fn clamp(val, low, high) {
|
|
|
2047
2124
|
`)+(w.output.length>0?`
|
|
2048
2125
|
`:""),v=w.exitCode!==void 0?w.exitCode:w.success?0:1,x={success:w.success&&v===0,stdout:b,output:[...w.output],value:w.value,exit_code:v,code:v,errors:w.errors??[]};return x.toString=()=>b,x})();{let w=S.run(T,{file:_}),b=w.output.join(`
|
|
2049
2126
|
`)+(w.output.length>0?`
|
|
2050
|
-
`:""),v=w.exitCode!==void 0?w.exitCode:w.success?0:1,x={success:w.success&&v===0,stdout:b,output:[...w.output],value:w.value,exit_code:v,code:v,errors:w.errors??[]};return x.toString=()=>b,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let g=e.get("urlget");(!g||g.isDefault)&&this.hostFunctions.set("urlget",{fn:h=>this.isAsync?dR(h):Xg(h),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let y=e.get("sleep");(!y||y.isDefault)&&this.hostFunctions.set("sleep",{fn:h=>{if(typeof h!="number"||!Number.isFinite(h)||h<0)throw new Error("sleep() duration must be a non-negative finite number");if(h>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(_=>setTimeout(_,h));let p=Date.now()+h;for(;Date.now()<p;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new lt,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 lt(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 P(`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 P("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 lr)break;if(s instanceof cr)continue;throw s}}return}case"ForStmt":{let n=new lt(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 P("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 lr)break;if(!(i instanceof cr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new pn(n)}case"BreakStmt":throw new lr;case"ContinueStmt":throw new cr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new P("'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 P(`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),dr(n,s,i),i;throw new P("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)dr(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 P("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]:wt(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 P(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new P("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 P(`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 hn)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>eo)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${eo})`,s,i,"RUNTIME",o);let l=new lt(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 pn)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 Ge||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`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 P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new hn(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new lt,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 lt(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 P(`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 P("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 lr)break;if(i instanceof cr)continue;throw i}}return}case"ForStmt":{let s=new lt(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 P("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 lr)break;if(!(o instanceof cr))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 pn(s)}case"BreakStmt":throw new lr;case"ContinueStmt":throw new cr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new P(`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 P("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),dr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("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 P(`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 P("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new P(`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),dr(s,i,o),o;throw new P("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)dr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,r,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new P("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]:wt(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 P(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new P("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 P(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>eo)throw this.asyncCallDepth.set(o,u-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${eo})`,s,i,"RUNTIME",a);let d=new lt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)d.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,d,o)}catch(m){if(m instanceof pn)return m.value;throw m}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...r);return u instanceof Promise?await u:u}catch(u){throw u instanceof Ge||u?.name==="LMScriptExit"||u?.isControlFlow?u:new P(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},hR=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],gR=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],_R=[{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);"}];ur=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 hR)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of gR)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of _R)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
|
|
2127
|
+
`:""),v=w.exitCode!==void 0?w.exitCode:w.success?0:1,x={success:w.success&&v===0,stdout:b,output:[...w.output],value:w.value,exit_code:v,code:v,errors:w.errors??[]};return x.toString=()=>b,x}},arity:{min:1,max:2},description:"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",isDefault:!0});let g=e.get("urlget");(!g||g.isDefault)&&this.hostFunctions.set("urlget",{fn:h=>this.isAsync?hR(h):Xg(h),arity:1,description:"Downloads UTF-8 text from a public HTTP(S) URL",isDefault:!0});let y=e.get("sleep");(!y||y.isDefault)&&this.hostFunctions.set("sleep",{fn:h=>{if(typeof h!="number"||!Number.isFinite(h)||h<0)throw new Error("sleep() duration must be a non-negative finite number");if(h>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");if(this.isAsync)return new Promise(_=>setTimeout(_,h));let p=Date.now()+h;for(;Date.now()<p;);return null},arity:1,description:"Sleeps for the specified milliseconds",isDefault:!0})}evaluateProgram(e){if(this.globalEnv=new lt,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 lt(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 P(`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 P("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 lr)break;if(s instanceof cr)continue;throw s}}return}case"ForStmt":{let n=new lt(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 P("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 lr)break;if(!(i instanceof cr))throw i}e.update&&this.evalExpr(e.update,n)}return}case"ReturnStmt":{let n=e.value?this.evalExpr(e.value,r):null;throw new pn(n)}case"BreakStmt":throw new lr;case"ContinueStmt":throw new cr;case"SyncAssignStmt":case"SyncIndexAssignStmt":case"SyncCallStmt":throw new P("Synchronized statements require asynchronous execution via engine.runAsync()",e.line,e.column,"RUNTIME",e.file);case"ExprStmt":return this.evalExpr(e.expr,r);default:return}}evalExpr(e,r){switch(e.kind){case"ParallelExpr":throw new P("'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 P(`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),dr(n,s,i),i;throw new P("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)dr(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 P("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]:wt(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 P(`Unknown unary operator: ${s}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?this.evalExpr(e.right,r):o}if(e.operator==="||"){let o=this.evalExpr(e.left,r);return this.isTruthy(o)?o:this.evalExpr(e.right,r)}let n=this.evalExpr(e.left,r),s=this.evalExpr(e.right,r),i=e.operator;switch(i){case"+":return typeof n=="string"||typeof s=="string"?String(n)+String(s):n+s;case"-":return n-s;case"*":return n*s;case"/":if(s===0)throw new P("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 P(`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 hn)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>eo)throw this.callDepth--,new P(`Execution fuel exhausted: maximum function call depth exceeded (${eo})`,s,i,"RUNTIME",o);let l=new lt(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 pn)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 Ge||l?.name==="LMScriptExit"||l?.isControlFlow?l:new P(`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 P(`'${e}' is not a function`,s,i,"RUNTIME",o):new P(`Undefined function '${e}'`,s,i,"RUNTIME",o)}resolveIdentifier(e,r){return r.has(e)?r.get(e):this.userFunctions.has(e)||this.hostFunctions.has(e)?new hn(e):r.get(e)}isTruthy(e){return!(e==null||e===!1||e===0||e==="")}async evaluateProgramAsync(e){if(this.globalEnv=new lt,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 lt(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 P(`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 P("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 lr)break;if(i instanceof cr)continue;throw i}}return}case"ForStmt":{let s=new lt(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 P("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 lr)break;if(!(o instanceof cr))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 pn(s)}case"BreakStmt":throw new lr;case"ContinueStmt":throw new cr;case"SyncAssignStmt":{let s=r.resolveBinding(e.target);if(!s)throw new P(`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 P("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),dr(s,o,a)},n);return}case"SyncCallStmt":{let s=e.call;if(s.args.length===0)throw new P("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 P(`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 P("Target of synchronized call must be an array or map",e.line,e.column,"RUNTIME",e.file);await this.lockManager.getObjectLock(o).withLock(async()=>{let l=[];for(let c=1;c<s.args.length;c++)l.push(await this.evalExprAsync(s.args[c],r,n));await this.invokeCallAsync(s.callee,[o,...l],r,e.line,e.column,n,e.file)},n);return}case"ExprStmt":return await this.evalExprAsync(e.expr,r,n);default:return}}async evalExprAsync(e,r,n){switch(e.kind){case"LiteralExpr":return e.value;case"IdentifierExpr":return this.resolveIdentifier(e.name,r);case"AssignExpr":{let s=await this.evalExprAsync(e.value,r,n);return r.set(e.target,s),s}case"TupleAssignExpr":{let s=await this.evalExprAsync(e.value,r,n);if(!Array.isArray(s))throw new P(`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),dr(s,i,o),o;throw new P("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)dr(s,i.key,await this.evalExprAsync(i.value,r,n));return s}case"ParallelExpr":{if(e.tasks.length===0)return[];let s=this.asyncCallDepth.get(n)??0,i=e.tasks.map(async c=>{let u=this.nextTaskId++;return this.asyncCallDepth.set(u,s),await this.evalExprAsync(c,r,u)}),o=await Promise.allSettled(i),a=[],l;for(let c of o)c.status==="fulfilled"?a.push(c.value):l||(l=c.reason);if(l)throw l;return a}case"IndexExpr":{let s=await this.evalExprAsync(e.target,r,n),i=await this.evalExprAsync(e.index,r,n);if(s==null)throw new P("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]:wt(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 P(`Unknown unary operator: ${i}`,e.line,e.column,"RUNTIME",e.file)}case"BinaryExpr":{if(e.operator==="&&"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?await this.evalExprAsync(e.right,r,n):a}if(e.operator==="||"){let a=await this.evalExprAsync(e.left,r,n);return this.isTruthy(a)?a:await this.evalExprAsync(e.right,r,n)}let s=await this.evalExprAsync(e.left,r,n),i=await this.evalExprAsync(e.right,r,n),o=e.operator;switch(o){case"+":return typeof s=="string"||typeof i=="string"?String(s)+String(i):s+i;case"-":return s-i;case"*":return s*i;case"/":if(i===0)throw new P("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 P(`Unknown binary operator: ${o}`,e.line,e.column,"RUNTIME",e.file)}}case"CallExpr":{let s=[];for(let i of e.args)s.push(await this.evalExprAsync(i,r,n));return await this.invokeCallAsync(e.callee,s,r,e.line,e.column,n,e.file)}}}async invokeCallAsync(e,r,n,s,i,o,a){let l=this.resolveCallTarget(e,n);if(this.userFunctions.has(l)){let c=this.userFunctions.get(l),u=(this.asyncCallDepth.get(o)??0)+1;if(this.asyncCallDepth.set(o,u),u>eo)throw this.asyncCallDepth.set(o,u-1),new P(`Execution fuel exhausted: maximum function call depth exceeded (${eo})`,s,i,"RUNTIME",a);let d=new lt(this.globalEnv,!0);for(let m=0;m<c.params.length;m++)d.define(c.params[m],r[m]);try{for(let m of c.body.statements)await this.execStmtAsync(m,d,o)}catch(m){if(m instanceof pn)return m.value;throw m}finally{this.asyncCallDepth.set(o,u-1)}return null}if(this.hostFunctions.has(l)){let c=this.hostFunctions.get(l);try{let u=c.fn(...r);return u instanceof Promise?await u:u}catch(u){throw u instanceof Ge||u?.name==="LMScriptExit"||u?.isControlFlow?u:new P(`Error in host function '${l}': ${u?.message||String(u)}`,s,i,"RUNTIME",a)}}throw n.has(l)&&!(this.userFunctions.has(l)||this.hostFunctions.has(l))?new P(`'${l}' is not a function`,s,i,"RUNTIME",a):new P(`Undefined function '${l}'`,s,i,"RUNTIME",a)}getRecordedErrors(){return[...this.recordedErrors]}},TR=[{name:"if",category:"Language Constructs",signature:"if (condition) { ... } else { ... }",description:"Conditional branching flow control.",example:'if (x > 0) { print("yes"); } else { print("no"); }'},{name:"while",category:"Language Constructs",signature:"while (condition) { ... }",description:"Looping flow control that repeats while condition is true.",example:"while (i < 10) { i = i + 1; }"},{name:"for",category:"Language Constructs",signature:"for (init; condition; update) { ... }",description:"C-style for loop for iteration. Use 'let' in the init clause (for (let i = 0; ...)) so the counter is fresh to this loop -- an init without 'let' (for (i = 0; ...)) reuses/mutates an outer i of the same name, which silently corrupts an enclosing loop that also counts with i.",example:"for (let i = 0; i < len(arr); i = i + 1) { print(arr[i]); }"},{name:"fn",category:"Language Constructs",signature:"fn name(arg1, arg2) { ... }",description:"Defines a custom function. A bare assignment (name = value) inside the body is local to THIS function by default -- it never mutates an outer/global variable that merely happens to share the name (same principle as Python/Perl/JS function scoping). See 'let' for a fresh binding even across nested if/while/for blocks within the same function.",example:"fn add(a, b) { return a + b; }"},{name:"let",category:"Language Constructs",signature:"let name = value;",description:"Declares a guaranteed-fresh local variable, scoped to the immediately enclosing block (function body, if/while/for body) -- it always shadows any outer variable of the same name and is discarded when the block exits, never mutating the outer one. Use it for a for-loop's own counter to keep nested loops sharing a name (e.g. two loops both using i) from corrupting each other: for (let i = 0; ...) { for (let i = 0; ...) { ... } }.",example:"fn f() { let total = 0; return total; }"},{name:"import",category:"Language Constructs",signature:'import "path"',description:"Imports and executes another script file.",example:'import "utils.lm"'},{name:"parallel",category:"Language Constructs",signature:"parallel([ call1(), call2() ])",description:"Executes an array of function calls concurrently, returning an array of results.",example:'(a,b) = parallel([ system("echo 1"), system("echo 2") ]);'},{name:"sync",category:"Language Constructs",signature:"sync expr",description:"Forces sequential execution of an assignment or container mutation inside a parallel block.",example:'sync push(results, "done");'},{name:"break",category:"Language Constructs",signature:"break",description:"Exits the innermost loop.",example:"while (true) { break; }"},{name:"continue",category:"Language Constructs",signature:"continue",description:"Skips to the next iteration of the innermost loop.",example:"for (let i = 0; i < 2; i = i + 1) { if (i == 0) { continue; } }"},{name:"return",category:"Language Constructs",signature:"return expr",description:"Returns a value from a function or script.",example:"return 42;"}],wR=[{name:"read_file",category:"File I/O",signature:"read_file(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string.",example:'content = read_file("config.json");'},{name:"read",category:"File I/O",signature:"read(path: string): string",description:"Reads the entire contents of a file as a UTF-8 string (alias for read_file).",example:'content = read("data.txt");'},{name:"read_lines",category:"File I/O",signature:"read_lines(path: string): array",description:"Reads a file and returns an array of string lines.",example:'lines = read_lines("items.txt");'},{name:"write_lines",category:"File I/O",signature:"write_lines(path: string, lines: array): boolean",description:"Writes an array of lines to a file with trailing newline, round-tripping with read_lines.",example:'write_lines("out.txt", ["a", "b"]);'},{name:"glob",category:"File I/O",signature:"glob(pattern: string): array",description:"Finds files matching a glob pattern and returns an array of matching paths.",example:'files = glob("~/repos/*/*.lmctl");'},{name:"list_dir",category:"File I/O",signature:"list_dir(path: string): array",description:"Lists filenames in a directory.",example:'entries = list_dir(".");'},{name:"write_file",category:"File I/O",signature:"write_file(path: string, content: any): boolean",description:"Writes content to a file, creating or overwriting it.",example:'write_file("out.txt", "hello");'},{name:"write",category:"File I/O",signature:"write(path: string, content: any): boolean",description:"Writes content to a file (alias for write_file).",example:'write("out.txt", "data");'},{name:"append_file",category:"File I/O",signature:"append_file(path: string, content: any): boolean",description:"Appends string content to the end of a file.",example:'append_file("log.txt", "step completed\\n");'},{name:"read_json",category:"File I/O",signature:"read_json(path: string): any",description:"Reads a JSON file from disk and parses it into an object or array.",example:'data = read_json("package.json");'},{name:"write_json",category:"File I/O",signature:"write_json(path: string, data: any, [indent: number = 2]): boolean",description:"Serializes data as formatted JSON and writes it to a file.",example:'write_json("out.json", { "status": "ok" }, 2);'},{name:"read_csv",category:"File I/O",signature:'read_csv(path: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Reads an RFC 4180 CSV file and parses it into an array of objects or rows.",example:'rows = read_csv("data.csv");'},{name:"write_csv",category:"File I/O",signature:'write_csv(path: string, data: array, [delimiter: string = ","]): boolean',description:"Serializes an array of objects or rows to CSV and writes to a file.",example:'write_csv("out.csv", [{ name: "Alice", age: 30 }]);'},{name:"csv_parse",category:"File I/O",signature:'csv_parse(text: string, [hasHeader: boolean = true], [delimiter: string = ","]): array',description:"Parses inline CSV text into an array of objects or rows.",example:'records = csv_parse("name,score\\nBob,95");'},{name:"csv_stringify",category:"File I/O",signature:'csv_stringify(data: array, [delimiter: string = ","]): string',description:"Serializes an array of objects or rows into RFC 4180 CSV text.",example:"csv_text = csv_stringify(records);"},{name:"file_exists",category:"File I/O",signature:"file_exists(path: string): boolean",description:"Checks if a file exists at the given path.",example:'if (file_exists("log.txt")) { print("found"); }'},{name:"temp_file",category:"File I/O",signature:"temp_file(): string",description:"Creates an empty temporary file and returns its absolute path.",example:"tmp = temp_file();"},{name:"mkdir",category:"File I/O",signature:"mkdir(dirPath: string, [recursive: boolean = true]): boolean",description:"Creates a directory, recursively by default.",example:'mkdir("out/logs");'},{name:"rmdir",category:"File I/O",signature:"rmdir(dirPath: string, [recursive: boolean = false]): boolean",description:"Removes a directory; pass true to remove a non-empty directory recursively.",example:'rmdir("out/logs", true);'},{name:"copy_file",category:"File I/O",signature:"copy_file(src: string, dest: string): boolean",description:"Copies a file to a new path.",example:'copy_file("a.txt", "b.txt");'},{name:"move_file",category:"File I/O",signature:"move_file(src: string, dest: string): boolean",description:"Moves/renames a file.",example:'move_file("draft.txt", "final.txt");'},{name:"basename",category:"File I/O",signature:"basename(filePath: string, [ext: string]): string",description:"Returns the last path segment, optionally stripping a trailing extension.",example:'name = basename("/a/b/c.txt", ".txt");'},{name:"dirname",category:"File I/O",signature:"dirname(filePath: string): string",description:"Returns the directory portion of a path.",example:'dir = dirname("/a/b/c.txt");'},{name:"path_join",category:"File I/O",signature:"path_join(...parts: string): string",description:"Joins path segments using the OS-native separator.",example:'p = path_join("a", "b", "c.txt");'},{name:"abs_path",category:"File I/O",signature:"abs_path(filePath: string): string",description:"Resolves a path to an absolute path.",example:'p = abs_path("relative/file.txt");'},{name:"env",category:"System & Process",signature:"env(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset.",example:'home = env("HOME");'},{name:"getenv",category:"System & Process",signature:"getenv(name: string, [fallback: any = null]): any",description:"Reads an environment variable, or a fallback if unset (alias for env).",example:'home = getenv("HOME");'},{name:"set_env",category:"System & Process",signature:"set_env(name: string, value: any): boolean",description:"Sets an environment variable for this process and its children.",example:'set_env("DEBUG", "1");'},{name:"now",category:"System & Process",signature:"now(): number",description:"Returns current epoch in ms (alias for clock).",example:"t = now();"},{name:"timestamp",category:"System & Process",signature:"timestamp(): number",description:"Returns current Unix epoch in whole seconds.",example:"t = timestamp();"},{name:"date",category:"System & Process",signature:"date([epochMs: number]): string",description:"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp.",example:"iso = date();"},{name:"strftime",category:"System & Process",signature:"strftime(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens.",example:'s = strftime(now(), "%Y-%m-%d");'},{name:"date_format",category:"System & Process",signature:"date_format(epochMs: number, fmt: string): string",description:"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime).",example:'s = date_format(now(), "%Y-%m-%d");'},{name:"coalesce",category:"System & Process",signature:"coalesce(...values: any): any",description:"Returns the first non-null/non-undefined argument, else null.",example:'v = coalesce(a, b, "default");'},{name:"if_null",category:"System & Process",signature:"if_null(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val.",example:'v = if_null(maybe_null, "default");'},{name:"default_to",category:"System & Process",signature:"default_to(val: any, fallback: any): any",description:"Returns fallback if val is null/undefined, else val (alias for if_null).",example:'v = default_to(maybe_null, "default");'},{name:"if_else",category:"System & Process",signature:"if_else(cond: any, thenVal: any, elseVal: any): any",description:"Expression-level ternary: returns thenVal if cond is truthy, else elseVal.",example:'label = if_else(count > 0, "some", "none");'},{name:"regex_test",category:"Strings",signature:"regex_test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = regex_test(s, "\\\\d+");'},{name:"test",category:"Strings",signature:"test(s: string, pattern: string, [flags: string]): boolean",description:"Tests whether a regex pattern matches anywhere in the string (alias for regex_test). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'has_digits = test(s, "\\\\d+");'},{name:"regex_match",category:"Strings",signature:"regex_match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = regex_match(line, "provider=(\\\\S+)");'},{name:"match",category:"Strings",signature:"match(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = match(line, "provider=(\\\\S+)");'},{name:"search",category:"Strings",signature:"search(s: string, pattern: string, [flags: string]): array|null",description:"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'m = search(line, "provider=(\\\\S+)");'},{name:"regex_find_all",category:"Strings",signature:"regex_find_all(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...]. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = regex_find_all(s, "\\\\d+");'},{name:"findall",category:"Strings",signature:"findall(s: string, pattern: string, [flags: string]): array",description:"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all). JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'nums = findall(s, "\\\\d+");'},{name:"regex_replace",category:"Strings",signature:"regex_replace(s: string, pattern: string, replacement: string, [flags: string]): string",description:'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].',example:'clean = regex_replace(s, "\\\\s+", " ", "g");'},{name:"split_regex",category:"Strings",signature:"split_regex(s: string, pattern: string, [flags: string]): array",description:"Splits a string into an array wherever the regex pattern matches. JavaScript RegExp syntax, not POSIX -- e.g. \\\\s not [[:space:]].",example:'parts = split_regex(s, "\\\\d+");'},{name:"split",category:"Strings",signature:'split(s: string, [delimiter: string = ""]): array',description:"Splits a string by delimiter into an array of substrings.",example:'parts = split("a,b,c", ",");'},{name:"lines",category:"Strings",signature:"lines(s: string): array",description:"Splits a string into an array of lines.",example:'arr = lines("line1\\nline2");'},{name:"last_line_as_status",category:"Strings",signature:"last_line_as_status(s: string): string|null",description:"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), otherwise returns null.",example:"status = last_line_as_status(reply);"},{name:"words",category:"Strings",signature:"words(s: string): array",description:"Splits a string into non-whitespace words.",example:'w = words("hello world from lmscript");'},{name:"join",category:"Strings",signature:'join(arr: array, [separator: string = ", "]): string',description:"Joins array elements into a string separated by delimiter.",example:'s = join(["apple", "banana"], ", ");'},{name:"trim",category:"Strings",signature:"trim(s: string): string",description:"Trims whitespace from both ends of a string.",example:'clean = trim(" hello ");'},{name:"strip",category:"Strings",signature:"strip(s: string): string",description:"Trims whitespace from both ends of a string (alias for trim).",example:'clean = strip(" hello ");'},{name:"trim_start",category:"Strings",signature:"trim_start(s: string): string",description:"Trims whitespace from the beginning of a string.",example:'s = trim_start(" hello");'},{name:"lstrip",category:"Strings",signature:"lstrip(s: string): string",description:"Trims whitespace from the beginning of a string (alias for trim_start).",example:'s = lstrip(" hello");'},{name:"trim_end",category:"Strings",signature:"trim_end(s: string): string",description:"Trims whitespace from the end of a string.",example:'s = trim_end("hello ");'},{name:"rstrip",category:"Strings",signature:"rstrip(s: string): string",description:"Trims whitespace from the end of a string (alias for trim_end).",example:'s = rstrip("hello ");'},{name:"to_upper",category:"Strings",signature:"to_upper(s: string): string",description:"Converts all characters in string to uppercase.",example:'u = to_upper("hello");'},{name:"upper",category:"Strings",signature:"upper(s: string): string",description:"Converts all characters in string to uppercase (alias for to_upper).",example:'u = upper("hello");'},{name:"toUpperCase",category:"Strings",signature:"toUpperCase(s: string): string",description:"Converts all characters in string to uppercase (alias for upper).",example:'u = toUpperCase("hello");'},{name:"to_lower",category:"Strings",signature:"to_lower(s: string): string",description:"Converts all characters in string to lowercase.",example:'l = to_lower("HELLO");'},{name:"lower",category:"Strings",signature:"lower(s: string): string",description:"Converts all characters in string to lowercase (alias for to_lower).",example:'l = lower("HELLO");'},{name:"toLowerCase",category:"Strings",signature:"toLowerCase(s: string): string",description:"Converts all characters in string to lowercase (alias for lower).",example:'l = toLowerCase("HELLO");'},{name:"capitalize",category:"Strings",signature:"capitalize(s: string): string",description:"Capitalizes the first character of a string.",example:'c = capitalize("hello");'},{name:"title_case",category:"Strings",signature:"title_case(s: string): string",description:"Converts words in a string to Title Case.",example:'t = title_case("hello world");'},{name:"contains",category:"Strings",signature:"contains(haystack: string|array, needle: any): boolean",description:"Checks if a string or array contains an item or substring.",example:'if (contains("hello", "ell")) { print("matched"); }'},{name:"includes",category:"Strings",signature:"includes(haystack: string|array, needle: any): boolean",description:"Alias for contains.",example:'if (includes([1, 2, 3], 2)) { print("found"); }'},{name:"starts_with",category:"Strings",signature:"starts_with(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix.",example:'if (starts_with("prefix_name", "prefix_")) { ... }'},{name:"startswith",category:"Strings",signature:"startswith(s: string, prefix: string): boolean",description:"Checks if a string starts with the given prefix (alias for starts_with).",example:'if (startswith("prefix_name", "prefix_")) { ... }'},{name:"ends_with",category:"Strings",signature:"ends_with(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix.",example:'if (ends_with("file.txt", ".txt")) { ... }'},{name:"endswith",category:"Strings",signature:"endswith(s: string, suffix: string): boolean",description:"Checks if a string ends with the given suffix (alias for ends_with).",example:'if (endswith("file.txt", ".txt")) { ... }'},{name:"index_of",category:"Strings",signature:"index_of(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found.",example:'idx = index_of("banana", "a");'},{name:"indexOf",category:"Strings",signature:"indexOf(haystack: string|array, needle: any, [fromIndex: number]): number",description:"Finds the first index of a substring or item, or -1 if not found (alias for index_of).",example:'idx = indexOf("banana", "a");'},{name:"last_index_of",category:"Strings",signature:"last_index_of(haystack: string|array, needle: any): number",description:"Finds the last index of a substring or item, or -1 if not found.",example:'idx = last_index_of("banana", "a");'},{name:"count_matches",category:"Strings",signature:"count_matches(s: string, sub: string): number",description:"Counts non-overlapping occurrences of a substring.",example:'n = count_matches("banana", "a");'},{name:"substr",category:"Strings",signature:"substr(s: string, start: number, [length: number]): string",description:"Returns a substring starting from start index of specified length.",example:'sub = substr("hello", 1, 3);'},{name:"substring",category:"Strings",signature:"substring(s: string, start: number, [end: number]): string",description:"Returns a substring between start and end indices.",example:'sub = substring("hello", 1, 4);'},{name:"slice",category:"Strings",signature:"slice(target: string|array, start: number, [end: number]): string|array",description:"Extracts a section of a string or array.",example:"part = slice([1, 2, 3, 4], 1, 3);"},{name:"char_at",category:"Strings",signature:"char_at(s: string, index: number): string",description:"Returns the character at the specified index.",example:'c = char_at("hello", 0);'},{name:"char_code",category:"Strings",signature:"char_code(s: string, [index: number = 0]): number",description:"Returns the Unicode code point at index.",example:'code = char_code("A");'},{name:"from_char_code",category:"Strings",signature:"from_char_code(...codes: number): string",description:"Returns string from character codes.",example:"s = from_char_code(65, 66, 67);"},{name:"replace",category:"Strings",signature:"replace(s: string, search: string, replacement: string): string",description:"Replaces the first occurrence of search substring.",example:'s = replace("hello world", "world", "lmscript");'},{name:"replace_all",category:"Strings",signature:"replace_all(s: string, search: string, replacement: string): string",description:"Replaces all occurrences of search substring.",example:'s = replace_all("foo bar foo", "foo", "baz");'},{name:"repeat",category:"Strings",signature:"repeat(s: string, count: number): string",description:"Repeats a string count times.",example:'stars = repeat("*", 10);'},{name:"pad_start",category:"Strings",signature:'pad_start(s: string, targetLength: number, [padChar: string = " "]): string',description:"Left-pads string to target length.",example:'num_str = pad_start("5", 3, "0");'},{name:"pad_end",category:"Strings",signature:'pad_end(s: string, targetLength: number, [padChar: string = " "]): string',description:"Right-pads string to target length.",example:'row = pad_end("title", 20, ".");'},{name:"reverse_str",category:"Strings",signature:"reverse_str(s: string): string",description:"Reverses characters in a string.",example:'rev = reverse_str("abc");'},{name:"is_empty",category:"Strings",signature:"is_empty(val: any): boolean",description:"Checks if a string, array, or object is empty or null.",example:'if (is_empty(arr)) { print("empty"); }'},{name:"is_digit",category:"Strings",signature:"is_digit(s: string): boolean",description:"Checks if a string contains only digits.",example:'if (is_digit("123")) { print("all digits"); }'},{name:"is_alpha",category:"Strings",signature:"is_alpha(s: string): boolean",description:"Checks if a string contains only alphabetic characters.",example:'if (is_alpha("abc")) { ... }'},{name:"is_alnum",category:"Strings",signature:"is_alnum(s: string): boolean",description:"Checks if a string contains only letters and digits.",example:'if (is_alnum("item42")) { ... }'},{name:"format",category:"Strings",signature:"format(template: string, ...args: any): string",description:"Formats a template string replacing {{}} brace escapes, positional {0}, auto {}, and {key} map placeholders.",example:'msg = format("Hello, {}! You have {} tasks.", "User", 3);'},{name:"sprintf",category:"Strings",signature:"sprintf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax).",example:'msg = sprintf("%s scored %d", "Alice", 95);'},{name:"shell_quote",category:"Strings",signature:"shell_quote(val: any): string",description:"Quotes string safely for POSIX shell command execution.",example:'escaped = shell_quote("arg with spaces");'},{name:"len",category:"Lists & Arrays",signature:"len(item: any): number",description:"Returns the length of a string, array, or number of object keys.",example:"n = len([10, 20, 30]);"},{name:"length",category:"Lists & Arrays",signature:"length(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = length([10, 20, 30]);"},{name:"count",category:"Lists & Arrays",signature:"count(item: any): number",description:"Returns the length of a string, array, or number of object keys (alias for len).",example:"n = count([10, 20, 30]);"},{name:"push",category:"Lists & Arrays",signature:"push(arr: array, item: any): array",description:"Appends an element to the end of an array and returns the array.",example:'push(items, "new_item");'},{name:"pop",category:"Lists & Arrays",signature:"pop(arr: array): any",description:"Removes and returns the last element of an array.",example:"last = pop(items);"},{name:"shift",category:"Lists & Arrays",signature:"shift(arr: array): any",description:"Removes and returns the first element of an array.",example:"first = shift(items);"},{name:"unshift",category:"Lists & Arrays",signature:"unshift(arr: array, item: any): array",description:"Prepends an element to the beginning of an array.",example:'unshift(items, "header");'},{name:"insert",category:"Lists & Arrays",signature:"insert(arr: array, index: number, item: any): array",description:"Inserts an element at the specified index in an array.",example:'insert(items, 1, "inserted");'},{name:"remove_at",category:"Lists & Arrays",signature:"remove_at(arr: array, index: number): any",description:"Removes and returns the element at the specified index.",example:"removed = remove_at(items, 0);"},{name:"concat",category:"Lists & Arrays",signature:"concat(a: array, b: array): array",description:"Concatenates two arrays into a new array.",example:"all = concat(arr1, arr2);"},{name:"reverse",category:"Lists & Arrays",signature:"reverse(arr: array): array",description:"Reverses elements of an array in place.",example:"reverse(items);"},{name:"sort",category:"Lists & Arrays",signature:"sort(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key.",example:'sorted = sort(users, "age");'},{name:"sorted",category:"Lists & Arrays",signature:"sorted(arr: array, [key: string]): array",description:"Sorts array elements numerically, alphabetically, or by object key (alias for sort).",example:'result = sorted(users, "age");'},{name:"unique",category:"Lists & Arrays",signature:"unique(arr: array): array",description:"Returns a new array with duplicate elements removed.",example:"deduped = unique([1, 2, 2, 3]);"},{name:"flatten",category:"Lists & Arrays",signature:"flatten(arr: array): array",description:"Flattens a nested array by one level.",example:"flat = flatten([[1, 2], [3, 4]]);"},{name:"first",category:"Lists & Arrays",signature:"first(arr: array): any",description:"Returns the first element of an array, or null if empty.",example:"top = first(items);"},{name:"last",category:"Lists & Arrays",signature:"last(arr: array): any",description:"Returns the last element of an array, or null if empty.",example:"tail = last(items);"},{name:"sum",category:"Lists & Arrays",signature:"sum(arr: array): number",description:"Computes the arithmetic sum of numeric elements in an array.",example:"total = sum([1, 2, 3, 4]);"},{name:"avg",category:"Lists & Arrays",signature:"avg(arr: array): number",description:"Computes the arithmetic mean of numeric elements in an array.",example:"mean = avg([10, 20, 30]);"},{name:"range",category:"Lists & Arrays",signature:"range(start: number, [end: number], [step: number = 1]): array",description:"Generates an array of numbers from start to end by step.",example:"nums = range(0, 5);"},{name:"keys",category:"Maps & Key-Value",signature:"keys(obj: object): array",description:"Returns an array of own property keys of an object.",example:"k = keys({ a: 1, b: 2 });"},{name:"values",category:"Maps & Key-Value",signature:"values(obj: object): array",description:"Returns an array of own property values of an object.",example:"v = values({ a: 1, b: 2 });"},{name:"entries",category:"Maps & Key-Value",signature:"entries(obj: object): array",description:"Returns an array of [key, value] pairs for an object.",example:"pairs = entries({ a: 1, b: 2 });"},{name:"items",category:"Maps & Key-Value",signature:"items(obj: object): array",description:"Returns an array of [key, value] pairs for an object (alias for entries).",example:"pairs = items({ a: 1, b: 2 });"},{name:"from_entries",category:"Maps & Key-Value",signature:"from_entries(pairs: array): object",description:"Constructs an object from an array of [key, value] pairs.",example:'obj = from_entries([["name", "Bob"], ["age", 25]]);'},{name:"has_key",category:"Maps & Key-Value",signature:"has_key(obj: object, key: string): boolean",description:"Checks if an object has the specified own property key.",example:'if (has_key(config, "port")) { ... }'},{name:"has",category:"Maps & Key-Value",signature:"has(obj: object, key: string): boolean",description:"Checks if an object has the specified key (alias for has_key).",example:'if (has(user, "email")) { ... }'},{name:"get",category:"Maps & Key-Value",signature:"get(obj: any, path: string|array, [defaultVal: any]): any",description:"Retrieves a nested property safely using a dot or array path.",example:'val = get(config, "database.host", "localhost");'},{name:"getstr",category:"Maps & Key-Value",signature:'getstr(obj: any, path: string|array, [fallback: string = ""]): string',description:'Typed form of get(): reads a string field, fallback (default "") when missing or null. A present number/bool is stringified (str(null) would instead return the 4-char string "null" -- getstr never does that). Pass a non-"" fallback (e.g. "?") when "missing" needs to read differently from a real empty string.',example:'dir = getstr(req, "dir");'},{name:"getnum",category:"Maps & Key-Value",signature:"getnum(obj: any, path: string|array, [fallback: number = 0]): number",description:"Typed form of get(): reads a numeric field, coercing a present value with num(); fallback when missing or null.",example:'count = getnum(req, "count", 1);'},{name:"getbool",category:"Maps & Key-Value",signature:"getbool(obj: any, path: string|array, [fallback: boolean = false]): boolean",description:'Typed form of get(): reads a boolean field. The strings "true"/"false" (any case) parse as booleans; fallback when missing or null.',example:'seed = getbool(req, "seed", true);'},{name:"getlist",category:"Maps & Key-Value",signature:"getlist(obj: any, path: string|array, [fallback: array = []]): array",description:"Typed form of get(): reads an array field, fallback (default []) when missing, null, or not actually an array.",example:'reviewers = getlist(req, "reviewers");'},{name:"set",category:"Maps & Key-Value",signature:"set(obj: object, path: string|array, value: any): object",description:"Sets a nested property on an object using a dot or array path.",example:'set(config, "server.port", 8080);'},{name:"delete_key",category:"Maps & Key-Value",signature:"delete_key(obj: object, key: string): object",description:"Deletes a key from an object.",example:'delete_key(data, "temp");'},{name:"merge",category:"Maps & Key-Value",signature:"merge(a: object, b: object): object",description:"Shallow merges two objects into a new object.",example:"combined = merge(defaults, overrides);"},{name:"clone",category:"Maps & Key-Value",signature:"clone(val: any): any",description:"Deep clones an object or array via JSON serialization.",example:"copy = clone(original);"},{name:"json",category:"JSON & Data",signature:"json(str: string): any",description:"Parses a JSON string into an object or array.",example:'data = json("{\\"key\\": \\"value\\"}");'},{name:"json_parse",category:"JSON & Data",signature:"json_parse(str: string): any",description:"Alias for json.",example:"data = json_parse(text);"},{name:"json_parse_safe",category:"JSON & Data",signature:"json_parse_safe(str: string, [fallback: any = null]): any",description:"Safely parses JSON with markdown fence and preamble tolerance, returning fallback (default null) without throwing.",example:'data = json_parse_safe(llm_output); if (data == null) { print("parse failed"); }'},{name:"json_stringify",category:"JSON & Data",signature:"json_stringify(val: any, [indent: number = 2]): string",description:"Serializes a value to formatted JSON string.",example:"text = json_stringify(obj, 2);"},{name:"pluck",category:"JSON & Data",signature:"pluck(arr: array, key: string): array",description:"Extracts the specified key from each object in an array.",example:'names = pluck(users, "name");'},{name:"filter_by",category:"JSON & Data",signature:"filter_by(arr: array, key: string, value: any): array",description:"Filters an array of objects where item[key] == value.",example:'active = filter_by(users, "active", true);'},{name:"find_by",category:"JSON & Data",signature:"find_by(arr: array, key: string, value: any): any",description:"Finds the first object in an array where item[key] == value.",example:'user = find_by(users, "id", 42);'},{name:"num",category:"Math",signature:"num(val: any): number",description:"Converts a value to a numeric type.",example:'n = num("42.5");'},{name:"round",category:"Math",signature:"round(n: number): number",description:"Rounds a number to the nearest integer.",example:"r = round(3.7);"},{name:"floor",category:"Math",signature:"floor(n: number): number",description:"Returns the largest integer less than or equal to a number.",example:"f = floor(3.9);"},{name:"ceil",category:"Math",signature:"ceil(n: number): number",description:"Returns the smallest integer greater than or equal to a number.",example:"c = ceil(3.1);"},{name:"min",category:"Math",signature:"min(...nums: number|array): number",description:"Returns the minimum value from numbers or a number array.",example:"m = min(10, 5, 20);"},{name:"max",category:"Math",signature:"max(...nums: number|array): number",description:"Returns the maximum value from numbers or a number array.",example:"m = max([10, 5, 20]);"},{name:"abs",category:"Math",signature:"abs(n: number): number",description:"Returns the absolute value of a number.",example:"a = abs(-42);"},{name:"sqrt",category:"Math",signature:"sqrt(n: number): number",description:"Returns the square root of a number.",example:"s = sqrt(16);"},{name:"pow",category:"Math",signature:"pow(base: number, exp: number): number",description:"Calculates base raised to exponent.",example:"p = pow(2, 8);"},{name:"random",category:"Math",signature:"random(): number",description:"Returns a pseudo-random floating point number in [0, 1).",example:"r = random();"},{name:"system",category:"System & Process",signature:"system(command: string|array, [timeoutMs: number = 60000]): SystemResult",description:"Executes a shell command string or argv array directly with shell:false, returning a structured process execution record.",parameters:[{name:"command",type:"string|array",description:"Shell command string or argv array to execute"},{name:"timeoutMs",type:"number",description:"(optional) Execution timeout in milliseconds (default: 60000)"}],returns:{type:"SystemResult",description:"{ stdout: string, stderr: string, code: number|null, signal: string|null, timed_out: bool, duration_ms: number, pid: number|null }"},example:'res = system(["git", "log", "-n", "1"]); if (res.code == 0) { print(res.stdout); }'},{name:"prompt_human",category:"System & Process",signature:"prompt_human([question: string]): string|null",description:"Pauses execution to prompt an operator on terminal stdin, returning the entered input line or null if stdin is closed/non-interactive.",example:'guidance = prompt_human("Enter instructions (or Enter to halt): "); if (guidance != null) { process(guidance); }'},{name:"error",category:"System & Process",signature:"error(...args: any): string",description:"Formats and logs an error to stderr and records it for the execution error summary.",example:'error("Operation failed:", reason);'},{name:"exit",category:"System & Process",signature:"exit([code: number = 0]): never",description:"Terminates script execution immediately with exit code.",example:"exit(0);"},{name:"require",category:"System & Process",signature:"require(value: any, message: string): any",description:'Validates a request-form field in one line: if value is missing ("", null, [], or false), prints "error: <message>" to stderr and stops with exit 2; otherwise returns value unchanged so it composes with getstr/getnum/getbool/getlist.',example:'dir = require(getstr(req, "dir"), "missing required field: dir");'},{name:"print",category:"System & Process",signature:"print(...args: any): string",description:"Formats and logs values to output.",example:'print("Result:", val);'},{name:"printf",category:"System & Process",signature:"printf(template: string, ...args: any): string",description:"Formats a template using %s/%d/%f/%% substitution and prints it (C/Perl/Python printf style).",example:'printf("%s scored %d", "Alice", 95);'},{name:"println",category:"System & Process",signature:"println(...args: any): string",description:"Formats and logs values followed by a newline.",example:'println("Done.");'},{name:"sleep",category:"System & Process",signature:"sleep(ms: number): void",description:"Pauses execution for specified milliseconds.",example:"sleep(1000);"},{name:"clock",category:"System & Process",signature:"clock(): number",description:"Returns current epoch timestamp in milliseconds.",example:"start = clock();"},{name:"str",category:"System & Process",signature:"str(val: any): string",description:"Converts a value to its string representation.",example:"s = str(123);"},{name:"to_string",category:"System & Process",signature:"to_string(val: any): string",description:"Converts a value to its string representation (alias for str).",example:"s = to_string(123);"},{name:"is_array",category:"System & Process",signature:"is_array(val: any): boolean",description:"Checks if a value is an array (type-check alias over type()).",example:"if (is_array(val)) { ... }"},{name:"is_string",category:"System & Process",signature:"is_string(val: any): boolean",description:"Checks if a value is a string (type-check alias over type()).",example:"if (is_string(val)) { ... }"},{name:"is_number",category:"System & Process",signature:"is_number(val: any): boolean",description:"Checks if a value is a number (type-check alias over type()).",example:"if (is_number(val)) { ... }"},{name:"is_map",category:"System & Process",signature:"is_map(val: any): boolean",description:"Checks if a value is a map/object (type-check alias over type()).",example:"if (is_map(val)) { ... }"},{name:"is_function",category:"System & Process",signature:"is_function(val: any): boolean",description:"Checks if a value is a first-class function reference (type-check alias over type()).",example:"if (is_function(val)) { ... }"},{name:"type",category:"System & Process",signature:"type(val: any): string",description:"Returns the runtime type of a value ('string', 'number', 'boolean', 'array', 'object', 'null', 'function').",example:"t = type(data);"},{name:"assert",category:"System & Process",signature:"assert(condition: any, [message: string]): boolean",description:"Throws an error if condition is falsy.",example:'assert(len(items) > 0, "Items list must not be empty");'},{name:"urlget",category:"System & Process",signature:"urlget(url: string): string",description:"Performs HTTP(S) GET request and returns response body string.",example:'html = urlget("https://example.com");'}],vR=[{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);"}];ur=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 TR)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of wR)this.functionDocs.set(e.name,{...e,module:e.module??"core"});for(let e of vR)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
|
|
2051
2128
|
`)?r=r.slice(0,-2):r.endsWith(`
|
|
2052
2129
|
`)&&(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(`
|
|
2053
2130
|
`)+`
|
|
2054
|
-
`;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(_e.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("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 Dg(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,$g(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Dg,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",$g,{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=_e.resolve(
|
|
2131
|
+
`;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(_e.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("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 Dg(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,$g(r,n),"utf-8"),!0),{min:2,max:3},"Writes array of objects or rows to CSV file"),this.registerFunction("csv_parse",Dg,{min:1,max:3},"Parses inline CSV text into records or rows"),this.registerFunction("csv_stringify",$g,{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=_e.resolve(pR(),`lmscript-${fR()}`),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 Ge(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)=>_e.basename(e,r),{min:1,max:2},"Returns the last path segment, optionally stripping a trailing extension"),this.registerFunction("dirname",e=>_e.dirname(e),1,"Returns the directory portion of a path"),this.registerFunction("path_join",(...e)=>_e.join(...e),void 0,"Joins path segments using the OS-native separator"),this.registerFunction("abs_path",e=>_e.resolve(e),1,"Resolves a path to an absolute path"),this.registerFunction("env",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset"),this.registerFunction("getenv",(e,r=null)=>process.env[e]!==void 0?process.env[e]:r,{min:1,max:2},"Reads an environment variable, or a fallback if unset (alias for env)"),this.registerFunction("set_env",(e,r)=>(process.env[e]=String(r),!0),2,"Sets an environment variable for this process and its children"),this.registerFunction("list",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("array",(...e)=>e,void 0,"Creates a new list/array"),this.registerFunction("push",(e,...r)=>(e.push(...r),e),void 0,"Pushes item(s) to end of array and returns the array",!0,!0),this.registerFunction("pop",e=>e.pop(),1,"Pops item from end of array",!0,!0),this.registerFunction("shift",e=>e.shift(),1,"Removes and returns first element",!0,!0),this.registerFunction("unshift",(e,...r)=>(e.unshift(...r),e),void 0,"Adds item(s) to front of array and returns the array",!0,!0),this.registerFunction("insert",(e,r,n)=>{let s=r<0?e.length+r:r;return e.splice(s,0,n),e},3,"Inserts item at index and returns the array",!0,!0),this.registerFunction("remove_at",(e,r)=>{let n=r<0?e.length+r:r,s=e.splice(n,1);return s.length>0?s[0]:null},2,"Removes element at index",!0,!0),this.registerFunction("concat",(e,...r)=>e.concat(...r),void 0,"Concatenates arrays"),this.registerFunction("reverse",e=>Array.isArray(e)?[...e].reverse():e,1,"Returns reversed array"),this.registerFunction("sort",(e,r)=>{if(!Array.isArray(e))return e;let n=[...e];return r?n.sort((s,i)=>{let o=s?s[r]:void 0,a=i?i[r]:void 0;return o<a?-1:o>a?1:0}):n.sort((s,i)=>typeof s=="number"&&typeof i=="number"?s-i:String(s).localeCompare(String(i)))},void 0,"Sorts array numerically, alphabetically, or by object key"),this.registerFunction("sorted",(e,r)=>this.hostFunctions.get("sort").fn(e,r),void 0,"Sorts array numerically, alphabetically, or by object key (alias for sort)"),this.registerFunction("unique",e=>Array.isArray(e)?Array.from(new Set(e)):[],1,"Removes duplicate elements"),this.registerFunction("flatten",e=>Array.isArray(e)?e.flat():[],1,"Flattens array one level"),this.registerFunction("first",e=>Array.isArray(e)&&e.length>0?e[0]:null,1,"Returns first element"),this.registerFunction("last",e=>Array.isArray(e)&&e.length>0?e[e.length-1]:null,1,"Returns last element"),this.registerFunction("sum",e=>Array.isArray(e)?e.reduce((r,n)=>r+(typeof n=="number"?n:Number(n)||0),0):0,1,"Calculates sum of array"),this.registerFunction("avg",e=>!Array.isArray(e)||e.length===0?0:e.reduce((n,s)=>n+(typeof s=="number"?s:Number(s)||0),0)/e.length,1,"Calculates average of array"),this.registerFunction("hash",()=>({}),0,"Creates a new empty map/hash"),this.registerFunction("from_entries",e=>Array.isArray(e)?Object.fromEntries(e):{},1,"Creates map from [key, value] pairs"),this.registerFunction("clear",e=>{if(Array.isArray(e))return e.length=0,e;if(e&&typeof e=="object"){for(let r of Object.keys(e))delete e[r];return e}return e},1,"Clears array or map",!0,!0),this.registerFunction("size",e=>Array.isArray(e)||typeof e=="string"?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns number of elements in array, string, or map"),this.registerFunction("system",(e,r=6e4)=>{if(!Number.isSafeInteger(r)||r<0)throw new Error("system() timeout must be a non-negative safe integer in milliseconds");return this.isAsyncMode?Jg(e,r):Gg(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=_e.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(`
|
|
2055
2132
|
`)+(a.output.length>0?`
|
|
2056
2133
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u})();{let a=o.run(s,{file:n}),l=a.output.join(`
|
|
2057
2134
|
`)+(a.output.length>0?`
|
|
2058
2135
|
`:""),c=a.exitCode!==void 0?a.exitCode:a.success?0:1,u={success:a.success&&c===0,stdout:l,output:[...a.output],value:a.value,exit_code:c,code:c,errors:a.errors??[]};return u.toString=()=>l,u}},{min:1,max:2},"Executes another LMScript file in-process and returns execution result with .stdout, .output, .success, .exit_code",!0),this.registerFunction("error",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return typeof process<"u"&&process.stderr?process.stderr.write(`error: ${r}
|
|
2059
|
-
`):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Xg(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?ys(e):_s(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)=>
|
|
2060
|
-
`):console.error(`error: ${String(r)}`),new Ge(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];(wt(i,a)==null||typeof wt(i,a)!="object")&&dr(i,a,{}),i=wt(i,a)}return s.length>0&&dr(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=>wt(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&wt(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&&wt(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=gs(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i:null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof hn,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>qg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<r.length?a(r[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>gs(e,r),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,r,n,s="")=>String(e).replace(new RegExp(r,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,r,n="")=>String(e).split(new RegExp(r,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,r)=>Math.pow(e,r),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,r)=>Pg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Pg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof hn?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,f=this.functionOriginModule.get(e);if(f&&f!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${f}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:yR(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}=pR(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new $c(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof P?{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 io(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof Ge||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let g=typeof c.exitCode=="number"?c.exitCode:0;return{success:g===0,value:g,exitCode:g,diagnostics:i,output:n,errors:u}}let d=c instanceof P?c.line:1,m=c instanceof P?c.column:1,f=c instanceof P&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:m,severity:"error",file:f}],output:n,errors:u}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new io(this.hostFunctions,u=>n.push(u),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof Ge||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let f=typeof l.exitCode=="number"?l.exitCode:0;return{success:f===0,value:f,exitCode:f,diagnostics:i,output:n,errors:c}}let u=l instanceof P?l.line:1,d=l instanceof P?l.column:1,m=l instanceof P&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Ug=_e.basename(Bg(import.meta.url));(Ug==="lmscript.ts"||Ug==="lmscript.js")&&process.argv[1]&&U.existsSync(process.argv[1])&&U.realpathSync(Bg(import.meta.url))===U.realpathSync(_e.resolve(process.argv[1]))&&TR()});import{mkdirSync as t_,readFileSync as wR,renameSync as vR,writeFileSync as SR,existsSync as r_}from"node:fs";import{homedir as bR}from"node:os";import{dirname as n_,join as oo,resolve as ao}from"node:path";import{fileURLToPath as IR}from"node:url";function NR(){return oo(bR(),".lmctl","cache","lmprice")}function gn(t,e){return oo(t,e)}function Nr(t){try{return JSON.parse(wR(t,"utf-8"))}catch{return null}}function i_(t,e){let r=`${t}.tmp-${process.pid}`;SR(r,e),vR(r,t)}function Uc(t){return t===null||typeof t=="number"}function lo(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)})}function co(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"&&CR.has(i.evidence)});return r&&n}function OR(t){let e=Nr(gn(t,s_)),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=Nr(gn(t,LR));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 DR(t){let e=OR(t),r=Nr(gn(t,jc)),n=Nr(gn(t,Bc));return{catalog:lo(r)?r:null,aliases:co(n)?n:null,meta:e}}function MR(t,e){try{t_(t,{recursive:!0}),i_(gn(t,s_),JSON.stringify(e))}catch{}}function Kg(t,e,r){try{t_(t,{recursive:!0}),i_(gn(t,e),JSON.stringify(r))}catch{}}function $R(t,e){let r=FR(t),n=r?[ao(r,"data",e)]:[ao(t,"..","..","data",e)];for(let s of n)if(r_(s))return s;return null}function FR(t){let e=ao(t);for(;;){if(r_(ao(e,"package.json")))return e;let r=n_(e);if(r===e)return null;e=r}}function Yg(t,e,r){let n=r!==void 0?r:$R(t,e);return n===null?null:Nr(n)}function PR(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Vg;let e=Number(t);return!Number.isFinite(e)||e<0?Vg:e*1e3}function UR(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function zg(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(AR)});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(RR)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function uo(t={}){return Object.keys(t).length===0?(Qg??=Zg(t),Qg):Zg(t)}async function Zg(t){let e=n_(IR(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:UR();if(r!==null&&r!==""){let g=Nr(oo(r,jc)),y=Nr(oo(r,Bc));if(lo(g)&&co(y)){let h={catalog:g,aliases:y,source:"pinned",generatedAt:g.generated_at??null};return Wc=h.generatedAt,h}return e_(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??NR(),i=t.now??Date.now(),o=t.ttlMs??PR(),a=DR(s),l=(g,y)=>g!==null&&y.last_checked!==null&&i-Date.parse(y.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},f=!1;if(!l(c,a.meta.model_list)){let g=await zg(n,xR,c,a.meta.model_list.etag);g.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),f=!0,lo(g.payload)&&(c=g.payload,g.etag!==null&&(m.model_list.etag=g.etag),Kg(s,jc,c),d=!0))}if(!l(u,a.meta.aliases)){let g=await zg(n,kR,u,a.meta.aliases.etag);g.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),f=!0,co(g.payload)&&(u=g.payload,g.etag!==null&&(m.aliases.etag=g.etag),Kg(s,Bc,u),d=!0))}if((f||d)&&MR(s,m),c!==null||u!==null){let g={catalog:c,aliases:u,source:d?"network":"cache",generatedAt:c?.generated_at??null};return Wc=g.generatedAt,g}return e_(t,e)}function e_(t,e){let r=Yg(e,"price-data.json",t.bundledPath),n=Yg(e,"price-aliases.json",t.bundledAliasesPath),s=lo(r)?r:null,i=co(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Wc=o.generatedAt,o}function o_(t,e){if(e===null)return null;let{input_per_1m_tokens:r,output_per_1m_tokens:n,input_cache_read_per_1m_tokens:s}=e;if(r===null||n===null)return null;let i=s??r,o=t.input/1e6*r+t.output/1e6*n+t.cachedInput/1e6*i;return Number(o.toPrecision(10))}var xR,kR,AR,RR,Vg,jc,Bc,s_,LR,CR,Wc,Qg,Hc=k(()=>{"use strict";xR="https://lmctl.com/dataset/model_list.json",kR="https://lmctl.com/dataset/aliases.json",AR=1e3,RR=1e4,Vg=6*60*60*1e3;jc="model_list.json",Bc="aliases.json",s_="meta.json",LR="model_list.meta.json";CR=new Set(["established","asserted","unresolved"]);Wc=null,Qg=null});function Cr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Lr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Cr(r)}function l_(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Cr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function jR(t,e){let r=new Set,n=l=>{r.add(Cr(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 _n(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=>jR(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=l_(n);return s.some(o=>i.has(o))}}}function WR(t){let e=t.trim(),r=BR.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function GR(t,e,r){let n=e.trim().toLowerCase(),s=Cr(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 JR(t,e,r){let n=[];for(let[s,i]of Object.entries(Es))s!==r&&GR(i,t,e)&&n.push(s);return n}function mo(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function VR(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 KR(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}${Cr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!VR(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 YR(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 h_(t,e){return t.map(YR).sort((r,n)=>{let s=mo(r.source)-mo(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 Xc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function zR(t,e,r){let n=KR(t),s=h_(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 qc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=zR(t,e,r),s=n.offers.find(Xc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function QR(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function ZR(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=Lr(i),a=r.records.filter(l=>Lr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:qc(a,o,Gc)}function g_(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let y=[e.trim().toLowerCase()];y.push(`${t.toLowerCase()}/${y[0]}`);let h=n.aliases.find(p=>y.includes(p.alias.toLowerCase()));if(h){if(h.evidence==="unresolved"||h.standard_slug===null)return{state:{kind:"unresolved",alias:h.alias},viaAlias:!0,pinRoute:null};let p=QR(n,h.standard_slug);return{state:ZR(h,p,r),viaAlias:!0,pinRoute:p?.catalog_record_id?.toLowerCase()??null}}}let s=Es[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=y=>({state:y,viaAlias:!1,pinRoute:null}),l=Cr(i),c=r.records.filter(y=>y.source_model_id.toLowerCase()===i&&s.matchRow(y,[l]));if(c.length>0){let y=Lr(c[0]),h=r.records.filter(p=>s.matchRow(p,[y])&&Lr(p)===y);return a(qc(h.length>0?h:c,y,a_[t]??Gc))}let u=r.records.filter(y=>s.matchRow(y,o));if(u.length===0){let y=JR(e,r,t);return y.length>0?a({kind:"wrong-provider",declared:e,otherProviders:y}):a({kind:"unknown",declared:e})}let d=new Map;for(let y of u){let h=Lr(y),p=d.get(h);p?p.push(y):d.set(h,[y])}let m=a_[t]??Gc,f=null,g=null;for(let y of d.values()){let h=h_(y,m);(g===null||eN(h[0],g[0],m)<0)&&(f=y,g=h)}return a(qc(f,Lr(f[0]),m))}function fo(t,e,r,n){return g_(t,e,r,n).state}function __(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=g_(t,e,r,n);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(u=>u.route.toLowerCase()===o);if(c!==void 0&&Xc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Xc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function y_(t,e){let r=Es[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Lr(s));return n.size}function eN(t,e,r){let n=mo(t.source)-mo(e.source);if(n!==0)return n;let s=t.provider!==null&&r.includes(t.provider)?0:1,i=e.provider!==null&&r.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var c_,d_,u_,m_,f_,p_,BR,HR,XR,qR,Es,a_,Gc,Jc=k(()=>{"use strict";c_=_n({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),d_=_n({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)(-|$)/}),u_=_n({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),m_=_n({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),f_=_n({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),p_=_n({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),BR=/\s*\(([^()]+)\)\s*$/;HR={"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"},XR=["gemini","google","vertex_ai-language-models","anthropic"],qR={normalize(t){let{model:e}=WR(t),r=HR[e.toLowerCase()];return r===void 0?[]:[Cr(r)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=l_(t);return e.some(n=>r.has(n))}},Es={claude:c_,codex:d_,gemini:u_,agy:qR,kimi:m_,qwen:f_,hermes:p_},a_={claude:c_.firstPartyProviders,codex:d_.firstPartyProviders,gemini:u_.firstPartyProviders,agy:XR,kimi:m_.firstPartyProviders,qwen:f_.firstPartyProviders,hermes:p_.firstPartyProviders};Gc=[]});import{spawnSync as Zc}from"node:child_process";import{existsSync as v_,readFileSync as S_}from"node:fs";import{homedir as b_}from"node:os";import{resolve as zc}from"node:path";function yn(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 sN(){let t=Zc("agy",["models"],{encoding:"utf-8",timeout:nN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function iN(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 oN(t){if(!t&&Vc)return Vc;let e=s=>(t||(Vc=s),s),r;try{r=(t??sN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?yn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:yn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=iN(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function lN(){let t=Zc("codex",["debug","models"],{encoding:"utf-8",timeout:aN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function cN(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 dN(t){if(!t&&Kc)return Kc;let e=s=>(t||(Kc=s),s),r;try{r=(t??lN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?yn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:yn("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=cN(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}function mN(t){let e=Zc("opencode",["models",t],{encoding:"utf-8",timeout:uN});return{status:e.status,stdout:e.stdout??"",error:e.error}}function fN(t,e){if(!e&&Yc.has(t))return Yc.get(t);let r=i=>(e||Yc.set(t,i),i),n;try{n=(e??mN)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?yn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:yn(`opencode models ${t}`,n.error)});if(n.status!==0)return r({available:!1,models:[],reason:`opencode models ${t} exited with status ${n.status??"unknown"}`});let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);return s.length===0?r({available:!1,models:[],reason:`opencode models ${t} returned no models`}):r({available:!0,models:s})}function ed(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),!n.model&&rN.has(s)&&r.push(`[${n.alias}] provider=${s} has no model= \u2014 ${s} will use its own ambient default, which cannot be linted or priced and may not be the intended one. Set model= explicitly.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s==="lmplayer"&&!n.model){r.push(`[${n.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model){r.push(`[${n.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}let i=gN(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=fN(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=pN(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: ${Ts(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=oN(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: ${Ts(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||T_.includes(n.model))continue;E_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Ts(E_)}. 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): ${Ts(T_)}. 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===w_&&r.push(`[${n.alias}] model="${w_}" 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=dN(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: ${Ts(i.models)}`);continue}n.model&&(I_.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 x_(t,e={}){let r=t.filter(o=>o.model!==void 0&&I_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await uo();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=fo(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let u=y_(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&tN.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function k_(t,e={}){return(await x_(t,e)).warnings}async function A_(t,e={}){return(await x_(t,e)).errors}function pN(t){let e=process.env.KIMI_CODE_HOME||zc(b_(),".kimi-code"),r=t??zc(e,"config.toml");if(!v_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=S_(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=hN(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 hN(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 gN(t){let e=t??zc(b_(),".config","opencode","opencode.json");if(!v_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(S_(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:_N(r)}}function _N(t){if(!Qc(t))return[];let e=po(t.provider)??po(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Qc(s))continue;let i=po(s.models)??po(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function po(t){return Qc(t)?t:null}function Qc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ts(t){return t.length>0?t.join(", "):"(none)"}var I_,tN,rN,E_,T_,w_,nN,Vc,aN,Kc,uN,Yc,R_=k(()=>{"use strict";Hc();Jc();I_=new Set(Object.keys(Es).filter(t=>t!=="codex"&&t!=="kimi")),tN=/\d\.(?=\d)/,rN=new Set(["claude","codex","gemini","qwen","kimi","agy"]),E_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],T_=["deepseek-flash","deepseek-pro"],w_="gpt-5.3-codex-spark",nN=15e3;Vc=null;aN=5e3;Kc=null;uN=5e3;Yc=new Map});import{homedir as yN}from"node:os";import{basename as EN}from"node:path";function N_(t,e){let r=new Set;return{text:t.replace(wN,(s,i)=>{let o=i.trim(),a=TN[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function L_(t){return{workdir:t.workdir,teamfile:t.teamfile,date:vN(t.date)}}function vN(t){return t.toISOString().slice(0,10)}var TN,wN,C_=k(()=>{"use strict";TN={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=EN(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>yN(),date:t=>t.date},wN=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var cd={};oe(cd,{GEMINI_PROVIDER_NOTICE:()=>P_,_setAgyModelsRunnerForTests:()=>RN,_setCatalogSnapshotForTests:()=>AN,_setCodexModelsRunnerForTests:()=>NN,_setLintOpenCodeConfigProbeForTests:()=>ON,_setLintSessiondirFsOpsForTests:()=>CN,_setTeamfileSeedForTests:()=>LN,buildRootTeamRegistrationRow:()=>q_,lintTeamfileStructured:()=>ld,registerRootTeam:()=>G_,runLint:()=>Mr,runSeed:()=>$r,seedTeamfile:()=>ho,sha256Text:()=>X_,validateMemberSpec:()=>Mt});import{createHash as SN}from"node:crypto";import{accessSync as bN,constants as O_,existsSync as IN,readFileSync as $_,realpathSync as nd,statSync as xN,writeFileSync as D_}from"node:fs";import{dirname as Dr,resolve as F_}from"node:path";function AN(t){vs=t??void 0}function B_(t){return k_(t,vs!==void 0?{snapshot:vs}:{})}function W_(t){return A_(t,vs!==void 0?{snapshot:vs}:{})}function RN(t){od=t??void 0}function NN(t){ad=t??void 0}function LN(t){U_=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(Ct(),vc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function CN(t){Or=t===null?sd:{...sd,...t}}function ON(t){j_=t??qn}async function DN(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 j_({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 MN(t,e){let r=Dr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=F_(o);if(n.has(a))continue;let l=$N(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 $N(t){try{if(Or.existsSync(t)){if(!Or.statSync(t).isDirectory())return"ENOTDIR";Or.accessSync(t,O_.W_OK);return}let e=PN(t);if(e===void 0)return;if(!Or.statSync(e).isDirectory())return"ENOTDIR";Or.accessSync(e,O_.W_OK);return}catch(e){return UN(e)??"permission check failed"}}function FN(t){let e=F_(t);try{return nd(e)}catch{return e}}function PN(t){let e=t;for(;;){try{if(Or.existsSync(e))return e}catch{return}let r=Dr(e);if(r===e)return;e=r}}function UN(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 H_(t,e){let r;try{r=await C(e,l=>he(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=Ne(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=ha(n,Dr(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2061
|
-
`);let i=ed(n.members,{agyModelsRunner:od,codexModelsRunner:ad});i.push(...await B_(n.members)),s.push(...await W_(n.members));let o=$_(r,"utf8"),a=N_(o,L_({workdir:Dr(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(...za(n.members,Dr(r))),i.push(...
|
|
2062
|
-
`);for(let l of n.members)id([l],e),l.session!==void 0&&l.session.length<ws&&i.push(`${l.alias}: sessionid is shorter than ${ws} chars; run lmctl seed to refresh it`);return{ok:!0,result:{config:n,absTeamfile:r,errors:s,warnings:i}}}async function Mr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(
|
|
2136
|
+
`):console.error(`error: ${r}`),r},void 0,"Formats and logs an error to stderr and records it for the execution error summary",!0),this.registerFunction("urlget",e=>Xg(e),1,"Downloads UTF-8 text from a public HTTP(S) URL",!0),this.registerFunction("sleep",e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)throw new Error("sleep() duration must be a non-negative finite number");if(e>2147483647)throw new Error("sleep() duration exceeds maximum supported timeout (2147483647 ms)");let r=Date.now()+e;for(;Date.now()<r;);return null},1,"Sleeps for the specified milliseconds",!0),this.registerFunction("prompt_human",e=>this.isAsyncMode?ys(e):_s(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)=>gR(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=fs(e,r);return s!==void 0?s:n},void 0,"Safely extracts nested property by path (e.g. 'user.address.city')"),this.registerFunction("getstr",(e,r,n="")=>{let s=fs(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=fs(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=fs(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=fs(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)}
|
|
2137
|
+
`):console.error(`error: ${String(r)}`),new Ge(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];(wt(i,a)==null||typeof wt(i,a)!="object")&&dr(i,a,{}),i=wt(i,a)}return s.length>0&&dr(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=>wt(n,r)):[],2,"Extracts key from array of objects"),this.registerFunction("filter_by",(e,r,n)=>Array.isArray(e)?e.filter(s=>s!=null&&wt(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&&wt(i,r)===n);return s!==void 0?s:null},3,"Finds first object in array where item[key] == value"),this.registerFunction("merge",(e,r)=>({...e,...r}),2,"Shallow merges two objects"),this.registerFunction("clone",e=>e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e)),1,"Deep clones an object or array"),this.registerFunction("delete_key",(e,r)=>(e&&typeof e=="object"&&delete e[r],e),2,"Deletes key from object",!0,!0),this.registerFunction("print",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints formatted values to output log",!0),this.registerFunction("println",(...e)=>{let r=e.map(n=>typeof n=="object"?JSON.stringify(n):String(n)).join(" ");return this.outputLogs.push(r),r},void 0,"Prints line to output log",!0),this.registerFunction("printf",(e,...r)=>{let n=gs(e,r);return this.outputLogs.push(n),n},void 0,"Formats a template using %s/%d/%f/%% substitution and prints it",!0),this.registerFunction("split",(e,r="")=>String(e).split(r),void 0,"Splits string by delimiter"),this.registerFunction("lines",e=>String(e).split(/\r?\n/),1,"Splits string into array of lines"),this.registerFunction("last_line_as_status",e=>{if(typeof e!="string")return null;let r=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0);if(r.length===0)return null;let n=a=>a==="DONE"||a==="NOTHING_TO_DO"||a==="BLOCKED"||a==="OTHER",s=r[r.length-1],i=r.length>1?r[r.length-2]:null,o=r.length>2?r[r.length-3]:null;return n(s)?i&&n(i)&&i!==s?null:s:i&&n(i)?o&&n(o)&&o!==i?null:i:null},1,"Returns the last non-blank line of a string if it is a valid state word (DONE, NOTHING_TO_DO, BLOCKED, OTHER), else null"),this.registerFunction("words",e=>String(e).trim().split(/\s+/).filter(Boolean),1,"Splits string into words"),this.registerFunction("join",(e,r=", ")=>Array.isArray(e)?e.join(r):String(e),void 0,"Joins array into string"),this.registerFunction("trim",e=>String(e).trim(),1,"Trims whitespace from both ends"),this.registerFunction("strip",e=>String(e).trim(),1,"Trims whitespace from both ends (alias for trim)"),this.registerFunction("trim_start",e=>String(e).trimStart(),1,"Trims leading whitespace"),this.registerFunction("lstrip",e=>String(e).trimStart(),1,"Trims leading whitespace (alias for trim_start)"),this.registerFunction("trim_end",e=>String(e).trimEnd(),1,"Trims trailing whitespace"),this.registerFunction("rstrip",e=>String(e).trimEnd(),1,"Trims trailing whitespace (alias for trim_end)"),this.registerFunction("to_upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("upper",e=>String(e).toUpperCase(),1,"Converts string to uppercase"),this.registerFunction("toUpperCase",e=>String(e).toUpperCase(),1,"Converts string to uppercase (alias for upper)"),this.registerFunction("to_lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("lower",e=>String(e).toLowerCase(),1,"Converts string to lowercase"),this.registerFunction("toLowerCase",e=>String(e).toLowerCase(),1,"Converts string to lowercase (alias for lower)"),this.registerFunction("capitalize",e=>{let r=String(e);return r.length===0?"":r.charAt(0).toUpperCase()+r.slice(1)},1,"Capitalizes first letter"),this.registerFunction("title_case",e=>String(e).replace(/\b\w/g,r=>r.toUpperCase()),1,"Converts string to Title Case"),this.registerFunction("contains",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("includes",(e,r)=>Array.isArray(e)?e.includes(r):String(e).includes(String(r)),2,"Checks if string or array contains item"),this.registerFunction("starts_with",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix"),this.registerFunction("startswith",(e,r)=>String(e).startsWith(r),2,"Checks if string starts with prefix (alias for starts_with)"),this.registerFunction("ends_with",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix"),this.registerFunction("endswith",(e,r)=>String(e).endsWith(r),2,"Checks if string ends with suffix (alias for ends_with)"),this.registerFunction("index_of",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring"),this.registerFunction("indexOf",(e,r,n)=>String(e).indexOf(r,n),void 0,"Finds index of substring (alias for index_of)"),this.registerFunction("last_index_of",(e,r)=>String(e).lastIndexOf(r),2,"Finds last index of substring"),this.registerFunction("count_matches",(e,r)=>r?String(e).split(r).length-1:0,2,"Counts occurrences of substring"),this.registerFunction("substr",(e,r,n)=>{let s=String(e);return n===void 0?s.substring(r):s.substring(r,r+n)},void 0,"Returns substring by start and length"),this.registerFunction("substring",(e,r,n)=>String(e).substring(r,n),void 0,"Returns substring between indices"),this.registerFunction("slice",(e,r,n)=>e!=null?e.slice(r,n):"",void 0,"Slices string or array"),this.registerFunction("char_at",(e,r)=>String(e).charAt(r),2,"Returns character at index"),this.registerFunction("char_code",(e,r=0)=>String(e).charCodeAt(r),void 0,"Returns character code at index"),this.registerFunction("from_char_code",(...e)=>String.fromCharCode(...e),void 0,"Returns string from character codes"),this.registerFunction("replace",(e,r,n)=>String(e).replace(r,n),3,"Replaces first occurrence"),this.registerFunction("replace_all",(e,r,n)=>String(e).replaceAll(r,n),3,"Replaces all occurrences"),this.registerFunction("repeat",(e,r)=>String(e).repeat(r),2,"Repeats string count times"),this.registerFunction("pad_start",(e,r,n=" ")=>String(e).padStart(r,n),void 0,"Left-pads string"),this.registerFunction("pad_end",(e,r,n=" ")=>String(e).padEnd(r,n),void 0,"Right-pads string"),this.registerFunction("reverse_str",e=>String(e).split("").reverse().join(""),1,"Reverses string"),this.registerFunction("is_empty",e=>e==null?!0:typeof e=="string"?e.trim().length===0:Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1,1,"Checks if string, array, or map is empty"),this.registerFunction("is_digit",e=>/^\d+$/.test(String(e)),1,"Checks if string contains only digits"),this.registerFunction("is_alpha",e=>/^[a-zA-Z]+$/.test(String(e)),1,"Checks if string contains only letters"),this.registerFunction("is_alnum",e=>/^[a-zA-Z0-9]+$/.test(String(e)),1,"Checks if string contains only letters and digits"),this.registerFunction("is_array",e=>Array.isArray(e),1,"Checks if value is an array"),this.registerFunction("is_string",e=>typeof e=="string",1,"Checks if value is a string"),this.registerFunction("is_number",e=>typeof e=="number",1,"Checks if value is a number"),this.registerFunction("is_map",e=>e!==null&&typeof e=="object"&&!Array.isArray(e),1,"Checks if value is a map/object"),this.registerFunction("is_function",e=>e instanceof hn,1,"Checks if value is a first-class function reference"),this.registerFunction("shell_quote",e=>qg(e),1,"Quotes string safely for POSIX shell command execution",!0),this.registerFunction("format",(e,...r)=>{let n=String(e),s=r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0])?r[0]:void 0,i=0,o="",a=l=>typeof l=="object"&&l!==null?JSON.stringify(l):String(l);for(let l=0;l<n.length;){let c=n[l];if(c==="{"&&n[l+1]==="{"){o+="{",l+=2;continue}if(c==="}"&&n[l+1]==="}"){o+="}",l+=2;continue}if(c!=="{"){o+=c,l+=1;continue}let u=n.indexOf("}",l+1);if(u<0){o+=c,l+=1;continue}let d=n.slice(l+1,u);if(d==="")o+=i<r.length?a(r[i++]):"{}";else if(/^\d+$/.test(d)){let m=Number(d);o+=m<r.length?a(r[m]):`{${d}}`}else s&&/^[a-zA-Z0-9_]+$/.test(d)&&Object.hasOwn(s,d)?o+=a(s[d]):o+=`{${d}}`;l=u+1}return o},void 0,"Formats string with arguments, supporting {{ and }} brace escapes, positional {0}, auto {}, and {key} map substitution"),this.registerFunction("sprintf",(e,...r)=>gs(e,r),void 0,"Formats a template using %s/%d/%f/%% substitution (C/Perl/Python printf style; use format() for {} brace syntax)"),this.registerFunction("regex_test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string"),this.registerFunction("test",(e,r,n="")=>new RegExp(r,n).test(String(e)),{min:2,max:3},"Tests whether a regex pattern matches anywhere in the string (alias for regex_test)"),this.registerFunction("regex_match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null"),this.registerFunction("match",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("search",(e,r,n="")=>{let s=String(e).match(new RegExp(r,n));return s?Array.from(s,i=>i===void 0?null:i):null},{min:2,max:3},"Returns [full_match, group1, group2, ...] for the first regex match anywhere in the string, or null (alias for regex_match)"),this.registerFunction("regex_find_all",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...]"),this.registerFunction("findall",(e,r,n="")=>{let s=new RegExp(r,n.includes("g")?n:`${n}g`),i=String(e),o=[],a;for(;(a=s.exec(i))!==null;)o.push(Array.from(a,l=>l===void 0?null:l)),a[0]===""&&(s.lastIndex+=1);return o},{min:2,max:3},"Returns an array of every regex match in the string, each as [full_match, group1, ...] (alias for regex_find_all)"),this.registerFunction("regex_replace",(e,r,n,s="")=>String(e).replace(new RegExp(r,s),n),{min:3,max:4},'Replaces regex match(es) with replacement (supports $1/$2 group backreferences); include "g" in flags to replace every occurrence, not just the first'),this.registerFunction("split_regex",(e,r,n="")=>String(e).split(new RegExp(r,n)),{min:2,max:3},"Splits a string into an array wherever the regex pattern matches"),this.registerFunction("len",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object"),this.registerFunction("length",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("count",e=>typeof e=="string"||Array.isArray(e)?e.length:e&&typeof e=="object"?Object.keys(e).length:0,1,"Returns length of string, array, or object (alias for len)"),this.registerFunction("range",(e,r,n=1)=>{let s=r===void 0?0:e,i=r===void 0?e:r,o=[];if(n>0)for(let a=s;a<i;a+=n)o.push(a);else if(n<0)for(let a=s;a>i;a+=n)o.push(a);return o},void 0,"Generates an array of numbers"),this.registerFunction("abs",e=>Math.abs(e),1,"Absolute value"),this.registerFunction("min",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.min(...r)},void 0,"Minimum value"),this.registerFunction("max",(...e)=>{let r=e.length===1&&Array.isArray(e[0])?e[0]:e;return Math.max(...r)},void 0,"Maximum value"),this.registerFunction("floor",e=>Math.floor(e),1,"Floor value"),this.registerFunction("ceil",e=>Math.ceil(e),1,"Ceil value"),this.registerFunction("round",e=>Math.round(e),1,"Round value"),this.registerFunction("sqrt",e=>Math.sqrt(e),1,"Square root"),this.registerFunction("pow",(e,r)=>Math.pow(e,r),2,"Power calculation"),this.registerFunction("random",()=>Math.random(),0,"Random float between 0 and 1"),this.registerFunction("clock",()=>Date.now(),0,"Returns current epoch in ms"),this.registerFunction("now",()=>Date.now(),0,"Returns current epoch in ms (alias for clock)"),this.registerFunction("timestamp",()=>Math.floor(Date.now()/1e3),0,"Returns current Unix epoch in whole seconds"),this.registerFunction("date",e=>new Date(e??Date.now()).toISOString(),{min:0,max:1},"Returns an ISO 8601 date-time string for now, or for a given epoch-ms timestamp"),this.registerFunction("strftime",(e,r)=>Pg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens"),this.registerFunction("date_format",(e,r)=>Pg(e,r),2,"Formats an epoch-ms timestamp using %Y/%m/%d/%H/%M/%S tokens (alias for strftime)"),this.registerFunction("coalesce",(...e)=>{for(let r of e)if(r!=null)return r;return null},void 0,"Returns the first non-null/non-undefined argument, else null"),this.registerFunction("if_null",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val"),this.registerFunction("default_to",(e,r)=>e??r,2,"Returns fallback if val is null/undefined, else val (alias for if_null)"),this.registerFunction("if_else",(e,r,n)=>e?r:n,3,"Expression-level ternary: returns thenVal if cond is truthy, else elseVal"),this.registerFunction("str",e=>e===null?"null":String(e),1,"Converts value to string"),this.registerFunction("to_string",e=>e===null?"null":String(e),1,"Converts value to string (alias for str)"),this.registerFunction("num",e=>Number(e),1,"Converts value to number"),this.registerFunction("type",e=>e===null?"null":Array.isArray(e)?"array":e instanceof hn?"function":typeof e,1,"Returns runtime type of value"),this.registerFunction("assert",(e,r="Assertion failed")=>{if(!e)throw new Error(r);return!0},void 0,"Throws error if condition is falsy")}registerFunction(e,r,n,s,i=!1,o=!1){let a=typeof s=="string"?s:s?.description,l=typeof s=="object"?!!s.isDefault:i,c=typeof s=="object"?!!s.isContainerMutation:o,u=typeof s=="object"?s.doc:void 0,d=typeof s=="object"?!!s.allowOverwrite:!1,m=typeof s=="object"&&s.module?s.module:this.currentRegisteringModule,f=this.functionOriginModule.get(e);if(f&&f!==m&&!d)throw new Error(`Cannot register function '${e}' from module '${m}': already registered by module '${f}'`);return this.functionOriginModule.set(e,m),this.hostFunctions.set(e,{fn:r,arity:n,description:a,isDefault:l,isContainerMutation:c,doc:u}),u?this.functionDocs.set(e,{...u,module:u.module??m}):a&&!this.functionDocs.has(e)&&this.functionDocs.set(e,{name:e,category:"Uncategorized",module:m,signature:SR(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}=ER(e,r),s=[...this.initialGlobals.keys(),...r.globals||[]],i=new $c(this.hostFunctions,{...r,globals:s}),o=i.check(n);return{ast:n,diagnostics:o,hasConcurrency:i.hasConcurrency}}catch(n){return n instanceof P?{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 io(this.hostFunctions,d=>n.push(d),!1,this.initialGlobals,r.stderr);let c=l.evaluateProgram(s);this.outputLogs=[...n];let u=l.getRecordedErrors();return this.lastRecordedErrors=u,{success:!0,value:c,diagnostics:i,output:n,errors:u}}catch(c){let u=l?l.getRecordedErrors():[];if(this.lastRecordedErrors=u,c instanceof Ge||c?.name==="LMScriptExit"||c?.isControlFlow){this.outputLogs=[...n];let g=typeof c.exitCode=="number"?c.exitCode:0;return{success:g===0,value:g,exitCode:g,diagnostics:i,output:n,errors:u}}let d=c instanceof P?c.line:1,m=c instanceof P?c.column:1,f=c instanceof P&&c.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:c?.message||String(c),line:d,column:m,severity:"error",file:f}],output:n,errors:u}}}async runAsync(e,r={}){let n=[],{ast:s,diagnostics:i}=this.scanAndCheck(e,r);if(i.filter(l=>l.severity==="error").length>0||!s)return this.outputLogs=n,this.lastRecordedErrors=[],{success:!1,diagnostics:i,output:n,errors:[]};let a;try{a=new io(this.hostFunctions,u=>n.push(u),!0,this.initialGlobals,r.stderr);let l=await a.evaluateProgramAsync(s);this.outputLogs=[...n];let c=a.getRecordedErrors();return this.lastRecordedErrors=c,{success:!0,value:l,diagnostics:i,output:n,errors:c}}catch(l){let c=a?a.getRecordedErrors():[];if(this.lastRecordedErrors=c,l instanceof Ge||l?.name==="LMScriptExit"||l?.isControlFlow){this.outputLogs=[...n];let f=typeof l.exitCode=="number"?l.exitCode:0;return{success:f===0,value:f,exitCode:f,diagnostics:i,output:n,errors:c}}let u=l instanceof P?l.line:1,d=l instanceof P?l.column:1,m=l instanceof P&&l.file||r.file;return this.outputLogs=[...n],{success:!1,diagnostics:[...i,{message:l?.message||String(l),line:u,column:d,severity:"error",file:m}],output:n,errors:c}}}lastRecordedErrors=[];getRecordedErrors(){return[...this.lastRecordedErrors]}hasFunction(e){return this.hostFunctions.has(e)}getRegisteredFunctions(){return Array.from(this.hostFunctions.keys())}};Ug=_e.basename(Bg(import.meta.url));(Ug==="lmscript.ts"||Ug==="lmscript.js")&&process.argv[1]&&U.existsSync(process.argv[1])&&U.realpathSync(Bg(import.meta.url))===U.realpathSync(_e.resolve(process.argv[1]))&&IR()});import{mkdirSync as t_,readFileSync as xR,renameSync as kR,writeFileSync as AR,existsSync as r_}from"node:fs";import{homedir as RR}from"node:os";import{dirname as n_,join as oo,resolve as ao}from"node:path";import{fileURLToPath as NR}from"node:url";function MR(){return oo(RR(),".lmctl","cache","lmprice")}function gn(t,e){return oo(t,e)}function Nr(t){try{return JSON.parse(xR(t,"utf-8"))}catch{return null}}function i_(t,e){let r=`${t}.tmp-${process.pid}`;AR(r,e),kR(r,t)}function Uc(t){return t===null||typeof t=="number"}function lo(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)})}function co(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"&&FR.has(i.evidence)});return r&&n}function PR(t){let e=Nr(gn(t,s_)),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=Nr(gn(t,$R));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 UR(t){let e=PR(t),r=Nr(gn(t,jc)),n=Nr(gn(t,Bc));return{catalog:lo(r)?r:null,aliases:co(n)?n:null,meta:e}}function jR(t,e){try{t_(t,{recursive:!0}),i_(gn(t,s_),JSON.stringify(e))}catch{}}function Kg(t,e,r){try{t_(t,{recursive:!0}),i_(gn(t,e),JSON.stringify(r))}catch{}}function BR(t,e){let r=WR(t),n=r?[ao(r,"data",e)]:[ao(t,"..","..","data",e)];for(let s of n)if(r_(s))return s;return null}function WR(t){let e=ao(t);for(;;){if(r_(ao(e,"package.json")))return e;let r=n_(e);if(r===e)return null;e=r}}function Yg(t,e,r){let n=r!==void 0?r:BR(t,e);return n===null?null:Nr(n)}function HR(){let t=process.env.LMCTL_PRICE_TTL;if(t===void 0||t==="")return Vg;let e=Number(t);return!Number.isFinite(e)||e<0?Vg:e*1e3}function XR(){let t=process.env.LMCTL_PRICE_DATA;return t!==void 0&&t!==""?t:null}async function zg(t,e,r,n){try{let s=await t(e,{method:"HEAD",signal:AbortSignal.timeout(OR)});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(DR)});return o.ok?{kind:"payload",payload:await o.json(),etag:o.headers.get("etag")??i}:{kind:"failed"}}catch{return{kind:"failed"}}}function uo(t={}){return Object.keys(t).length===0?(Qg??=Zg(t),Qg):Zg(t)}async function Zg(t){let e=n_(NR(import.meta.url)),r=t.pinDir!==void 0?t.pinDir:XR();if(r!==null&&r!==""){let g=Nr(oo(r,jc)),y=Nr(oo(r,Bc));if(lo(g)&&co(y)){let h={catalog:g,aliases:y,source:"pinned",generatedAt:g.generated_at??null};return Wc=h.generatedAt,h}return e_(t,e)}let n=t.fetchImpl??fetch,s=t.cacheDir??MR(),i=t.now??Date.now(),o=t.ttlMs??HR(),a=UR(s),l=(g,y)=>g!==null&&y.last_checked!==null&&i-Date.parse(y.last_checked)<o,c=a.catalog,u=a.aliases,d=!1,m={model_list:{...a.meta.model_list},aliases:{...a.meta.aliases}},f=!1;if(!l(c,a.meta.model_list)){let g=await zg(n,LR,c,a.meta.model_list.etag);g.kind==="match"?(m.model_list.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(m.model_list.last_checked=new Date(i).toISOString(),f=!0,lo(g.payload)&&(c=g.payload,g.etag!==null&&(m.model_list.etag=g.etag),Kg(s,jc,c),d=!0))}if(!l(u,a.meta.aliases)){let g=await zg(n,CR,u,a.meta.aliases.etag);g.kind==="match"?(m.aliases.last_checked=new Date(i).toISOString(),f=!0):g.kind==="payload"&&(m.aliases.last_checked=new Date(i).toISOString(),f=!0,co(g.payload)&&(u=g.payload,g.etag!==null&&(m.aliases.etag=g.etag),Kg(s,Bc,u),d=!0))}if((f||d)&&jR(s,m),c!==null||u!==null){let g={catalog:c,aliases:u,source:d?"network":"cache",generatedAt:c?.generated_at??null};return Wc=g.generatedAt,g}return e_(t,e)}function e_(t,e){let r=Yg(e,"price-data.json",t.bundledPath),n=Yg(e,"price-aliases.json",t.bundledAliasesPath),s=lo(r)?r:null,i=co(n)?n:null,o={catalog:s,aliases:i,source:s!==null||i!==null?"bundled":"unavailable",generatedAt:s?.generated_at??null};return Wc=o.generatedAt,o}function o_(t,e){if(e===null)return null;let{input_per_1m_tokens:r,output_per_1m_tokens:n,input_cache_read_per_1m_tokens:s}=e;if(r===null||n===null)return null;let i=s??r,o=t.input/1e6*r+t.output/1e6*n+t.cachedInput/1e6*i;return Number(o.toPrecision(10))}var LR,CR,OR,DR,Vg,jc,Bc,s_,$R,FR,Wc,Qg,Hc=k(()=>{"use strict";LR="https://lmctl.com/dataset/model_list.json",CR="https://lmctl.com/dataset/aliases.json",OR=1e3,DR=1e4,Vg=6*60*60*1e3;jc="model_list.json",Bc="aliases.json",s_="meta.json",$R="model_list.meta.json";FR=new Set(["established","asserted","unresolved"]);Wc=null,Qg=null});function Cr(t){return t.toLowerCase().replace(/(\d)\.(\d)/g,"$1-$2")}function Lr(t){let e=t.source_model_id.toLowerCase(),r=e.slice(e.lastIndexOf("/")+1);return Cr(r)}function l_(t){let e=new Set,r=n=>{let s=n.toLowerCase().split("/");for(let i=0;i<s.length;i+=1)e.add(Cr(s.slice(i).join("/")))};return r(t.source_model_id),t.gateway_id&&r(t.gateway_id),e}function qR(t,e){let r=new Set,n=l=>{r.add(Cr(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 _n(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=>qR(n,t.vendorPrefixes),matchRow(n,s){if(!r(n))return!1;let i=l_(n);return s.some(o=>i.has(o))}}}function JR(t){let e=t.trim(),r=GR.exec(e);return r?{model:e.slice(0,r.index).trim(),effort:r[1].trim()}:{model:e,effort:null}}function zR(t,e,r){let n=e.trim().toLowerCase(),s=Cr(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 QR(t,e,r){let n=[];for(let[s,i]of Object.entries(Es))s!==r&&zR(i,t,e)&&n.push(s);return n}function mo(t){return t==="moonshot"?0:t==="litellm"?1:t==="openrouter"?2:t==="manual"?3:4}function ZR(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 eN(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}${Cr(a)}`,c=e.get(l);if(c===void 0){e.set(l,n);continue}if(!ZR(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 tN(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 h_(t,e){return t.map(tN).sort((r,n)=>{let s=mo(r.source)-mo(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 Xc(t){return t.pricing.input_per_1m_tokens!==null&&t.pricing.output_per_1m_tokens!==null}function rN(t,e,r){let n=eN(t),s=h_(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 qc(t,e,r){if(t.length===0)return{kind:"known-unpriced",id:e};let n=rN(t,e,r),s=n.offers.find(Xc);return s===void 0?{kind:"known-unpriced",id:e}:s.estimated?{kind:"estimated",model:n}:{kind:"priced",model:n}}function nN(t,e){return t.standards.find(r=>r.standard_slug.toLowerCase()===e.toLowerCase())??null}function sN(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=Lr(i),a=r.records.filter(l=>Lr(l)!==o?!1:l.mode===void 0||l.mode===null||l.mode==="chat");return a.length===0?{kind:"known-unpriced",id:n}:qc(a,o,Gc)}function g_(t,e,r,n){if(r===null||!Array.isArray(r.records))return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};if(n!==null){let y=[e.trim().toLowerCase()];y.push(`${t.toLowerCase()}/${y[0]}`);let h=n.aliases.find(p=>y.includes(p.alias.toLowerCase()));if(h){if(h.evidence==="unresolved"||h.standard_slug===null)return{state:{kind:"unresolved",alias:h.alias},viaAlias:!0,pinRoute:null};let p=nN(n,h.standard_slug);return{state:sN(h,p,r),viaAlias:!0,pinRoute:p?.catalog_record_id?.toLowerCase()??null}}}let s=Es[t];if(!s)return{state:{kind:"no-catalog"},viaAlias:!1,pinRoute:null};let i=e.trim().toLowerCase(),o=s.normalize(e),a=y=>({state:y,viaAlias:!1,pinRoute:null}),l=Cr(i),c=r.records.filter(y=>y.source_model_id.toLowerCase()===i&&s.matchRow(y,[l]));if(c.length>0){let y=Lr(c[0]),h=r.records.filter(p=>s.matchRow(p,[y])&&Lr(p)===y);return a(qc(h.length>0?h:c,y,a_[t]??Gc))}let u=r.records.filter(y=>s.matchRow(y,o));if(u.length===0){let y=QR(e,r,t);return y.length>0?a({kind:"wrong-provider",declared:e,otherProviders:y}):a({kind:"unknown",declared:e})}let d=new Map;for(let y of u){let h=Lr(y),p=d.get(h);p?p.push(y):d.set(h,[y])}let m=a_[t]??Gc,f=null,g=null;for(let y of d.values()){let h=h_(y,m);(g===null||iN(h[0],g[0],m)<0)&&(f=y,g=h)}return a(qc(f,Lr(f[0]),m))}function fo(t,e,r,n){return g_(t,e,r,n).state}function __(t,e,r,n){let{state:s,viaAlias:i,pinRoute:o}=g_(t,e,r,n);if(s.kind!=="priced"&&s.kind!=="estimated")return{state:s,offer:null,provenance:null};let a=s.model.offers;if(i&&o!==null){let c=a.find(u=>u.route.toLowerCase()===o);if(c!==void 0&&Xc(c))return{state:s,offer:c,provenance:"alias-pin"}}let l=a.find(Xc)??null;return{state:s,offer:l,provenance:i&&o!==null?"alias-pin":"route-preference"}}function y_(t,e){let r=Es[e];if(!r)return null;let n=new Set;for(let s of t.records)r.coversRecord(s)&&n.add(Lr(s));return n.size}function iN(t,e,r){let n=mo(t.source)-mo(e.source);if(n!==0)return n;let s=t.provider!==null&&r.includes(t.provider)?0:1,i=e.provider!==null&&r.includes(e.provider)?0:1;return s!==i?s-i:t.sourceModelId.localeCompare(e.sourceModelId)}var c_,d_,u_,m_,f_,p_,GR,VR,KR,YR,Es,a_,Gc,Jc=k(()=>{"use strict";c_=_n({vendorPrefixes:["anthropic"],family:/claude/,firstPartyProviders:["anthropic"]}),d_=_n({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)(-|$)/}),u_=_n({vendorPrefixes:["google","gemini"],family:/gemini|gemma/,firstPartyProviders:["gemini","google","vertex_ai-language-models"],nonChatName:/embedding|imagen|-image|tts|audio|veo|lyria|live|realtime|video/}),m_=_n({vendorPrefixes:["moonshot","moonshotai"],family:/kimi|moonshot/,firstPartyProviders:["moonshot"]}),f_=_n({vendorPrefixes:["dashscope","qwen"],family:/qwen/,firstPartyProviders:["dashscope"]}),p_=_n({vendorPrefixes:["deepseek","nousresearch"],family:/deepseek|nous|hermes-\d/,firstPartyProviders:["deepseek","nousresearch"]}),GR=/\s*\(([^()]+)\)\s*$/;VR={"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"},KR=["gemini","google","vertex_ai-language-models","anthropic"],YR={normalize(t){let{model:e}=JR(t),r=VR[e.toLowerCase()];return r===void 0?[]:[Cr(r)]},isChatModel(t){return t.mode===void 0||t.mode===null||t.mode==="chat"},coversRecord(t){return this.isChatModel(t)&&/gemini|claude/.test(t.source_model_id.toLowerCase())},matchRow(t,e){if(!this.coversRecord(t))return!1;let r=l_(t);return e.some(n=>r.has(n))}},Es={claude:c_,codex:d_,gemini:u_,agy:YR,kimi:m_,qwen:f_,hermes:p_},a_={claude:c_.firstPartyProviders,codex:d_.firstPartyProviders,gemini:u_.firstPartyProviders,agy:KR,kimi:m_.firstPartyProviders,qwen:f_.firstPartyProviders,hermes:p_.firstPartyProviders};Gc=[]});import{spawnSync as Zc}from"node:child_process";import{existsSync as v_,readFileSync as S_}from"node:fs";import{homedir as b_}from"node:os";import{resolve as zc}from"node:path";function yn(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 cN(){let t=Zc("agy",["models"],{encoding:"utf-8",timeout:lN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function dN(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 uN(t){if(!t&&Vc)return Vc;let e=s=>(t||(Vc=s),s),r;try{r=(t??cN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?yn("agy models",s):`agy models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:yn("agy models",r.error)});if(r.status!==0)return e({available:!1,models:[],reason:`agy models exited with status ${r.status??"unknown"}`});let n=dN(r.stdout);return n.length===0?e({available:!1,models:[],reason:"agy models returned no models"}):e({available:!0,models:n})}function fN(){let t=Zc("codex",["debug","models"],{encoding:"utf-8",timeout:mN});return{status:t.status,stdout:t.stdout??"",error:t.error}}function pN(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 hN(t){if(!t&&Kc)return Kc;let e=s=>(t||(Kc=s),s),r;try{r=(t??fN)()}catch(s){return e({available:!1,models:[],reason:s instanceof Error?yn("codex debug models",s):`codex debug models could not be run: ${String(s)}`})}if(r.error)return e({available:!1,models:[],reason:yn("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=pN(r.stdout);return n===void 0?e({available:!1,models:[],reason:"codex debug models did not return parseable JSON"}):n.length===0?e({available:!1,models:[],reason:"codex debug models returned no user-visible models"}):e({available:!0,models:n})}function _N(t){let e=Zc("opencode",["models",t],{encoding:"utf-8",timeout:gN});return{status:e.status,stdout:e.stdout??"",error:e.error}}function yN(t,e){if(!e&&Yc.has(t))return Yc.get(t);let r=i=>(e||Yc.set(t,i),i),n;try{n=(e??_N)(t)}catch(i){return r({available:!1,models:[],reason:i instanceof Error?yn(`opencode models ${t}`,i):`opencode models ${t} could not be run: ${String(i)}`})}if(n.error)return r({available:!1,models:[],reason:yn(`opencode models ${t}`,n.error)});if(n.status!==0)return r({available:!1,models:[],reason:`opencode models ${t} exited with status ${n.status??"unknown"}`});let s=n.stdout.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);return s.length===0?r({available:!1,models:[],reason:`opencode models ${t} returned no models`}):r({available:!0,models:s})}function ed(t,e={}){let r=[];for(let n of t){let s=n.provider.trim().toLowerCase();if(n.effort&&s!=="opencode"&&s!=="lmplayer"&&s!=="qwen"&&r.push(`[${n.alias}] effort="${n.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),s==="qwen"&&n.effort&&r.push(`[${n.alias}] effort="${n.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),!n.model&&aN.has(s)&&r.push(`[${n.alias}] provider=${s} has no model= \u2014 ${s} will use its own ambient default, which cannot be linted or priced and may not be the intended one. Set model= explicitly.`),s==="copilot"){if(!n.model)continue;r.push(`[${n.alias}] model="${n.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(s==="lmplayer"&&!n.model){r.push(`[${n.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}if(s!=="lmplayer"){if(s==="opencode"){if(n.effort&&!n.model&&r.push(`[${n.alias}] effort="${n.effort}" has no effect without model= on an opencode member.`),!n.model){r.push(`[${n.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.5).`);continue}let i=wN(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=yN(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=EN(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: ${Ts(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=uN(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: ${Ts(i.models)}`):r.push(`[${n.alias}] model="${n.model}" cannot be verified for agy: ${i.reason}.`);continue}if(s==="dsh"){if(!n.model||T_.includes(n.model))continue;E_.includes(n.model)||r.push(`[${n.alias}] model="${n.model}" is not in dsh's built-in catalog. Valid pinned models: ${Ts(E_)}. 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): ${Ts(T_)}. 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===w_&&r.push(`[${n.alias}] model="${w_}" 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=hN(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: ${Ts(i.models)}`);continue}n.model&&(I_.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 x_(t,e={}){let r=t.filter(o=>o.model!==void 0&&I_.has(o.provider.trim().toLowerCase()));if(r.length===0)return{warnings:[],errors:[]};let n=e.snapshot??await uo();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=fo(a,l,n.catalog,n.aliases);if(c.kind==="unknown"){let u=y_(n.catalog,a)??0;s.push(`[${o.alias}] model "${l}" is unknown to the lmprice catalog for provider "${a}" (${u} known) -- not necessarily wrong: may be a model too new for lmprice to have published yet, or a typo. A matching lmprice catalog/alias entry would resolve this; lint cannot otherwise confirm whether ${a} accepts it.`)}else c.kind==="wrong-provider"?i.push({field:o.alias,message:`model "${l}" is not offered by provider "${a}" -- it is a recognized model, but only under: ${c.otherProviders.join(", ")}. Declare provider="${c.otherProviders[0]}" (or another listed provider), or use a model "${a}" actually offers.`}):c.kind==="known-unpriced"&&s.push(`[${o.alias}] model "${l}" is recognized in the lmprice catalog but has no price information \u2014 cost will be unavailable`);if(a==="claude"&&(c.kind==="priced"||c.kind==="known-unpriced"||c.kind==="estimated")&&oN.test(l)){let u=l.replace(/(\d)\.(?=\d)/g,"$1-");s.push(`[${o.alias}] model="${l}" matches the lmprice catalog only through its OpenRouter-style spelling ("." between version numbers); claude's own CLI expects "-" there and does an exact match, so it may reject this string verbatim even though lint recognizes it. If seed/chat fails with "issue with the selected model," try model="${u}" instead.`)}}return{warnings:s,errors:i}}async function k_(t,e={}){return(await x_(t,e)).warnings}async function A_(t,e={}){return(await x_(t,e)).errors}function EN(t){let e=process.env.KIMI_CODE_HOME||zc(b_(),".kimi-code"),r=t??zc(e,"config.toml");if(!v_(r))return{available:!1,models:[],reason:`${r} not found`};let n;try{n=S_(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=TN(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 TN(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 wN(t){let e=t??zc(b_(),".config","opencode","opencode.json");if(!v_(e))return{available:!0,models:[]};let r;try{r=JSON.parse(S_(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:vN(r)}}function vN(t){if(!Qc(t))return[];let e=po(t.provider)??po(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Qc(s))continue;let i=po(s.models)??po(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function po(t){return Qc(t)?t:null}function Qc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ts(t){return t.length>0?t.join(", "):"(none)"}var I_,oN,aN,E_,T_,w_,lN,Vc,mN,Kc,gN,Yc,R_=k(()=>{"use strict";Hc();Jc();I_=new Set(Object.keys(Es).filter(t=>t!=="codex"&&t!=="kimi")),oN=/\d\.(?=\d)/,aN=new Set(["claude","codex","gemini","qwen","kimi","agy"]),E_=["deepseek-v4-flash","deepseek-v4-pro","deepseek-v4-flash-vision-exp"],T_=["deepseek-flash","deepseek-pro"],w_="gpt-5.3-codex-spark",lN=15e3;Vc=null;mN=5e3;Kc=null;gN=5e3;Yc=new Map});import{homedir as SN}from"node:os";import{basename as bN}from"node:path";function N_(t,e){let r=new Set;return{text:t.replace(xN,(s,i)=>{let o=i.trim(),a=IN[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function L_(t){return{workdir:t.workdir,teamfile:t.teamfile,date:kN(t.date)}}function kN(t){return t.toISOString().slice(0,10)}var IN,xN,C_=k(()=>{"use strict";IN={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=bN(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>SN(),date:t=>t.date},xN=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var cd={};oe(cd,{GEMINI_PROVIDER_NOTICE:()=>P_,_setAgyModelsRunnerForTests:()=>DN,_setCatalogSnapshotForTests:()=>ON,_setCodexModelsRunnerForTests:()=>MN,_setLintOpenCodeConfigProbeForTests:()=>PN,_setLintSessiondirFsOpsForTests:()=>FN,_setTeamfileSeedForTests:()=>$N,buildRootTeamRegistrationRow:()=>q_,lintTeamfileStructured:()=>ld,registerRootTeam:()=>G_,runLint:()=>Mr,runSeed:()=>$r,seedTeamfile:()=>ho,sha256Text:()=>X_,validateMemberSpec:()=>Mt});import{createHash as AN}from"node:crypto";import{accessSync as RN,constants as O_,existsSync as NN,readFileSync as $_,realpathSync as nd,statSync as LN,writeFileSync as D_}from"node:fs";import{dirname as Dr,resolve as F_}from"node:path";function ON(t){vs=t??void 0}function B_(t){return k_(t,vs!==void 0?{snapshot:vs}:{})}function W_(t){return A_(t,vs!==void 0?{snapshot:vs}:{})}function DN(t){od=t??void 0}function MN(t){ad=t??void 0}function $N(t){U_=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(Ct(),vc)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function FN(t){Or=t===null?sd:{...sd,...t}}function PN(t){j_=t??qn}async function UN(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 j_({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 jN(t,e){let r=Dr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=F_(o);if(n.has(a))continue;let l=BN(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 BN(t){try{if(Or.existsSync(t)){if(!Or.statSync(t).isDirectory())return"ENOTDIR";Or.accessSync(t,O_.W_OK);return}let e=HN(t);if(e===void 0)return;if(!Or.statSync(e).isDirectory())return"ENOTDIR";Or.accessSync(e,O_.W_OK);return}catch(e){return XN(e)??"permission check failed"}}function WN(t){let e=F_(t);try{return nd(e)}catch{return e}}function HN(t){let e=t;for(;;){try{if(Or.existsSync(e))return e}catch{return}let r=Dr(e);if(r===e)return;e=r}}function XN(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 H_(t,e){let r;try{r=await C(e,l=>he(t,l))}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let n;try{n=Ne(r)}catch(l){return{ok:!1,message:`${t}: ${l instanceof Error?l.message:String(l)}`}}let s=ha(n,Dr(r));e.stderr.write(`notice: checking teamfile and models ...
|
|
2138
|
+
`);let i=ed(n.members,{agyModelsRunner:od,codexModelsRunner:ad});i.push(...await B_(n.members)),s.push(...await W_(n.members));let o=$_(r,"utf8"),a=N_(o,L_({workdir:Dr(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(...za(n.members,Dr(r))),i.push(...jN(n.members,r)),i.push(...await UN(n.members,Dr(r),e.env));for(let l of s)e.stderr.write(`error: ${l.field}: ${l.message}
|
|
2139
|
+
`);for(let l of n.members)id([l],e),l.session!==void 0&&l.session.length<ws&&i.push(`${l.alias}: sessionid is shorter than ${ws} chars; run lmctl seed to refresh it`);return{ok:!0,result:{config:n,absTeamfile:r,errors:s,warnings:i}}}async function Mr(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(CN),0;let r=ae(t,[],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2063
2140
|
`),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
|
|
2064
2141
|
`),2;let n=r.positionals[0],s=await H_(n,e);if(!s.ok)return En(e,s.message);let{errors:i,warnings:o}=s.result;for(let a of o)e.stderr.write(`warning: ${a}
|
|
2065
2142
|
`);return e.stderr.write(`notice: ${i.length} error${i.length===1?"":"s"}, ${o.length} warning${o.length===1?"":"s"}
|
|
2066
2143
|
`),i.length>0?1:(e.stdout.write(`ok
|
|
2067
|
-
`),0)}function
|
|
2144
|
+
`),0)}function JN(t,e){let r=qN.exec(t);if(r){let s=e.get(r[1].toLowerCase());if(s!==void 0)return{alias:s,message:r[2]}}let n=GN.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 ld(t,e){let r=await H_(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=>JN(c,o));for(let c of l)e.stderr.write(`warning: ${c.alias?`${c.alias}: `:""}${c.message}
|
|
2068
2145
|
`);return e.stderr.write(`notice: ${a.length} error${a.length===1?"":"s"}, ${l.length} warning${l.length===1?"":"s"}
|
|
2069
|
-
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}async function $r(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(td),0;let r=ae(t,[],[]);return r.error!==void 0?M_(e,r.error,td):r.positionals.length!==1?M_(e,"expected <teamfile.lmctl>",td):ho(r.positionals[0],e)}function
|
|
2146
|
+
`),{status:a.length>0?"error":"ok",errors:a,warnings:l,counts:{errors:a.length,warnings:l.length}}}async function $r(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(td),0;let r=ae(t,[],[]);return r.error!==void 0?M_(e,r.error,td):r.positionals.length!==1?M_(e,"expected <teamfile.lmctl>",td):ho(r.positionals[0],e)}function VN(t,e,r,n){if(e.preamble===void 0)return t.toLowerCase()!=="lead"?void 0:`${J}
|
|
2070
2147
|
|
|
2071
2148
|
Teamfile ${r}:
|
|
2072
2149
|
${n}
|
|
2073
2150
|
|
|
2074
2151
|
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 ho(t,e,r={}){let n;try{n=await C(e,p=>he(t,p))}catch(p){return En(e,`${t}: ${p instanceof Error?p.message:String(p)}`)}let s;try{s=nd(n)}catch(p){return En(e,`${t}: ${p instanceof Error?p.message:String(p)}`)}let i=Dr(n),o;try{o=Ne(n)}catch(p){return En(e,`${t}: ${p instanceof Error?p.message:String(p)}`)}let l=$_(n,"utf8").split(`
|
|
2075
|
-
`),c=
|
|
2152
|
+
`),c=KN(l),u=ha(o,i);if(u.length>0){id(o.members,e);for(let p of u)e.stderr.write(`error: ${p.field}: ${p.message}
|
|
2076
2153
|
`);return 1}try{Hr(e,o,n)}catch{}id(o.members,e),e.stderr.write(`notice: checking teamfile and models ...
|
|
2077
2154
|
`);for(let p of ed(o.members,{agyModelsRunner:od,codexModelsRunner:ad}))e.stderr.write(`warning: ${p}
|
|
2078
2155
|
`);for(let p of await B_(o.members))e.stderr.write(`warning: ${p}
|
|
@@ -2082,25 +2159,25 @@ After this seed finishes, use \`lmctl prompt ${JSON.stringify(r)} <alias> "<mess
|
|
|
2082
2159
|
`),1;for(let p of o.members){if(p.teamfile!==void 0)continue;if(p.session!==void 0&&p.session.length>=ws){e.stderr.write(`warning: ${p.alias}: existing sessionid preserved; skipping
|
|
2083
2160
|
`);continue}let _=p.sessiondir??i;e.stderr.write(`${p.alias}: launching ${p.provider} seed session; this can take several seconds
|
|
2084
2161
|
`);let T=ot(e,w=>`${p.alias}: still launching (${w}s elapsed)
|
|
2085
|
-
`),E=
|
|
2162
|
+
`),E=VN(p.alias,r,n,l.join(`
|
|
2086
2163
|
`)),S;try{S=Qu(n,p.alias)}catch(w){return T.stop(),En(e,w instanceof Error?w.message:String(w))}try{let w;try{w=await U_({provider:p.provider,cwd:_,...p.model!==void 0?{model:p.model}:{},...p.effort!==void 0?{effort:p.effort}:{},...E!==void 0?{prompt:E}:{}})}finally{T.stop()}for(let I of w.warnings??[])e.stderr.write(`warning: ${p.alias}: ${I}
|
|
2087
2164
|
`);if(w.error!==void 0||w.sessionId===void 0||w.sessionId.length<ws){let I=`provider did not report a sessionid; no new session was found for ${_} (possible provider workspace/cwd mismatch)`;return e.stderr.write(`error: ${p.alias}: seed failed${w.error!==void 0?`: ${w.error}`:`; ${I}`}
|
|
2088
2165
|
`),1}let b=c.get(p.alias.toLowerCase());if(b===void 0)return e.stderr.write(`error: ${p.alias}: could not find matching _MEMBER_ line to update
|
|
2089
|
-
`),1;let v=
|
|
2166
|
+
`),1;let v=WN(_),x=rd(l[b],"sessionid",w.sessionId);if(x=rd(x,"sessiondir",v),p.model===void 0){let I;try{I=(await Re(w.sessionId,p.provider))?.model}catch{I=void 0}I!==void 0&&I.length>0?x=rd(x,"model",I):e.stderr.write(`warning: ${p.alias}: seed could not determine which model ${p.provider} selected; model= left unset
|
|
2090
2167
|
`)}l[b]=x,m+=1,D_(n,l.join(`
|
|
2091
2168
|
`),"utf8"),e.stdout.write(`${p.alias}: seeded ${w.sessionId} provider=${p.provider} sessiondir=${v}
|
|
2092
2169
|
`)}finally{S()}}let g=l.join(`
|
|
2093
|
-
`),y=
|
|
2094
|
-
`);let h=new Date().toISOString();try{await C(e,p=>{G_(p,{teamfilePath:s,name:o.name,rawText:y,now:h})})}catch(p){return En(e,p instanceof Error?p.message:String(p))}return 0}function X_(t){return
|
|
2170
|
+
`),y=ZN(g,nd(n));y!==g&&D_(n,y,"utf8"),m===0&&e.stdout.write(`no members needed seeding
|
|
2171
|
+
`);let h=new Date().toISOString();try{await C(e,p=>{G_(p,{teamfilePath:s,name:o.name,rawText:y,now:h})})}catch(p){return En(e,p instanceof Error?p.message:String(p))}return 0}function X_(t){return AN("sha256").update(t).digest("hex")}function q_(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:X_(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function G_(t,e){let r=Gs(e.rawText,e.teamfilePath);ya(t,e.teamfilePath,r);let n=q_(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(n),n}function KN(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=zN(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function YN(t){return/^[A-Za-z][A-Za-z0-9_-]*$/u.test(t)}function zN(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function rd(t,e,r){let n=`${e}=${QN(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(i,o)=>`${o}${n}`):`${t.trimEnd()} ${n}`}function QN(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function ZN(t,e){let r=`#teamfile: ${e}`,n=t.indexOf(`
|
|
2095
2172
|
`),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}
|
|
2096
2173
|
${i}`:`${r}
|
|
2097
2174
|
`:t.length>0?`${r}
|
|
2098
2175
|
${t}`:`${r}
|
|
2099
|
-
`}function Mt(t){if(!
|
|
2176
|
+
`}function Mt(t){if(!YN(t.alias))return`invalid alias "${t.alias}"`;if(!J_(t.provider))return`invalid provider "${t.provider}"`}function J_(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 En(t,e){return t.stderr.write(`error: ${e}
|
|
2100
2177
|
`),1}function M_(t,e,r){return t.stderr.write(`error: ${e}
|
|
2101
2178
|
${r}`),2}function id(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_
|
|
2102
2179
|
`),r.provider==="gemini"&&e.stderr.write(`${P_.replace("%s",r.alias)}
|
|
2103
|
-
`)}var ws,
|
|
2180
|
+
`)}var ws,CN,td,P_,sd,U_,Or,j_,od,ad,vs,qN,GN,$t=k(()=>{"use strict";kt();R_();Qa();ll();ar();ge();At();C_();Qs();wa();Oe();ws=5,CN=`usage: lmctl lint <teamfile.lmctl>
|
|
2104
2181
|
|
|
2105
2182
|
Validate an lmctl teamfile and warn about stale or placeholder session ids.
|
|
2106
2183
|
For opencode members with model=, lint also asks the local ACP provider to
|
|
@@ -2160,34 +2237,34 @@ possibly work, seed reports it as an error and seeds nothing.
|
|
|
2160
2237
|
and save it to <file> (lmctl.com curates these, not lmctl itself).
|
|
2161
2238
|
Refuses to overwrite an existing <file> unless --force is given.
|
|
2162
2239
|
--script <name> With --save-script, fetch commands/<name>.lms instead of the default
|
|
2163
|
-
`,P_='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',sd={existsSync:IN,statSync:xN,accessSync:bN},U_=async t=>{let{seed:e}=await Promise.resolve().then(()=>(Ct(),vc)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Or=sd,j_=qn;jN=/^\[([^\]]+)\]\s+(.*)$/s,BN=/^([^:\s][^:]*):\s+(.*)$/s});function De(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 vt(t,e){if(t==null||typeof t=="boolean")return null;let r=Number(t);return De(e==="percent"?r/100:r)}function V_(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 K_(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function Y_(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 z_(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"}function go(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 YN)r=r.replace(n,"***REDACTED***");return r}function Je(t){let e=De(t.used_fraction),r=De(t.remaining_fraction),n=t.resets_at==null?K_(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?V_(n):V_(K_(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:De(1-r)),remaining_fraction:r??(e===null?null:De(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 ve(t,e,r={}){let n={$schema:KN,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 Ae(t,e,r,n,s,i=[],o){return ve(t,e,{source:s??null,reason:r,...n==null?{}:{detail:go(n,i)},...o==null?{}:{retry_after_seconds:o}})}function Q_(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}var KN,YN,Ss=k(()=>{"use strict";KN="https://lmctl.com/schemas/lmratelimit-v1.json";YN=[/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]});import{spawnSync as zN}from"node:child_process";import{readdirSync as QN,readFileSync as ZN}from"node:fs";import{join as eL}from"node:path";function aL(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function lL(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 cL(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 dL(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=cL(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=De(o/100);r.push(Je({bucket_id:`${lL(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:De(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 bs(t,e,r){return Ae("agy","provider_unavailable",t,e,"agy_cli_print")}function uL(t,e){try{let r=iL(Math.max(t,60)*1e3,aL(e));if(r.error?.code==="ENOENT")return bs("agy_not_found","the agy CLI is not on PATH",t);if(r.error?.code==="ETIMEDOUT")return bs("cli_timeout","agy -p /usage did not finish in time",t);if(r.error)return bs("cli_failed",r.error.message,t);let n=dL(r.stdout??"");return n.length===0?bs("cli_unparseable",`exit ${r.status??1}; no buckets parsed from CLI output`,t):ve("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n})}catch(r){return bs("cli_failed",r instanceof Error?r.message:String(r),t)}}function mL(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[Z_],t[ey],-1);try{for(let s of QN("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of ZN(eL("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[Z_],i[ey],Number(s))}catch{}}catch{}return e}function fL(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=vt(l.remainingFraction,"fraction");n.push(Je({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:z_(l.window),used_fraction:c===null?null:De(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??""))),ve("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function pL(t,e){let r=mL(e);if(r.length===0)return Ae("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let n=[];for(let[s,i,o]of r)try{let a=await oL(`http://${s}${tL}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":i},t*1e3);if(a.status===200){let l;try{l=JSON.parse(a.body)}catch{n.push(`pid=${o}: unparseable response`);continue}let c=fL(l);if(c)return c;n.push(`pid=${o}: response had no quota groups`)}else a.status===401||a.status===403?n.push(`pid=${o}: HTTP ${a.status} unauthorized`):n.push(`pid=${o}: HTTP ${a.status}`)}catch(a){n.push(`pid=${o}: ${a instanceof Error?a.message:String(a)}`)}return Ae("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${n.slice(0,5).join("; ")}`,"agy_connect_rpc",r.map(([,s])=>s))}async function ty(t){let e=uL(t.timeoutSeconds,t.env);if(e.status==="ok")return e;let r=await pL(t.timeoutSeconds,t.env);return r.status==="ok"?r:Ae("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")}var Z_,ey,tL,rL,nL,sL,iL,oL,ry=k(()=>{"use strict";Ss();Z_="ANTIGRAVITY_LS_ADDRESS",ey="ANTIGRAVITY_CSRF_TOKEN",tL="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",rL=["-p","/usage"],nL=(t,e)=>{let r=zN("agy",rL,{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}},sL=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()}},iL=nL,oL=sL});import{spawnSync as oy}from"node:child_process";import{existsSync as hL,readFileSync as gL}from"node:fs";import{homedir as ay}from"node:os";import{join as ly}from"node:path";function TL(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"}function cy(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE")))}function wL(t){try{let e=oy("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:cy(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function Ze(t,e,r,n="claude_oauth_api",s){return Ae("claude",t,e,r,n,void 0,s)}function vL(t){let e=t.CLAUDE_CODE_OAUTH_TOKEN;if(e)return{oauth:{accessToken:e,source:"CLAUDE_CODE_OAUTH_TOKEN"}};let r=ly(ay(),".claude",".credentials.json");if(!hL(r))return t.ANTHROPIC_API_KEY?{error:"not_claude_ai_subscriber"}:{error:"no_credentials_found"};try{let n=JSON.parse(gL(r,"utf8")),s=typeof n=="object"&&n!==null&&"claudeAiOauth"in n?n.claudeAiOauth:void 0;return!s||typeof s!="object"||!("accessToken"in s)||!s.accessToken?{error:"not_claude_ai_subscriber"}:{oauth:s}}catch(n){return{error:`credentials_unreadable: ${n instanceof Error?n.name:"Error"}`}}}function SL(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function bL(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}function xL(t){let e=[];for(let r of t.split(/\r?\n/)){let n=IL.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(Je({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:vt(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:bL(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 kL(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 sy(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=vt(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 iy(t,e,r){try{let n=oy("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:cy(e),maxBuffer:16777216}),s=typeof n.stdout=="string"?n.stdout:"",i=xL(s);if(!i.length)return;let o=kL(s);return ve("claude",Be.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:i,...Object.keys(o).length?{characteristics:o}:{}})}catch{return}}async function dy({timeoutSeconds:t,env:e}){let r=vL(e);if(r.error==="not_claude_ai_subscriber")return Ze(Be.notApplicable,r.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(r.error==="no_credentials_found")return Ze(Be.unavailable,"credentials_missing",`credentials file not found: ${ly(ay(),".claude",".credentials.json")}`);if(r.error)return Ze(Be.expired,"oauth_token_expired_or_invalid",r.error);let n=r.oauth,s=Array.isArray(n.scopes)?n.scopes:[];if(s.length&&!s.includes(ny))return Ze(Be.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${ny} scope required by the usage endpoint`);if(typeof n.expiresAt=="number"&&Date.now()+EL>=n.expiresAt)return Ze(Be.expired,"oauth_token_expired_or_invalid","local credential expiry has passed; run `claude` to renew the token");let i=new AbortController,o=setTimeout(()=>i.abort(),t*1e3),a;try{a=await fetch(`${_L}/api/oauth/usage`,{headers:{Authorization:`Bearer ${n.accessToken}`,"anthropic-beta":yL,"Content-Type":"application/json","User-Agent":wL(e)},signal:i.signal})}catch(m){let f=await iy(n,e,t);return f||Ze(Be.unavailable,"request_failed",`${m instanceof Error?m.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(o)}if(a.status===401)return Ze(Be.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(a.status===403)return Ze(Be.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(a.status===429){let m=SL(a.headers),f=await iy(n,e,t);return f||Ze(Be.throttled,"rate_limited",`usage endpoint rate limited${m==null?"":`; retry after ${m}s`}`,"claude_oauth_api",m)}if(a.status!==200)return Ze(Be.unavailable,`http_${a.status}`,"usage endpoint returned an unexpected status");let l;try{l=await a.json()}catch{return Ze(Be.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!l||typeof l!="object"||Array.isArray(l))return Ze(Be.unavailable,"malformed_response","response was not an object");let c=l,u=Array.isArray(c.limits)?c.limits:[],d=u.length?u.flatMap(m=>{if(!m||typeof m!="object")return[];let f=m.kind,g=TL(f==="session"?"session":f),y=m.scope?.model?.display_name,h=f==="session"?"session":f==="weekly_all"?"week-all-models":`week-scoped-${y||f}`;return[Je({bucket_id:h,group_name:f==="session"?"session":"weekly",window_type:g,used_fraction:vt(m.percent,"percent"),resets_at_iso:m.resets_at,raw_value:m.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(m=>{let f=c[m];return!f||typeof f!="object"?[]:[Je({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:vt(f.utilization,"percent"),resets_at_iso:f.resets_at,raw_value:f.utilization,raw_scale:"used_percent"})]});return ve("claude",Be.ok,{source:"claude_oauth_api",account_id:null,plan_type:n.subscriptionType??n.rateLimitTier??null,ordinary_usage_allowed:null,buckets:d.sort((m,f)=>String(m.window_type).localeCompare(String(f.window_type))||String(m.bucket_id).localeCompare(String(f.bucket_id))),...sy(c.spend)?{spend_control:sy(c.spend)}:{}})}var _L,yL,ny,EL,Be,IL,uy=k(()=>{"use strict";Ss();_L="https://api.anthropic.com",yL="oauth-2025-04-20",ny="user:profile",EL=3e5;Be={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};IL=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/});import{readFileSync as AL}from"node:fs";import{homedir as RL}from"node:os";import{join as NL}from"node:path";function et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function my(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 fy(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function OL(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||NL(RL(),".codex","auth.json");try{let r=JSON.parse(AL(e,"utf8")),n=et(r)&&et(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 DL(t){if(et(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function ML(t){let e=[],r=et(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=et(r[o])?r[o]:void 0;if(!a)continue;let l=my(a.limit_window_seconds);e.push(Je({bucket_id:`codex-${fy(l)}`,group_name:"codex",window_type:l,used_fraction:vt(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(!et(o))continue;let a=et(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,u=c||l||"additional",d=typeof a.allowed=="boolean"?a.allowed:void 0,m=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let f of["primary_window","secondary_window"]){let g=et(a[f])?a[f]:void 0;if(!g)continue;let y=my(g.limit_window_seconds);e.push(Je({bucket_id:`${u}-${fy(y)}`,group_name:l||u,window_type:y,used_fraction:vt(g.used_percent,"percent"),resets_at:g.reset_at,raw_value:g.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...d===void 0?{}:{allowed:d},...m===void 0?{}:{limit_reached:m}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function $L(t){let e=et(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=et(t.spend_control)?t.spend_control:void 0,s=et(t.credits)?t.credits:void 0;return ve("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:ML(t),...s?{credits:DL(s)}:{},...n?{spend_control:n}:{}})}async function py(t){let{timeoutSeconds:e,env:r}=t,n=OL(r);if(!n.token)return ve("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let s=new AbortController,i=setTimeout(()=>s.abort(),Math.ceil(e*1e3));try{let o={Authorization:`Bearer ${n.token}`,"User-Agent":CL,"Content-Type":"application/json",Accept:"application/json"};n.accountId&&(o["ChatGPT-Account-Id"]=n.accountId);let a=(r.CODEX_BASE_URL||LL).replace(/\/$/,""),l=await fetch(`${a}/wham/usage`,{headers:o,signal:s.signal});if(l.status===401)return ve("codex","auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(l.status===429){let u=l.headers.get("retry-after"),d=u===null?void 0:Number.parseInt(u,10);return ve("codex","reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...d!==void 0&&Number.isFinite(d)&&d>=0?{retry_after_seconds:d}:{}})}if(!l.ok)return ve("codex","provider_unavailable",{source:"codex_http",reason:`http_${l.status}`,detail:"codex usage endpoint returned an unexpected status"});let c;try{c=await l.json()}catch(u){return ve("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:go(String(u),[n.token])})}return et(c)?$L(c):ve("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(o){let a=o instanceof Error?`${o.name}: ${o.message}`:String(o);return ve("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:go(a,[n.token])})}finally{clearTimeout(i)}}var LL,CL,hy=k(()=>{"use strict";Ss();LL="https://chatgpt.com/backend-api",CL="codex-cli"});import{homedir as _y}from"node:os";import{join as Is}from"node:path";import{readFileSync as yy,readdirSync as FL,statSync as gy}from"node:fs";function BL(t){if(t.KIMI_CREDENTIALS_PATH)return t.KIMI_CREDENTIALS_PATH;let e=t.KIMI_CODE_HOME?Is(t.KIMI_CODE_HOME,"credentials"):PL,r=[];try{for(let n of FL(e))(n==="kimi-code.json"||n.startsWith("kimi-code-env-")&&n.endsWith(".json"))&&r.push(Is(e,n))}catch{}return r.length>0?r.sort((n,s)=>{try{return gy(s).mtimeMs-gy(n).mtimeMs}catch{return 0}})[0]:Is(e,"kimi-code.json")}function WL(t){let e=BL(t),r;try{r=yy(e,"utf8")}catch{return{error:"credentials_missing"}}let n;try{n=JSON.parse(r)}catch{return{error:"credentials_malformed"}}return!n||typeof n!="object"||!n.access_token?{error:"credentials_malformed"}:{access_token:n.access_token}}function HL(t){if(t.KIMI_CODE_BASE_URL)return t.KIMI_CODE_BASE_URL;let e=t.KIMI_CODE_CONFIG_PATH||UL;try{let r=yy(e,"utf8"),n=!1;for(let s of r.split(`
|
|
2164
|
-
`)){let i=s.trim();if(i.startsWith("[")){n=i==='[providers."managed:kimi-code"]';continue}if(n&&i.startsWith("base_url")){let o=i.match(/base_url\s*=\s*(?:"([^"]+)"|'([^']+)')/);if(o)return o[1]||o[2]}}}catch{}return
|
|
2165
|
-
`)}}function
|
|
2166
|
-
`),null}}function
|
|
2240
|
+
`,P_='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',sd={existsSync:NN,statSync:LN,accessSync:RN},U_=async t=>{let{seed:e}=await Promise.resolve().then(()=>(Ct(),vc)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Or=sd,j_=qn;qN=/^\[([^\]]+)\]\s+(.*)$/s,GN=/^([^:\s][^:]*):\s+(.*)$/s});function De(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 vt(t,e){if(t==null||typeof t=="boolean")return null;let r=Number(t);return De(e==="percent"?r/100:r)}function V_(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 K_(t){if(typeof t!="string"||t.trim()==="")return null;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):null}function Y_(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 z_(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"}function go(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 tL)r=r.replace(n,"***REDACTED***");return r}function Je(t){let e=De(t.used_fraction),r=De(t.remaining_fraction),n=t.resets_at==null?K_(t.resets_at_iso):Number(t.resets_at),s=t.resets_at_iso==null?V_(n):V_(K_(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:De(1-r)),remaining_fraction:r??(e===null?null:De(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 ve(t,e,r={}){let n={$schema:eL,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 Ae(t,e,r,n,s,i=[],o){return ve(t,e,{source:s??null,reason:r,...n==null?{}:{detail:go(n,i)},...o==null?{}:{retry_after_seconds:o}})}function Q_(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}var eL,tL,Ss=k(()=>{"use strict";eL="https://lmctl.com/schemas/lmratelimit-v1.json";tL=[/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]});import{spawnSync as rL}from"node:child_process";import{readdirSync as nL,readFileSync as sL}from"node:fs";import{join as iL}from"node:path";function mL(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("ANTIGRAVITY")))}function fL(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 pL(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 hL(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=pL(s[1]);if(!i)continue;let o=Number(s[2].replace(/%$/,"").trim());if(!Number.isFinite(o))continue;let a=De(o/100);r.push(Je({bucket_id:`${fL(s[0])}-${e[i]}`,group_name:s[0],window_type:i,used_fraction:a===null?null:De(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 bs(t,e,r){return Ae("agy","provider_unavailable",t,e,"agy_cli_print")}function gL(t,e){try{let r=dL(Math.max(t,60)*1e3,mL(e));if(r.error?.code==="ENOENT")return bs("agy_not_found","the agy CLI is not on PATH",t);if(r.error?.code==="ETIMEDOUT")return bs("cli_timeout","agy -p /usage did not finish in time",t);if(r.error)return bs("cli_failed",r.error.message,t);let n=hL(r.stdout??"");return n.length===0?bs("cli_unparseable",`exit ${r.status??1}; no buckets parsed from CLI output`,t):ve("agy","ok",{source:"agy_cli_print",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n})}catch(r){return bs("cli_failed",r instanceof Error?r.message:String(r),t)}}function _L(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[Z_],t[ey],-1);try{for(let s of nL("/proc"))if(/^\d+$/.test(s))try{let i={};for(let o of sL(iL("/proc",s,"environ")).toString("utf8").split("\0")){let a=o.indexOf("=");a>0&&(i[o.slice(0,a)]=o.slice(a+1))}n(i[Z_],i[ey],Number(s))}catch{}}catch{}return e}function yL(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=vt(l.remainingFraction,"fraction");n.push(Je({bucket_id:l.bucketId??l.displayName??"unknown",group_name:o,window_type:z_(l.window),used_fraction:c===null?null:De(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??""))),ve("agy","ok",{source:"agy_connect_rpc",account_id:null,plan_type:null,ordinary_usage_allowed:null,buckets:n}))}async function EL(t,e){let r=_L(e);if(r.length===0)return Ae("agy","provider_unavailable","no_active_session","no live agy process exposed ANTIGRAVITY_LS_ADDRESS/ANTIGRAVITY_CSRF_TOKEN","agy_connect_rpc");let n=[];for(let[s,i,o]of r)try{let a=await uL(`http://${s}${oL}`,{"Content-Type":"application/json","Connect-Protocol-Version":"1","x-codeium-csrf-token":i},t*1e3);if(a.status===200){let l;try{l=JSON.parse(a.body)}catch{n.push(`pid=${o}: unparseable response`);continue}let c=yL(l);if(c)return c;n.push(`pid=${o}: response had no quota groups`)}else a.status===401||a.status===403?n.push(`pid=${o}: HTTP ${a.status} unauthorized`):n.push(`pid=${o}: HTTP ${a.status}`)}catch(a){n.push(`pid=${o}: ${a instanceof Error?a.message:String(a)}`)}return Ae("agy","provider_unavailable","no_active_session",`all candidate language servers failed: ${n.slice(0,5).join("; ")}`,"agy_connect_rpc",r.map(([,s])=>s))}async function ty(t){let e=gL(t.timeoutSeconds,t.env);if(e.status==="ok")return e;let r=await EL(t.timeoutSeconds,t.env);return r.status==="ok"?r:Ae("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")}var Z_,ey,oL,aL,lL,cL,dL,uL,ry=k(()=>{"use strict";Ss();Z_="ANTIGRAVITY_LS_ADDRESS",ey="ANTIGRAVITY_CSRF_TOKEN",oL="/exa.language_server_pb.LanguageServerService/RetrieveUserQuotaSummary",aL=["-p","/usage"],lL=(t,e)=>{let r=rL("agy",aL,{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}},cL=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()}},dL=lL,uL=cL});import{spawnSync as oy}from"node:child_process";import{existsSync as TL,readFileSync as wL}from"node:fs";import{homedir as ay}from"node:os";import{join as ly}from"node:path";function IL(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"}function cy(t){return Object.fromEntries(Object.entries(t).filter(([e])=>!e.startsWith("CLAUDE")))}function xL(t){try{let e=oy("claude",["--version"],{encoding:"utf8",timeout:2e4,stdio:["ignore","pipe","ignore"],env:cy(t)}),r=typeof e.stdout=="string"?e.stdout.trim().split(/\s+/)[0]:"";if(r)return`claude-code/${r}`}catch{}return"claude-code/unknown"}function Ze(t,e,r,n="claude_oauth_api",s){return Ae("claude",t,e,r,n,void 0,s)}function kL(t){let e=t.CLAUDE_CODE_OAUTH_TOKEN;if(e)return{oauth:{accessToken:e,source:"CLAUDE_CODE_OAUTH_TOKEN"}};let r=ly(ay(),".claude",".credentials.json");if(!TL(r))return t.ANTHROPIC_API_KEY?{error:"not_claude_ai_subscriber"}:{error:"no_credentials_found"};try{let n=JSON.parse(wL(r,"utf8")),s=typeof n=="object"&&n!==null&&"claudeAiOauth"in n?n.claudeAiOauth:void 0;return!s||typeof s!="object"||!("accessToken"in s)||!s.accessToken?{error:"not_claude_ai_subscriber"}:{oauth:s}}catch(n){return{error:`credentials_unreadable: ${n instanceof Error?n.name:"Error"}`}}}function AL(t){let e=t.get("retry-after");if(!e)return;let r=Number.parseInt(e,10);return Number.isFinite(r)?r:void 0}function RL(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}function LL(t){let e=[];for(let r of t.split(/\r?\n/)){let n=NL.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(Je({bucket_id:l,group_name:o?"session":"weekly",window_type:c,used_fraction:vt(Number(n[2]),"percent"),raw_value:Number(n[2]),raw_scale:"used_percent",resets_at:RL(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 CL(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 sy(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=vt(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 iy(t,e,r){try{let n=oy("claude",["-p","/usage"],{encoding:"utf8",timeout:Math.max(r,60)*1e3,input:"",env:cy(e),maxBuffer:16777216}),s=typeof n.stdout=="string"?n.stdout:"",i=LL(s);if(!i.length)return;let o=CL(s);return ve("claude",Be.ok,{source:"claude_cli_print",account_id:null,plan_type:t.subscriptionType??t.rateLimitTier??null,ordinary_usage_allowed:null,buckets:i,...Object.keys(o).length?{characteristics:o}:{}})}catch{return}}async function dy({timeoutSeconds:t,env:e}){let r=kL(e);if(r.error==="not_claude_ai_subscriber")return Ze(Be.notApplicable,r.error,"no OAuth subscription credentials; API-key accounts have no subscription quota endpoint");if(r.error==="no_credentials_found")return Ze(Be.unavailable,"credentials_missing",`credentials file not found: ${ly(ay(),".claude",".credentials.json")}`);if(r.error)return Ze(Be.expired,"oauth_token_expired_or_invalid",r.error);let n=r.oauth,s=Array.isArray(n.scopes)?n.scopes:[];if(s.length&&!s.includes(ny))return Ze(Be.notApplicable,"not_claude_ai_subscriber",`credential lacks the ${ny} scope required by the usage endpoint`);if(typeof n.expiresAt=="number"&&Date.now()+bL>=n.expiresAt)return Ze(Be.expired,"oauth_token_expired_or_invalid","local credential expiry has passed; run `claude` to renew the token");let i=new AbortController,o=setTimeout(()=>i.abort(),t*1e3),a;try{a=await fetch(`${vL}/api/oauth/usage`,{headers:{Authorization:`Bearer ${n.accessToken}`,"anthropic-beta":SL,"Content-Type":"application/json","User-Agent":xL(e)},signal:i.signal})}catch(m){let f=await iy(n,e,t);return f||Ze(Be.unavailable,"request_failed",`${m instanceof Error?m.name:"request failed"} (CLI fallback also unavailable)`)}finally{clearTimeout(o)}if(a.status===401)return Ze(Be.expired,"oauth_token_expired_or_invalid","HTTP 401 from usage endpoint");if(a.status===403)return Ze(Be.notApplicable,"not_claude_ai_subscriber","HTTP 403 from usage endpoint (account is not usage-eligible)");if(a.status===429){let m=AL(a.headers),f=await iy(n,e,t);return f||Ze(Be.throttled,"rate_limited",`usage endpoint rate limited${m==null?"":`; retry after ${m}s`}`,"claude_oauth_api",m)}if(a.status!==200)return Ze(Be.unavailable,`http_${a.status}`,"usage endpoint returned an unexpected status");let l;try{l=await a.json()}catch{return Ze(Be.unavailable,"malformed_response","SyntaxError: malformed JSON")}if(!l||typeof l!="object"||Array.isArray(l))return Ze(Be.unavailable,"malformed_response","response was not an object");let c=l,u=Array.isArray(c.limits)?c.limits:[],d=u.length?u.flatMap(m=>{if(!m||typeof m!="object")return[];let f=m.kind,g=IL(f==="session"?"session":f),y=m.scope?.model?.display_name,h=f==="session"?"session":f==="weekly_all"?"week-all-models":`week-scoped-${y||f}`;return[Je({bucket_id:h,group_name:f==="session"?"session":"weekly",window_type:g,used_fraction:vt(m.percent,"percent"),resets_at_iso:m.resets_at,raw_value:m.percent,raw_scale:"used_percent"})]}):["five_hour","seven_day"].flatMap(m=>{let f=c[m];return!f||typeof f!="object"?[]:[Je({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:vt(f.utilization,"percent"),resets_at_iso:f.resets_at,raw_value:f.utilization,raw_scale:"used_percent"})]});return ve("claude",Be.ok,{source:"claude_oauth_api",account_id:null,plan_type:n.subscriptionType??n.rateLimitTier??null,ordinary_usage_allowed:null,buckets:d.sort((m,f)=>String(m.window_type).localeCompare(String(f.window_type))||String(m.bucket_id).localeCompare(String(f.bucket_id))),...sy(c.spend)?{spend_control:sy(c.spend)}:{}})}var vL,SL,ny,bL,Be,NL,uy=k(()=>{"use strict";Ss();vL="https://api.anthropic.com",SL="oauth-2025-04-20",ny="user:profile",bL=3e5;Be={ok:"ok",unavailable:"provider_unavailable",expired:"auth_expired",notApplicable:"not_applicable",throttled:"reader_throttled"};NL=/^Current\s+(.+?):\s*(\d+(?:\.\d+)?)\s*%\s*used(?:\s*[·-]\s*resets\s*(.+?))?$/});import{readFileSync as OL}from"node:fs";import{homedir as DL}from"node:os";import{join as ML}from"node:path";function et(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function my(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 fy(t){return t==="five_hour"?"5h":t==="weekly"?"weekly":t==="monthly"?"monthly":"window"}function PL(t){if(t.CODEX_ACCESS_TOKEN)return{token:t.CODEX_ACCESS_TOKEN,accountId:t.CODEX_ACCOUNT_ID};let e=t.CODEX_AUTH_PATH||ML(DL(),".codex","auth.json");try{let r=JSON.parse(OL(e,"utf8")),n=et(r)&&et(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 UL(t){if(et(t))return{has_credits:t.has_credits,unlimited:t.unlimited,balance:t.balance}}function jL(t){let e=[],r=et(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=et(r[o])?r[o]:void 0;if(!a)continue;let l=my(a.limit_window_seconds);e.push(Je({bucket_id:`codex-${fy(l)}`,group_name:"codex",window_type:l,used_fraction:vt(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(!et(o))continue;let a=et(o.rate_limit)?o.rate_limit:{},l=typeof o.limit_name=="string"?o.limit_name:void 0,c=typeof o.metered_feature=="string"?o.metered_feature:void 0,u=c||l||"additional",d=typeof a.allowed=="boolean"?a.allowed:void 0,m=typeof a.limit_reached=="boolean"?a.limit_reached:void 0;for(let f of["primary_window","secondary_window"]){let g=et(a[f])?a[f]:void 0;if(!g)continue;let y=my(g.limit_window_seconds);e.push(Je({bucket_id:`${u}-${fy(y)}`,group_name:l||u,window_type:y,used_fraction:vt(g.used_percent,"percent"),resets_at:g.reset_at,raw_value:g.used_percent,raw_scale:"used_percent",...l===void 0?{}:{limit_name:l},...c===void 0?{}:{metered_feature:c},...d===void 0?{}:{allowed:d},...m===void 0?{}:{limit_reached:m}}))}}return e.sort((o,a)=>String(o.group_name??"").localeCompare(String(a.group_name??""))||String(o.bucket_id).localeCompare(String(a.bucket_id)))}function BL(t){let e=et(t.rate_limit)?t.rate_limit:{},r=typeof e.allowed=="boolean"?e.allowed:void 0,n=et(t.spend_control)?t.spend_control:void 0,s=et(t.credits)?t.credits:void 0;return ve("codex","ok",{source:"codex_http",account_id:t.account_id,plan_type:t.plan_type,...r===void 0?{}:{ordinary_usage_allowed:r},buckets:jL(t),...s?{credits:UL(s)}:{},...n?{spend_control:n}:{}})}async function py(t){let{timeoutSeconds:e,env:r}=t,n=PL(r);if(!n.token)return ve("codex","provider_unavailable",{source:"codex_http",reason:"credentials_missing",detail:"no access_token in ~/.codex/auth.json (or $CODEX_ACCESS_TOKEN)"});let s=new AbortController,i=setTimeout(()=>s.abort(),Math.ceil(e*1e3));try{let o={Authorization:`Bearer ${n.token}`,"User-Agent":FL,"Content-Type":"application/json",Accept:"application/json"};n.accountId&&(o["ChatGPT-Account-Id"]=n.accountId);let a=(r.CODEX_BASE_URL||$L).replace(/\/$/,""),l=await fetch(`${a}/wham/usage`,{headers:o,signal:s.signal});if(l.status===401)return ve("codex","auth_expired",{source:"codex_http",reason:"oauth_token_expired_or_invalid",detail:"HTTP 401 from the codex usage endpoint"});if(l.status===429){let u=l.headers.get("retry-after"),d=u===null?void 0:Number.parseInt(u,10);return ve("codex","reader_throttled",{source:"codex_http",reason:"throttled",detail:"HTTP 429 from codex usage endpoint",...d!==void 0&&Number.isFinite(d)&&d>=0?{retry_after_seconds:d}:{}})}if(!l.ok)return ve("codex","provider_unavailable",{source:"codex_http",reason:`http_${l.status}`,detail:"codex usage endpoint returned an unexpected status"});let c;try{c=await l.json()}catch(u){return ve("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:go(String(u),[n.token])})}return et(c)?BL(c):ve("codex","provider_unavailable",{source:"codex_http",reason:"malformed_response",detail:"response was not an object"})}catch(o){let a=o instanceof Error?`${o.name}: ${o.message}`:String(o);return ve("codex","provider_unavailable",{source:"codex_http",reason:"http_request_failed",detail:go(a,[n.token])})}finally{clearTimeout(i)}}var $L,FL,hy=k(()=>{"use strict";Ss();$L="https://chatgpt.com/backend-api",FL="codex-cli"});import{homedir as _y}from"node:os";import{join as Is}from"node:path";import{readFileSync as yy,readdirSync as WL,statSync as gy}from"node:fs";function GL(t){if(t.KIMI_CREDENTIALS_PATH)return t.KIMI_CREDENTIALS_PATH;let e=t.KIMI_CODE_HOME?Is(t.KIMI_CODE_HOME,"credentials"):HL,r=[];try{for(let n of WL(e))(n==="kimi-code.json"||n.startsWith("kimi-code-env-")&&n.endsWith(".json"))&&r.push(Is(e,n))}catch{}return r.length>0?r.sort((n,s)=>{try{return gy(s).mtimeMs-gy(n).mtimeMs}catch{return 0}})[0]:Is(e,"kimi-code.json")}function JL(t){let e=GL(t),r;try{r=yy(e,"utf8")}catch{return{error:"credentials_missing"}}let n;try{n=JSON.parse(r)}catch{return{error:"credentials_malformed"}}return!n||typeof n!="object"||!n.access_token?{error:"credentials_malformed"}:{access_token:n.access_token}}function VL(t){if(t.KIMI_CODE_BASE_URL)return t.KIMI_CODE_BASE_URL;let e=t.KIMI_CODE_CONFIG_PATH||XL;try{let r=yy(e,"utf8"),n=!1;for(let s of r.split(`
|
|
2241
|
+
`)){let i=s.trim();if(i.startsWith("[")){n=i==='[providers."managed:kimi-code"]';continue}if(n&&i.startsWith("base_url")){let o=i.match(/base_url\s*=\s*(?:"([^"]+)"|'([^']+)')/);if(o)return o[1]||o[2]}}}catch{}return qL}async function Ey({timeoutSeconds:t,env:e}){let r=JL(e);if(r.error==="credentials_missing")return Ae("kimi","provider_unavailable",r.error);if(r.error)return Ae("kimi","provider_unavailable",r.error);let n=VL(e),s=new AbortController,i=setTimeout(()=>s.abort(),t*1e3),o;try{o=await fetch(`${n}/usages`,{headers:{Authorization:`Bearer ${r.access_token}`,Accept:"application/json"},signal:s.signal})}catch(d){return Ae("kimi","provider_unavailable","connection_error",d instanceof Error?d.name:String(d))}finally{clearTimeout(i)}if(o.status===401)return Ae("kimi","auth_expired","HTTP 401 from Kimi usage endpoint");if(o.status===403)return Ae("kimi","not_applicable","HTTP 403 from Kimi usage endpoint");if(o.status===429){let d=Q_(o.headers);return Ae("kimi","reader_throttled","HTTP 429 from Kimi usage endpoint",void 0,"kimi_http",[],d)}if(o.status!==200)return Ae("kimi","provider_unavailable",`HTTP ${o.status} from Kimi usage endpoint`);let a;try{a=await o.json()}catch{return Ae("kimi","provider_unavailable","malformed_response","SyntaxError: malformed JSON")}if(!a||typeof a!="object")return Ae("kimi","provider_unavailable","malformed_response","response was not an object");let l=[],c=new Set;function u(d){let m=String(d.bucket_id),f=m,g=2;for(;c.has(m);)m=`${f}-${g}`,g++;c.add(m),d.bucket_id=m,l.push(Je(d))}if(Array.isArray(a.limits))for(let d of a.limits){if(!d||typeof d!="object")continue;let m=d.window,f=d.detail;if(!m||typeof m!="object"||!f||typeof f!="object")continue;let g=0;if(m.timeUnit==="TIME_UNIT_MINUTE")g=Number(m.duration);else if(m.timeUnit==="TIME_UNIT_HOUR")g=Number(m.duration)*60;else if(m.timeUnit==="TIME_UNIT_DAY")g=Number(m.duration)*1440;else if(m.timeUnit==="TIME_UNIT_WEEK")g=Number(m.duration)*10080;else if(m.timeUnit==="TIME_UNIT_MONTH")g=Number(m.duration)*43200;else continue;let y=Y_(g),h="window";y==="five_hour"&&(h="5h"),y==="weekly"&&(h="weekly"),y==="monthly"&&(h="monthly"),f.used===void 0&&(f.used=0),f.limit===void 0&&(f.limit=0);let p=Number(f.used),_=Number(f.limit);if(!Number.isFinite(p)||!Number.isFinite(_)||_<=0||p<0)continue;let T=Math.max(0,_-p);if(f.remaining!==void 0){let E=Number(f.remaining);Number.isFinite(E)&&(T=E)}u({bucket_id:`kimi-${h}`,window_type:y,used_fraction:De(p/_),remaining_fraction:De(T/_),resets_at_iso:f.resetTime,raw_value:(Number.isInteger(p),p),raw_scale:"count"})}if(a.usage&&typeof a.usage=="object"){let d=a.usage.used,m=a.usage.limit;if(d!==void 0&&m!==void 0){let f=Number(d),g=Number(m);if(Number.isFinite(f)&&Number.isFinite(g)&&g>0&&f>=0){let y=Math.max(0,g-f);if(a.usage.remaining!==void 0){let h=Number(a.usage.remaining);Number.isFinite(h)&&(y=h)}u({bucket_id:"kimi-weekly",window_type:"weekly",used_fraction:De(f/g),remaining_fraction:De(y/g),resets_at_iso:a.usage.resetTime,raw_value:(Number.isInteger(f),f),raw_scale:"count"})}}}if(a.usages&&typeof a.usages=="object"){let d=[{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:f,type:g}of d){if(c.has(f))continue;let y=a.usages[m];if(!y||typeof y!="object"||typeof y.used_ratio=="boolean")continue;let h=Number(y.used_ratio);!Number.isFinite(h)||h<0||(c.add(f),l.push(Je({bucket_id:f,window_type:g,used_fraction:De(h),resets_at_iso:typeof y.reset_time=="string"&&y.reset_time?y.reset_time:null,raw_value:h,raw_scale:"ratio"})))}}return ve("kimi","ok",{source:"kimi_http",buckets:l})}var HL,XL,qL,Ty=k(()=>{"use strict";Ss();HL=Is(_y(),".kimi-code","credentials"),XL=Is(_y(),".kimi-code","config.toml"),qL="https://api.kimi.com/coding/v1"});async function yo(t={}){let e=t.targets??t.providers??["all"];if(!Array.isArray(e)||e.length===0||e.some(o=>typeof o!="string"))return{status:"error",error:"providers must be a non-empty list of provider names",readings:[]};for(let o of e)if(!_o.includes(o))return{status:"error",error:`unknown provider: ${o} (valid targets: ${_o.join(", ")})`,readings:[]};let r=t.timeoutSeconds??KL;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 i=[];s.has("codex")&&i.push(py({timeoutSeconds:r,env:n})),s.has("agy")&&i.push(ty({timeoutSeconds:r,env:n})),s.has("claude")&&i.push(dy({timeoutSeconds:r,env:n})),s.has("kimi")&&i.push(Ey({timeoutSeconds:r,env:n}));try{return{status:"ok",readings:(await Promise.all(i)).filter(Boolean)}}catch(o){return{status:"error",error:String(o),readings:[]}}}var _o,KL,dd=k(()=>{"use strict";ry();uy();hy();Ty();_o=["all","codex","agy","claude","kimi"],KL=15});import{execFile as YL}from"node:child_process";import{realpathSync as wy,statSync as zL}from"node:fs";import{tmpdir as QL}from"node:os";import{isAbsolute as vy,relative as ZL}from"node:path";import{promisify as eC}from"node:util";function nC(t){if(typeof t!="string"||!t||!vy(t))throw new Error("lmbee: snapshot_db must be an absolute path to a temporary database copy");let e;try{e=wy(t);let n=zL(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=ZL(wy(QL()),e);if(!r||r===".."||r.startsWith("../")||vy(r))throw new Error("lmbee: snapshot_db must be a temporary database copy inside the system temp directory");return e}function Sy(t){if(t!=null){if(typeof t!="string"||!t.trim())throw new Error("lmbee: team must be a nonempty string");return t}}function by(t){let e=async(r,n,s)=>{let i=nC(r),o={...t,LMBEE_DB:i};delete o.LMBEE_TEAM_NAME;let a;try{({stdout:a}=await tC("lmbee",["queue",n,...s===void 0?[]:[s],"--json"],{env:o,timeout:3e4,maxBuffer:16777216}))}catch(l){let c=l;throw c.code==="ENOENT"?new Error("lmbee executable not found on PATH"):new Error(`lmbee queue ${n} failed: ${c.stderr?.trim()||c.message}`)}try{let l=JSON.parse(a);if(l===null||typeof l!="object"||Array.isArray(l))throw new Error("expected a JSON object");return l}catch{throw new Error(`lmbee queue ${n} returned invalid JSON`)}};return{name:"lmbee",description:"Read-only queue queries against temporary lmbee database copies",docs:rC,register(r){r.registerFunction("lmbee_queue_list",(n,s)=>e(n,"list",Sy(s)),{min:1,max:2}),r.registerFunction("lmbee_queue_get",(n,s)=>{if(typeof s!="number"||!Number.isSafeInteger(s)||s<=0)throw new Error("lmbee: id must be a positive integer");return e(n,"get",String(s))},2),r.registerFunction("lmbee_queue_stats",(n,s)=>e(n,"stats",Sy(s)),{min:1,max:2})}}}var tC,rC,Iy=k(()=>{"use strict";tC=eC(YL),rC=[{name:"lmbee_queue_list",category:"Queue Management",signature:"lmbee_queue_list(snapshot_db, team = null)",description:"Lists queue rows from a temporary lmbee database copy.",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:"{ queue: [...] } from lmbee queue list --json"},example:'rows = lmbee_queue_list("/tmp/lmbee-copy/state.db", "worker");'},{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 } or lmbee\u2019s JSON 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 queue counts from a temporary lmbee database copy.",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: [...] } from lmbee queue stats --json"},example:'counts = lmbee_queue_stats("/tmp/lmbee-copy/state.db", "worker");'}]});import{readFileSync as sC}from"node:fs";import{createInterface as iC}from"node:readline";async function oC(t){let e=t.provider.trim().toLowerCase();return cn.includes(e)||Qr().tools[e]?.agent!==void 0||!Sr.includes(e)?!1:dn().includes(e)}async function ud(t,e){try{await C(t,r=>{r.releaseAgentInflight(e.row,e.leaseId)})}catch(r){t.stderr.write(`warning: failed to release batch bundle lease: ${r instanceof Error?r.message:String(r)}
|
|
2242
|
+
`)}}function aC(t,e){let r=mn(t,e);if(r.ok)return Dt(r.identity);if(r.reason==="unset")return null;throw new Error(Ot("batch"))}async function lC(t,e){try{let{member:r}=e;return await C(t,n=>n.startTrackedInvocation({kind:"exec",origin:"operator",scope_teamfile:r.teamfile,from_identity:`${r.teamfile}:batch`,target_teamfile:r.teamfile,target_alias:r.alias,root_teamfile:r.teamfile,cwd:r.sessiondir,command:`lmctl batch ${r.teamfile} ${r.alias} ${e.batchfile}`,holder_pid:process.pid,launch_source:"exec",parent_invocation_id:e.parentInvocationId,meta:JSON.stringify({batchfile:e.batchfile,prompt_count:e.promptCount,provider:r.provider,sessionid:r.sessionid,...r.model!==void 0?{model:r.model}:{}})}).id)}catch(r){return t.stderr.write(`warning: failed to start batch root invocation: ${r instanceof Error?r.message:String(r)}
|
|
2243
|
+
`),null}}function cC(t,e,r,n){try{if(t.dal!==void 0){t.dal.finishTrackedInvocation(e,r);return}let s=it({path:pe(n?.LMCTL_DB)});try{s.finishTrackedInvocation(e,r)}finally{s.close()}}catch{}}async function xy(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 ud(e,t.heldLease),t.rootId!==null){let s=r==="done"?{status:"done",exit_code:0,result_summary:`batch completed ${t.promptCount}/${t.promptCount} prompts`}:{status:t.rootFinish.status??(r==="cancelled"?"cancelled":"error"),exit_code:1,error:n??t.rootFinish.error,result_summary:t.rootFinish.result_summary};try{await C(e,i=>{i.finishTrackedInvocation(t.rootId,s)})}catch(i){e.stderr.write(`warning: failed to finish batch root invocation: ${i instanceof Error?i.message:String(i)}
|
|
2167
2244
|
`)}}r==="done"&&e.stderr.write(`batch ${Ue()}: completed ${t.promptCount}/${t.promptCount} prompts
|
|
2168
|
-
`)}}function
|
|
2245
|
+
`)}}function uC(t={}){let e=new ur;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+`
|
|
2169
2246
|
`),i},void 0,{description:"Prints formatted values to stdout",allowOverwrite:!0}),e.registerFunction("println",(...s)=>{let i=s.map(o=>typeof o=="object"?JSON.stringify(o):String(o)).join(" ");return n.stdout.write(i+`
|
|
2170
2247
|
`),i},void 0,{description:"Prints line to stdout",allowOverwrite:!0}),e.registerFunction("printf",(s,...i)=>{let o=gs(s,i);return n.stdout.write(o+`
|
|
2171
|
-
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return ys(s,i,o)}return _s(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
|
|
2248
|
+
`),o},void 0,{description:"Formats a template using %s/%d/%f/%% substitution and prints it",allowOverwrite:!0}),e.registerFunction("prompt_human",s=>{if(e.isAsyncMode){let i=n.stdin??(typeof process<"u"?process.stdin:null),o=n.stdout??(typeof process<"u"?process.stdout:null);return ys(s,i,o)}return _s(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 mC(t,e,r,n=process.env){t.registerFunction("lm_exit",(h=0)=>{let p=Math.floor(Number(h)),_=Number.isFinite(p)&&p>=0&&p<=255?p:1;throw new Ge(_)},{min:0,max:1},"Exits the LMScript execution with an exit code"),t.registerFunction("lm_log",(...h)=>{let p=h.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(p+(p.endsWith(`
|
|
2172
2249
|
`)?"":`
|
|
2173
2250
|
`)),p},void 0,"Writes formatted log message to stderr"),t.registerFunction("lm_error",(...h)=>{let p=h.map(_=>typeof _=="object"?JSON.stringify(_):String(_)).join(" ");return e.stderr.write(`error: ${p}
|
|
2174
|
-
`),r.recordError(p),p},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(h,p=!1)=>{try{let _=
|
|
2175
|
-
`);return!!p?[_.trim()].filter(E=>E.length>0):_.split(/\n\s*\n/u).map(E=>E.trim()).filter(Boolean)}catch(_){throw A(e,`batch: ${_ instanceof Error?_.message:String(_)}`),new Ge(1)}};t.registerFunction("lm_read_prompts",(h,p=!1)=>s(h,p),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",h=>s(h,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",h=>{try{return Ne(String(h)).members.map(_=>({alias:_.alias,provider:_.provider,model:_.model,sessionid:_.session,sessiondir:_.sessiondir}))}catch(p){throw new Error(`Failed to read teamfile '${h}': ${p?.message||String(p)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(h,p)=>{try{let _=me(String(h),String(p),e.dal);return{alias:_.alias,provider:_.provider,model:_.model,sessionid:_.sessionid,sessiondir:_.sessiondir,isLead:_.isLead,teamfile:_.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(h,p,_,T={})=>{if(typeof h!="string"){if(!h||Array.isArray(h)||typeof h!="object"||typeof h.provider!="string"||!h.provider.trim())throw new Error("lm_batch_open: member map requires provider");let $=p??{};if(typeof $!="object"||Array.isArray($)||_!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let q={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...h},sourceMember:h,options:{...$},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(q),q}if(typeof p!="string"||typeof _!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let E;try{E=me(String(h),String(p),e.dal)}catch($){return A(e,`batch: ${$?.message||String($)}`),null}let S=Number(T?.promptCount??1),b=!!!T?.legacy&&S>1&&await
|
|
2176
|
-
`);try{if(b){let Q=await C(e,Z=>(Yr(Z,E.teamfile,E.alias),pt(Z,E.teamfile,E.alias)));if(Q.busy){let Z=Q.reason==="in-flight"?`${E.alias} is servicing ${Q.inFlight.sender_alias} (${Q.inFlight.sender_teamfile}) since ${Q.inFlight.started_at} \u2014 wait and retry`:Q.source==="terminal-lock"?xr(Q.terminalLock):`${E.alias} is busy (interactive terminal); wait and retry`;return x!==null&&await C(e,D=>{D.finishTrackedInvocation(x,{status:"busy",exit_code:1,error:Z,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${Z}`),null}let be=await C(e,Z=>
|
|
2251
|
+
`),r.recordError(p),p},void 0,"Writes error message to stderr and records it for end-of-run error summary");let s=(h,p=!1)=>{try{let _=sC(String(h),"utf8").replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
2252
|
+
`);return!!p?[_.trim()].filter(E=>E.length>0):_.split(/\n\s*\n/u).map(E=>E.trim()).filter(Boolean)}catch(_){throw A(e,`batch: ${_ instanceof Error?_.message:String(_)}`),new Ge(1)}};t.registerFunction("lm_read_prompts",(h,p=!1)=>s(h,p),{min:1,max:2},"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or single prompt"),t.registerFunction("lm_read_paragraphs",h=>s(h,!1),1,"Reads file and splits into blank-line-separated paragraphs"),t.registerFunction("lm_members",h=>{try{return Ne(String(h)).members.map(_=>({alias:_.alias,provider:_.provider,model:_.model,sessionid:_.session,sessiondir:_.sessiondir}))}catch(p){throw new Error(`Failed to read teamfile '${h}': ${p?.message||String(p)}`)}},1,"Resolves all members declared in a teamfile"),t.registerFunction("lm_member",(h,p)=>{try{let _=me(String(h),String(p),e.dal);return{alias:_.alias,provider:_.provider,model:_.model,sessionid:_.sessionid,sessiondir:_.sessiondir,isLead:_.isLead,teamfile:_.teamfile}}catch{return null}},2,"Resolves a specific member in a teamfile"),t.registerFunction("lm_batch_open",async(h,p,_,T={})=>{if(typeof h!="string"){if(!h||Array.isArray(h)||typeof h!="object"||typeof h.provider!="string"||!h.provider.trim())throw new Error("lm_batch_open: member map requires provider");let $=p??{};if(typeof $!="object"||Array.isArray($)||_!==void 0)throw new Error("lm_batch_open(member, options): options must be a map");let q={kind:"agent",id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,member:{...h},sourceMember:h,options:{...$},closed:!1,failed:!1,inFlight:!1};return r.registerBatch(q),q}if(typeof p!="string"||typeof _!="string")throw new Error("lm_batch_open(teamfile, alias, batchfile, options): alias and batchfile are required");let E;try{E=me(String(h),String(p),e.dal)}catch($){return A(e,`batch: ${$?.message||String($)}`),null}let S=Number(T?.promptCount??1),b=!!!T?.legacy&&S>1&&await oC(E),v={...e.env??n},x=await lC(e,{member:E,batchfile:String(_),promptCount:S,parentInvocationId:Kt(v.LMCTL_INVOCATION_ID)});x!==null&&(v.LMCTL_INVOCATION_ID=String(x));let I,R,M,N=!1;e.stderr.write(`batch ${Ue()}: starting ${S} prompt${S===1?"":"s"} -> ${E.alias} (teamfile=${h} input=${_})
|
|
2253
|
+
`);try{if(b){let Q=await C(e,Z=>(Yr(Z,E.teamfile,E.alias),pt(Z,E.teamfile,E.alias)));if(Q.busy){let Z=Q.reason==="in-flight"?`${E.alias} is servicing ${Q.inFlight.sender_alias} (${Q.inFlight.sender_teamfile}) since ${Q.inFlight.started_at} \u2014 wait and retry`:Q.source==="terminal-lock"?xr(Q.terminalLock):`${E.alias} is busy (interactive terminal); wait and retry`;return x!==null&&await C(e,D=>{D.finishTrackedInvocation(x,{status:"busy",exit_code:1,error:Z,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${Z}`),null}let be=await C(e,Z=>aC(v,Z)),ye=await C(e,Z=>Xt(Z,{receiver_teamfile:E.teamfile,receiver_alias:E.alias,sender_teamfile:be?.teamfile??E.teamfile,sender_alias:be?.alias??"operator",ttlMs:ft(v)}));if(!ye.acquired){let Z=`${E.alias} is servicing ${ye.current.sender_alias} (${ye.current.sender_teamfile}) since ${ye.current.started_at} \u2014 wait and retry`;return x!==null&&await C(e,D=>{D.finishTrackedInvocation(x,{status:"busy",exit_code:1,error:Z,result_summary:"0 prompts completed"})}),A(e,`batch: cannot start bundle: ${Z}`),null}I={row:ye.lease,leaseId:ye.leaseId};let fr=Gr(Z=>C(e,D=>D.heartbeatAgentInflight(I.row,I.leaseId,Z)));M={stop:()=>clearInterval(fr)};let bt=ot(e,Z=>`batch ${Ue()}: opening provider session (${Z}s elapsed)
|
|
2177
2254
|
`);try{let Z={...v};try{let D=await C(e,Y=>Y.getRootTeam(E.teamfile)?.name??null);D!==null&&(Z.LMBEE_TEAM_NAME=D)}catch{}R=await is({provider:E.provider,sessionId:E.sessionid,cwd:E.sessiondir,env:Z,...E.model!==void 0?{model:E.model}:{},...E.effort!==void 0?{effort:E.effort}:{},alias:E.alias,isLead:E.isLead,permissionMode:"yolo",holdOpen:cs(e,{teamfile:E.teamfile,alias:E.alias},Z)}),N=!0}catch{M&&M.stop(),M=void 0,await ud(e,I),I=void 0,N=!1}finally{bt.stop()}}let q={id:`batch-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,teamfile:String(h),alias:String(p),batchfile:String(_),member:E,promptCount:S,useBundle:N,rootId:x,rootFinish:{status:"error",error:"batch exited without a terminal outcome"},heldLease:I,bundleSession:R,heartbeatTimer:M,closed:!1,env:v};return r.registerBatch(q),q}catch($){if(M){try{M.stop()}catch{}M=void 0}if(I){try{await ud(e,I)}catch{}I=void 0}if(R){try{await R.close()}catch{}R=void 0}if(x!==null)try{await C(e,q=>{q.finishTrackedInvocation(x,{status:"error",exit_code:1,error:$?.message||String($),result_summary:"0 prompts completed"})})}catch{}throw $}},{min:1,max:4},"Opens a batch from a member map or a teamfile with lifecycle management"),t.registerFunction("lm_batch_turn",async(h,p,_,T)=>{let E=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;if(!E)throw new Error("Invalid or unmanaged batch handle");if(E.kind==="agent"){if(r.getBatch(E.id)!==E)throw new Error("Invalid or unmanaged batch handle");if(E.closed||E.failed)return{status:"error",reply:"",error:"Batch is closed or stopped after a failed turn"};if(E.inFlight)return{status:"busy",reply:"",error:"Batch already has an active turn"};E.inFlight=!0;try{let v=E.member.sessionid,x=await u(E.member,String(p),E.options);return E.member.sessionid&&E.sourceMember.provider===E.member.provider&&E.sourceMember.sessionid===v&&(E.sourceMember.sessionid=E.member.sessionid),x.status!=="ok"&&(E.failed=!0),{status:x.status,reply:x.reply.replace(/\n+$/u,""),error:x.error}}finally{E.inFlight=!1}}let S=Number(_),w=Number(T);e.stderr.write(`batch ${Ue()}: prompt ${S}/${w} -> ${E.member.alias}
|
|
2178
2255
|
`);let b=ot(e,v=>`batch ${Ue()}: prompt ${S}/${w} still running (${v}s elapsed)
|
|
2179
|
-
`);try{let v=await Ar({teamfile:E.member.teamfile,alias:E.member.alias,prompt:String(p),expectedSession:{provider:E.member.provider,sessionid:E.member.sessionid},permissionMode:"yolo",env:{...E.env},messageType:"batch",...E.heldLease!==void 0?{heldLease:E.heldLease}:{},...E.bundleSession!==void 0?{bundleSession:E.bundleSession}:{},io:e,onEvent:I=>{b.poke(),I.kind==="warning"&&e.stderr.write(I.message)}}),x=v.replyText?String(v.replyText).replace(/\n+$/u,""):"";if(v.status!=="ok"){let I=v.status==="stalled"?"provider stalled":v.status==="empty"?"provider returned no content and no observed activity for this turn":v.message,R=`batch: stopped at prompt ${S}/${w} (${S-1} completed): ${I}; later prompts were not sent`;return E.rootFinish={status:v.status==="busy"?"busy":"error",exit_code:1,error:R,result_summary:`${S-1}/${w} prompts completed`},A(e,R),{status:v.status,reply:x,error:R}}return{status:"ok",reply:x,error:null}}catch(v){let x=`batch: stopped at prompt ${S}/${w} (${S-1} completed): ${v instanceof Error?v.message:String(v)}; later prompts were not sent`;return E.rootFinish={status:"error",exit_code:1,error:x,result_summary:`${S-1}/${w} prompts completed`},A(e,x),{status:"error",reply:"",error:x}}finally{b.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(h,p="done",_)=>{let T=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;return T?(await
|
|
2256
|
+
`);try{let v=await Ar({teamfile:E.member.teamfile,alias:E.member.alias,prompt:String(p),expectedSession:{provider:E.member.provider,sessionid:E.member.sessionid},permissionMode:"yolo",env:{...E.env},messageType:"batch",...E.heldLease!==void 0?{heldLease:E.heldLease}:{},...E.bundleSession!==void 0?{bundleSession:E.bundleSession}:{},io:e,onEvent:I=>{b.poke(),I.kind==="warning"&&e.stderr.write(I.message)}}),x=v.replyText?String(v.replyText).replace(/\n+$/u,""):"";if(v.status!=="ok"){let I=v.status==="stalled"?"provider stalled":v.status==="empty"?"provider returned no content and no observed activity for this turn":v.message,R=`batch: stopped at prompt ${S}/${w} (${S-1} completed): ${I}; later prompts were not sent`;return E.rootFinish={status:v.status==="busy"?"busy":"error",exit_code:1,error:R,result_summary:`${S-1}/${w} prompts completed`},A(e,R),{status:v.status,reply:x,error:R}}return{status:"ok",reply:x,error:null}}catch(v){let x=`batch: stopped at prompt ${S}/${w} (${S-1} completed): ${v instanceof Error?v.message:String(v)}; later prompts were not sent`;return E.rootFinish={status:"error",exit_code:1,error:x,result_summary:`${S-1}/${w} prompts completed`},A(e,x),{status:"error",reply:"",error:x}}finally{b.stop()}},4,"Executes a prompt turn within a batch session"),t.registerFunction("lm_batch_close",async(h,p="done",_)=>{let T=typeof h=="string"?r.getBatch(h):h?.id?r.getBatch(h.id)??h:void 0;return T?(await xy(T,e,p==="done"?"done":p==="cancelled"?"cancelled":"error",_),!0):!1},{min:1,max:3},"Closes a batch session and cleans up resources"),t.registerFunction("lm_ratelimit_readings",async(h={})=>{try{if(!h||typeof h!="object"||Array.isArray(h))throw new Error("lm_ratelimit_readings: options must be a map");let p=h.providers??(h.provider===void 0?["all"]:[h.provider]);if(!Array.isArray(p)||p.some(T=>typeof T!="string"||!T||T.startsWith("-")))throw new Error("lm_ratelimit_readings: providers must be a list of provider names");let _=h.timeoutSeconds??15;if(typeof _!="number"||!Number.isFinite(_)||_<=0)throw new Error("lm_ratelimit_readings: timeoutSeconds must be a positive finite number");return yo({providers:p.length?p:["all"],timeoutSeconds:_,env:e.env??n,progress:T=>{e.stderr.write(`${T}
|
|
2180
2257
|
`)}})}catch(p){return{status:"error",error:p instanceof Error?p.message:String(p),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(h,p,_={},T=!1)=>{let E=(v,x="",I=null)=>({status:v,reply:x,error:I,message_id:null,team_chat_log_id:null}),S,w=!1,b;try{if(!h||typeof h!="object"||Array.isArray(h))throw new Error("lm_agent: member must be a map");for(let $ of["provider","alias","model","effort","sessiondir","sessionid"]){let q=h[$];if(q!=null&&(typeof q!="string"||!q.trim()))throw new Error(`lm_agent: ${$} must be a nonempty string when supplied`)}if(!h.provider)throw new Error("lm_agent: provider is required");if(typeof p!="string")throw new Error("lm_agent: prompt must be a string");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_agent: options must be a map");let v=_.permissionMode??"yolo";if(v!=="yolo"&&v!=="plan")throw new Error("lm_agent: permissionMode must be yolo or plan");if(_.idleTimeoutMs!=null&&(typeof _.idleTimeoutMs!="number"||!Number.isFinite(_.idleTimeoutMs)||_.idleTimeoutMs<0))throw new Error("lm_agent: idleTimeoutMs must be a finite nonnegative number");let x=h.provider,I=h.sessiondir??process.cwd(),R=h.sessionid??"";if(S=R?JSON.stringify([x,R]):void 0,i.has(h)||S!==void 0&&(o.has(S)||!T&&a.has(S)))return E("busy","","lm_agent: session already has an active turn in this engine");i.add(h),S!==void 0&&o.add(S),w=!0,e.stderr.write(`agent ${Ue()}: prompting ${h.alias??x}
|
|
2181
2258
|
`),b=ot(e,$=>`agent ${Ue()}: still running (${$}s elapsed)
|
|
2182
2259
|
`);let M=R;if(!M&&["agy","pi","dsh"].includes(x)){if(v!=="yolo")throw new Error(`lm_agent: fresh ${x} sessions require yolo seed; supply sessionid for resume`);let $=await Tc({provider:x,cwd:I,model:h.model,effort:h.effort});for(let q of $.warnings??[])e.stderr.write(`warning: ${q}
|
|
2183
2260
|
`);if(!$.success||!$.sessionId)throw new Error($.error??"lm_agent: provider did not identify the seeded session");M=$.sessionId,h.sessionid=M,S=JSON.stringify([x,M]),o.add(S)}let N=await Ir({provider:x,cwd:I,sessionId:M,prompt:p,model:h.model,effort:h.effort,alias:h.alias,isLead:!1,permissionMode:v,timeoutMs:_.idleTimeoutMs,requireResume:!!M,env:{...e.env??n},onDelta:()=>b?.poke(),onProgress:()=>b?.poke()});for(let $ of N.warnings??[])e.stderr.write(`warning: ${$}
|
|
2184
|
-
`);return M&&N.sessionId!==M?E("error","","lm_agent: provider changed session identity during resume"):(N.sessionId&&(h.sessionid=N.sessionId),N.status==="stalled"?E("stalled",N.text,"provider stalled"):N.status==="empty"?E("empty","","lm_agent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):N.sessionId?E("ok",N.text):E("error",N.text,"lm_agent: provider did not return a session ID"))}catch(v){return E("error","",v instanceof Error?v.message:String(v))}finally{b?.stop(),w&&(i.delete(h),S!==void 0&&o.delete(S))}},u=async(h,p,_={},T=!1)=>{let E=await c(h,p,_,T);if(h?.sessionid&&E.status!=="busy"){let S=JSON.stringify([h.provider,h.sessionid]),w=l.get(S)??{lines:[],options:{}};w.lines.push(`You: ${p}`),E.reply&&w.lines.push(`Agent: ${E.reply}`),E.error&&w.lines.push(`${E.status}: ${E.error}`),w.options={..._},l.set(S,w)}return E};t.registerFunction("lm_agent",u,{min:2,max:3},"Prompts an agent described by a map without a teamfile"),t.registerFunction("lm_session_list",async(h={})=>{if(!h||typeof h!="object"||Array.isArray(h)||h.provider!=null&&(typeof h.provider!="string"||!h.provider.trim())||h.sessiondir!=null&&(typeof h.sessiondir!="string"||!h.sessiondir.trim())||h.all!=null&&typeof h.all!="boolean")throw new Error("lm_session_list: expected options map with provider, sessiondir, and all");return(await os({provider:h.provider,workspace:h.all?void 0:h.sessiondir??process.cwd()})).map(_=>({provider:_.provider,sessionid:_.sessionId,sessiondir:_.cwd,modifiedAt:_.modifiedAt.toISOString()}))},{min:0,max:1},"Lists native provider sessions"),t.registerFunction("lm_session_delete",async(h,p={})=>{let _=(E,S=null)=>({status:E,error:S});if(!h||typeof h!="object"||Array.isArray(h)||typeof h.provider!="string"||!h.provider.trim()||typeof h.sessionid!="string"||!h.sessionid.trim())return _("error","lm_session_delete: member requires provider and sessionid");if(!p||typeof p!="object"||Array.isArray(p)||p.force!==!0)return _("error","lm_session_delete: force: true is required because cross-process turns cannot be detected");let T=JSON.stringify([h.provider,h.sessionid]);if(i.has(h)||o.has(T)||a.has(T))return _("busy","lm_session_delete: session has an active turn in this engine");o.add(T);try{return await wc(h.provider,h.sessionid)?(l.delete(T),h.sessionid=null,_("deleted")):_("not_found")}catch(E){return _("error",E instanceof Error?E.message:String(E))}finally{o.delete(T)}},{min:1,max:2},"Deletes a native session with explicit cross-process race acceptance");let d=async(h,p,_={})=>{if(!Array.isArray(h))throw new Error("lm_fanout: participants must be an array of member maps");if(h.length===0)return[];let T;if(typeof p=="string")T=h.map(()=>p);else if(Array.isArray(p)){if(p.length!==h.length)throw new Error(`lm_fanout: prompts array length (${p.length}) must match participants length (${h.length})`);for(let E of p)if(typeof E!="string")throw new Error("lm_fanout: every prompts[] entry must be a string");T=p}else throw new Error("lm_fanout: prompts must be a string (broadcast to every participant) or an array of strings (one per participant)");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_fanout: options must be a map");return Promise.all(h.map((E,S)=>u(E,T[S],_)))};t.registerFunction("lm_fanout",d,{min:2,max:3},"Dispatches a prompt to every participant in an array concurrently (runtime-sized, unlike parallel()); returns an array of lm_agent-shaped results in the same order as participants. prompts is a single string broadcast to all, or an array of strings (one per participant, same length).");let m=async(h,p={})=>{if(typeof h!="string"||h.length===0)throw new Error("lm_seed: teamfile must be a nonempty string");if(!p||typeof p!="object"||Array.isArray(p))throw new Error("lm_seed: options must be a map");if(p.preamble!==void 0&&typeof p.preamble!="string"&&(typeof p.preamble!="object"||p.preamble===null||Array.isArray(p.preamble)))throw new Error("lm_seed: options.preamble must be a string or a map keyed by alias");let _=p.preamble!==void 0?{preamble:p.preamble}:{};return{status:await ho(h,e,_)===0?"ok":"error"}};t.registerFunction("lm_seed",m,{min:1,max:2},"Seeds a real teamfile over the exact same path lmctl seed takes; options.preamble overrides the default Lead prompt (string) or per-alias prompts (map).");let f=async h=>{if(typeof h!="string"||h.length===0)throw new Error("lm_lint: teamfile must be a nonempty string");return ld(h,e)};t.registerFunction("lm_lint",f,1,"Validates a teamfile over the exact same path lmctl lint takes, returning { status, errors, warnings, counts } instead of text to parse.");let g=!1,y=async h=>{let p=h!==null&&typeof h=="object";if(g)throw new Error("prompt_human: another operator prompt is active");g=!0;let _,T;try{let E=e.stdin??process.stdin;if(!p)return await ys(h,E,e.stdout);let S={...h};if(Array.isArray(h)||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 w=JSON.stringify([S.provider,S.sessionid]);if(o.has(w))return{command:"busy",args:["Agent turn is still running"]};a.add(w),T=w;let b=E;if(b.destroyed||b.readableEnded)return{command:"eof",args:[]};_=
|
|
2261
|
+
`);return M&&N.sessionId!==M?E("error","","lm_agent: provider changed session identity during resume"):(N.sessionId&&(h.sessionid=N.sessionId),N.status==="stalled"?E("stalled",N.text,"provider stalled"):N.status==="empty"?E("empty","","lm_agent: provider reported a normal completion but returned no content and no observed activity -- often an upstream failure (rate limit, quota, auth) the provider did not report as an error"):N.sessionId?E("ok",N.text):E("error",N.text,"lm_agent: provider did not return a session ID"))}catch(v){return E("error","",v instanceof Error?v.message:String(v))}finally{b?.stop(),w&&(i.delete(h),S!==void 0&&o.delete(S))}},u=async(h,p,_={},T=!1)=>{let E=await c(h,p,_,T);if(h?.sessionid&&E.status!=="busy"){let S=JSON.stringify([h.provider,h.sessionid]),w=l.get(S)??{lines:[],options:{}};w.lines.push(`You: ${p}`),E.reply&&w.lines.push(`Agent: ${E.reply}`),E.error&&w.lines.push(`${E.status}: ${E.error}`),w.options={..._},l.set(S,w)}return E};t.registerFunction("lm_agent",u,{min:2,max:3},"Prompts an agent described by a map without a teamfile"),t.registerFunction("lm_session_list",async(h={})=>{if(!h||typeof h!="object"||Array.isArray(h)||h.provider!=null&&(typeof h.provider!="string"||!h.provider.trim())||h.sessiondir!=null&&(typeof h.sessiondir!="string"||!h.sessiondir.trim())||h.all!=null&&typeof h.all!="boolean")throw new Error("lm_session_list: expected options map with provider, sessiondir, and all");return(await os({provider:h.provider,workspace:h.all?void 0:h.sessiondir??process.cwd()})).map(_=>({provider:_.provider,sessionid:_.sessionId,sessiondir:_.cwd,modifiedAt:_.modifiedAt.toISOString()}))},{min:0,max:1},"Lists native provider sessions"),t.registerFunction("lm_session_delete",async(h,p={})=>{let _=(E,S=null)=>({status:E,error:S});if(!h||typeof h!="object"||Array.isArray(h)||typeof h.provider!="string"||!h.provider.trim()||typeof h.sessionid!="string"||!h.sessionid.trim())return _("error","lm_session_delete: member requires provider and sessionid");if(!p||typeof p!="object"||Array.isArray(p)||p.force!==!0)return _("error","lm_session_delete: force: true is required because cross-process turns cannot be detected");let T=JSON.stringify([h.provider,h.sessionid]);if(i.has(h)||o.has(T)||a.has(T))return _("busy","lm_session_delete: session has an active turn in this engine");o.add(T);try{return await wc(h.provider,h.sessionid)?(l.delete(T),h.sessionid=null,_("deleted")):_("not_found")}catch(E){return _("error",E instanceof Error?E.message:String(E))}finally{o.delete(T)}},{min:1,max:2},"Deletes a native session with explicit cross-process race acceptance");let d=async(h,p,_={})=>{if(!Array.isArray(h))throw new Error("lm_fanout: participants must be an array of member maps");if(h.length===0)return[];let T;if(typeof p=="string")T=h.map(()=>p);else if(Array.isArray(p)){if(p.length!==h.length)throw new Error(`lm_fanout: prompts array length (${p.length}) must match participants length (${h.length})`);for(let E of p)if(typeof E!="string")throw new Error("lm_fanout: every prompts[] entry must be a string");T=p}else throw new Error("lm_fanout: prompts must be a string (broadcast to every participant) or an array of strings (one per participant)");if(!_||typeof _!="object"||Array.isArray(_))throw new Error("lm_fanout: options must be a map");return Promise.all(h.map((E,S)=>u(E,T[S],_)))};t.registerFunction("lm_fanout",d,{min:2,max:3},"Dispatches a prompt to every participant in an array concurrently (runtime-sized, unlike parallel()); returns an array of lm_agent-shaped results in the same order as participants. prompts is a single string broadcast to all, or an array of strings (one per participant, same length).");let m=async(h,p={})=>{if(typeof h!="string"||h.length===0)throw new Error("lm_seed: teamfile must be a nonempty string");if(!p||typeof p!="object"||Array.isArray(p))throw new Error("lm_seed: options must be a map");if(p.preamble!==void 0&&typeof p.preamble!="string"&&(typeof p.preamble!="object"||p.preamble===null||Array.isArray(p.preamble)))throw new Error("lm_seed: options.preamble must be a string or a map keyed by alias");let _=p.preamble!==void 0?{preamble:p.preamble}:{};return{status:await ho(h,e,_)===0?"ok":"error"}};t.registerFunction("lm_seed",m,{min:1,max:2},"Seeds a real teamfile over the exact same path lmctl seed takes; options.preamble overrides the default Lead prompt (string) or per-alias prompts (map).");let f=async h=>{if(typeof h!="string"||h.length===0)throw new Error("lm_lint: teamfile must be a nonempty string");return ld(h,e)};t.registerFunction("lm_lint",f,1,"Validates a teamfile over the exact same path lmctl lint takes, returning { status, errors, warnings, counts } instead of text to parse.");let g=!1,y=async h=>{let p=h!==null&&typeof h=="object";if(g)throw new Error("prompt_human: another operator prompt is active");g=!0;let _,T;try{let E=e.stdin??process.stdin;if(!p)return await ys(h,E,e.stdout);let S={...h};if(Array.isArray(h)||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 w=JSON.stringify([S.provider,S.sessionid]);if(o.has(w))return{command:"busy",args:["Agent turn is still running"]};a.add(w),T=w;let b=E;if(b.destroyed||b.readableEnded)return{command:"eof",args:[]};_=iC({input:b,output:e.stdout,terminal:!!b.isTTY,crlfDelay:1/0});let v=_[Symbol.asyncIterator](),x=!1;_.on("SIGINT",()=>{x=!0,_?.close()}),e.stdout.write(`Session ${S.alias??S.provider} (${S.sessionid})
|
|
2185
2262
|
`);let I=l.get(w);if(I)for(let R of I.lines)e.stdout.write(`${R}
|
|
2186
2263
|
`);else{let R=await Yt(or()).getSession(S.sessionid,S.provider);if(!R)return{command:"error",args:["Could not load session history"]};for(let M of R.messages)(M.role==="user"||M.role==="assistant")&&e.stdout.write(`${M.role==="user"?"You":"Agent"}: ${M.content}
|
|
2187
2264
|
`)}for(e.stdout.write(`Talk to the agent. Return to the script with /exit [command] [args...].
|
|
2188
2265
|
`);;){e.stdout.write("You> ");let R=await v.next();if(x)return{command:"cancelled",args:[]};if(R.done)return{command:"eof",args:[]};let M=R.value.trim();if(!M)continue;if(/^\/exit(?:\s|$)/u.test(M)){let $=M.split(/\s+/u).slice(1);return{command:$.shift()??"exit",args:$}}let N=await u(S,R.value,I?.options??{},!0);if(N.reply&&e.stdout.write(`Agent: ${N.reply}
|
|
2189
2266
|
`),N.status!=="ok")return e.stdout.write(`${N.status}: ${N.error}
|
|
2190
|
-
`),{command:N.status,args:[N.error??"Agent turn failed"]}}}catch(E){if(!p)throw E;return{command:"error",args:[E instanceof Error?E.message:String(E)]}}finally{_?.close(),T!==void 0&&a.delete(T),g=!1}};t.registerFunction("prompt_human",h=>{if(!t.isAsyncMode&&(h===null||typeof h!="object")){if(g)throw new Error("prompt_human: another operator prompt is active");return _s(h)}return y(h)},{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(h,p,_,T={})=>{try{let E=await Ar({teamfile:String(h),alias:String(p),prompt:String(_),permissionMode:T?.permissionMode??"yolo",idleTimeoutMs:T?.idleTimeoutMs,env:{...e.env??n},messageType:T?.messageType,io:e});return{status:E.status,reply:E.replyText??"",error:E.message??null,message_id:E.messageId??null,team_chat_log_id:E.teamChatLogId??null}}catch(E){return{status:"error",reply:"",error:E?.message||String(E),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}function
|
|
2267
|
+
`),{command:N.status,args:[N.error??"Agent turn failed"]}}}catch(E){if(!p)throw E;return{command:"error",args:[E instanceof Error?E.message:String(E)]}}finally{_?.close(),T!==void 0&&a.delete(T),g=!1}};t.registerFunction("prompt_human",h=>{if(!t.isAsyncMode&&(h===null||typeof h!="object")){if(g)throw new Error("prompt_human: another operator prompt is active");return _s(h)}return y(h)},{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(h,p,_,T={})=>{try{let E=await Ar({teamfile:String(h),alias:String(p),prompt:String(_),permissionMode:T?.permissionMode??"yolo",idleTimeoutMs:T?.idleTimeoutMs,env:{...e.env??n},messageType:T?.messageType,io:e});return{status:E.status,reply:E.replyText??"",error:E.message??null,message_id:E.messageId??null,team_chat_log_id:E.teamChatLogId??null}}catch(E){return{status:"error",reply:"",error:E?.message||String(E),message_id:null,team_chat_log_id:null}}},{min:3,max:4},"Sends a prompt directly to a team member and returns the reply")}function pC(t,e,r=new Ft,n=process.env){return t.registerModule(fC,{io:e,registry:r,env:n})}function xs(t,e=[],r=new Ft,n=process.env){let s=uC({scriptArgs:e,io:t,env:n});return pC(s,t,r,n),n.LMCTL_LMBEE_BRIDGE==="1"&&s.registerModule(by(n)),s}async function ky(t,e,r={stdout:process.stdout,stderr:process.stderr},n=process.env,s){let i=new Ft,o=u=>{for(let d of i.getOpenBatches()){if(d.kind==="agent"){d.closed=!0;continue}if(d.heartbeatTimer){try{d.heartbeatTimer.stop()}catch{}d.heartbeatTimer=void 0}if(d.heldLease){try{if(r.dal)r.dal.releaseAgentInflight(d.heldLease.row,d.heldLease.leaseId);else{let m=it({path:pe(n?.LMCTL_DB)});try{m.releaseAgentInflight(d.heldLease.row,d.heldLease.leaseId)}finally{m.close()}}}catch{}d.heldLease=void 0}d.rootId!==null&&cC(r,d.rootId,{status:"cancelled",signal:u,error:`batch interrupted by ${u}`},n)}process.exit(u==="SIGINT"?130:143)};process.once("SIGINT",o),process.once("SIGTERM",o);let a=!1,l,c=()=>{if(a)return;a=!0;let u=i.getErrors(),d=l?l.getRecordedErrors():[],m=[...u];for(let f of d)m.includes(f)||m.push(f);if(m.length>0){r.stderr.write(`
|
|
2191
2268
|
=== LMScript Error Summary (${m.length} error${m.length===1?"":"s"}) ===
|
|
2192
2269
|
`);for(let f=0;f<m.length;f++)r.stderr.write(` ${f+1}. ${m[f]}
|
|
2193
2270
|
`);r.stderr.write(`==========================================
|
|
@@ -2195,7 +2272,7 @@ possibly work, seed reports it as an error and seeds nothing.
|
|
|
2195
2272
|
`)?m:`${m}
|
|
2196
2273
|
`)}});if(c(),d.exitCode!==void 0)return d.exitCode;if(!d.success){for(let m of d.diagnostics){let f=m.file?`${m.file}:${m.line}:${m.column}`:`${m.line}:${m.column}`;r.stderr.write(`error:${f}: ${m.message}
|
|
2197
2274
|
`)}return 1}return i.hasErrors()||d.errors&&d.errors.length>0?1:0}catch(u){return c(),u instanceof Ge||u?.name==="LMScriptExit"?u.exitCode:(r.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
|
|
2198
|
-
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var Ft,zL,eC,Sy=k(()=>{"use strict";Pc();Zi();We();$t();kt();dd();On();Ct();Qi();ge();Jt();ct();st();Ln();as();fn();ls();xn();Pc();Ft=class{batchHandles=new Map;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}async forceCloseAll(e){for(let r of this.getOpenBatches())await wy(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}};zL=[{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_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"Values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"Error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));eC={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:zL,register(t,e){ZL(t,e.io,e.registry,e.env)}}});var ky={};oe(ky,{formatCategoryOverview:()=>fd,formatFunctionDoc:()=>Iy,formatModuleOverview:()=>xy,runScript:()=>nC});import{readFileSync as by}from"node:fs";import{resolve as rC}from"node:path";function Iy(t){let e="";if(e+=`Function: ${t.signature||t.name}
|
|
2275
|
+
`),1)}finally{process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o),await i.forceCloseAll(r)}}var Ft,dC,fC,Ay=k(()=>{"use strict";Pc();Zi();We();$t();kt();dd();On();Ct();Qi();ge();Jt();ct();st();Ln();as();fn();ls();xn();Iy();Pc();Ft=class{batchHandles=new Map;loggedErrors=[];registerBatch(e){this.batchHandles.set(e.id,e)}getBatch(e){return this.batchHandles.get(e)}getOpenBatches(){return Array.from(this.batchHandles.values()).filter(e=>!e.closed)}recordError(e){this.loggedErrors.push(e)}getErrors(){return[...this.loggedErrors]}hasErrors(){return this.loggedErrors.length>0}async forceCloseAll(e){for(let r of this.getOpenBatches())await xy(r,e,"error","script execution interrupted or terminated without orderly close");this.batchHandles.clear()}};dC=[{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_lint",category:"lmctl Automation",signature:"lm_lint(teamfile)",description:'Validates a teamfile over the exact same internal path `lmctl lint` takes, returning structured findings instead of text a script would otherwise have to parse (operator, 2026-09-30: "lmscript does not use lmctl cli... expose lmctl internal working as api"). status is "error" ONLY for a genuine validation error (unparseable file, bad _MEMBER_ line, confirmed wrong-provider model) -- warnings never flip it to "error", matching the CLI\'s own exit-0-on-warnings contract. Progress/error/warning lines are also written to stderr, same as lmctl lint.',parameters:[{name:"teamfile",type:"string",description:"Path to the team configuration file to validate"}],returns:{type:"map",description:'{ status: "ok"|"error", errors: [{alias, message}], warnings: [{alias, message}], counts: {errors, warnings} }; alias is "" when a finding is about the file rather than a member. Both lists are always arrays, never null.'},example:'result = lm_lint("team.lmctl"); if (result.counts.warnings > 0) { lm_log(result.counts.warnings + " warning(s)"); }'},{name:"lm_ratelimit_readings",category:"lmctl Automation",signature:"lm_ratelimit_readings(options = {})",description:"Queries live provider quota readings using the existing ratelimit reader; preserves raw fields without cost aggregation or inferred availability.",parameters:[{name:"options",type:"map",description:"(optional) providers: string[] or provider: string (default all); timeoutSeconds: positive number (default 15)"}],returns:{type:"map",description:'{ status: "ok", readings: map[] } or { status: "error", error: string, readings: [] }. Provider-level failures remain reading data; inspect each reading.status and bucket flags.'},example:'quota = lm_ratelimit_readings({ providers: ["codex", "claude"] });'},{name:"lm_read_prompts",category:"lmctl Automation",signature:"lm_read_prompts(batchfile, single = false)",description:"Reads prompt file with BOM and CRLF normalization, splitting into paragraphs or reading entire file as single prompt.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"},{name:"single",type:"bool",description:"(optional) If true, treats entire file as one prompt; if false, splits on blank lines"}],returns:{type:"string[]",description:"List of prompt strings"},example:'prompts = lm_read_prompts("prompts.txt");'},{name:"lm_read_paragraphs",category:"lmctl Automation",signature:"lm_read_paragraphs(batchfile)",description:"Reads a prompt file and splits it into blank-line-separated paragraphs.",parameters:[{name:"batchfile",type:"string",description:"Path to prompt file"}],returns:{type:"string[]",description:"List of paragraph strings"},example:'paragraphs = lm_read_paragraphs("spec.md");'},{name:"lm_members",category:"lmctl Automation",signature:"lm_members(teamfile)",description:"Resolves all team members declared in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"}],returns:{type:"map[]",description:"List of member records { alias, provider, model, sessionid, sessiondir }"},example:'members = lm_members("team.lmctl");'},{name:"lm_member",category:"lmctl Automation",signature:"lm_member(teamfile, alias)",description:"Resolves a specific member in a team configuration file.",parameters:[{name:"teamfile",type:"string",description:"Path to team configuration file"},{name:"alias",type:"string",description:"Member alias to look up"}],returns:{type:"map|null",description:"Member record { alias, provider, model, sessionid, sessiondir, isLead, teamfile } or null"},example:'m = lm_member("team.lmctl", "reviewer");'},{name:"lm_log",category:"lmctl Automation",signature:"lm_log(...args)",description:"Writes formatted log messages to standard error with trailing newline.",parameters:[{name:"args",type:"any[]",description:"Values or messages to log to stderr"}],returns:{type:"string",description:"The formatted text"},example:'lm_log("Step completed successfully");'},{name:"lm_error",category:"lmctl Automation",signature:"lm_error(...args)",description:"Writes error messages to standard error prefixed with 'error: '.",parameters:[{name:"args",type:"any[]",description:"Error details to write to stderr"}],returns:{type:"string",description:"The formatted error text"},example:'lm_error("Failed to connect to team member");'},{name:"lm_exit",category:"lmctl Automation",signature:"lm_exit(code = 0)",description:"Immediately terminates script execution with the specified integer exit code (0-255).",parameters:[{name:"code",type:"number",description:"(optional) Exit status code between 0 and 255 (default: 0)"}],returns:{type:"never",description:"Raises LMScriptExit control flow"},example:"lm_exit(1);"}].map(t=>({...t,module:"lmctl"}));fC={name:"lmctl",description:"lmctl Automation & Orchestration Host Functions",docs:dC,register(t,e){mC(t,e.io,e.registry,e.env)}}});var Cy={};oe(Cy,{formatCategoryOverview:()=>fd,formatFunctionDoc:()=>Ny,formatModuleOverview:()=>Ly,runScript:()=>gC});import{readFileSync as Ry}from"node:fs";import{resolve as hC}from"node:path";function Ny(t){let e="";if(e+=`Function: ${t.signature||t.name}
|
|
2199
2276
|
`,t.module&&(e+=`Module: ${t.module}
|
|
2200
2277
|
`),e+=`Category: ${t.category}
|
|
2201
2278
|
`,e+=`Description: ${t.description}
|
|
@@ -2207,7 +2284,7 @@ Returns: ${t.returns.type} - ${t.returns.description}
|
|
|
2207
2284
|
`),t.example&&(e+=`
|
|
2208
2285
|
Example:
|
|
2209
2286
|
${t.example}
|
|
2210
|
-
`),e}function
|
|
2287
|
+
`),e}function Ly(t,e){let r=`Module: ${e.name}
|
|
2211
2288
|
`;e.description&&(r+=`Description: ${e.description}
|
|
2212
2289
|
`);let n=t.getFunctionsByModule(e.name);if(n.length===0)return r+=`
|
|
2213
2290
|
No functions registered in this module.
|
|
@@ -2229,8 +2306,8 @@ Available Functions (by module):
|
|
|
2229
2306
|
`}}}return e+=`
|
|
2230
2307
|
Use 'lmctl script help <function>' for parameter details, return types, and examples.
|
|
2231
2308
|
Use 'lmctl script help <module>' to inspect a module.
|
|
2232
|
-
`,e}async function
|
|
2233
|
-
`)}return 2}return 0}return
|
|
2309
|
+
`,e}async function gC(t,e={stdout:process.stdout,stderr:process.stderr}){if(oi(e),t.length===0)return A(e,md.trimEnd());if(t[0]==="help"){let c=xs(e,[],new Ft,e.env);if(t.length===1)return e.stdout.write(fd(c)),0;let u=t[1],d=c.getModule(u);if(d)return e.stdout.write(Ly(c,d)),0;let m=c.getFunctionDoc(u);return m?(e.stdout.write(Ny(m)),0):A(e,`script: function '${u}' not found. Run 'lmctl script help' to see all available functions.`)}if(t[0]==="--help"||t[0]==="-h"){let c=xs(e,[],new Ft,e.env);return e.stdout.write(fd(c)),0}let r,n=!1,s,i=[],o=0;for(;o<t.length;){let c=t[o];if(c==="-e"){if(o+1>=t.length)return A(e,"script: -e requires a code argument");r=t[o+1],o+=2,i.push(...t.slice(o));break}else if(c==="--check"||c==="--dry-run")n=!0,o++;else{if(c.startsWith("-")&&c!=="-")return A(e,`script: unknown flag: ${c}`);s=c,i.push(...t.slice(o+1));break}}let a,l=s&&s!=="-"?hC(s):void 0;if(r!==void 0)a=r;else if(s!==void 0)if(s==="-")try{e.stdin&&typeof e.stdin.on=="function"?a=await new Promise((c,u)=>{let d="";e.stdin.on("data",m=>{d+=m}),e.stdin.on("end",()=>c(d)),e.stdin.on("error",u)}):a=Ry(0,"utf8")}catch(c){return A(e,`script: failed to read standard input: ${c?.message||String(c)}`)}else try{a=Ry(s,"utf8")}catch(c){return A(e,`script: ${c?.message||String(c)}`)}else return A(e,md.trimEnd());if(n){let c=new Ft,u=xs(e,i,c,e.env),{diagnostics:d}=u.scanAndCheck(a,{file:l});if(d.filter(f=>f.severity==="error").length>0){for(let f of d){let g=f.file?`${f.file}:${f.line}:${f.column}`:`${f.line}:${f.column}`;e.stderr.write(`error:${g}: ${f.message}
|
|
2310
|
+
`)}return 2}return 0}return ky(a,i,e,e.env,l)}var md,Eo,Oy=k(()=>{"use strict";ge();Ay();md=`usage: lmctl script [flags] <scriptfile> [args...]
|
|
2234
2311
|
lmctl script [flags] -e '<code>' [args...]
|
|
2235
2312
|
lmctl script [flags] - [args...]
|
|
2236
2313
|
lmctl script help [module|function]
|
|
@@ -2245,12 +2322,12 @@ Flags:
|
|
|
2245
2322
|
-e <code> Execute inline script code
|
|
2246
2323
|
--check, --dry-run Scan and check script without executing host effects
|
|
2247
2324
|
-h, --help Show this help message and function listing
|
|
2248
|
-
`,Eo=["Language Constructs","lmctl Automation","Strings","Lists & Arrays","Maps & Key-Value","File I/O","JSON & Data","Math","System & Process"]});function
|
|
2325
|
+
`,Eo=["Language Constructs","lmctl Automation","Strings","Lists & Arrays","Maps & Key-Value","File I/O","JSON & Data","Math","System & Process"]});function Dy(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}function My(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2249
2326
|
WHERE run_id = ?
|
|
2250
2327
|
AND acknowledged_at IS NULL
|
|
2251
2328
|
AND requires_user = 1
|
|
2252
|
-
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var pd=k(()=>{"use strict"});function
|
|
2253
|
-
WHERE a.id = ?`,e)[0];return n===void 0?null:
|
|
2329
|
+
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var pd=k(()=>{"use strict"});function $y(t,e={}){return t.query("SELECT * FROM run ORDER BY id DESC LIMIT ?",e.limit??100)}function Fy(t,e){let n=t.query(`${_C}
|
|
2330
|
+
WHERE a.id = ?`,e)[0];return n===void 0?null:yC(n)}function yC(t){let{payload_json:e,...r}=t,n={...r,node_path:null,expected_response:null,transcript_tail:null,paused_at:null,created_run_inputs:null,workflow_version_id:null,workflow_step:null,escalation_tier:null,escalation_token:null,escalation_reason:null,declared_outcomes:null,agent_output:null};if(e==null)return n;let s;try{s=JSON.parse(e)}catch{return n}if(s===null||typeof s!="object")return n;let i=s;if(Array.isArray(i.node_path)&&i.node_path.every(o=>typeof o=="string")&&(n.node_path=i.node_path),i.expected_response!==null&&typeof i.expected_response=="object"){let o=i.expected_response;if(typeof o.kind=="string"){let a=Array.isArray(o.choices)&&o.choices.every(l=>typeof l=="string")?o.choices:null;n.expected_response={kind:o.kind,choices:a}}}if(Array.isArray(i.transcript_tail)&&i.transcript_tail.every(o=>typeof o=="string")&&(n.transcript_tail=i.transcript_tail),typeof i.paused_at=="string"&&(n.paused_at=i.paused_at),i.created_run_inputs!==null&&typeof i.created_run_inputs=="object"&&!Array.isArray(i.created_run_inputs)&&(n.created_run_inputs=i.created_run_inputs),typeof i.workflow_version_id=="number"?n.workflow_version_id=i.workflow_version_id:i.workflow_version_id===null&&(n.workflow_version_id=null),i.step!==null&&typeof i.step=="object"&&!Array.isArray(i.step)){let o=i.step;typeof o.id=="string"&&o.id.length>0&&(n.workflow_step={id:o.id,name:typeof o.name=="string"?o.name:null,type:typeof o.type=="string"?o.type:null})}return typeof i.tier=="string"&&(n.escalation_tier=i.tier),typeof i.token=="string"&&(n.escalation_token=i.token),typeof i.reason=="string"&&(n.escalation_reason=i.reason),Array.isArray(i.declared_outcomes)&&i.declared_outcomes.every(o=>typeof o=="string")&&(n.declared_outcomes=i.declared_outcomes),typeof i.agent_output=="string"&&(n.agent_output=i.agent_output),n}var _C,hd=k(()=>{"use strict";_C=`SELECT a.id AS attention_id,
|
|
2254
2331
|
a.kind AS kind,
|
|
2255
2332
|
a.severity AS severity,
|
|
2256
2333
|
a.created_at AS created_at,
|
|
@@ -2272,31 +2349,31 @@ Flags:
|
|
|
2272
2349
|
ON isess.run_id = a.run_id
|
|
2273
2350
|
AND isess.id = (
|
|
2274
2351
|
SELECT MAX(id) FROM interactive_session WHERE run_id = a.run_id
|
|
2275
|
-
)`});var _d={};oe(_d,{parseIdleTimeoutMs:()
|
|
2352
|
+
)`});var _d={};oe(_d,{parseIdleTimeoutMs:()=>By,resolvePromptInput:()=>jy,runChat:()=>gd});import{readFileSync as EC,openSync as TC}from"node:fs";import{homedir as wC}from"node:os";import{join as vC}from"node:path";import{spawn as SC}from"node:child_process";function IC(t){return vC(wC(),".lmctl",`daemonize-${t}.log`)}function xC(t){let e=process.stdout.isTTY===!0,r=process.stderr.isTTY===!0;if(!e&&!r)return{stdio:["ignore","inherit","inherit"],logPath:null};let n=IC(t),s=TC(n,"a");return{stdio:["ignore",e?s:"inherit",r?s:"inherit"],logPath:n}}function kC(t,e){let{stdio:r,logPath:n}=xC(process.pid),s=SC(process.argv[0],[process.argv[1],"chat",...t],{detached:!0,stdio:r,env:{...process.env,[To]:"1"}});return s.on("error",i=>{e.stderr.write(`error: --daemonize failed to spawn the detached child: ${i.message}
|
|
2276
2353
|
`)}),s.unref(),e.stdout.write(`${JSON.stringify({status:"detached",pid:s.pid??null,logPath:n})}
|
|
2277
|
-
`),0}async function gd(t,e={stdout:process.stdout,stderr:process.stderr}){let r=e.env??process.env;if(t.length===0||t[0]==="--help"||t[0]==="-h")return e.stdout.write(`${
|
|
2278
|
-
`),t.length===0?2:0;if(t.includes("--daemonize")&&r[To]!=="1")return
|
|
2279
|
-
${
|
|
2280
|
-
`),2;if(n.promptFile!==void 0){let d=await
|
|
2354
|
+
`),0}async function gd(t,e={stdout:process.stdout,stderr:process.stderr}){let r=e.env??process.env;if(t.length===0||t[0]==="--help"||t[0]==="-h")return e.stdout.write(`${Py}
|
|
2355
|
+
`),t.length===0?2:0;if(t.includes("--daemonize")&&r[To]!=="1")return kC(t.filter(d=>d!=="--daemonize"),e);r[To]==="1"&&(oi(e),delete process.env[To]);let n=AC(t);if(typeof n=="string")return e.stderr.write(`error: ${n}
|
|
2356
|
+
${Py}
|
|
2357
|
+
`),2;if(n.promptFile!==void 0){let d=await jy(n.promptFile,e);if(typeof d!="string")return e.stderr.write(`error: ${d.error}
|
|
2281
2358
|
`),2;n.prompt=d}if(n.runFlag!==void 0){let d=Number.parseInt(n.runFlag,10);return!Number.isFinite(d)||d<=0||String(d)!==n.runFlag?(e.stderr.write(`error: invalid --run "${n.runFlag}" (expected a positive integer run id)
|
|
2282
2359
|
`),2):await C(e,async m=>{let f=m.getRun(d);if(f===null)return e.stderr.write(`error: run ${d}: not found
|
|
2283
|
-
`),1;if(f.terminal_state!==null&&f.terminal_state.length>0)return A(e,`run ${d}: already terminal (${f.terminal_state}); chat --run cannot resume a terminated run`);let g=
|
|
2360
|
+
`),1;if(f.terminal_state!==null&&f.terminal_state.length>0)return A(e,`run ${d}: already terminal (${f.terminal_state}); chat --run cannot resume a terminated run`);let g=My(m,d);if(g===null)return e.stderr.write(`error: run ${d}: no pending operator-answerable attention (chat --run only resumes paused runs)
|
|
2284
2361
|
`),1;if(g.kind==="workflow_escalation"){if(n.done)return e.stderr.write(`error: --done is not valid for workflow_escalation (the decision itself is terminal)
|
|
2285
2362
|
`),2;let y=m.resumeEscalation(g.attention_id,n.prompt);return y.resumed===!0?(e.stdout.write(`run ${d}: escalation resumed (decision: ${n.prompt})
|
|
2286
2363
|
`),0):(e.stderr.write(`error: run ${d}: resumeEscalation failed (${y.reason})
|
|
2287
|
-
`),1)}if(g.kind==="interactive_waiting_operator"){let y=
|
|
2364
|
+
`),1)}if(g.kind==="interactive_waiting_operator"){let y=Fy(m,g.attention_id);if(y===null||y.step_id===null)return e.stderr.write(`error: run ${d}: pending interactive_waiting_operator attention has no associated interactive step
|
|
2288
2365
|
`),1;let h=m.resumeInteractive(y.step_id,n.prompt,n.done===!0);return h.resumed===!0?(e.stdout.write(`run ${d}: interactive resumed (step ${y.step_id}${n.done===!0?", done":""})
|
|
2289
2366
|
`),0):(e.stderr.write(`error: run ${d}: resumeInteractive failed (${h.reason})
|
|
2290
2367
|
`),1)}return e.stderr.write(`error: run ${d}: pending attention kind "${g.kind}" is not operator-answerable
|
|
2291
|
-
`),1})}let s=ut(
|
|
2368
|
+
`),1})}let s=ut(bC,{target:n.target,alias:n.alias,flags:{session:n.sessionFlag,provider:n.providerFlag}});if(s.mode==="error")return e.stderr.write(`error: ${s.message}
|
|
2292
2369
|
`),2;if(s.mode==="managed")return e.stderr.write(`error: chat managed mode requires --run <id>
|
|
2293
2370
|
`),2;let i;if(s.mode==="ai-team"){if(s.alias===void 0)return e.stderr.write(`error: chat: alias required (internal)
|
|
2294
2371
|
`),2;e.stderr.write(`${s.alias}: turn running; this can take minutes
|
|
2295
2372
|
`);let d=ot(e,f=>`${s.alias}: turn still running (${f}s elapsed)
|
|
2296
|
-
`),m;try{m=await Ar({teamfile:s.teamfile,alias:s.alias,prompt:n.prompt,permissionMode:n.permissionMode,...n.idleTimeoutMs!==void 0?{idleTimeoutMs:n.idleTimeoutMs}:{},...n.rootFlag!==void 0?{rootFlag:n.rootFlag}:{},env:r,io:e,onEvent:f=>{d.poke(),!(n.json===!0&&f.kind==="delta")&&
|
|
2373
|
+
`),m;try{m=await Ar({teamfile:s.teamfile,alias:s.alias,prompt:n.prompt,permissionMode:n.permissionMode,...n.idleTimeoutMs!==void 0?{idleTimeoutMs:n.idleTimeoutMs}:{},...n.rootFlag!==void 0?{rootFlag:n.rootFlag}:{},env:r,io:e,onEvent:f=>{d.poke(),!(n.json===!0&&f.kind==="delta")&&LC(e,f,n.verbose===!0)},...n.json===!0?{onAccepted:f=>{d.poke(),e.stdout.write(`${JSON.stringify({status:"accepted",message_id:f})}
|
|
2297
2374
|
`)}}:{}})}finally{d.stop()}return n.json===!0?m.status==="busy"?(e.stdout.write(`${JSON.stringify({status:"busy",message:m.message,teamChatLogId:m.teamChatLogId})}
|
|
2298
2375
|
`),1):m.status==="error"?(e.stdout.write(`${JSON.stringify({status:"error",errorKind:m.errorKind,message:m.message,teamChatLogId:m.teamChatLogId,...m.messageId===null?{}:{message_id:m.messageId}})}
|
|
2299
|
-
`),1):(e.stdout.write(`${JSON.stringify({status:m.status,replyText:m.replyText,teamChatLogId:m.teamChatLogId,...m.messageId===null?{}:{message_id:m.messageId},turn_finished:!0,note:
|
|
2376
|
+
`),1):(e.stdout.write(`${JSON.stringify({status:m.status,replyText:m.replyText,teamChatLogId:m.teamChatLogId,...m.messageId===null?{}:{message_id:m.messageId},turn_finished:!0,note:Uy(s.alias)})}
|
|
2300
2377
|
`),m.status==="stalled"||m.status==="empty"?1:0):m.status==="busy"?(e.stderr.write(`error: ${m.message}
|
|
2301
2378
|
`),1):m.status==="error"?(m.errorKind==="cycle"?e.stderr.write(`${m.message}
|
|
2302
2379
|
`):e.stderr.write(`error: ${m.message}
|
|
@@ -2305,18 +2382,18 @@ ${Oy}
|
|
|
2305
2382
|
`)||e.stdout.write(`
|
|
2306
2383
|
`):e.stdout.write(`${m.replyText}${m.replyText.endsWith(`
|
|
2307
2384
|
`)?"":`
|
|
2308
|
-
`}`),e.stderr.write(`note: ${
|
|
2385
|
+
`}`),e.stderr.write(`note: ${Uy(s.alias)}
|
|
2309
2386
|
`),m.status==="stalled"?1:0)}else{if(s.provider===void 0)return e.stderr.write(`error: chat raw mode (bare sessionid / --session) requires --provider <name>
|
|
2310
|
-
`),2;i={provider:s.provider,sessionId:s.sessionid,cwd:process.cwd()}}let o=!1,a=z(),l=0,c=0,u=0;try{let d={provider:i.provider,sessionId:i.sessionId,cwd:i.cwd,prompt:n.prompt,permissionMode:n.permissionMode,env:r,onDelta:f=>{o=!0,a&&(l+=1,u=Buffer.byteLength(f,"utf8"),c+=u),e.stdout.write(f)},onProgress:f=>
|
|
2387
|
+
`),2;i={provider:s.provider,sessionId:s.sessionid,cwd:process.cwd()}}let o=!1,a=z(),l=0,c=0,u=0;try{let d={provider:i.provider,sessionId:i.sessionId,cwd:i.cwd,prompt:n.prompt,permissionMode:n.permissionMode,env:r,onDelta:f=>{o=!0,a&&(l+=1,u=Buffer.byteLength(f,"utf8"),c+=u),e.stdout.write(f)},onProgress:f=>Wy(e,i.alias??"(raw)",f,n.verbose===!0)};i.model!==void 0&&(d.model=i.model),i.effort!==void 0&&(d.effort=i.effort),i.alias!==void 0&&(d.alias=i.alias),i.isLead!==void 0&&(d.isLead=i.isLead),n.idleTimeoutMs!==void 0&&(d.timeoutMs=n.idleTimeoutMs);let m=await Ir(d);return a&&Ee(JSON.stringify({event:"chat_return",alias:i.alias??"(raw)",provider:i.provider,streamed:o,blockCount:l,streamedBytes:c,resultTextBytes:Buffer.byteLength(m.text,"utf8"),lastChunkBytes:u,tailPreview:NC(m.text,200)})),m.status==="empty"?(e.stderr.write(`error: 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
|
|
2311
2388
|
`),1):(o?m.text.endsWith(`
|
|
2312
2389
|
`)||e.stdout.write(`
|
|
2313
2390
|
`):e.stdout.write(`${m.text}${m.text.endsWith(`
|
|
2314
2391
|
`)?"":`
|
|
2315
2392
|
`}`),m.status==="stalled"?1:0)}catch(d){let m=d instanceof Error?d.message:String(d);return e.stderr.write(`error: ${m}
|
|
2316
|
-
`),1}}function
|
|
2393
|
+
`),1}}function Uy(t){return`${t}'s turn has finished and exited; resubmit \`lmctl prompt\` to continue (no persistent session is left running)`}function AC(t){let e=[],r="yolo",n,s,i,o,a,l,c=!1,u=!1,d=!1;for(let h=0;h<t.length;h+=1){let p=t[h];if(p==="--permission-mode"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --permission-mode";if(_!=="plan"&&_!=="yolo")return`--permission-mode must be one of plan|yolo (got "${_}")`;r=_;continue}if(p==="--idle-timeout"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --idle-timeout";let T=By(_);if(typeof T=="string")return T;n=T;continue}if(p==="--session"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --session";s=_;continue}if(p==="--provider"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --provider";i=_;continue}if(p==="--from"||p.startsWith("--from="))return Tg("chat");if(p.startsWith("I_am="))return`unknown argument: ${p}`;if(p==="--root"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --root";o=_;continue}if(p==="--prompt-file"){let _=t[++h];if(_===void 0||_!=="-"&&_.startsWith("--"))return"missing value for --prompt-file";a=_;continue}if(p==="--force"||p.startsWith("--force="))return"unknown option --force (a dead holder auto-reclaims; for a live holder use lmctl prompt)";if(p==="--json"){u=!0;continue}if(p==="--verbose"){d=!0;continue}if(p==="--run"){let _=t[++h];if(_===void 0||_.startsWith("--"))return"missing value for --run";l=_;continue}if(p==="--done"){c=!0;continue}if(p.startsWith("--"))return`unknown flag: ${p}`;e.push(p)}if(l!==void 0){if(s!==void 0)return"--run is mutually exclusive with --session";if(i!==void 0)return"--run is mutually exclusive with --provider";if(o!==void 0)return"--run is mutually exclusive with --root";if(a!==void 0&&e.length>0)return"--prompt-file is mutually exclusive with a positional answer; pass one or the other";if(a===void 0&&e.length===0)return"a prompt (answer) is required with --run";if(e.length>1)return`--run takes exactly one positional (the answer); got ${e.length}`;let h={prompt:a!==void 0?"":e[0],permissionMode:r,runFlag:l,done:c,json:u,verbose:d};return a!==void 0&&(h.promptFile=a),h}let m,f,g;if(a!==void 0){if(e.length===0){if(s===void 0)return"expected <teamfile>:<alias> --prompt-file <path> | <teamfile> <alias> --prompt-file <path> | --session <id> --prompt-file <path>"}else if(e.length===1)m=e[0];else if(e.length===2)m=e[0],f=e[1];else return"--prompt-file is mutually exclusive with a positional prompt; pass one or the other";g=""}else{if(e.length===0)return"a prompt is required";if(e.length===1){if(s===void 0)return'expected <teamfile>:<alias> "<prompt>" | <teamfile> <alias> "<prompt>" | <sessionid> "<prompt>" | --session <id> "<prompt>"';g=e[0]}else if(e.length===2)m=e[0],g=e[1];else if(e.length===3)m=e[0],f=e[1],g=e[2];else return`too many positionals (${e.length}); expected at most <teamfile> <alias> <prompt>`}if(c)return"--done requires --run";let y={prompt:g,permissionMode:r};return m!==void 0&&(y.target=m),f!==void 0&&(y.alias=f),n!==void 0&&(y.idleTimeoutMs=n),s!==void 0&&(y.sessionFlag=s),i!==void 0&&(y.providerFlag=i),o!==void 0&&(y.rootFlag=o),a!==void 0&&(y.promptFile=a),u&&(y.json=u),d&&(y.verbose=d),y}async function jy(t,e,r=process.stdin){let n;try{n=t==="-"?await RC(r):EC(t,"utf8")}catch(i){let o=i instanceof Error?i.message:String(i);return{error:`--prompt-file ${t}: ${o}`}}let s=n.endsWith(`\r
|
|
2317
2394
|
`)?n.slice(0,-2):n.endsWith(`
|
|
2318
|
-
`)?n.slice(0,-1):n;return s.length===0?{error:`--prompt-file ${t}: file is empty; a prompt is required`}:s}async function
|
|
2319
|
-
`)}function
|
|
2395
|
+
`)?n.slice(0,-1):n;return s.length===0?{error:`--prompt-file ${t}: file is empty; a prompt is required`}:s}async function RC(t){let e=[];for await(let r of t)e.push(typeof r=="string"?Buffer.from(r,"utf8"):r);return Buffer.concat(e).toString("utf8")}function By(t){if(t==="0")return 0;if(/^\d+$/.test(t)){let i=Number(t);return i>0&&i<1e3?`--idle-timeout ${t} means ${t}ms, not ${t}s \u2014 that's not enough time for any real provider call to make progress. Use an explicit unit, e.g. --idle-timeout ${t}s.`:i}let e=/^(\d+)([smhd])$/.exec(t);if(e===null)return`invalid --idle-timeout "${t}" (expected <n>(s|m|h|d), integer ms >= 1000, or 0)`;let r=Number(e[1]),n=e[2];return r*(n==="s"?1e3:n==="m"?6e4:n==="h"?36e5:864e5)}function Wy(t,e,r,n=!1){if(r.kind!=="tool_use"&&r.kind!=="tool_result"&&r.kind!=="api_retry")return;let s=r.kind==="tool_use"?`[${e}] tool_use ${r.tool??"tool"}${r.summary?`: ${r.summary}`:""}`:r.kind==="tool_result"?`[${e}] tool_result${r.status?` ${r.status}`:""}${r.summary?`: ${r.summary}`:""}`:`[${e}] api_retry${r.summary?`: ${r.summary}`:""}`;L({event:"chat_progress",alias:e,progress_kind:r.kind,line:s}),n&&t.stderr.write(`${s}
|
|
2396
|
+
`)}function NC(t,e){return t.slice(-e)}function LC(t,e,r=!1){e.kind==="delta"?t.stdout.write(e.chunk):e.kind==="progress"?Wy(t,e.alias,e.event,r):t.stderr.write(e.message)}var bC,Py,To,wo=k(()=>{"use strict";Ct();ge();We();Zi();fn();V();pd();hd();ge();bC={name:"chat",allowsBareTeamfile:!1,supportsRaw:!0},Py=`usage: lmctl prompt <teamfile>:<alias> "<prompt>"
|
|
2320
2397
|
lmctl prompt <teamfile> <alias> "<prompt>"
|
|
2321
2398
|
lmctl prompt <sessionid> "<prompt>" --provider <name>
|
|
2322
2399
|
lmctl prompt --provider <name> --session <id> "<prompt>"
|
|
@@ -2374,7 +2451,7 @@ File input:
|
|
|
2374
2451
|
<file> unless --force is given. --script <name> fetches commands/<name>.lms
|
|
2375
2452
|
instead of the default.
|
|
2376
2453
|
|
|
2377
|
-
Send a prompt to a team member or raw provider session, or answer a paused run.`,To="LMCTL_CHAT_DAEMONIZED"});import*as
|
|
2454
|
+
Send a prompt to a team member or raw provider session, or answer a paused run.`,To="LMCTL_CHAT_DAEMONIZED"});import*as Hy from"node:child_process";function CC(t,e){try{let r=e(t,["--version"],{encoding:"utf-8",timeout:5e3});return r.status===0?{found:!0,version:(r.stdout??"").toString().trim().split(/\r?\n/,1)[0]?.trim()||void 0}:r.status===null?{found:!1,failureMode:"not installed"}:{found:!1,failureMode:"runs but failed"}}catch{return{found:!1,failureMode:"not installed"}}}function Xy(t,e={}){let r=e.spawnSync===void 0&&process.env[OC]==="1",n=e.spawnSync??Hy.spawnSync,s=new Set,i=[];for(let o of t){if(s.has(o))continue;s.add(o);let a=vo[o];if(!a){i.push({provider:o,binary:"<unknown>",found:!1,failureMode:"not installed"});continue}if(r){i.push({provider:o,binary:a,found:!0,version:"(skipped)"});continue}let l=CC(a,n);l.found?i.push({provider:o,binary:a,found:!0,version:l.version}):i.push({provider:o,binary:a,found:!1,failureMode:l.failureMode})}return i}var vo,OC,qy=k(()=>{"use strict";vo={claude:"claude",codex:"codex",copilot:"copilot",gemini:"gemini",opencode:"opencode",lmplayer:"lmplayer",qwen:"qwen",agy:"agy",kimi:"kimi",dsh:"dsh",hermes:"hermes",pi:"pi"};OC="LMCTL_SKIP_BINARY_CHECK"});function Jy(t){return Ed[t.trim().toLowerCase()]}function Vy(t){let e=t.split(":");if(e.length<2)return{error:`invalid member spec "${t}" \u2014 expected Alias:provider[:model]`};let[r,n]=e,s=e.length>2?e.slice(2).join(":"):void 0;if(r===""||n==="")return{error:`invalid member spec "${t}" \u2014 expected Alias:provider[:model]`};let i=Mt({alias:r,provider:n});return i!==void 0?{error:i}:s!==void 0&&s===""?{error:`invalid member spec "${t}" \u2014 empty model`}:{spec:{alias:r,provider:n,...s!==void 0?{model:s}:{}}}}function Gy(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function DC(t){return[`_MEMBER_ provider=${t.provider} alias=${Gy(t.alias)}`,...t.model!==void 0?[`model=${Gy(t.model)}`]:[]].join(" ")}function bo(t){let{teamName:e,members:r}=t,n=r.map(DC).join(`
|
|
2378
2455
|
`);return`# ${e}
|
|
2379
2456
|
#
|
|
2380
2457
|
# This is a starting point, not a finished teamfile -- edit alias/provider/model
|
|
@@ -2383,10 +2460,10 @@ Send a prompt to a team member or raw provider session, or answer a paused run.`
|
|
|
2383
2460
|
# Format, and what lint/seed each do: https://lmctl.com/lmctl/docs/manuals/teamfile-format
|
|
2384
2461
|
|
|
2385
2462
|
${n}
|
|
2386
|
-
`}function
|
|
2387
|
-
`).map(e=>
|
|
2463
|
+
`}function Yy(t){return t.split(`
|
|
2464
|
+
`).map(e=>Ky.test(e)?e.replace(/\s+sessionid=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessionid=(?:"[^"]*"|\S+)\s+/g,"$1 ").replace(/\s+sessiondir=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessiondir=(?:"[^"]*"|\S+)\s+/g,"$1 "):e).join(`
|
|
2388
2465
|
`)}function yd(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function Io(t){let e=[];for(let r of t.split(`
|
|
2389
|
-
`)){if(!
|
|
2466
|
+
`)){if(!Ky.test(r))continue;let n=yd(r,"alias"),s=yd(r,"provider");if(n===void 0||s===void 0)continue;let i=yd(r,"model");e.push({alias:n,provider:s,...i!==void 0&&i!==""?{model:i}:{}})}return e}var Ed,So,Ky,Td=k(()=>{"use strict";$t();Ed={1:["Lead"],lead:["Lead"],2:["Lead","Reviewer"],"lead-reviewer":["Lead","Reviewer"],3:["Lead","Coder","Reviewer"],"lead-coder-reviewer":["Lead","Coder","Reviewer"]},So="1|2|3|lead|lead-reviewer|lead-coder-reviewer";Ky=/^\s*_MEMBER_\s+\S/});import{mkdtempSync as MC,readFileSync as $C,rmSync as FC,writeFileSync as PC}from"node:fs";import{tmpdir as UC}from"node:os";import{spawnSync as jC}from"node:child_process";import{basename as xo,extname as wd,join as vd,resolve as Sd}from"node:path";import*as zy from"node:readline";function BC(t){return e=>{let r=t.EDITOR??t.VISUAL??"vi";jC(r,[e],{stdio:"inherit"})}}async function Qy(t){let{io:e,cwd:r,env:n=process.env}=t,s=t.initial??{},i=zy.createInterface({input:t.input,output:e.stdout,terminal:!1}),o=[],a=[];i.on("line",d=>{let m=a.shift();m!==void 0?m(d):o.push(d)});let l=!1;i.on("close",()=>{for(l=!0;a.length>0;)a.shift()("")});let c=async d=>{e.stdout.write(d);let m=o.shift();return m!==void 0?m.trim():l?"":new Promise(f=>a.push(g=>f(g.trim())))},u=()=>i.close();try{let d,m;if(s.output!==void 0)d=Sd(r,s.output),m=xo(d,wd(d));else{let p=Sd(r,t.directory??"."),_=await c(`Directory [${p}]: `),T=_===""?p:Sd(r,_),E=`${xo(T)}.lmctl`,S=await c(`Teamfile name [${E}]: `),w=S===""?E:S,b=wd(w)?w:`${w}.lmctl`;d=vd(T,b),m=xo(b,wd(b))}let f;if(s.members!==void 0&&s.members.length>0)f=s.members.map(p=>({...p,model:p.model??s.model}));else{let _=(t.checkProviders??(()=>Xy(Object.keys(vo))))(),T=_.filter(x=>x.found).map(x=>x.provider),E=_.filter(x=>!x.found).map(x=>x.provider);e.stdout.write(`detected providers: ${T.length>0?T.join(", "):"(none)"}
|
|
2390
2467
|
`),E.length>0&&e.stdout.write(`not found: ${E.join(", ")}
|
|
2391
2468
|
`);let S=s.provider??(T.length===1?T[0]:void 0),w=S;for(;w===void 0;){let x=await c(`Default provider${S!==void 0?` [${S}]`:""}: `),I=x===""?S:x;if(I===void 0){if(l)return e.stderr.write(`error: stdin closed (EOF) at the provider prompt and no default is available
|
|
2392
2469
|
`),u(),null;continue}if(Mt({alias:"Probe",provider:I})!==void 0){e.stdout.write(`unknown provider "${I}" (known: ${Object.keys(vo).join(", ")})
|
|
@@ -2399,10 +2476,10 @@ ${n}
|
|
|
2399
2476
|
`);continue}let $=M.toLowerCase();if(R.has($)){e.stdout.write(`duplicate member alias "${M}"
|
|
2400
2477
|
`);continue}R.add($),v.push(M)}}else v=Ed[I],v===void 0&&e.stdout.write(`unknown pattern "${I}"
|
|
2401
2478
|
`)}f=[];for(let x of v){let I=await c(`Provider for ${x} [${w}]: `),R=I===""?w:I,M=Mt({alias:x,provider:R});if(M!==void 0)return e.stdout.write(`error: ${M}
|
|
2402
|
-
`),u(),null;let N=s.model,$=await c(`Model for ${x}${N!==void 0?` [${N}]`:" (blank to omit)"}: `),q=$===""?N:$;f.push({alias:x,provider:R,...q!==void 0?{model:q}:{}})}}let g=bo({teamName:m,members:f}),y=t.editFile??
|
|
2479
|
+
`),u(),null;let N=s.model,$=await c(`Model for ${x}${N!==void 0?` [${N}]`:" (blank to omit)"}: `),q=$===""?N:$;f.push({alias:x,provider:R,...q!==void 0?{model:q}:{}})}}let g=bo({teamName:m,members:f}),y=t.editFile??BC(n),h=s.seed??!0;for(;;){e.stdout.write(`
|
|
2403
2480
|
--- ${d} ---
|
|
2404
2481
|
${g}---
|
|
2405
|
-
`);let p=(await c(`Write and seed? [${h?"Y/n":"y/N"}/e(dit)]: `)).toLowerCase();if(p==="e"||p==="edit"){let T=
|
|
2482
|
+
`);let p=(await c(`Write and seed? [${h?"Y/n":"y/N"}/e(dit)]: `)).toLowerCase();if(p==="e"||p==="edit"){let T=MC(vd(UC(),"lmctl-plan-edit-"));try{let E=vd(T,xo(d));PC(E,g,"utf8"),y(E),g=$C(E,"utf8")}finally{FC(T,{recursive:!0,force:!0})}continue}if(p==="q"||p==="quit"||p==="abort")return u(),null;let _=p===""?h:p!=="n"&&p!=="no";return u(),{destPath:d,text:g,seed:_}}}catch(d){throw u(),d}}function Zy(t){return Io(t)}var eE=k(()=>{"use strict";qy();$t();Td()});import{existsSync as WC,mkdirSync as HC,readdirSync as XC,readFileSync as qC,writeFileSync as GC}from"node:fs";import{homedir as rE}from"node:os";import{dirname as JC,join as Fr}from"node:path";function Ao(){return Fr(rE(),".lmctl","init.toml")}function bd(t){let e=tE[t]??tE.claude;return{provider:t,model1:e[0],model2:e[1],model3:e[2]}}function nE(t){let e=t.filter((o,a)=>t.indexOf(o)===a),r=e.length>0?e:["claude"],[n,s=n,i=n]=r;return{provider1:bd(n),provider2:bd(s),provider3:bd(i)}}function ks(t){try{return WC(t)&&XC(t).length>0}catch{return!1}}function sE(){let t=rE(),e=process.env.KIMI_CODE_HOME??Fr(t,".kimi-code"),r=[];return ks(Fr(t,".claude","projects"))&&r.push("claude"),(ks(Fr(t,".codex","sessions"))||ks(Fr(t,".code","sessions")))&&r.push("codex"),ks(Fr(t,".gemini","antigravity-cli","conversations"))&&r.push("agy"),ks(Fr(e,"sessions"))&&r.push("kimi"),r}function ko(t){return`"${t.replace(/"/g,'\\"')}"`}function Ro(t){let e=(r,n)=>[`[${r}]`,`provider = ${ko(n.provider)}`,`model1 = ${ko(n.model1)}`,`model2 = ${ko(n.model2)}`,`model3 = ${ko(n.model3)}`].join(`
|
|
2406
2483
|
`);return`# Generated by \`lmctl init\`. This is a STARTING POINT, not a fixed answer --
|
|
2407
2484
|
# edit any value below to change what \`lmctl plan\`/\`lmctl quickrun\` resolve to.
|
|
2408
2485
|
#
|
|
@@ -2420,8 +2497,8 @@ ${e("Provider1",t.provider1)}
|
|
|
2420
2497
|
${e("Provider2",t.provider2)}
|
|
2421
2498
|
|
|
2422
2499
|
${e("Provider3",t.provider3)}
|
|
2423
|
-
`}function
|
|
2424
|
-
`)){let l=a.trim();if(l===""||l.startsWith("#"))continue;if(l.startsWith("[")&&l.endsWith("]")){r=l.slice(1,-1).trim(),e[r]??={};continue}if(r===null)continue;let c=l.indexOf("=");if(c===-1)continue;let u=l.slice(0,c).trim(),d=
|
|
2500
|
+
`}function VC(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\"/g,'"'):e}function KC(t){let e={},r=null;for(let a of t.split(`
|
|
2501
|
+
`)){let l=a.trim();if(l===""||l.startsWith("#"))continue;if(l.startsWith("[")&&l.endsWith("]")){r=l.slice(1,-1).trim(),e[r]??={};continue}if(r===null)continue;let c=l.indexOf("=");if(c===-1)continue;let u=l.slice(0,c).trim(),d=VC(l.slice(c+1));(u==="provider"||u==="model1"||u==="model2"||u==="model3")&&(e[r][u]=d)}let n=a=>{let l=e[a];return!l||!l.provider||!l.model1||!l.model2||!l.model3?null:{provider:l.provider,model1:l.model1,model2:l.model2,model3:l.model3}},s=n("Provider1"),i=n("Provider2"),o=n("Provider3");return!s||!i||!o?null:{provider1:s,provider2:i,provider3:o}}function Tn(t){let e=t??Ao(),r;try{r=qC(e,"utf-8")}catch{return null}return KC(r)}function iE(t,e){let r=e??Ao();HC(JC(r),{recursive:!0}),GC(r,Ro(t),"utf-8")}function oE(t,e){let r={Provider1:e.provider1.provider,Provider2:e.provider2.provider,Provider3:e.provider3.provider,Model1:e.provider1.model1,Model2:e.provider2.model1,Model3:e.provider3.model1};return t.replace(/\$\{(Provider[123]|Model[123])\}/g,(n,s)=>r[s]??n)}var tE,No=k(()=>{"use strict";tE={claude:["claude-opus-5","claude-sonnet-5","claude-sonnet-5"],codex:["gpt-5.6-sol","gpt-5.5","gpt-6-astra"],agy:["Gemini 3.8 Flash (High)","Gemini 3.8 Flash (Medium)","Gemini 3.1 Pro (High)"],kimi:["kimi-code/k3","kimi-code/k3","kimi-code/k3"]}});var pE={};oe(pE,{readPlanSource:()=>mr,runPlan:()=>n0});import{existsSync as cE,mkdirSync as YC,readdirSync as zC,readFileSync as aE,statSync as QC,writeFileSync as ZC}from"node:fs";import{basename as dE,dirname as e0,extname as t0,join as uE,resolve as xd}from"node:path";async function n0(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(r0),0;let n=[],s=[];for(let I=0;I<t.length;I+=1){let R=t[I];if(R==="--member"){let M=t[I+1];if(M===void 0||M.startsWith("--"))return e.stderr.write(`error: missing value for --member
|
|
2425
2502
|
`),2;n.push(M),I+=1;continue}s.push(R)}let i=ae(s,["--pattern","--provider","--model","--from","--output"],["--json","--stdout","--force","--seed","--no-seed","--wizard","--non-interactive","--no-interactive"]);if(i.error!==void 0)return e.stderr.write(`error: ${i.error}
|
|
2426
2503
|
`),e.stderr.write(`usage: lmctl plan [directory] [options]
|
|
2427
2504
|
`),2;if(i.positionals.length>1)return e.stderr.write(`usage: lmctl plan [directory] [options]
|
|
@@ -2432,19 +2509,19 @@ ${e("Provider3",t.provider3)}
|
|
|
2432
2509
|
`),2;if(_&&f)return e.stderr.write(`error: --wizard cannot be combined with --json
|
|
2433
2510
|
`),2;let E=l!==void 0||c!==void 0||u!==void 0||d!==void 0||n.length>0,S=e.stdin??process.stdin,w=r.stdinIsTTY??(e.stdin===void 0?process.stdin.isTTY===!0:S.isTTY===!0),b=_||!T&&!E&&!g&&!f&&w,v;if(b){if(d!==void 0)return e.stderr.write(`error: --from cannot be combined with --wizard
|
|
2434
2511
|
`),2;if(l!==void 0&&n.length>0)return e.stderr.write(`error: --pattern and --member are mutually exclusive
|
|
2435
|
-
`),2;let I=
|
|
2436
|
-
`)});if(I.error!==void 0)return 1;v=await
|
|
2437
|
-
`),2;let I=await
|
|
2512
|
+
`),2;let I=fE(n,u,R=>{e.stderr.write(`error: ${R}
|
|
2513
|
+
`)});if(I.error!==void 0)return 1;v=await s0(e,S,o,a,{provider:c,model:u,pattern:l,members:I.members,seed:!p,output:m},r)}else{if(!E)return e.stderr.write(`error: ${mE}
|
|
2514
|
+
`),2;let I=await i0({pattern:l,provider:c,model:u,from:d,memberRaws:n,output:m,directory:a,cwd:o,seedFlag:h,deps:r},R=>{e.stderr.write(`error: ${R}
|
|
2438
2515
|
`)});if(typeof I=="number")return I;v=I}if(v===null)return e.stderr.write(`aborted
|
|
2439
|
-
`),1;if(g)return e.stdout.write(v.text),0;let x=v.destPath;return
|
|
2440
|
-
`),1;
|
|
2516
|
+
`),1;if(g)return e.stdout.write(v.text),0;let x=v.destPath;return a0(v,x,{asJson:f,force:y,seed:v.seed},e)}async function s0(t,e,r,n,s,i){let o=await Qy({io:t,input:e,cwd:r,...n!==void 0?{directory:n}:{},initial:s,...i.checkProviders!==void 0?{checkProviders:i.checkProviders}:{},...i.editFile!==void 0?{editFile:i.editFile}:{},...t.env!==void 0?{env:t.env}:{}});return o===null?null:{text:o.text,destPath:o.destPath,members:Zy(o.text),seed:o.seed}}async function i0(t,e){let{pattern:r,provider:n,model:s,from:i,memberRaws:o,output:a,directory:l,cwd:c,seedFlag:u,deps:d}=t,m=[r!==void 0,o.length>0,i!==void 0].filter(Boolean).length;if(m===0)return e(mE),2;if(m>1)return e("--pattern, --member and --from are mutually exclusive"),2;if(i!==void 0&&(n!==void 0||s!==void 0))return e("--from cannot be combined with --provider or --model (the source teamfile defines the roster)"),2;let f=o0(a,l,c);if(i!==void 0){let h;try{h=await mr(i,d.fetchFn??globalThis.fetch,c)}catch(T){return e(T instanceof Error?T.message:String(T)),1}let p=Yy(h),_=Io(p);return _.length===0?(e(`--from source "${i}" has no parseable _MEMBER_ lines`),1):{text:p,destPath:f,members:_,seed:u}}let g;if(o.length>0){let h=fE(o,s,e);if(h.error!==void 0)return 1;g=h.members}else{let h=Jy(r);if(h===void 0)return e(`invalid pattern "${r}" (expected ${So})`),2;if(n!==void 0){let p=Mt({alias:"Lead",provider:n});if(p!==void 0)return e(p),1;g=h.map(_=>({alias:_,provider:n,...s!==void 0?{model:s}:{}}))}else{let p=Tn(d.initConfigPath);if(p===null)return e("missing --provider, and no ~/.lmctl/init.toml found. Run `lmctl init` first, or pass --provider explicitly."),2;let _=[p.provider1,p.provider2,p.provider3];g=h.map((T,E)=>{let S=_[E%_.length];return{alias:T,provider:S.provider,model:s??S.model1}})}}let y=dE(f,t0(f));return{text:bo({teamName:y,members:g}),destPath:f,members:g,seed:u}}function fE(t,e,r){if(t.length===0)return{members:void 0};let n=[],s=new Set;for(let i of t){let o=Vy(i);if(o.error!==void 0)return r(o.error),{error:o.error};let a=o.spec,l=a.alias.toLowerCase();if(s.has(l))return r(`duplicate member alias "${a.alias}"`),{error:l};s.add(l),n.push({...a,model:a.model??e})}return n[0].alias.toLowerCase()!=="lead"?(r(`the first member must be Lead (got "${n[0].alias}")`),{error:"lead-not-first"}):{members:n}}function o0(t,e,r){if(t!==void 0)return xd(r,t);let n=xd(r,e??".");return uE(n,`${dE(n)}.lmctl`)}async function a0(t,e,r,n){if(cE(e)&&!r.force)return n.stderr.write(`error: ${e} already exists (use --force to overwrite)
|
|
2517
|
+
`),1;YC(e0(e),{recursive:!0}),ZC(e,t.text,"utf8");let s=r.asJson?{...n,stdout:{write:()=>{}}}:n;if(!(await Mr([e],s)===0))return r.seed&&n.stderr.write(`error: refusing to seed \u2014 lint failed
|
|
2441
2518
|
`),r.asJson&&se(n,Id(e,!1,!1,t.members)),1;let a=!1;if(r.seed){let l=await $r([e],s);return a=l===0,r.asJson&&se(n,Id(e,!0,a,t.members)),l}return r.asJson?(se(n,Id(e,!0,!1,t.members)),0):(n.stdout.write(`Created ${e}
|
|
2442
2519
|
`),n.stdout.write(`This is a starting point, not a finished teamfile -- edit it freely.
|
|
2443
2520
|
`),n.stdout.write(`Only _MEMBER_ lines are parsed; everything else is free-form.
|
|
2444
2521
|
`),n.stdout.write(`Format, and what lint/seed each do: https://lmctl.com/lmctl/docs/manuals/teamfile-format
|
|
2445
2522
|
`),n.stdout.write(`After editing, run: lmctl lint ${e}
|
|
2446
2523
|
`),n.stdout.write(`Then run: lmctl seed ${e}
|
|
2447
|
-
`),0)}function Id(t,e,r,n){return{path:t,linted:e,seeded:r,members:n.map(s=>({alias:s.alias,provider:s.provider,...s.model!==void 0?{model:s.model}:{}}))}}async function mr(t,e,r){if(/^http:\/\//i.test(t))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(t))return
|
|
2524
|
+
`),0)}function Id(t,e,r,n){return{path:t,linted:e,seeded:r,members:n.map(s=>({alias:s.alias,provider:s.provider,...s.model!==void 0?{model:s.model}:{}}))}}async function mr(t,e,r){if(/^http:\/\//i.test(t))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(t))return c0(t,e);let n=xd(r,t);if(!cE(n))throw new Error(`source not found: ${t}`);if(!QC(n).isDirectory())return aE(n,"utf8");let i=zC(n).filter(o=>o.endsWith(".lmctl"));if(i.length===0)throw new Error(`no .lmctl files in source directory: ${t}`);if(i.length>1)throw new Error(`multiple .lmctl files in source directory: ${t}; specify the source file explicitly`);return aE(uE(n,i[0]),"utf8")}async function c0(t,e){let r=new URL(t);for(let n=0;;n+=1){if(r.protocol!=="https:")throw new Error("HTTPS redirects must remain https://");let s=await e(r.href,{redirect:"manual"});if(s.url!==""&&new URL(s.url).protocol!=="https:")throw new Error("HTTPS redirects must remain https://");if(!l0.has(s.status)){if(!s.ok)throw new Error(`HTTP ${s.status}`);return await s.text()}if(n>=lE)throw new Error(`too many HTTPS redirects (maximum ${lE})`);let i=s.headers.get("location");if(i===null)throw new Error(`HTTP ${s.status} redirect missing Location header`);r=new URL(i,r)}}var r0,mE,l0,lE,As=k(()=>{"use strict";ge();eE();$t();No();Td();r0=`usage: lmctl plan [directory] [options]
|
|
2448
2525
|
|
|
2449
2526
|
Generate an lmctl teamfile. With no config flags and a TTY, an interactive
|
|
2450
2527
|
wizard runs; with flags, everything is non-interactive.
|
|
@@ -2480,41 +2557,41 @@ Examples:
|
|
|
2480
2557
|
lmctl plan ./backend --member Lead:claude --member Reviewer:codex:o3
|
|
2481
2558
|
lmctl plan ./backend-v2 --from https://example.com/backend.lmctl
|
|
2482
2559
|
lmctl plan ./backend --pattern 3 --provider claude --seed
|
|
2483
|
-
`,
|
|
2560
|
+
`,mE=`missing required flags for non-interactive plan:
|
|
2484
2561
|
one of: --pattern <${So}>, --member <Alias:provider[:model]>, or --from <file|dir|url>
|
|
2485
|
-
plus: --provider <name> (required with --pattern)`;
|
|
2486
|
-
`),1;let a=`${
|
|
2562
|
+
plus: --provider <name> (required with --pattern)`;l0=new Set([301,302,303,307,308]),lE=10});var Lo={};oe(Lo,{extractSaveScriptFlags:()=>gE,performSaveScript:()=>_E,runWithSaveScript:()=>E0});import{existsSync as d0,mkdirSync as u0,renameSync as m0,writeFileSync as f0}from"node:fs";import{dirname as p0,extname as h0,join as g0}from"node:path";function gE(t,e,r={}){let n=[],s,i,o=!1;for(let c=0;c<t.length;c+=1){let u=t[c];if(u==="--save-script"){let d=t[c+1];if(d===void 0)return{rest:n,error:"--save-script requires a file path"};s=d,c+=1;continue}if(u==="--script"){let d=t[c+1];if(d===void 0)return{rest:n,error:"--script requires a name"};i=d,c+=1;continue}if(u==="--force"&&!r.ownsForce){o=!0;continue}n.push(u)}if(r.ownsForce&&(o=t.includes("--force")),s===void 0)return i!==void 0?{rest:n,error:"--script requires --save-script"}:{rest:n};let a=i??e;if(!hE.test(a))return{rest:n,error:`--script "${a}" must match ${hE} (letters, digits, ., _, -)`};let l=r.extension??".lms";return{rest:n,request:{destPath:s,slug:a,extension:l,force:o}}}function y0(t){let e=t.slice(0,512).trimStart().toLowerCase();return e.startsWith("<!doctype html")||e.startsWith("<html")}async function _E(t,e,r=fetch){let{destPath:n,slug:s,extension:i,force:o}=e;if(d0(n)&&!o)return t.stderr.write(`error: --save-script: ${n} already exists (use --force to overwrite)
|
|
2563
|
+
`),1;let a=`${_0}/${s}${i}`,l;try{l=await mr(a,r,process.cwd())}catch(d){let m=d instanceof Error?d.message:String(d);return m==="HTTP 404"?t.stderr.write(`error: --save-script: no script is published at ${a} for this command
|
|
2487
2564
|
`):t.stderr.write(`error: --save-script: could not fetch ${a}: ${m}
|
|
2488
|
-
`),1}if(
|
|
2565
|
+
`),1}if(h0(n).toLowerCase()!==i.toLowerCase()&&t.stderr.write(`warning: --save-script: ${n} does not end in "${i}", the extension lmctl.com actually serves for this command
|
|
2489
2566
|
`),l.trim().length===0)return t.stderr.write(`error: --save-script: ${a} returned an empty response
|
|
2490
|
-
`),1;if(
|
|
2491
|
-
`),1;let c=
|
|
2492
|
-
`),0}async function
|
|
2493
|
-
`),2;let o=await n(i.rest);return o!==0||i.request===void 0?o:
|
|
2494
|
-
`).length})),i({status:"ok",data:{text:l.trim()||"(empty response)"}});return}i({status:"error",code:u??1,message:c.trim()||`lmctl prompt exited with code ${u}`})})})}function
|
|
2495
|
-
`}async function
|
|
2567
|
+
`),1;if(y0(l))return t.stderr.write(`error: --save-script: ${a} did not return a script (looks like an HTML page, not lmscript)
|
|
2568
|
+
`),1;let c=p0(n);u0(c,{recursive:!0});let u=g0(c,`.save-script-${process.pid}-${Date.now()}.tmp`);return f0(u,l,"utf8"),m0(u,n),t.stdout.write(`Saved ${a} to ${n}
|
|
2569
|
+
`),0}async function E0(t,e,r,n,s={}){let i=gE(r,e,s);if(i.error!==void 0)return t.stderr.write(`error: ${i.error}
|
|
2570
|
+
`),2;let o=await n(i.rest);return o!==0||i.request===void 0?o:_E(t,i.request)}var _0,hE,Co=k(()=>{"use strict";As();_0="https://lmctl.com/lmscript/commands",hE=/^[A-Za-z0-9._-]+$/});var Rs,A2,kd=k(()=>{"use strict";Rs=[{name:"lmctl_chat",description:"Synchronous/blocking backup: send one prompt to a member of an AI-managed .lmctl team \u2014 addressed by teamfile path (team) and alias \u2014 and return the reply. This is the only MCP tool lmctl exposes. Prefer the CLI for normal delegation. For async or long-running work, use the provider or host runtime background/task surface around the blocking command.",inputSchema:{type:"object",properties:{team:{type:"string",description:"Path to .lmctl teamfile"},alias:{type:"string",description:"Target alias; omitted means Lead"},prompt:{type:"string",description:"Prompt text to send"}},required:["team","prompt"]},local:!0}],A2=Rs.length});import{spawn as T0}from"node:child_process";async function EE(t,e,r){let n=v0.get(t);if(n===void 0)return{status:"error",code:404,message:`unknown tool: ${t}`};let s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};for(let i of n.inputSchema.required??[])if(s[i]===void 0)return{status:"error",code:400,message:`missing required parameter: ${i}`};return S0(n.name,s)}function S0(t,e){return t==="lmctl_chat"?b0(e):{status:"error",code:404,message:`unknown local tool: ${t}`}}function b0(t){let e=typeof t.prompt=="string"?t.prompt:"";if(e.length===0)return Promise.resolve({status:"error",code:400,message:"missing required parameter: prompt"});let r=typeof t.team=="string"?t.team:"";if(r.length===0)return Promise.resolve({status:"error",code:400,message:"missing required parameter: team"});let n=typeof t.alias=="string"&&t.alias.length>0?t.alias:"Lead",s=["prompt",r,n,e];return z()&&Ee(JSON.stringify({event:"mcp_chat_spawn",team:r,alias:n})),I0(s,process.cwd())}function I0(t,e){return new Promise(r=>{let n=!1,s,i=u=>{n||(n=!0,s!==void 0&&clearTimeout(s),r(u))},o=T0("lmctl",t,{cwd:e,env:process.env,stdio:["ignore","pipe","pipe"]}),a=x0(process.env);s=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}i({status:"error",code:124,message:`lmctl prompt timed out after ${a}ms`})},a),s.unref?.();let l="",c="";o.stdout?.on("data",u=>{l+=u.toString("utf8")}),o.stderr?.on("data",u=>{c+=u.toString("utf8")}),o.on("error",u=>{i({status:"error",code:1,message:`failed to spawn lmctl prompt: ${u.message}`})}),o.on("exit",u=>{if(u===0){z()&&Ee(JSON.stringify({event:"mcp_chat_payload",bytes:Buffer.byteLength(l,"utf8"),lines:l.split(`
|
|
2571
|
+
`).length})),i({status:"ok",data:{text:l.trim()||"(empty response)"}});return}i({status:"error",code:u??1,message:c.trim()||`lmctl prompt exited with code ${u}`})})})}function x0(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return yE;let r=Number(e);return!Number.isFinite(r)||r<=0?yE:r}function Ad(t,e=process.env){let n=t.getConfig("api.url")??(e.LMCTL_API_URL!==void 0&&e.LMCTL_API_URL.length>0?e.LMCTL_API_URL:w0),s=t.getConfig("api.token"),i=e.LMCTL_API_TOKEN!==void 0&&e.LMCTL_API_TOKEN.length>0?e.LMCTL_API_TOKEN:s;return{baseUrl:n,token:i}}var w0,yE,v0,Rd=k(()=>{"use strict";kd();V();w0="http://127.0.0.1:8787",yE=30*60*1e3,v0=new Map(Rs.map(t=>[t.name,t]))});async function N0(t,e){let r=t.id===void 0,n=t.id??null;if(t.method==="exit")return r||e.io.write(Nd({jsonrpc:"2.0",id:n,result:null})),{kind:"exit"};if(t.method==="initialize")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{protocolVersion:k0,capabilities:{tools:{listChanged:!1}},serverInfo:{name:A0,version:R0}}}};if(t.method==="notifications/initialized")return{kind:"notification"};if(t.method==="shutdown")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:null}};if(t.method==="tools/list")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{tools:Rs.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema}))}}};if(t.method==="tools/call"){let s=t.params!==null&&typeof t.params=="object"?t.params:{},i=typeof s.name=="string"?s.name:"",o=s.arguments,a=await EE(i,o,e.dispatch),l=i==="lmctl_chat"&&a.status==="ok"&&a.data!==null&&typeof a.data=="object"&&typeof a.data.text=="string"?a.data.text:JSON.stringify(a);return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{isError:a.status==="error",content:[{type:"text",text:l}]}}}}return r?{kind:"notification"}:{kind:"response",message:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`method not found: ${t.method}`}}}}function Nd(t){return`${JSON.stringify(t)}
|
|
2572
|
+
`}async function TE(t,e){let r=!1,n="",s=!1,i=async o=>{let a=o.trim();if(a.length===0)return;let l;try{l=JSON.parse(a)}catch(u){t.io.write(Nd({jsonrpc:"2.0",id:null,error:{code:-32700,message:`parse error: ${u instanceof Error?u.message:String(u)}`}}));return}l.method==="shutdown"&&(r=!0);let c=await N0(l,t);c.kind==="response"?t.io.write(Nd(c.message)):c.kind==="exit"&&(s=!0)};return new Promise(o=>{let a=Promise.resolve(),l=!1,c=d=>{l||(l=!0,o(d))},u=()=>{let d=n.indexOf(`
|
|
2496
2573
|
`);for(;d!==-1;){let m=n.slice(0,d);n=n.slice(d+1),a=a.then(()=>i(m)).then(()=>{s&&c(0)}),d=n.indexOf(`
|
|
2497
2574
|
`)}};e.setEncoding("utf8"),e.on("data",d=>{n+=d,u()}),e.on("end",()=>{n.trim().length>0&&(a=a.then(()=>i(n))),a.finally(()=>c(0))}),e.on("error",d=>{t.io.log?.(`mcp: stdin error: ${d.message}
|
|
2498
|
-
`),a.finally(()=>c(1))})})}var
|
|
2499
|
-
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??
|
|
2575
|
+
`),a.finally(()=>c(1))})})}var k0,A0,R0,wE=k(()=>{"use strict";kd();Rd();k0="2025-06-18",A0="lmctl",R0="0.0.1"});var SE={};oe(SE,{runMcp:()=>C0});async function C0(t,e={stdout:process.stdout,stderr:process.stderr},r=process.stdin){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(L0),0;if(t.length>0)return e.stderr.write(`usage: lmctl mcp
|
|
2576
|
+
`),2;L({event:"mcp_bridge_start",pid:process.pid});let n=e.dal===void 0,s=e.dal??O0(),i=1;try{let o=s===void 0?Ad({getConfig:()=>null},process.env):Ad(s,process.env);return i=await TE({io:{write:l=>e.stdout.write(l),log:l=>e.stderr.write(l)},dispatch:{config:o,...s!==void 0?{dal:s}:{}}},r),i}finally{L({event:"mcp_bridge_exit",pid:process.pid,exit_code:i}),n&&s!==void 0&&s.close()}}function O0(){let t=pe(),e=3;for(let r=1;r<=e;r+=1)try{return it({path:t})}catch(n){let s=n instanceof Error?n.message:String(n);if(L({event:"mcp_bridge_db_open_failed",pid:process.pid,attempt:r,db_path:t,error_message:s}),r<e&&vE(s))D0(50*r);else if(!vE(s))break}}function vE(t){return/SQLITE_BUSY|database is locked|database is busy/i.test(t)}function D0(t){let e=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(e,0,0,t)}var L0,bE=k(()=>{"use strict";Jt();Rd();wE();V();ct();L0=`usage: lmctl mcp
|
|
2500
2577
|
|
|
2501
2578
|
Start the stdio MCP bridge. The bridge resolves api.url and api.token from
|
|
2502
2579
|
local config, then uses stdin/stdout for JSON-RPC frames.
|
|
2503
|
-
`});function
|
|
2504
|
-
`),0;let r=ae(t,["--lines","--max-bytes","--watch-interval","--provider","--session","--run","--since"],["--watch","--help","--json"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=W(r,"--since"),i=
|
|
2505
|
-
`),c={kind:"bytes",maxBytes:p}}let u=X(r,"--watch"),d=W(r,"--watch-interval"),m=d===void 0?
|
|
2506
|
-
`)}},T=setInterval(()=>{_()},m*1e3),E=()=>{clearInterval(T),p(0)};process.once("SIGINT",E),process.once("SIGTERM",E)}):0}async function
|
|
2580
|
+
`});function IE(t,e){if(t===void 0)return{date:void 0};let r=/^(\d+)([smhd])$/.exec(t);if(r!==null){let s=Number(r[1]),i=r[2],o=i==="s"?s:i==="m"?s*60:i==="h"?s*3600:s*86400;return{date:new Date(Date.now()-o*1e3)}}let n=Date.parse(t);return Number.isFinite(n)?{date:new Date(n)}:{error:`invalid ${e} "${t}" (expected ISO8601 or duration like 24h)`}}var xE=k(()=>{"use strict"});var $E={};oe($E,{applyMaxBytes:()=>Mo,parseTailSince:()=>DE,renderMessage:()=>OE,runTail:()=>U0});async function U0(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${P0}
|
|
2581
|
+
`),0;let r=ae(t,["--lines","--max-bytes","--watch-interval","--provider","--session","--run","--since"],["--watch","--help","--json"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=W(r,"--since"),i=DE(s);if("error"in i)return A(e,i.error);let o=i.date,a=W(r,"--lines"),l=W(r,"--max-bytes");if(a!==void 0&&l!==void 0)return A(e,"--lines and --max-bytes are mutually exclusive (choose one)");let c;if(a!==void 0){let p=Number.parseInt(a,10);if(!Number.isFinite(p)||p<1||String(p)!==a)return A(e,`invalid --lines "${a}" (expected a positive integer)`);c={kind:"lines",lines:p}}else{let p=l===void 0?$0:Number.parseInt(l,10);if(!Number.isFinite(p)||p<0||l!==void 0&&String(p)!==l)return A(e,`invalid --max-bytes "${l}" (expected a non-negative integer)`);n&&l!==void 0&&e.stderr.write(`warning: --max-bytes has no effect under --json (byte-truncation has no JSON analog); ignoring
|
|
2582
|
+
`),c={kind:"bytes",maxBytes:p}}let u=X(r,"--watch"),d=W(r,"--watch-interval"),m=d===void 0?F0:Number.parseInt(d.replace(/s$/,""),10);if(!Number.isFinite(m)||m<1)return A(e,`invalid --watch-interval "${d}" (expected <N>s, N\u22651)`);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected [target] [alias]`);let f=W(r,"--run");if(f!==void 0){if(r.positionals.length>0)return A(e,"--run is mutually exclusive with positional [target] [alias]");if(W(r,"--session")!==void 0)return A(e,"--run is mutually exclusive with --session");if(W(r,"--provider")!==void 0)return A(e,"--run is mutually exclusive with --provider");let p=Number.parseInt(f,10);if(!Number.isFinite(p)||p<=0||String(p)!==f)return A(e,`invalid --run "${f}" (expected a positive integer run id)`);try{return await C(e,async _=>j0(e,_,p,c,u,m,o,n))}catch(_){return ze(e,_)}}let g=ut(M0,{target:r.positionals[0],alias:r.positionals[1],flags:{session:W(r,"--session"),provider:W(r,"--provider")}});if(g.mode==="error")return A(e,g.message);if(g.mode==="managed")return A(e,"tail managed mode requires --run <id>");let y;if(g.mode==="ai-team")if(g.alias===void 0){let p;try{p=await C(e,E=>he(g.teamfile,E))}catch(E){return A(e,`tail: ${E instanceof Error?E.message:String(E)}`)}let _;try{_=Ne(p)}catch(E){return A(e,`tail: ${E instanceof Error?E.message:String(E)}`)}let T=Bt(_);if(T===void 0)return A(e,`tail: ${g.teamfile} has no Lead member; pass <tf>:<alias>`);try{let E=await C(e,S=>me(g.teamfile,T.alias,S));y={provider:E.provider,sessionId:E.sessionid,cwd:E.sessiondir}}catch(E){return E instanceof ne?A(e,E.message):ze(e,E)}}else try{let p=await C(e,_=>me(g.teamfile,g.alias,_));y={provider:p.provider,sessionId:p.sessionid,cwd:p.sessiondir}}catch(p){return p instanceof ne?A(e,p.message):ze(e,p)}else{let p=g.sessionid,_=g.provider;if(_===void 0){let T=await un(p);if(T.length===0)return A(e,`tail: session "${p}" not found in any provider store`);if(T.length>1)return A(e,`tail: session "${p}" matches multiple providers (${T.join(", ")}); pass --provider`);_=T[0]}y={provider:_,sessionId:p}}let h=await kE(e,y.provider,y.sessionId,c,-1,o,n);return h===Do?1:u?await new Promise(p=>{let _=async()=>{try{let S=await kE(e,y.provider,y.sessionId,c,h,o,n);S!==Do&&(h=S)}catch(S){e.stderr.write(`tail: ${S instanceof Error?S.message:String(S)}
|
|
2583
|
+
`)}},T=setInterval(()=>{_()},m*1e3),E=()=>{clearInterval(T),p(0)};process.once("SIGINT",E),process.once("SIGTERM",E)}):0}async function kE(t,e,r,n,s,i,o){let a;try{a=await Re(r,e)}catch(m){return t.stderr.write(`tail: failed to load session: ${m instanceof Error?m.message:String(m)}
|
|
2507
2584
|
`),Do}if(a===null)return t.stderr.write(`tail: session not found: ${r} (provider=${e})
|
|
2508
|
-
`),Do;let l=a.messages??[],c=s<0&&n.kind==="lines"?Math.max(0,l.length-n.lines):s+1;if(s<0&&i!==void 0){let m=i.getTime(),f=l.length;for(let g=0;g<l.length;g+=1){let y=l[g].timestamp,h=y===void 0?NaN:(y instanceof Date?y:new Date(y)).getTime();if(!Number.isNaN(h)&&h>=m){f=g;break}}c=Math.max(c,f)}let u=s<0&&c>0;if(c>=l.length)return o===!0&&s<0&&se(t,{schema_version:Oo,provider:e,sessionId:r,messages:[],truncated:u}),l.length-1;if(o===!0){let m=l.slice(c).map(g=>({role:g.role,content:g.content,model:g.model??null,timestamp:(g.timestamp instanceof Date?g.timestamp:new Date(g.timestamp)).toISOString()}));return se(t,{schema_version:Oo,provider:e,sessionId:r,messages:m,truncated:u}),l.length-1}let d="";for(let m=c;m<l.length;m+=1)d+=`${
|
|
2509
|
-
`;return t.stdout.write(n.kind==="bytes"?Mo(d,n.maxBytes):d),l.length-1}function
|
|
2585
|
+
`),Do;let l=a.messages??[],c=s<0&&n.kind==="lines"?Math.max(0,l.length-n.lines):s+1;if(s<0&&i!==void 0){let m=i.getTime(),f=l.length;for(let g=0;g<l.length;g+=1){let y=l[g].timestamp,h=y===void 0?NaN:(y instanceof Date?y:new Date(y)).getTime();if(!Number.isNaN(h)&&h>=m){f=g;break}}c=Math.max(c,f)}let u=s<0&&c>0;if(c>=l.length)return o===!0&&s<0&&se(t,{schema_version:Oo,provider:e,sessionId:r,messages:[],truncated:u}),l.length-1;if(o===!0){let m=l.slice(c).map(g=>({role:g.role,content:g.content,model:g.model??null,timestamp:(g.timestamp instanceof Date?g.timestamp:new Date(g.timestamp)).toISOString()}));return se(t,{schema_version:Oo,provider:e,sessionId:r,messages:m,truncated:u}),l.length-1}let d="";for(let m=c;m<l.length;m+=1)d+=`${OE(l[m])}
|
|
2586
|
+
`;return t.stdout.write(n.kind==="bytes"?Mo(d,n.maxBytes):d),l.length-1}function OE(t){let e=ME(t.timestamp),r=e?`${e} ${t.role}`:t.role,s=(t.content??"").replace(/\r\n/g,`
|
|
2510
2587
|
`).replace(/\r/g,`
|
|
2511
2588
|
`).split(`
|
|
2512
2589
|
`),i=s[0]??"",o=s.slice(1);return o.length===0?`${r}: ${i}`:`${r}: ${i}
|
|
2513
2590
|
${o.map(a=>` ${a}`).join(`
|
|
2514
|
-
`)}`}function
|
|
2515
|
-
`).join("");t.stdout.write(n.kind==="bytes"?Mo(m,n.maxBytes):m)}let d=c.length>0?c[c.length-1].id:0;return s?await new Promise(m=>{let g=setInterval(()=>{try{let h=e.listSessionEvents(r,d);if(h.length===0)return;for(let _ of h)d=_.id;if(a===!0){se(t,{schema_version:Oo,run_id:r,truncated:!1,events:
|
|
2591
|
+
`)}`}function AE(t){return t.map(e=>({id:e.id,kind:e.kind,step_id:e.step_id,timestamp:new Date(e.timestamp_ms).toISOString(),payload:e.payload}))}async function j0(t,e,r,n,s,i,o,a){if(e.getRun(r)===null)return A(t,`tail: run ${r}: not found`);let c=o===void 0?e.listSessionEvents(r):e.listSessionEvents(r).filter(m=>m.timestamp_ms>=o.getTime()),u=n.kind==="lines"?c.slice(Math.max(0,c.length-n.lines)):c;if(a===!0)se(t,{schema_version:Oo,run_id:r,truncated:u.length<c.length,events:AE(u)});else{let m=u.map(f=>`${LE(f)}
|
|
2592
|
+
`).join("");t.stdout.write(n.kind==="bytes"?Mo(m,n.maxBytes):m)}let d=c.length>0?c[c.length-1].id:0;return s?await new Promise(m=>{let g=setInterval(()=>{try{let h=e.listSessionEvents(r,d);if(h.length===0)return;for(let _ of h)d=_.id;if(a===!0){se(t,{schema_version:Oo,run_id:r,truncated:!1,events:AE(h)});return}let p=h.map(_=>`${LE(_)}
|
|
2516
2593
|
`).join("");t.stdout.write(n.kind==="bytes"?Mo(p,n.maxBytes):p)}catch(h){t.stderr.write(`tail: ${h instanceof Error?h.message:String(h)}
|
|
2517
|
-
`)}},i*1e3),y=()=>{clearInterval(g),m(0)};process.once("SIGINT",y),process.once("SIGTERM",y)}):0}function Mo(t,e){if(e===0||Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.byteLength(
|
|
2594
|
+
`)}},i*1e3),y=()=>{clearInterval(g),m(0)};process.once("SIGINT",y),process.once("SIGTERM",y)}):0}function Mo(t,e){if(e===0||Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.byteLength(RE,"utf8");if(n>=e)return NE(t,e);let s=e-n,i=NE(t,s);return`${RE}${i}`}function NE(t,e){if(e<=0)return"";let r=Buffer.from(t,"utf8"),n=Math.max(0,r.length-e);for(;n<r.length&&(r[n]&192)===128;)n+=1;return r.subarray(n).toString("utf8")}function LE(t){let e=ME(new Date(t.timestamp_ms))??"",r="";try{let i=JSON.parse(t.payload);typeof i.alias=="string"&&(r=`alias=${i.alias}`),typeof i.provider=="string"&&(r+=`${r?" ":""}provider=${i.provider}`),typeof i.tool=="string"&&(r+=`${r?" ":""}tool=${i.tool}`),typeof i.status=="string"&&(r+=`${r?" ":""}status=${i.status}`),(typeof i.tokens_in=="number"||typeof i.tokens_out=="number")&&(r+=`${r?" ":""}tokens=${i.tokens_in??0}/${i.tokens_out??0}`)}catch{}let n=r!==""?r:t.payload.slice(0,200),s=t.step_id===null?"":` step=${t.step_id}`;return`${e} ${t.kind}${s}: ${n}`}function DE(t){return IE(t,"--since")}function ME(t){if(t===void 0)return;let e=(0,CE.formatLocalTimestamp)(t);return e==="unknown"?void 0:e}var CE,M0,$0,F0,Oo,P0,Do,RE,FE=k(()=>{"use strict";ar();CE=It(gt(),1);ge();We();kt();At();xE();M0={name:"tail",allowsBareTeamfile:!0,supportsRaw:!0},$0=4096,F0=2,Oo=1,P0=`usage: lmctl tail [target] [alias]
|
|
2518
2595
|
lmctl tail --session <id> [--provider <name>]
|
|
2519
2596
|
lmctl tail --run <id>
|
|
2520
2597
|
[--lines N | --max-bytes N] [--since <duration|ISO8601>]
|
|
@@ -2541,12 +2618,12 @@ everything new by construction. --max-bytes has no JSON analog and is
|
|
|
2541
2618
|
ignored under --json (a stderr note is printed if you passed it
|
|
2542
2619
|
explicitly); --lines still applies. --watch --json emits one JSON
|
|
2543
2620
|
object per poll tick with something new (NDJSON) -- a tick with
|
|
2544
|
-
nothing new prints no line at all, same as text mode.`;Do=-2;
|
|
2545
|
-
`});var
|
|
2621
|
+
nothing new prints no line at all, same as text mode.`;Do=-2;RE=`\u2026 [truncated older output \u2014 raise with --max-bytes]
|
|
2622
|
+
`});var UE={};oe(UE,{runExport:()=>B0});async function B0(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(PE),0;let r=ae(t,[],["--prompt-only"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length!==2)return A(e,PE.trimEnd());let n;try{n=me(r.positionals[0],r.positionals[1],e.dal)}catch(a){return a instanceof ne?A(e,a.message):ze(e,a)}let s;try{s=await Re(n.sessionid,n.provider)}catch(a){return A(e,`export: failed to load session: ${a instanceof Error?a.message:String(a)}`)}if(s===null)return A(e,`export: session not found: ${n.sessionid} (provider=${n.provider})`);let i=X(r,"--prompt-only"),o=[];if(i){let a=s.userPrompts??s.messages.filter(l=>l.role==="user").map(l=>l.content);for(let l of a){if(l.trimStart().replace(/^["']/u,"").startsWith("lmctl seed initial connection only. Create or pin this provider session, then stop."))continue;let c=l.split(/\r\n|[\r\n\u2028\u2029]/u).map(u=>u.trim()).filter(Boolean).join(" ");c!==""&&o.push(c)}}else for(let a of s.messages)a.role!=="user"&&a.role!=="assistant"||a.content.trim()!==""&&o.push(`${a.role}:
|
|
2546
2623
|
${a.content}`);return o.length>0&&e.stdout.write(`${o.join(`
|
|
2547
2624
|
|
|
2548
2625
|
`)}
|
|
2549
|
-
`),0}var
|
|
2626
|
+
`),0}var PE,jE=k(()=>{"use strict";ar();ge();We();PE=`usage: lmctl export <teamfile> <alias> [--prompt-only]
|
|
2550
2627
|
|
|
2551
2628
|
Export all user and assistant messages from a member's provider session.
|
|
2552
2629
|
Messages retain their formatting, with role labels and a blank line between
|
|
@@ -2555,8 +2632,8 @@ messages. No timestamps, tool activity, or truncation.
|
|
|
2555
2632
|
context, one paragraph per prompt with a blank line between prompts.
|
|
2556
2633
|
Codex prompts require native prompt metadata or user_message events;
|
|
2557
2634
|
unclassified user-role records are omitted in this compact mode.
|
|
2558
|
-
`});var
|
|
2559
|
-
`),0;let r=ae(t,["--provider"],["--json"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <target> [alias]`);let n=X(r,"--json"),s=ut(
|
|
2635
|
+
`});var BE={};oe(BE,{runCost:()=>G0});function H0(t,e,r,n){let s=new Set,i=[];for(let o of e){let a=r===null?null:fo(t,o,r,n),l=a?.kind==="priced"||a?.kind==="estimated"?`id:${a.model.normalizedId}`:a?.kind==="known-unpriced"?`id:${a.id}`:`raw:${o.trim().toLowerCase()}`;s.has(l)||(s.add(l),i.push(o))}return i}async function G0(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${q0}
|
|
2636
|
+
`),0;let r=ae(t,["--provider"],["--json"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <target> [alias]`);let n=X(r,"--json"),s=ut(W0,{target:r.positionals[0],alias:r.positionals[1],flags:{provider:W(r,"--provider")}});if(s.mode==="error")return A(e,s.message);if(s.mode==="managed")return A(e,"cost: managed-run targets are not supported (no per-run token/model rollup exists)");let i,o;if(s.mode==="ai-team")try{let I=await C(e,R=>me(s.teamfile,s.alias,R));i=I.provider,o=I.sessionid}catch(I){if(I instanceof ne)return A(e,I.message);throw I}else if(o=s.sessionid,s.provider!==void 0)i=s.provider;else{let I=await un(o);if(I.length===0)return A(e,`cost: session "${o}" not found in any provider store`);if(I.length>1)return A(e,`cost: session "${o}" matches multiple providers (${I.join(", ")}); pass --provider`);i=I[0]}let a;try{a=await Re(o,i)}catch(I){return A(e,`cost: failed to load session: ${I instanceof Error?I.message:String(I)}`)}if(a===null)return A(e,`cost: session not found: ${o} (provider=${i})`);let l=[...new Set(a.messages.map(I=>I.model).filter(I=>I!==void 0&&I!=="<synthetic>"))],c=[...a.messages].reverse().find(I=>I.model!==void 0&&I.model!=="<synthetic>")?.model,u=a.model??c??null,d={input:a.totalInputTokens??null,output:a.totalOutputTokens??null,cachedInput:a.totalCachedInputTokens??null},m=await uo(),f=H0(i,l,m.catalog,m.aliases),g=f.length>1,y="unavailable",h=null,p=null,_=null,T=null,E=!1,S=null,w=null;if(u!==null&&m.catalog!==null){let I=__(i,u,m.catalog,m.aliases);if(y=I.state.kind,I.offer!==null)w=I.offer.pricing,h=I.offer.route,p=I.offer.source,_=I.offer.sourceModelId,T=I.provenance,E=I.offer.estimated;else switch(I.state.kind){case"unresolved":S=`alias "${I.state.alias}" is deliberately unresolved in the lmprice alias table`;break;case"known-unpriced":S=`"${I.state.id}" is a known model with no published price row`;break;case"unknown":S=`model "${u}" not found in lmprice catalog for provider "${i}"`;break;case"wrong-provider":S=`model "${u}" is not offered by provider "${i}" (found under: ${I.state.otherProviders.join(", ")})`;break;default:S=`no lmprice catalog coverage for provider "${i}"`;break}}else u!==null&&(S="lmprice catalog unavailable");let b=w===null?null:{inputPer1m:w.input_per_1m_tokens,outputPer1m:w.output_per_1m_tokens,cachedInputPer1m:w.input_cache_read_per_1m_tokens},v=d.input===null||d.output===null?null:o_({input:d.input,output:d.output,cachedInput:d.cachedInput??0},w),x={schema_version:X0,provider:i,sessionId:o,model:u,modelsUsed:f,approximate:g,tokens:d,pricePerModel:b,costUsd:v,priceResolution:y,priceRoute:h,priceSource:p,priceSourceModelId:_,priceProvenance:T,priceEstimated:E,costUnavailableReason:S,priceDataSource:m.source,priceDataGeneratedAt:m.generatedAt};return n?(se(e,x),0):(e.stdout.write(`Session: ${o}
|
|
2560
2637
|
`),e.stdout.write(` Provider: ${i}
|
|
2561
2638
|
`),e.stdout.write(` Model: ${u??"(unknown)"}
|
|
2562
2639
|
`),g&&e.stdout.write(` NOTE: this session used multiple models (${f.join(", ")}) -- cost below is approximate, priced at ${u}'s rate for the whole session.
|
|
@@ -2565,7 +2642,7 @@ unclassified user-role records are omitted in this compact mode.
|
|
|
2565
2642
|
`):e.stdout.write(` Cost: ~$${v.toFixed(4)}${g?" (approximate)":""}${E?" (estimated rate)":""}
|
|
2566
2643
|
`),h!==null&&e.stdout.write(` Price route: ${h}${E?" (manual/estimated row)":""}
|
|
2567
2644
|
`),e.stdout.write(` Price data: ${m.source}${m.generatedAt?` (generated ${m.generatedAt})`:""}
|
|
2568
|
-
`),0)}var $o,
|
|
2645
|
+
`),0)}var $o,W0,X0,q0,WE=k(()=>{"use strict";ar();$o=It(gt(),1);Hc();Jc();ge();We();W0={name:"cost",allowsBareTeamfile:!1,supportsRaw:!0};X0=1,q0=`usage: lmctl cost <target> [alias] [--json]
|
|
2569
2646
|
lmctl cost <sessionid> [--provider <name>]
|
|
2570
2647
|
|
|
2571
2648
|
Estimate a session's dollar cost: aggregate token usage x the model's
|
|
@@ -2588,24 +2665,24 @@ unavailable) and
|
|
|
2588
2665
|
\`priceDataGeneratedAt\` says how fresh it is -- the online check has a
|
|
2589
2666
|
strict short timeout and NEVER blocks or fails this command: any network
|
|
2590
2667
|
error degrades silently to the local cache, then the bundled built-in
|
|
2591
|
-
copy, in that order.`});var
|
|
2592
|
-
`),0;let r=ae(t,["--provider","--sessiondir","--format","--limit"],["--recursive","--all","--json","--runs","--help"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>0)return A(e,"ls does not accept positional targets (use --provider/--sessiondir/--all to filter)");let n=W(r,"--format"),s=X(r,"--json");if(X(r,"--runs")){for(let h of["--provider","--sessiondir"])if(W(r,h)!==void 0)return A(e,`--runs is mutually exclusive with ${h}`);for(let h of["--recursive","--all"])if(X(r,h))return A(e,`--runs is mutually exclusive with ${h}`);if(n==="teamfile")return A(e,"--runs is mutually exclusive with --format teamfile (runs are not teamfile members)");let f=W(r,"--limit"),g=
|
|
2668
|
+
copy, in that order.`});var XE={};oe(XE,{runLs:()=>Y0});import{resolve as Ld}from"node:path";function K0(t){let e=new Map;for(let r of t){let n=`${r.provider}:${r.sessionId}`,s=e.get(n);(s===void 0||r.modifiedAt.getTime()>s.modifiedAt.getTime())&&e.set(n,r)}return[...e.values()]}async function Y0(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${J0}
|
|
2669
|
+
`),0;let r=ae(t,["--provider","--sessiondir","--format","--limit"],["--recursive","--all","--json","--runs","--help"]);if(r.error!==void 0)return A(e,r.error);if(r.positionals.length>0)return A(e,"ls does not accept positional targets (use --provider/--sessiondir/--all to filter)");let n=W(r,"--format"),s=X(r,"--json");if(X(r,"--runs")){for(let h of["--provider","--sessiondir"])if(W(r,h)!==void 0)return A(e,`--runs is mutually exclusive with ${h}`);for(let h of["--recursive","--all"])if(X(r,h))return A(e,`--runs is mutually exclusive with ${h}`);if(n==="teamfile")return A(e,"--runs is mutually exclusive with --format teamfile (runs are not teamfile members)");let f=W(r,"--limit"),g=V0;if(f!==void 0){let h=Number.parseInt(f,10);if(!Number.isFinite(h)||h<1||String(h)!==f)return A(e,`invalid --limit "${f}" (expected a positive integer)`);if(h>HE)return A(e,`--limit ${h} exceeds maximum (${HE})`);g=h}let y=n==="json"||s===!0?"json":"table";try{return await C(e,async h=>z0(e,h,g,y))}catch(h){return ze(e,h)}}let o=Q0(n,s);if("error"in o)return A(e,o.error);let a=o.format,l=W(r,"--provider"),c=W(r,"--sessiondir"),u=X(r,"--recursive"),d=X(r,"--all"),m;try{m=await os(l?{provider:l}:{})}catch(f){return A(e,`ls: discovery failed: ${f instanceof Error?f.message:String(f)}`)}if(!d){let f=c!==void 0?Ld(c):Ld(process.cwd());m=m.filter(g=>{let y=Ld(g.cwd);return u?y===f||y.startsWith(`${f}/`):y===f})}if(m=K0(m),a==="json")return se(e,m.map(f=>({provider:f.provider,sessionId:f.sessionId,cwd:f.cwd,messageCount:f.messageCount,modifiedAt:f.modifiedAt.toISOString(),...f.model!==void 0?{model:f.model}:{}}))),0;if(m.length===0){if(a==="table"){let f=d?"(all)":c??process.cwd(),g=u?"under":"in";e.stdout.write(`No native sessions found ${g} ${f}.
|
|
2593
2670
|
`)}return 0}if(a==="teamfile"){for(let f of m)e.stdout.write(`_MEMBER_ alias=- provider=${f.provider} sessionid=${f.sessionId} sessiondir=${f.cwd}
|
|
2594
|
-
`);return 0}return(0,Me.printTable)(m.map(f=>[(0,Me.escapeCell)(f.sessionId),(0,Me.escapeCell)(f.provider),(0,Me.escapeCell)(f.cwd.length>36?`\u2026${f.cwd.slice(-35)}`:f.cwd),(0,Me.formatRelativeTime)(f.modifiedAt)]),{headers:["SESSION","PROVIDER","SESSIONDIR","MODIFIED"],stream:e.stdout}),0}async function
|
|
2595
|
-
`),0):((0,Me.printTable)(s.map(i=>[(0,Me.escapeCell)(i.id),(0,Me.escapeCell)(i.workflow_id),(0,Me.escapeCell)(i.team_id),(0,Me.escapeCell)(i.current_state??""),(0,Me.escapeCell)(i.terminal_state??""),(0,Me.escapeCell)(i.started_at)]),{headers:["RUN_ID","WORKFLOW","TEAM","STATE","TERMINAL","STARTED"],stream:t.stdout}),0)}function
|
|
2671
|
+
`);return 0}return(0,Me.printTable)(m.map(f=>[(0,Me.escapeCell)(f.sessionId),(0,Me.escapeCell)(f.provider),(0,Me.escapeCell)(f.cwd.length>36?`\u2026${f.cwd.slice(-35)}`:f.cwd),(0,Me.formatRelativeTime)(f.modifiedAt)]),{headers:["SESSION","PROVIDER","SESSIONDIR","MODIFIED"],stream:e.stdout}),0}async function z0(t,e,r,n){let s=$y(e,{limit:r});return n==="json"?(se(t,s.map(i=>({id:i.id,job_id:i.job_id,workflow_id:i.workflow_id,team_id:i.team_id,current_state:i.current_state,terminal_state:i.terminal_state,started_at:i.started_at,ended_at:i.ended_at,paused_at:i.paused_at}))),0):s.length===0?(t.stdout.write(`No runs found.
|
|
2672
|
+
`),0):((0,Me.printTable)(s.map(i=>[(0,Me.escapeCell)(i.id),(0,Me.escapeCell)(i.workflow_id),(0,Me.escapeCell)(i.team_id),(0,Me.escapeCell)(i.current_state??""),(0,Me.escapeCell)(i.terminal_state??""),(0,Me.escapeCell)(i.started_at)]),{headers:["RUN_ID","WORKFLOW","TEAM","STATE","TERMINAL","STARTED"],stream:t.stdout}),0)}function Q0(t,e){return t===void 0?{format:e?"json":"teamfile"}:t==="table"||t==="teamfile"||t==="json"?{format:t}:{error:`invalid --format "${t}" (expected: table | teamfile | json)`}}var Me,J0,V0,HE,qE=k(()=>{"use strict";Me=It(gt(),1);Ct();ge();hd();J0=`usage: lmctl ls [--provider <name>] [--sessiondir <path>]
|
|
2596
2673
|
[--recursive] [--all] [--format table|teamfile|json] [--json]
|
|
2597
2674
|
lmctl ls --runs [--limit N] [--format table|json] [--json]
|
|
2598
2675
|
|
|
2599
|
-
List native provider sessions in scope, or list recent managed runs with --runs.`,
|
|
2676
|
+
List native provider sessions in scope, or list recent managed runs with --runs.`,V0=50,HE=500});var GE={};oe(GE,{runInit:()=>eO});async function eO(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(Z0),0;let n=t.includes("--force"),s=t.find(c=>c!=="--force"&&c!=="--help"&&c!=="-h");if(s!==void 0)return e.stderr.write(`error: unknown argument: ${s}
|
|
2600
2677
|
`),2;let i=r.configPath??Ao(),o=Tn(i);if(o!==null&&!n)return e.stdout.write(`${i} already exists:
|
|
2601
2678
|
|
|
2602
|
-
`),e.stdout.write(Ro(o)),e.stdout.write("\nEdit it directly, or run `lmctl init --force` to regenerate it from what's detected on this machine now (this OVERWRITES your edits).\n"),0;let a=(r.detectProviders??
|
|
2679
|
+
`),e.stdout.write(Ro(o)),e.stdout.write("\nEdit it directly, or run `lmctl init --force` to regenerate it from what's detected on this machine now (this OVERWRITES your edits).\n"),0;let a=(r.detectProviders??sE)(),l=nE(a);return iE(l,i),e.stdout.write(`Wrote ${i}
|
|
2603
2680
|
|
|
2604
2681
|
`),e.stdout.write(Ro(l)),e.stdout.write(`
|
|
2605
2682
|
This is a starting point, not a fixed answer -- edit provider/model1/model2/model3 above before running lmctl plan or lmctl quickrun if it is not right.
|
|
2606
2683
|
`),a.length===0?e.stderr.write(`warning: no supported provider (claude, codex, agy, kimi) was detected on this machine -- using claude as a placeholder for all three slots. Edit the file above to match what you actually have.
|
|
2607
2684
|
`):a.length<3&&e.stderr.write(`notice: only ${a.length} provider${a.length===1?" was":"s were"} detected (${a.join(", ")}) -- duplicated to fill the remaining slot${a.length===1?"s":""}. Spreading slots across different providers (where you have them) balances load, but is never required.
|
|
2608
|
-
`),0}var
|
|
2685
|
+
`),0}var Z0,JE=k(()=>{"use strict";No();Z0=`usage: lmctl init [--force]
|
|
2609
2686
|
|
|
2610
2687
|
Writes ~/.lmctl/init.toml: three provider slots (Provider1/2/3), each
|
|
2611
2688
|
resolved to a provider and a starting model, detected from which provider
|
|
@@ -2623,16 +2700,16 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2623
2700
|
|
|
2624
2701
|
--force Overwrite ~/.lmctl/init.toml if it already exists
|
|
2625
2702
|
-h, --help display help for command
|
|
2626
|
-
`});import{execFileSync as
|
|
2627
|
-
`),Ie({event:"model_ignored",provider:u.provider,model:u.model,reason:u.reason}),r?.(u)}});if(a===null||a.length===0)return A(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(u=>{let d=
|
|
2628
|
-
`),t.stdout.write(`${
|
|
2703
|
+
`});import{execFileSync as tO}from"node:child_process";import{resolve as VE}from"node:path";function rO(t){return t.filter(e=>e.state!=="retired")}function KE(t,e,r){if(r!==void 0){let a=e.findProjectByName(r);return a===null?A(t,`project not found: ${r}`):a}let n=t.cwd??process.cwd(),s;try{s=tO("git",["rev-parse","--show-toplevel"],{cwd:n,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return A(t,"terminal cannot infer a member from cwd because this directory is not in a git repo; use `lmctl terminal <teamfile> <alias>`")}let i=VE(s),o=e.listProjects().find(a=>VE(a.local_path)===i);return o===void 0?A(t,`terminal cannot infer a member from cwd ${i}; use \`lmctl terminal <teamfile> <alias>\``):o}function YE(t,e,r,n){if(n!==void 0){let i=e.findTeamByName(n);return i===null?A(t,`team not found: ${n}`):i}let s=e.getTeam(r.team_id);return s===null?A(t,`project ${r.name} has no assigned team; use --team <name>`):s}function zE(t,e,r,n){if(n!==void 0){let i=e.findTeamMemberByAlias(r.id,n);return i===null||i.state==="retired"?A(t,`member not found: ${n}`):i}let s=rO(e.listTeamMembers(r.id)).find(i=>i.role==="agent");return s===void 0?A(t,`team ${r.name} has no active agent member`):s}var QE=k(()=>{"use strict";ge()});var tT={};oe(tT,{SIZE_WARN_EST_TOKENS:()=>Ns,estimateTokens:()=>eT,runTerminal:()=>Cd});import{spawn as nO}from"node:child_process";import{statSync as sO}from"node:fs";async function Cd(t,e){if(t.includes("--help")||t.includes("-h"))return mO(e);let r=ae(t,["--project","--team","--alias","--run"],["--size","--json","--help"]);if(r.error!==void 0)return A(e,r.error);let n=W(r,"--run");if(n!==void 0){let s=Number.parseInt(n,10);if(!Number.isFinite(s)||s<=0||String(s)!==n)return A(e,`invalid --run "${n}" (expected a positive integer run id)`);if(r.positionals.length>0)return A(e,"--run is mutually exclusive with positional <teamfile>[:alias]");let i=["--team","--project","--size","--json"];for(let o of i)if(o==="--size"||o==="--json"?X(r,o):W(r,o)!==void 0)return A(e,`--run is mutually exclusive with ${o}`);try{return await C(e,async o=>{let a=W(r,"--alias"),l=Dy(o,s,a);return"err"in l?A(e,l.err):Od(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 ze(e,o)}}if(r.positionals.length>0){let s=["--team","--project","--size","--alias"];for(let l of s)if(l==="--size"?X(r,l):W(r,l)!==void 0)return A(e,`positional <teamfile>[:alias] is mutually exclusive with ${l} (alias is the SECOND POSITIONAL: \`terminal <teamfile> <alias>\`).`);if(r.positionals.length>2)return A(e,`too many positionals (${r.positionals.length}); expected <teamfile>[:alias] [alias]`);let i=r.positionals[0],o=r.positionals[1],a=ut(iO,{target:i,alias:o,flags:{}});return a.mode==="error"?A(e,a.message):a.mode!=="ai-team"?A(e,`internal: terminal positional yielded unexpected mode "${a.mode}"`):a.alias===void 0?A(e,"terminal: alias required for the teamfile target"):await C(e,l=>oO(e,a.teamfile,a.alias,l,X(r,"--json")))}try{return await C(e,async s=>{let i=cO(e,s,r);if(typeof i=="number")return i;let o=W(r,"--alias");return X(r,"--size")?uO(e,s,i,o,X(r,"--json")):dO(e,s,i,o)})}catch(s){return ze(e,s)}}async function oO(t,e,r,n,s){let i;try{i=me(e,r,n)}catch(m){return m instanceof ne?A(t,m.message):ze(t,m)}let o=Xt(n,{receiver_teamfile:i.teamfile,receiver_alias:i.alias,sender_teamfile:i.teamfile,sender_alias:"terminal",ttlMs:ft()});if(!o.acquired){let m=o.current.holder_pid,f=m===null?null:Ce(m)?"live":"dead",g=`${i.alias} is busy/held by ${o.current.sender_alias} (${o.current.sender_teamfile}) since ${o.current.started_at} `+(m===null?"(holder_pid=unavailable)":`(holder_pid=${m}, ${f})`);return s?(se(t,{status:"error",errorKind:"busy",message:g,holder_pid:m,holder_liveness:f}),1):A(t,g)}let a=_g({teamfile:i.teamfile,alias:i.alias}),l=null,c=null,u=null,d=[];try{n.setTerminalLock(a),c=aO(n,i),c!==null&&(process.env.LMCTL_INVOCATION_ID=String(c));let m=n.getRootTeam(i.teamfile)?.name??null;m!==null&&(process.env.LMBEE_TEAM_NAME=m),l=setInterval(()=>{try{let f=new Date().toISOString(),g=n.heartbeatTerminalLock(a.teamfile,a.alias,a.lock_id,f);g&&n.heartbeatAgentInflight(o.lease,o.leaseId,f),!g&&l!==null&&(clearInterval(l),l=null)}catch{}},yg()),l.unref?.();try{Hr(t,Ne(i.teamfile),i.teamfile)}catch{}return u=await Od(t,{provider:i.provider,sessionid:i.sessionid,sessiondir:i.sessiondir,...i.model!==void 0?{model:i.model}:{},isLead:i.isLead},f=>{d.push(`${f.provider} terminal ignored model=${f.model}: ${f.reason}`)}),u}finally{l!==null&&clearInterval(l),n.clearTerminalLock(a.teamfile,a.alias,a.lock_id),n.releaseAgentInflight(o.lease,o.leaseId),lO(n,c,u,d)}}function aO(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:Kt(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 lO(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 Od(t,e,r){let{provider:n,sessionid:s,sessiondir:i,model:o}=e;if(!zi(n))return A(t,`no resume incantation for provider "${n}"`);if(!cg.test(s))return A(t,"refusing to resume: malformed sessionid");let a=Ic(n,s,{isLead:e.isLead,model:o,onModelIgnored:u=>{let d=`warning: ${u.provider} terminal ignored model=${u.model}: ${u.reason}`;t.stderr.write(`${d}
|
|
2704
|
+
`),Ie({event:"model_ignored",provider:u.provider,model:u.model,reason:u.reason}),r?.(u)}});if(a===null||a.length===0)return A(t,`no resume incantation for provider "${n}"`);let[l,...c]=a;return await new Promise(u=>{let d=nO(l,c,{stdio:"inherit",cwd:i,env:we(process.env,i,s,"terminal")});d.on("error",m=>{u(A(t,`failed to launch ${l}: ${m.message}`))}),d.on("exit",m=>u(m??0))})}function cO(t,e,r){let n=W(r,"--team");if(n!==void 0){let o=e.findTeamByName(n);return o===null?A(t,`team not found: ${n}`):o}let s=KE(t,e,W(r,"--project"));return typeof s=="number"?s:YE(t,e,s,void 0)}async function dO(t,e,r,n){let s=zE(t,e,r,n);if(typeof s=="number")return s;let i=s.sessionid;return i===null||i.trim().length===0?A(t,`member ${s.alias} has no session yet \u2014 seed it first: lmctl seed <teamfile> (check with lmctl status <teamfile>)`):Od(t,{provider:Ca(s),sessionid:i,sessiondir:s.sessiondir,...s.model!==null&&s.model!==void 0?{model:s.model}:{}})}function eT(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=sO(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 uO(t,e,r,n,s){let i;if(n!==void 0){let a=e.findTeamMemberByAlias(r.id,n);if(a===null||a.state==="retired")return A(t,`member not found: ${n}`);i=[a]}else i=e.listTeamMembers(r.id).filter(a=>a.state!=="retired"&&a.sessionid!==null);let o=[];for(let a of i){let l=a.sessionid;if(l===null)continue;let c=Ca(a),u=a.model??null,d=null;zi(c)&&(d=await Re(l,c));let m=eT(d),f=m.est>Ns;o.push({alias:a.alias,provider:c,sessionid:l,messages:m.messages,bytes:m.bytes,est_tokens:m.est,estimate:!0,over_guide:f,model:u,resume_incantation:f?dg(c,l,u!==null?{model:u}:{}):null})}if(s)return se(t,{estimate:!0,legend:ZE,guide_tokens:Ns,members:o}),0;t.stdout.write(`session size \u2014 ESTIMATE only (nothing is changed automatically)
|
|
2705
|
+
`),t.stdout.write(`${ZE}
|
|
2629
2706
|
`);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)
|
|
2630
2707
|
`),a.over_guide&&t.stdout.write(` \u26A0 ${a.alias}: estimated ~${a.est_tokens} tokens \u2014 ESTIMATE only, exceeds the 200K guide.
|
|
2631
2708
|
Nothing was changed automatically. If you choose to compact, open the
|
|
2632
2709
|
session yourself:
|
|
2633
2710
|
${a.resume_incantation??"(no resume incantation for provider "+a.provider+")"}
|
|
2634
2711
|
(or: lmctl terminal --team ${r.name} --alias ${a.alias})
|
|
2635
|
-
`)}return 0}function
|
|
2712
|
+
`)}return 0}function mO(t){return t.stdout.write(`usage: lmctl terminal <teamfile>:<alias> [--json]
|
|
2636
2713
|
lmctl terminal <teamfile> <alias> [--json]
|
|
2637
2714
|
lmctl terminal --run <id> [--alias A]
|
|
2638
2715
|
lmctl terminal [--project P] [--team T] [--alias A] [--size] [--json]
|
|
@@ -2665,12 +2742,12 @@ what it detected; use --force to overwrite an existing file (without
|
|
|
2665
2742
|
tokens it surfaces the resume incantation so YOU can
|
|
2666
2743
|
open & self-compact. Nothing is ever changed
|
|
2667
2744
|
automatically; ${Ns} is a guide, not a gate.
|
|
2668
|
-
`),0}var
|
|
2745
|
+
`),0}var iO,Ns,ZE,Dd=k(()=>{"use strict";Jt();ar();ge();QE();We();kt();_t();Qs();st();xn();as();pd();V();gr();iO={name:"terminal",allowsBareTeamfile:!1,supportsRaw:!1},Ns=2e5,ZE="est = rough local heuristic (~4 chars/token), NOT an exact provider token count \u2014 open the session to verify before acting."});var nT={};oe(nT,{runQuickrun:()=>TO});import{existsSync as fO,mkdirSync as pO,writeFileSync as hO}from"node:fs";import{basename as gO,dirname as _O,join as rT}from"node:path";function EO(t){let e=gO(t),r=rT(t,`${e}.lmctl`),n=2;for(;fO(r);)r=rT(t,`${e}${n}.lmctl`),n+=1;return r}async function TO(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(yO),0;let n=t.includes("--no-seed"),s=t.includes("--no-terminal"),i=t.filter(h=>h!=="--no-seed"&&h!=="--no-terminal"&&h!=="--help"&&h!=="-h");if(i.length!==1)return e.stderr.write(`usage: lmctl quickrun <url-or-path>
|
|
2669
2746
|
`),2;let o=i[0],a=r.cwd??process.cwd(),l=r.fetchFn??fetch,c=Tn(r.initConfigPath);if(c===null)return e.stderr.write("error: no ~/.lmctl/init.toml found. Run `lmctl init` first, then try quickrun again.\n"),1;let u;try{u=await mr(o,l,a)}catch(h){return e.stderr.write(`error: could not fetch ${o}: ${h instanceof Error?h.message:String(h)}
|
|
2670
|
-
`),1}let d=
|
|
2747
|
+
`),1}let d=oE(u,c),m=EO(a);if(pO(_O(m),{recursive:!0}),hO(m,d,"utf8"),e.stdout.write(`Wrote ${m}
|
|
2671
2748
|
`),await Mr([m],e)!==0)return e.stderr.write(`error: ${m} failed lint after substitution -- check the values in ~/.lmctl/init.toml.
|
|
2672
2749
|
`),1;if(n)return e.stdout.write(`Edit ${m} if needed, then run: lmctl seed ${m}
|
|
2673
|
-
`),0;let g=await $r([m],e);return g!==0?g:s?0:(r.openTerminal??Cd)([m,"Lead"],e)}var
|
|
2750
|
+
`),0;let g=await $r([m],e);return g!==0?g:s?0:(r.openTerminal??Cd)([m,"Lead"],e)}var yO,sT=k(()=>{"use strict";No();As();$t();Dd();yO=`usage: lmctl quickrun <url-or-path>
|
|
2674
2751
|
|
|
2675
2752
|
Fetches a .lmctl teamfile template (any https:// URL or local file/dir
|
|
2676
2753
|
path -- lmctl.com publishes example templates, but this is not restricted
|
|
@@ -2687,13 +2764,13 @@ taken, so quickrun never overwrites an existing teamfile.
|
|
|
2687
2764
|
--no-seed Write the resolved teamfile but do not seed or open it
|
|
2688
2765
|
--no-terminal Seed, but do not open the Lead's terminal afterward
|
|
2689
2766
|
-h, --help display help for command
|
|
2690
|
-
`});var
|
|
2691
|
-
`),2;let o=r.cwd??process.cwd(),a=r.fetchFn??fetch,l=`${
|
|
2692
|
-
`),1}let u=
|
|
2767
|
+
`});var oT={};oe(oT,{runHello:()=>bO});import{writeFileSync as wO}from"node:fs";import{join as vO}from"node:path";async function bO(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(SO),0;let n,s,i=[];for(let g=0;g<t.length;g+=1){let y=t[g];if(y==="-p"||y==="--prompt"){s=t[g+1],g+=1;continue}i.push(y)}if(i.length===1&&(n=i[0]),n===void 0||s===void 0)return e.stderr.write(`usage: lmctl hello <provider> -p "<prompt>"
|
|
2768
|
+
`),2;let o=r.cwd??process.cwd(),a=r.fetchFn??fetch,l=`${iT}/${n}.lmctl`,c;try{c=await mr(l,a,o)}catch(g){return e.stderr.write(`error: could not fetch ${l}: ${g instanceof Error?g.message:String(g)}
|
|
2769
|
+
`),1}let u=vO(o,`${n}_hello.lmctl`);if(wO(u,c,"utf8"),e.stdout.write(`Wrote ${u}
|
|
2693
2770
|
`),await Mr([u],e)!==0)return e.stderr.write(`error: ${u} failed lint -- lmctl.com's ${n}.lmctl example may be out of date.
|
|
2694
|
-
`),1;let m=await $r([u],e);return m!==0?m:(r.sendPrompt??gd)([u,"Lead",s],e)}var
|
|
2771
|
+
`),1;let m=await $r([u],e);return m!==0?m:(r.sendPrompt??gd)([u,"Lead",s],e)}var iT,SO,aT=k(()=>{"use strict";As();$t();wo();iT="https://lmctl.com/helloexample",SO=`usage: lmctl hello <provider> -p "<prompt>"
|
|
2695
2772
|
|
|
2696
|
-
Downloads ${
|
|
2773
|
+
Downloads ${iT}/<provider>.lmctl, saves it as
|
|
2697
2774
|
<provider>_hello.lmctl in the current directory, seeds it, sends your
|
|
2698
2775
|
prompt to the Lead, and prints the answer -- the one-command proof that a
|
|
2699
2776
|
provider works at all.
|
|
@@ -2703,10 +2780,10 @@ provider works at all.
|
|
|
2703
2780
|
|
|
2704
2781
|
Example:
|
|
2705
2782
|
lmctl hello claude -p "hi"
|
|
2706
|
-
`});import{execFileSync as Md}from"node:child_process";import{dirname as
|
|
2783
|
+
`});import{execFileSync as Md}from"node:child_process";import{dirname as lT,resolve as IO}from"node:path";function cT(t){return(0,$d.formatCount)(t)}async function Fd(t,e){return C(t,r=>{let n=r.query(`SELECT config_warnings FROM tracked_invocation
|
|
2707
2784
|
WHERE target_teamfile = ? AND target_alias = ? AND config_warnings IS NOT NULL
|
|
2708
|
-
ORDER BY started_at DESC LIMIT 1`,e.teamfile,e.alias);if(n.length!==0)try{let s=JSON.parse(n[0].config_warnings);if(!Array.isArray(s))return;let i=s.filter(o=>typeof o=="string"&&o.length>0);return i.length>0?i:void 0}catch{return}})}function Pd(t,e,r,n){let s=he(t,e);if(r.has(s))return[];r.add(s);let i=Ve(s,e);if(i.parseErrors.length>0)throw new Error(`${s}: ${i.parseErrors.join("; ")}`);let o=[];for(let a of i.members){if(a.teamfile!==void 0){o.push(...Pd(
|
|
2709
|
-
`)}catch{}}async function
|
|
2785
|
+
ORDER BY started_at DESC LIMIT 1`,e.teamfile,e.alias);if(n.length!==0)try{let s=JSON.parse(n[0].config_warnings);if(!Array.isArray(s))return;let i=s.filter(o=>typeof o=="string"&&o.length>0);return i.length>0?i:void 0}catch{return}})}function Pd(t,e,r,n){let s=he(t,e);if(r.has(s))return[];r.add(s);let i=Ve(s,e);if(i.parseErrors.length>0)throw new Error(`${s}: ${i.parseErrors.join("; ")}`);let o=[];for(let a of i.members){if(a.teamfile!==void 0){o.push(...Pd(IO(lT(s),a.teamfile),e,r,[...n,a.alias]));continue}o.push({teamfile:s,alias:a.alias,reportPath:[...n,a.alias].join("/"),provider:a.provider,sessionid:a.session!==void 0&&a.session.length>0?a.session:null,model:a.model??null})}return o}async function Ud(t,e){try{let r=await C(t,n=>e.map(s=>{let i=pt(n,s.teamfile,s.alias);return[Fo(s.teamfile,s.alias),xO(i)]}));return new Map(r)}catch{return new Map}}function Fo(t,e){return`${t}\0${e.toLowerCase()}`}function xO(t){return t.busy?t.reason==="terminal-held"?t.source==="terminal-invocation"?{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:null,terminalInvocation:{id:t.terminalInvocation.id,startedAt:t.terminalInvocation.started_at,lastHeartbeat:t.terminalInvocation.last_heartbeat_at,holderPid:t.terminalInvocation.holder_pid,holderHost:t.terminalInvocation.holder_host},reclaimable:null}:{state:"busy",reason:"terminal-held",inFlight:null,terminalLock:{startedAt:t.terminalLock.started_at,lastHeartbeat:t.terminalLock.last_heartbeat,holderPid:t.terminalLock.holder_pid,holderHost:t.terminalLock.holder_host},terminalInvocation:null,reclaimable:null}:{state:"busy",reason:"in-flight",inFlight:{senderTeamfile:t.inFlight.sender_teamfile,senderAlias:t.inFlight.sender_alias,startedAt:t.inFlight.started_at,activeCount:t.inFlight.active_count,holderPid:t.inFlight.holder_pid},terminalLock:null,terminalInvocation:null,reclaimable:null}:Po(t.reclaimable===void 0?null:{source:t.reclaimable.source,holderPid:t.reclaimable.holder_pid,holderHost:t.reclaimable.holder_host,reason:t.reclaimable.reason})}function Po(t=null){return{state:"idle",reason:null,inFlight:null,terminalLock:null,terminalInvocation:null,reclaimable:t}}function Uo(t){if(t.state!=="idle")return`busy (${t.reason})`;if(t.reclaimable!==null){let{holderPid:e,holderHost:r,reason:n}=t.reclaimable;return`idle (reclaimable lock: ${e!==null?`pid ${e}${r!==null?` on ${r}`:""}`:"holder"} ${n==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale"})`}return"idle"}function jd(t){return t.resets_at!==null?t.resets_at:t.timezone!==null?`${t.reset_time} (${t.timezone})`:t.reset_time}function tt(t){return t==null?"unknown":(0,$d.formatCount)(t)}function dT(t){return t==="n/a"?t:tt(t)}function uT(t,e,r=String){return t!==void 0?r(t):e?"n/a":"unknown"}function Bd(t){let e=lT(t),r;try{Md("git",["-C",e,"rev-parse","--is-inside-work-tree"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-repo",teamDir:e}}try{r=Md("git",["-C",e,"log","-2","--format=%ct"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{kind:"unavailable",reason:"no-commits",teamDir:e}}let n=r.split(/\r?\n/).map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(n.length===0)return{kind:"unavailable",reason:"no-commits",teamDir:e};let s=n.slice(0,2).map((i,o)=>({ref:o===0?"HEAD":`HEAD~${o}`,timestamp:new Date(i*1e3)}));return{kind:"repo",teamDir:e,since:s[0].timestamp,commits:s,working:kO(e)}}function kO(t){let e;try{e=Md("git",["-C",t,"status","--porcelain"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}catch{return{uncommittedTracked:null,untracked:null}}let r=0,n=0;for(let s of e.split(/\r?\n/))s.trim().length!==0&&(s.startsWith("??")?n+=1:r+=1);return{uncommittedTracked:r,untracked:n}}function Wd(t,e){let r=e.getTime();return t.messages.filter(n=>(n.role==="user"||n.role==="assistant")&&Number.isFinite(n.timestamp.getTime())&&n.timestamp.getTime()>r).length}function Hd(t){if(t===null)return null;let e=[t.totalInputTokens,t.totalCachedInputTokens,t.totalCacheWriteInputTokens,t.totalOutputTokens,t.totalReasoningOutputTokens].filter(r=>typeof r=="number"&&Number.isFinite(r));return e.length===0?null:e.reduce((r,n)=>r+n,0)}var $d,mT=k(()=>{"use strict";$d=It(gt(),1);st();ge();At()});function Xd(t){for(let e=t.length-1;e>=0;e-=1){let r=t[e],n=AO.exec(r.content);if(n===null){if(r.role==="assistant"&&r.content.trim().length>0)return null;continue}let s=Number.parseInt(n[1],10),i=n[2]===void 0?0:Number.parseInt(n[2],10),o=n[3].toLowerCase(),a=n[4]?.trim()??null,l=`${n[1]}${n[2]!==void 0?`:${n[2]}`:""}${o}`;return{state:"LIMITED",resets_at:a===null?null:RO(r.timestamp,s,i,o,a),reset_time:l,timezone:a,detected_at:r.timestamp.toISOString()}}return null}function RO(t,e,r,n,s){if(!Number.isFinite(t.getTime())||e<1||e>12||r<0||r>59)return null;let i=NO(e,n);try{let o=LO(t,s),a=fT(o.year,o.month,o.day,i,r,s);if(a.getTime()<=t.getTime()){let l=MO(o,1);a=fT(l.year,l.month,l.day,i,r,s)}return a.toISOString()}catch{return null}}function NO(t,e){return e==="am"?t===12?0:t:t===12?12:t+12}function LO(t,e){let r=pT(e,!1).formatToParts(t);return{year:Pt(r,"year"),month:Pt(r,"month"),day:Pt(r,"day")}}function fT(t,e,r,n,s,i){let o=Date.UTC(t,e-1,r,n,s,0,0);for(let a=0;a<3;a+=1){let l=CO(new Date(o),i);o=Date.UTC(t,e-1,r,n,s,0,0)-l}return new Date(o)}function CO(t,e){let r=pT(e,!0).formatToParts(t);return Date.UTC(Pt(r,"year"),Pt(r,"month")-1,Pt(r,"day"),Pt(r,"hour"),Pt(r,"minute"),Pt(r,"second"),0)-t.getTime()}function pT(t,e){let r=e?DO:OO,n=r.get(t);if(n!==void 0)return n;let s=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",...e?{hour:"2-digit",minute:"2-digit",second:"2-digit"}:{}});return r.set(t,s),s}function Pt(t,e){let r=t.find(n=>n.type===e)?.value;if(r===void 0)throw new Error(`missing ${e}`);return Number.parseInt(r,10)}function MO(t,e){let r=new Date(Date.UTC(t.year,t.month-1,t.day+e));return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate()}}var AO,OO,DO,hT=k(()=>{"use strict";AO=/you['\u2019]ve hit your session limit\s*(?:\u00b7|-|:)?\s*resets\s+([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;OO=new Map,DO=new Map});var AT={};oe(AT,{appendIntent:()=>qd,formatAge:()=>Ls,formatDuration:()=>Wo,resolveIntentLogPath:()=>wT,runStatus:()=>GO,shortIdentity:()=>St});import{appendFileSync as $O,existsSync as FO,mkdirSync as PO}from"node:fs";import{homedir as UO}from"node:os";import{basename as jO,dirname as TT,isAbsolute as BO,join as WO,resolve as HO}from"node:path";function wT(){return process.env.LMCTL_INTENT_LOG??WO(UO(),".lmctl","recent-intents.log")}function qd(t){try{let e=wT();PO(TT(e),{recursive:!0});let r=JSON.stringify({ts:t.ts??new Date().toISOString(),cwd:t.cwd??process.cwd(),verb:t.verb,args:[...t.args]});$O(e,`${r}
|
|
2786
|
+
`)}catch{}}async function GO(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(XO),0;let r=t.find(a=>a==="--project"||a.startsWith("--project=")||a==="--web");if(r!==void 0)return A(e,`unknown option ${r}; lmctl status is team/SELF scoped now`);let n=ae(t,["--since"],["--json","--details"]);if(n.error!==void 0)return A(e,n.error);let s=X(n,"--json"),i=X(n,"--details");if(n.positionals.length>0){let a=await VO(e,n.positionals,{json:s,details:i,since:W(n,"--since")});return a===0&&qd({verb:"status",args:t}),a}if(i)return A(e,"--details only applies with a teamfile argument (lmctl status <teamfile> --details)");let o=hD(W(n,"--since"));if("error"in o)return A(e,o.error);try{let a=e.env??process.env;if(s){let l=await C(e,c=>yT(c,a));se(e,{schema_version:zd,...l})}else{let l=await C(e,async c=>aD(await yT(c,a),{sinceIso:o.iso}));e.stdout.write(l)}return qd({verb:"status",args:t}),0}catch(a){return A(e,a instanceof Error?a.message:String(a))}}async function VO(t,e,r){if(e.length>2)return A(t,`too many positionals (${e.length}); expected <teamfile> [alias]`);if(r.since!==void 0)return A(t,"--since only applies to the activity view (lmctl status with no teamfile argument)");let n=ut(JO,{target:e[0],alias:e[1],flags:{}});if(n.mode==="error")return A(t,n.message);if(n.mode!=="ai-team")return A(t,"lmctl status: expected <teamfile> [alias]");try{return n.alias===void 0?await gD(t,n.teamfile,r.json,r.details):await vD(t,n.teamfile,n.alias,r.json)}catch(s){return s instanceof ne?A(t,s.message):A(t,`status: ${s instanceof Error?s.message:String(s)}`)}}async function yT(t,e){let r=Rc(e,t);if(!r.ok){if(r.reason==="not-found")throw new Error(Ot("status"));return await YO(t)}return await KO(t,r.identity)}async function KO(t,e){let r=Dt(e),n=t.getRootTeam(r.teamfile);if(n===null)throw new Error(Ot("status"));let s=Ve(n.teamfile_path,t),i=Jd(Bo(t,{from:r.value})),o=Jd(Bo(t,{target_teamfile:r.teamfile,target_alias:r.alias})),a=eD([...Gd(t,{from:r.value}),...Gd(t,{target_teamfile:r.teamfile,target_alias:r.alias})]);return{scope:"self",identity:r.value,...vT(),team:{name:s.name,teamfile:n.teamfile_path},members:s.members.map(l=>QO(t,n.teamfile_path,l)),activity:{from_me:i.map(l=>Vd(l)),to_me:o.map(l=>Vd(l))},transcript_harvest:await ST(a)}}function vT(){let t=null;try{t=If(Qr())}catch{}return{db_path:pe(),site_name:t}}async function YO(t){let e=t.listRootTeams();return{scope:"db",identity:null,...vT(),teams:e.map(r=>zO(t,r)),activity:Jd(Bo(t)).map(r=>Vd(r)),transcript_harvest:await ST(Gd(t))}}function zO(t,e){if(!FO(e.teamfile_path))return{name:e.name,teamfile:e.teamfile_path,member_count:0,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at,missing_on_disk:!0};let r=0;try{r=Ve(e.teamfile_path,t).members.length}catch{r=0}return{name:e.name,teamfile:e.teamfile_path,member_count:r,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at}}function QO(t,e,r){let n=r.teamfile===void 0?null:he(BO(r.teamfile)?r.teamfile:HO(TT(e),r.teamfile),t),s=pt(t,e,r.alias),i=s.busy&&s.reason==="in-flight"?ZO(t,e,r.alias,s.inFlight):null;return{alias:r.alias,provider:r.provider,model:r.model??null,teamfile:e,referenced_teamfile:n,sessionid:r.session??null,sessiondir:r.sessiondir??null,state:s.busy?"busy":"idle",reason:s.busy?s.reason:null,handling:i,reclaimable:!s.busy&&s.reclaimable!==void 0?s.reclaimable:null}}function ZO(t,e,r,n){let s=n.sender_alias==="operator"?"operator":`${n.sender_teamfile}:${n.sender_alias}`,o=t.db.prepare(`
|
|
2710
2787
|
SELECT * FROM tracked_invocation
|
|
2711
2788
|
WHERE kind = 'chat'
|
|
2712
2789
|
AND status = 'running'
|
|
@@ -2716,27 +2793,27 @@ Example:
|
|
|
2716
2793
|
AND holder_pid IS ?
|
|
2717
2794
|
ORDER BY started_at DESC, id DESC
|
|
2718
2795
|
LIMIT 5
|
|
2719
|
-
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:
|
|
2796
|
+
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:pD(o.request_payload)}}function Bo(t,e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.target_teamfile!==void 0&&(r.push("target_teamfile = ?"),n.push(e.target_teamfile)),e.target_alias!==void 0&&(r.push("target_alias = ?"),n.push(e.target_alias));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`;return t.db.prepare(`
|
|
2720
2797
|
SELECT * FROM tracked_invocation
|
|
2721
2798
|
${s}
|
|
2722
2799
|
ORDER BY started_at DESC, id DESC
|
|
2723
|
-
`).all(...n)}function Gd(t,e={}){return Bo(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&qt(n)==="dead")}function
|
|
2800
|
+
`).all(...n)}function Gd(t,e={}){return Bo(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&qt(n)==="dead")}function eD(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(n));return r.sort((n,s)=>{let i=Date.parse(s.started_at)-Date.parse(n.started_at);return Number.isFinite(i)&&i!==0?i:s.id-n.id})}function Jd(t){return t.filter(e=>qt(e)!=="dead")}async function ST(t){let e=[];for(let r of t)e.push(await tD(r));return e}async function tD(t){let e=t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,r={tracked_invocation_id:t.id,from_identity:t.from_identity,target:e??"(unknown)",started_at:t.started_at,tail_hint:e===null?"":`lmctl tail "${t.target_teamfile}" ${t.target_alias}`};if(e===null)return Pr(r,"missing-target",null,null);if(t.request_payload===null||t.request_payload.length===0)return Pr(r,"missing-request-payload",null,null);let n=rD(t.meta);if(n.provider===null||n.sessionid===null)return Pr(r,"missing-session-metadata",n.provider,n.sessionid);if(!nD(n.provider))return Pr(r,"unsupported-provider",n.provider,n.sessionid);let s;try{s=await Re(n.sessionid,n.provider)}catch{return Pr(r,"read-error",n.provider,n.sessionid)}if(s===null)return Pr(r,"session-not-found",n.provider,n.sessionid);let i=sD(t.request_payload,s.messages);return i.state!=="completed"?Pr(r,i.reason,n.provider,n.sessionid):{...r,state:"completed",reason:null,provider:n.provider,session_id:n.sessionid,result_payload:i.result,result_preview:kT(i.result),assistant_timestamp:i.assistantTimestamp,matched_user_index:i.userIndex}}function Pr(t,e,r,n){return{...t,state:"unreconciled",reason:e,provider:r,session_id:n,result_payload:null,result_preview:null,assistant_timestamp:null,matched_user_index:null}}function rD(t){if(t===null||t.trim()==="")return{provider:null,sessionid:null};try{let e=JSON.parse(t);return{provider:typeof e.provider=="string"&&e.provider.length>0?e.provider:null,sessionid:typeof e.sessionid=="string"&&e.sessionid.length>0?e.sessionid:null}}catch{return{provider:null,sessionid:null}}}function nD(t){return["claude","codex","gemini","copilot","opencode","lmplayer","qwen","agy","kimi","dsh","hermes","pi","ClaudeMock"].includes(t)}function sD(t,e){let r=e.map((i,o)=>({message:i,index:o})).filter(({message:i})=>i.role==="user"&&i.content===t);if(r.length===0)return{state:"unreconciled",reason:"request-not-found"};if(r.length>1)return{state:"unreconciled",reason:"duplicate-request"};let n=r[0].index,s=[];for(let i of e.slice(n+1)){if(i.role==="user")break;i.role==="assistant"&&i.content.trim().length>0&&s.push(i)}return s.length===0?{state:"unreconciled",reason:"no-assistant-response"}:{state:"completed",userIndex:n,result:s.map(i=>i.content).join(`
|
|
2724
2801
|
|
|
2725
|
-
`),assistantTimestamp:
|
|
2726
|
-
`)}function
|
|
2727
|
-
`)}function
|
|
2728
|
-
`)}d.detailLoaded=f!==null,d.messageCount=f?.messageCount??null,d.observedModel=f?.model??"(unknown)",d.lastContext=f?.lastInputTokens??null,d.totalInputTokens=f?.totalInputTokens??null,d.totalOutputTokens=f?.totalOutputTokens??null,f?.totalCachedInputTokens!==void 0&&(d.totalCachedInputTokens=f.totalCachedInputTokens),d.sessionLimit=f===null?null:Xd(f.messages),o!==null&&(d.activitySinceLastCommit={messageCount:f===null?null:Wd(f,o.since),tokens:null},d.cumulativeTokens=f===null?null:Hd(f)??"n/a"),f?.messageCount===void 0?c=void 0:c!==void 0&&(c+=f.messageCount)}l.push(d)}return r?(se(t,{schema_version:zd,scope:"team",team:s.teamName,teamfile:s.teamfile,details:n,git:o===null?null:{teamDir:o.teamDir,commits:o.commits.map(u=>({ref:u.ref,timestamp:u.timestamp.toISOString()})),since:o.since.toISOString(),working:o.working},members:l.map(u=>{let d={alias:u.alias,reportPath:u.reportPath,teamfile:u.teamfile,provider:u.provider,sessionid:u.sessionid,seeded:u.sessionid!==null,model:u.declaredModel,liveness:u.liveness};return u.configWarnings!==void 0&&(d.config_warnings=u.configWarnings),u.probed&&(d.messageCount=u.messageCount??null,d.observed_model=u.observedModel,d.lastContext=u.lastContext??null,d.totalInputTokens=u.totalInputTokens??null,d.totalOutputTokens=u.totalOutputTokens??null,u.totalCachedInputTokens!==void 0&&(d.totalCachedInputTokens=u.totalCachedInputTokens),d.sessionLimit=u.sessionLimit??null,u.activitySinceLastCommit!==void 0&&(d.activitySinceLastCommit=u.activitySinceLastCommit),u.cumulativeTokens!==void 0&&(d.cumulativeTokens=u.cumulativeTokens==="n/a"?null:u.cumulativeTokens)),d}),...n?{total:{messageCount:c??null}}:{}}),0):(t.stdout.write(
|
|
2802
|
+
`),assistantTimestamp:iD(s[s.length-1]?.timestamp)}}function iD(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function oD(t){if(!(t===null||t.trim()===""))try{let e=JSON.parse(t);if(!Array.isArray(e))return;let r=e.filter(n=>typeof n=="string"&&n.length>0);return r.length>0?r:void 0}catch{return}}function Vd(t){let e=oD(t.config_warnings);return{id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:qt(t),from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:ET(t.result_summary),error:ET(t.error),...e!==void 0?{config_warnings:e}:{}}}function aD(t,e){return t.scope==="self"?cD(t,e):dD(t,e)}function lD(t){if(t===null)return"idle";let e=t.holder_pid!==null?`pid ${t.holder_pid}${t.holder_host!==null?` on ${t.holder_host}`:""}`:"holder",r=t.reason==="dead-pid"?"appears dead -- usually a mid-turn kill, most often a shell `timeout` wrapper; use --idle-timeout instead":"stale";return`idle (reclaimable lock: ${e} ${r})`}function cD(t,e){let r=[];r.push(`identity: ${t.identity}`),r.push(`team: ${t.team.name}`),r.push(`teamfile: ${t.team.teamfile}`),r.push(""),r.push("members:"),t.members.length===0&&r.push(" none");for(let n of t.members){let s=n.model===null?"":` model=${n.model}`,i=n.sessionid===null?"":` session=${n.sessionid}`,o=n.state==="idle"?lD(n.reclaimable):`busy (${n.reason})`,a=n.handling===null?"":` handling="${n.handling.request_preview}"`;r.push(` ${n.alias}: ${o} provider=${n.provider}${s}${i}${a}`)}return r.push(""),r.push("transcript harvest:"),IT(r,t.transcript_harvest,"self"),r.push(""),r.push("activity from me:"),Kd(r,Yd(t.activity.from_me,e.sinceIso),"from-me"),r.push(""),r.push("activity to me:"),Kd(r,Yd(t.activity.to_me,e.sinceIso),"to-me"),r.push(""),r.push(bT(t)),r.join(`
|
|
2803
|
+
`)}function dD(t,e){let r=[];r.push("scope: db"),r.push("identity: none"),r.push(""),r.push("teams:"),t.teams.length===0&&r.push(" none");for(let n of t.teams){let s=n.name===null?"(unnamed)":n.name;r.push(` ${s}: ${n.teamfile} (${n.member_count} members)`)}return r.push(""),r.push("transcript harvest:"),IT(r,t.transcript_harvest,"db"),r.push(""),r.push("recent activity:"),Kd(r,Yd(t.activity,e.sinceIso),"db"),r.push(""),r.push(bT(t)),r.join(`
|
|
2804
|
+
`)}function bT(t){return Sn(t.db_path)}function Kd(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,jo))uD(t,n,r);xT(t,e.length,jo,"older")}function IT(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,jo)){let s=r==="db"?` from ${St(n.from_identity)} -> ${St(n.target)}`:` -> ${St(n.target)}`;if(n.state==="completed"){let i=n.result_preview===null?"":` "${n.result_preview}"`;t.push(` #${n.tracked_invocation_id} completed in transcript; lmctl DB not finalized${s} since ${n.started_at}${i}`)}else t.push(` #${n.tracked_invocation_id} unreconciled${s} since ${n.started_at} (${n.reason??"unknown"})`);n.tail_hint.length>0&&t.push(` inspect: ${n.tail_hint}`)}xT(t,e.length,jo,"more transcript harvest rows")}function Yd(t,e){let r=Date.parse(e);return Number.isFinite(r)?t.filter(n=>{let s=Date.parse(n.ended_at??n.started_at);return Number.isFinite(s)&&s>=r}):t}function uD(t,e,r){let n=fD(e,r),s=e.status==="running"?`since ${e.started_at}`:`ended ${e.ended_at??e.started_at}`,i=e.error??e.result,o=i===null?"":` "${kT(i)}"`;if(t.push(` #${e.id} ${mD(e)} ${e.kind}${n} ${s}${o}`),e.config_warnings!==void 0)for(let a of e.config_warnings)t.push(` config not applied: ${a}`)}function mD(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.status.toUpperCase()}function fD(t,e){if(e==="from-me")return t.target===null?"":` -> ${St(t.target)}`;if(e==="to-me")return` from ${St(t.from_identity)}`;let r=t.target===null?"":` -> ${St(t.target)}`;return` from ${St(t.from_identity)}${r}`}function xT(t,e,r,n){let s=e-r;s>0&&t.push(` (+${s} ${n} -- use --json)`)}function ET(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function kT(t){let e=t.replace(/\s+/g," ").trim();return e.length<=gT?e:`${e.slice(0,gT-3)}...`}function pD(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=_T?e:`${e.slice(0,_T-3)}...`}function Wo(t){return(0,$e.formatDuration)(t)}function Ls(t){return(0,$e.formatRelativeTime)(t)}function St(t){if(t==="operator")return t;try{let e=Dt(t);return`${jO(e.teamfile)}:${e.alias}`}catch{return t}}function hD(t){if(t===void 0)return{iso:new Date(Date.now()-qO).toISOString()};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2],i=s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400;return{iso:new Date(Date.now()-i*1e3).toISOString()}}let r=Date.parse(t);return Number.isFinite(r)?{iso:new Date(r).toISOString()}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}async function gD(t,e,r,n){let s=await C(t,u=>{let d=he(e,u),m=Ve(d,u);if(m.parseErrors.length>0)throw new Error(m.parseErrors.join("; "));return{teamfile:d,teamName:m.name,targets:Pd(d,u,new Set,[])}}),i=Bd(s.teamfile),o=i.kind==="repo"?i:null,a=await Ud(t,s.targets),l=[],c=0;for(let u of s.targets){let d={alias:u.alias,reportPath:u.reportPath,teamfile:u.teamfile,provider:u.provider,sessionid:u.sessionid,declaredModel:u.model,liveness:a.get(Fo(u.teamfile,u.alias))??Po(),probed:!1,detailLoaded:!1},m=await Fd(t,{teamfile:u.teamfile,alias:u.alias});if(m!==void 0&&(d.configWarnings=m),n&&u.sessionid!==null){d.probed=!0;let f=null;try{f=await Re(u.sessionid,u.provider)}catch(g){t.stderr.write(`warning: failed to load session "${u.sessionid}" for ${u.reportPath} (${u.provider}): ${g instanceof Error?g.message:String(g)}
|
|
2805
|
+
`)}d.detailLoaded=f!==null,d.messageCount=f?.messageCount??null,d.observedModel=f?.model??"(unknown)",d.lastContext=f?.lastInputTokens??null,d.totalInputTokens=f?.totalInputTokens??null,d.totalOutputTokens=f?.totalOutputTokens??null,f?.totalCachedInputTokens!==void 0&&(d.totalCachedInputTokens=f.totalCachedInputTokens),d.sessionLimit=f===null?null:Xd(f.messages),o!==null&&(d.activitySinceLastCommit={messageCount:f===null?null:Wd(f,o.since),tokens:null},d.cumulativeTokens=f===null?null:Hd(f)??"n/a"),f?.messageCount===void 0?c=void 0:c!==void 0&&(c+=f.messageCount)}l.push(d)}return r?(se(t,{schema_version:zd,scope:"team",team:s.teamName,teamfile:s.teamfile,details:n,git:o===null?null:{teamDir:o.teamDir,commits:o.commits.map(u=>({ref:u.ref,timestamp:u.timestamp.toISOString()})),since:o.since.toISOString(),working:o.working},members:l.map(u=>{let d={alias:u.alias,reportPath:u.reportPath,teamfile:u.teamfile,provider:u.provider,sessionid:u.sessionid,seeded:u.sessionid!==null,model:u.declaredModel,liveness:u.liveness};return u.configWarnings!==void 0&&(d.config_warnings=u.configWarnings),u.probed&&(d.messageCount=u.messageCount??null,d.observed_model=u.observedModel,d.lastContext=u.lastContext??null,d.totalInputTokens=u.totalInputTokens??null,d.totalOutputTokens=u.totalOutputTokens??null,u.totalCachedInputTokens!==void 0&&(d.totalCachedInputTokens=u.totalCachedInputTokens),d.sessionLimit=u.sessionLimit??null,u.activitySinceLastCommit!==void 0&&(d.activitySinceLastCommit=u.activitySinceLastCommit),u.cumulativeTokens!==void 0&&(d.cumulativeTokens=u.cumulativeTokens==="n/a"?null:u.cumulativeTokens)),d}),...n?{total:{messageCount:c??null}}:{}}),0):(t.stdout.write(ED(s.teamName,s.teamfile,i,l,n,c)),0)}function _D(t){return t.sessionid??"(not seeded)"}function yD(t){return t.sessionid===null?"not seeded":Uo(t.liveness)}function ED(t,e,r,n,s,i){let o=[],a=r.kind==="repo"?r:null;if(o.push(`TEAM: ${t}`),o.push(`teamfile: ${e}`),r.kind==="repo"){o.push("Git progress:");for(let y of r.commits)o.push(` ${y.ref}: ${y.timestamp.toISOString()}`);o.push(` Uncommitted: ${tt(r.working.uncommittedTracked)} changed (tracked), ${tt(r.working.untracked)} untracked`)}else r.reason==="no-commits"?o.push(`Git progress: git repository in ${r.teamDir} has no commits (no commit-based progress to report)`):o.push(`Git progress: no git repository in ${r.teamDir} (no commit-based progress to report)`);if(!s){o.push("members:"),n.length===0&&o.push(" none");for(let y of n){let h=y.declaredModel===null?"":` model=${y.declaredModel}`;if(y.sessionid===null?o.push(` ${y.reportPath}: not seeded provider=${y.provider}${h} (run: lmctl seed "${y.teamfile}")`):o.push(` ${y.reportPath}: ${Uo(y.liveness)} provider=${y.provider}${h} session=${y.sessionid}`),y.configWarnings!==void 0)for(let p of y.configWarnings)o.push(` config not applied: ${p}`)}return o.push(""),o.push("session detail (observed model, messages, tokens, limits) not probed -- use --details"),`${o.join(`
|
|
2729
2806
|
`)}
|
|
2730
|
-
`}let l=a!==null?["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT","MSGS SINCE COMMIT","TOKENS SINCE COMMIT","TOKENS (cumulative)"]:["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT"],c=l.map((y,h)=>h>=5?"right":"left"),u=!1,d=n.filter(y=>y.sessionLimit!=null),m=[];for(let y of n){let h=
|
|
2807
|
+
`}let l=a!==null?["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT","MSGS SINCE COMMIT","TOKENS SINCE COMMIT","TOKENS (cumulative)"]:["SESSION","ALIAS","PROVIDER","OBSERVED MODEL","LIVE","MSGS","LAST CONTEXT"],c=l.map((y,h)=>h>=5?"right":"left"),u=!1,d=n.filter(y=>y.sessionLimit!=null),m=[];for(let y of n){let h=uT(y.lastContext??void 0,y.detailLoaded,cT);(h==="n/a"||y.cumulativeTokens==="n/a")&&(u=!0);let p=[(0,$e.escapeCell)(_D(y)),(0,$e.escapeCell)(y.reportPath),(0,$e.escapeCell)(y.provider),(0,$e.escapeCell)(y.observedModel??"(unknown)"),yD(y),tt(y.messageCount),h];a!==null&&p.push(tt(y.activitySinceLastCommit?.messageCount),tt(y.activitySinceLastCommit?.tokens),dT(y.cumulativeTokens)),m.push(p)}let f=["TOTAL","","","","",tt(i)];a!==null&&f.push("",tt(TD(n)),tt(null),tt(wD(n))),m.push(f);let g=(0,$e.formatTable)(m,{headers:l,align:c,margin:2}).split(`
|
|
2731
2808
|
`);if(o.push(g[0]),n.forEach((y,h)=>{if(o.push(g[h+1]),y.configWarnings!==void 0)for(let p of y.configWarnings)o.push(` config not applied: ${p}`)}),o.push(g[g.length-1]),u&&o.push("n/a = this provider does not expose a context/token total; absence is not a health signal."),o.push(`LAST CONTEXT = prompt size of the LAST COMPLETED turn, so it LAGS BY ONE TURN.
|
|
2732
2809
|
Right after a compaction the last completed turn IS the summarisation request, which carried the
|
|
2733
2810
|
full pre-compaction prompt \u2014 so this reads the OLD large number while the live context is already
|
|
2734
2811
|
small. Re-read after the next turn before concluding a compaction failed or gating on the value.`),d.length>0){o.push("Session limits:");for(let y of d)o.push(` ${y.reportPath}: LIMITED resets_at=${jd(y.sessionLimit)}`)}return`${o.join(`
|
|
2735
2812
|
`)}
|
|
2736
|
-
`}function
|
|
2813
|
+
`}function TD(t){let e=0;for(let r of t){let n=r.activitySinceLastCommit?.messageCount;n==null?e=void 0:e!==void 0&&(e+=n)}return e}function wD(t){let e=0;for(let r of t){let n=r.cumulativeTokens;n==null||n==="n/a"?e=void 0:e!==void 0&&(e+=n)}return e}async function vD(t,e,r,n){let s=await C(t,g=>me(e,r,g)),i;try{i=await Re(s.sessionid,s.provider)}catch(g){return A(t,`status: failed to load session: ${g instanceof Error?g.message:String(g)}`)}if(i===null)return A(t,`status: session not found: ${s.sessionid} (provider=${s.provider})`);let o=Xd(i.messages),l=(await Ud(t,[{teamfile:s.teamfile,alias:s.alias}])).get(Fo(s.teamfile,s.alias))??Po(),c=await Fd(t,{teamfile:s.teamfile,alias:s.alias}),u=Bd(s.teamfile),d=u.kind==="repo"?u:null,m={provider:i.provider,sessionid:i.sessionId,seeded:!0,alias:s.alias,teamfile:s.teamfile,reportPath:s.alias,cwd:i.cwd,messageCount:i.messageCount??null,model:s.model??null,observed_model:i.model??null,lastContext:i.lastInputTokens??null,liveness:l,totalInputTokens:i.totalInputTokens??null,totalOutputTokens:i.totalOutputTokens??null,...i.totalCachedInputTokens!==void 0?{totalCachedInputTokens:i.totalCachedInputTokens}:{},sessionLimit:o,...c!==void 0?{config_warnings:c}:{},...d!==null?{activitySinceLastCommit:{messageCount:Wd(i,d.since),tokens:null},cumulativeTokens:Hd(i)}:{},createdAt:i.createdAt.toISOString(),modifiedAt:i.modifiedAt.toISOString()};if(n)return se(t,{schema_version:zd,scope:"member",...m}),0;let f=[];if(f.push(`Session: ${i.sessionId}`),f.push(` Provider: ${i.provider}`),f.push(` Alias: ${s.alias}`),f.push(` Liveness: ${Uo(l)}`),f.push(` CWD: ${i.cwd}`),f.push(` Messages: ${tt(i.messageCount)}`),f.push(` Model (declared): ${s.model??"(none)"}`),f.push(` Model (observed): ${i.model??"(unknown)"}`),c!==void 0)for(let g of c)f.push(` Config NOT applied: ${g}`);if(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)f.push(" Tokens: n/a");else{let g=` Tokens: ${(0,$e.formatCount)(i.totalInputTokens)} in / ${(0,$e.formatCount)(i.totalOutputTokens)} out`;m.totalCachedInputTokens!==void 0&&(g+=` (cached: ${(0,$e.formatCount)(m.totalCachedInputTokens)})`),f.push(g)}return(i.totalInputTokens===void 0||i.totalOutputTokens===void 0)&&f.push(" n/a = this provider does not expose a context/token total; absence is not a health signal."),f.push(` lastContext = prompt size of the LAST COMPLETED turn; it LAGS BY ONE TURN. Right after a
|
|
2737
2814
|
compaction it still reports the pre-compaction size (the summarisation request itself).`),o!==null&&f.push(` SessionLimit: LIMITED resets_at=${jd(o)}`),f.push(` Created: ${m.createdAt}`),f.push(` Modified: ${m.modifiedAt}`),t.stdout.write(`${f.join(`
|
|
2738
2815
|
`)}
|
|
2739
|
-
`),0}var $e,
|
|
2816
|
+
`),0}var $e,XO,zd,jo,qO,gT,_T,JO,Qd=k(()=>{"use strict";$e=It(gt(),1);st();ge();ls();ct();fn();At();We();mT();On();ar();hT();XO=`usage: lmctl status [--json] [--since <duration|ISO8601>]
|
|
2740
2817
|
lmctl status <teamfile> [--details] [--json]
|
|
2741
2818
|
lmctl status <teamfile> <alias> [--json]
|
|
2742
2819
|
|
|
@@ -2755,26 +2832,26 @@ With a teamfile and an alias: single-member deep view (session detail, token
|
|
|
2755
2832
|
breakdown, liveness with terminal-lock/in-flight holder info).
|
|
2756
2833
|
|
|
2757
2834
|
--json emits { schema_version: 2, scope: 'self'|'db'|'team'|'member', ... }.
|
|
2758
|
-
`,zd=2,jo=5,
|
|
2759
|
-
`,1)[0];return e.length<=
|
|
2835
|
+
`,zd=2,jo=5,qO=24*60*60*1e3,gT=72,_T=80;JO={name:"status",allowsBareTeamfile:!0,supportsRaw:!1}});var MT={};oe(MT,{_setRunningWatchMaxTicksForTests:()=>ID,runRunning:()=>$D});function ID(t){nu=t??void 0}function kD(t){let e=t.split(`
|
|
2836
|
+
`,1)[0];return e.length<=NT?e:`${e.slice(0,NT)}\u2026`}function Ho(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function eu(t,e){let r=t.target_teamfile,n=t.target_alias;if(r===null||n===null)return Zd;let s=e.get(r);if(s===void 0){try{s=Ne(r)}catch{s=null}e.set(r,s)}return s===null?Zd:Xs(s,n)?.model??Zd}function su(t){return t.target!==null?St(t.target):t.from_identity}function LT(t){return[(0,rt.escapeCell)(su(t)),t.kind,"running",t.holder_liveness,(0,rt.escapeCell)(t.model),Ls(t.started_at)]}function CT(t){return[(0,rt.escapeCell)(su(t)),t.kind,"DEAD","",(0,rt.escapeCell)(t.model),`stale ${Ls(t.started_at)}, holder process confirmed dead`]}function OT(t){let e=`ran ${Wo(t.ran_ms)}, idle ${Ls(t.ended_at)}`;return t.status==="error"&&t.error!==null&&t.error!==""&&(e+=` \u2014 ${(0,rt.escapeCell)(kD(t.error))}`),[(0,rt.escapeCell)(su(t)),t.kind,t.status,"",(0,rt.escapeCell)(t.model),e]}function tu(t){return t.filter(e=>e!=="").join(" ")}function DT(t){let e=new Map(t.map(i=>[i.id,i])),r=new Map,n=[];for(let i of t){let o=i.parent_invocation_id;if(o!==null&&e.has(o)){let a=r.get(o)??[];a.push(i),r.set(o,a)}else n.push(i)}let s=(i,o)=>o.started_at.localeCompare(i.started_at);n.sort(s);for(let i of r.values())i.sort(s);return{roots:n,childrenByParent:r}}function RD(t){let{roots:e,childrenByParent:r}=DT(t),n=[],s=(i,o)=>{n.push(`${" ".repeat(o+1)}${i.line}`);for(let a of r.get(i.id)??[])s(a,o+1)};for(let i of e)s(i,0);return n}function ND(t,e,r){let n=[...t.map(a=>({state:"running",...a})),...e.map(a=>({state:"dead",...a})),...r.map(a=>({state:"idle",...a}))],{roots:s,childrenByParent:i}=DT(n),o=a=>({...a,children:(i.get(a.id)??[]).map(o)});return s.map(o)}function LD(t){if(t===void 0)return{windowMs:SD};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2];return{windowMs:(s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400)*1e3}}let r=Date.parse(t);return Number.isFinite(r)?{windowMs:Math.max(0,Date.now()-r)}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}function ru(t,e){return!(e.teamfile!==void 0&&t.target_teamfile!==e.teamfile||e.member!==void 0&&(t.target_alias??"").toLowerCase()!==e.member)}function CD(t,e,r={}){let n=Date.now(),s=t.listAllRunningTrackedInvocations().filter(f=>ru(f,e)),i=new Map,o=[],a=[];for(let f of s){let g=qt(f),y=n-new Date(f.started_at).getTime(),h={id:f.id,kind:f.kind,origin:f.origin,from_identity:f.from_identity,target:Ho(f),model:eu(f,i),started_at:f.started_at,parent_invocation_id:f.parent_invocation_id};if(g==="dead"){if(Da(t,f)!==null)continue;a.push({...h,stale_for_ms:y})}else o.push({...h,running_for_ms:y,holder_liveness:g??"unknown"})}let l=new Set(s.map(Ho).filter(f=>f!==null)),c=new Date(n-e.idleWindowMs).toISOString(),u=t.listRecentlyFinishedTrackedInvocations(c).filter(f=>ru(f,e)),d=new Set,m=[];for(let f of u){let g=Ho(f);g===null||l.has(g)||d.has(g)||(d.add(g),m.push({id:f.id,kind:f.kind,origin:f.origin,from_identity:f.from_identity,target:g,model:eu(f,i),status:f.status,started_at:f.started_at,ended_at:f.ended_at,idle_ms:n-new Date(f.ended_at).getTime(),ran_ms:new Date(f.ended_at).getTime()-new Date(f.started_at).getTime(),error:f.error,parent_invocation_id:f.parent_invocation_id}))}if(r.tree===!0){let f=new Set([...o.map(y=>y.id),...a.map(y=>y.id),...m.map(y=>y.id)]),g=[...f];for(;g.length>0;){let y=t.listFinishedTrackedInvocationChildren(g,c).filter(h=>!f.has(h.id)&&ru(h,e));if(y.length===0)break;g=[];for(let h of y){f.add(h.id),g.push(h.id);let p=Ho(h);m.push({id:h.id,kind:h.kind,origin:h.origin,from_identity:h.from_identity,target:p,model:eu(h,i),status:h.status,started_at:h.started_at,ended_at:h.ended_at,idle_ms:n-new Date(h.ended_at).getTime(),ran_ms:new Date(h.ended_at).getTime()-new Date(h.started_at).getTime(),error:h.error,parent_invocation_id:h.parent_invocation_id})}}}return{running:o,dead:a,idle:m}}function OD(t,e){return e?{schema_version:RT,tree:ND(t.running,t.dead,t.idle)}:{schema_version:RT,...t}}function DD(t){let e=[...t.running.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:tu(LT(n))})),...t.dead.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:tu(CT(n))})),...t.idle.map(n=>({id:n.id,parent_invocation_id:n.parent_invocation_id,started_at:n.started_at,line:tu(OT(n))}))],r=RD(e);return`${r.length>0?r.join(`
|
|
2760
2837
|
`):" none"}
|
|
2761
|
-
`}function
|
|
2838
|
+
`}function MD(t,e){let r=[{title:`Running (${t.running.length}):`,rows:t.running.map(LT)},{title:`Dead (reclaimable) (${t.dead.length}):`,rows:t.dead.map(CT)},{title:`Idle, finished in the last ${Wo(e)} (${t.idle.length}):`,rows:t.idle.map(OT)}],n=["MEMBER","KIND","STATE","LIVENESS","MODEL","TIMING"],s=(0,rt.measureColumns)([{rows:[],headers:n},...r.map(a=>a.rows)],{max:AD}),i=!1,o=[];return r.forEach((a,l)=>{if(l>0&&o.push(""),o.push(a.title),a.rows.length===0){o.push(" none");return}let c=!i;i=!0,o.push((0,rt.renderGrid)(a.rows,{widths:s,margin:2,...c?{headers:n}:{}}))}),`${o.join(`
|
|
2762
2839
|
`)}
|
|
2763
|
-
`}async function
|
|
2764
|
-
`),0;let r=ae(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=X(r,"--tree"),i=X(r,"--watch"),o=W(r,"--team"),a=W(r,"--member"),l=
|
|
2765
|
-
`):se(e,y),0}return e.stdout.write(s?
|
|
2766
|
-
`)}finally{g=!1}f+=1,nu!==void 0&&f>=nu&&y(_)}},p=setInterval(()=>{h(p)},u*1e3);h(p),process.once("SIGINT",()=>y(p)),process.once("SIGTERM",()=>y(p))}):d()}var rt,
|
|
2767
|
-
`),
|
|
2768
|
-
${
|
|
2769
|
-
`),2}async function
|
|
2770
|
-
`),0;let r=ae(t,["--timeout"],["--json"]);if(r.error!==void 0)return ou(e,r.error);let n=X(r,"--json");for(let p of r.positionals)if(!
|
|
2840
|
+
`}async function $D(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${xD}
|
|
2841
|
+
`),0;let r=ae(t,["--team","--member","--since","--watch-interval"],["--json","--tree","--watch"]);if(r.error!==void 0)return A(e,r.error);let n=X(r,"--json"),s=X(r,"--tree"),i=X(r,"--watch"),o=W(r,"--team"),a=W(r,"--member"),l=LD(W(r,"--since"));if("error"in l)return A(e,l.error);let c=W(r,"--watch-interval"),u=c===void 0?bD:Number.parseInt(c.replace(/s$/,""),10);if(!Number.isFinite(u)||u<1)return A(e,`invalid --watch-interval "${c}" (expected <N>s, N\u22651)`);let d=()=>C(e,m=>{let f={...o!==void 0?{teamfile:he(o,m)}:{},...a!==void 0?{member:a.toLowerCase()}:{},idleWindowMs:l.windowMs},g=CD(m,f,{tree:s});if(n){let y=OD(g,s);return i?e.stdout.write(`${JSON.stringify(y)}
|
|
2842
|
+
`):se(e,y),0}return e.stdout.write(s?DD(g):MD(g,l.windowMs)),0});return i?await new Promise(m=>{let f=0,g=!1,y=_=>{clearInterval(_),m(0)},h=async _=>{if(!g){g=!0;try{await d()}catch(T){e.stderr.write(`running: ${T instanceof Error?T.message:String(T)}
|
|
2843
|
+
`)}finally{g=!1}f+=1,nu!==void 0&&f>=nu&&y(_)}},p=setInterval(()=>{h(p)},u*1e3);h(p),process.once("SIGINT",()=>y(p)),process.once("SIGTERM",()=>y(p))}):d()}var rt,SD,RT,bD,nu,xD,NT,Zd,AD,$T=k(()=>{"use strict";rt=It(gt(),1);st();Ln();kt();ge();Qd();At();SD=24*60*60*1e3,RT=3,bD=2;xD=["usage: lmctl running [--team <file>] [--member <alias>] [--since <duration|ISO8601>]"," [--tree] [--watch] [--watch-interval Ns] [--json]","","Shows tracked_invocation activity DB-wide across the whole fleet, split","into three sections (flat mode, the default):",' - Running: status="running" with a live (or unverifiable cross-host)'," holder -- genuinely in-flight work.",' - Dead (reclaimable): status="running" but the holder process is'," confirmed dead -- an orphaned record, not active work. Its elapsed",' time is reported as staleness, not as "running", so a dead worker'," is never mistaken for one that is genuinely still building."," - Idle: targets with nothing running or dead, showing their most"," recent finish from the last 24 hours and how long they've been"," idle since.","","--team <file> narrows the view to one teamfile (path is canonicalized","before matching); --member <alias> narrows it to one member alias","(case-insensitive; combinable with --team). --since sets the lookback","window for the Idle section -- a relative duration (<n>s|m|h|d, e.g. 7d)","or an absolute ISO8601 timestamp (default 24h). Running and Dead are","point-in-time current state and are not time-filtered.","","--watch re-renders the full snapshot every --watch-interval (default 2s)","until interrupted (SIGINT/SIGTERM). With --json, each snapshot is emitted","as ONE compact JSON object per line (NDJSON).","","--tree shows the same rows as one hierarchical dispatch-lineage view","instead: no section headers (each row already carries its own status),","indented under the session that dispatched it (who woke whom), sorted","by the most recent root session first. A node is a specific turn at a","specific time, not a team:alias identity -- the same member can appear","as multiple nodes for its different turns. Lineage is only known for","turns dispatched by a NESTED `lmctl prompt`/`lmctl terminal` call made","from within another turn's own tool calls; anything else (a human's","direct dispatch, or a turn from before this feature existed) has no","recorded parent and shows as its own root. Unlike the flat Idle section,","--tree does NOT collapse finished rows to one per target: every finished","descendant of a node in view (within the --since window) is rendered, so","a `lmctl batch` run shows as its batch root with ALL of its per-prompt","turns nested underneath.","","Every row also carries `model`: the target member's declared `model=`",'read straight from its teamfile (no session/provider query) -- "default"',"when the teamfile has no model= attribute, the alias/file can't be","resolved, or there is no target at all. This is the DECLARED value only,","not necessarily what actually ran (see the MODEL column in `lmctl status","<teamfile> --details`).","","--json emits { schema_version, running, dead, idle } (flat, one array","per section, matching the three flat-mode sections -- each row carries","its own status/timing/error fields). --tree --json instead emits","{ schema_version, tree } -- an array of root nodes, each row's full",'fields plus a "state" discriminant ("running"/"dead"/"idle") and a','"children" array of the same shape, nested per the dispatch lineage.',"","Queries lmctl's own database only -- never touches native provider","session files."].join(`
|
|
2844
|
+
`),NT=120;Zd="default";AD=[26,void 0,void 0,void 0,24,void 0]});var jT={};oe(jT,{runRatelimit:()=>WD});function iu(t){return typeof t=="object"&&t!==null}function FD(t){return(0,Se.formatPercent)(typeof t=="number"?t:null)}function PD(t,e){let r=typeof e.bucket_id=="string"&&e.bucket_id!==""?e.bucket_id:"unknown-bucket";return r==="session"?r="5h":r==="week-all-models"?r="weekly":r.startsWith("week-scoped-")&&(r=`weekly-${r.slice(12)}`),t!==""&&!r.startsWith(`${t}-`)&&(r=`${t}-${r}`),(0,Se.escapeCell)(r)}function jD(t,e){let r="unknown",n=null,s,i=null;if(typeof e.resets_at_iso=="string"&&e.resets_at_iso!==""){let c=Date.parse(e.resets_at_iso);i=Number.isFinite(c)?c-Date.now():null,i!==null&&(Math.abs(i)<1e3?r="now":i>0?r=`in ${(0,Se.formatDuration)(i,{maxUnit:"d",style:"compact"})}`:r=`${(0,Se.formatDuration)(-i,{maxUnit:"d",style:"compact"})} ago`,s=UD[typeof e.window_type=="string"?e.window_type:""],s!==void 0&&(n=Math.min(1,Math.max(0,1-i/s))))}n!==null&&(r=`${(0,Se.formatBar)(n)} ${r}`);let o="";if(n!==null&&s!==void 0&&i!==null&&typeof e.used_fraction=="number"&&Number.isFinite(e.used_fraction)){let c=e.used_fraction;if(c<=n){let u=n>0?Math.max(0,1-c/n):NaN;o=`unused +${(0,Se.formatPercent)(u)}`}else{let u=n*s,d=u>0?(1-c)/c*u:0,m=Math.max(0,i-d);o=`needing -${(0,Se.formatDuration)(m,{maxUnit:"d",style:"compact"})}`}}let a=[];e.is_exhausted===!0&&a.push("[EXHAUSTED]"),e.allowed===!1&&a.push("allowed=false"),e.limit_reached===!0&&a.push("limit_reached");let l=[PD(t,e),`${(0,Se.formatBar)(typeof e.used_fraction=="number"?e.used_fraction:null)} ${FD(e.used_fraction)}`,r];return o!==""&&l.push(o),a.length>0&&l.push(a.join(" ")),l}function BD(t){let e=typeof t.provider=="string"&&t.provider!==""?t.provider:"unknown",r=typeof t.status=="string"?t.status:"unknown",n=typeof t.source=="string"&&t.source!==""?t.source:"unknown source",s=typeof t.plan_type=="string"&&t.plan_type!==""?t.plan_type:"?",i=typeof t.read_at=="number"&&Number.isFinite(t.read_at)?(0,Se.formatClock)(t.read_at*1e3):"unknown",o=typeof t.reason=="string"?t.reason:"",a=`${e}: ${r} (${n}) plan=${s} read ${i}`;r==="auth_expired"?(a=`${e}: unavailable (${n}) plan=${s} read ${i}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`)):r==="provider_unavailable"&&UT.has(o)?(a=`${e}: not installed/configured (${n}) plan=${s} read ${i}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`)):r!=="ok"&&(a+=` -- ${o!==""?o:"no reason given"}`,typeof t.detail=="string"&&t.detail!==""&&(a+=` -- ${t.detail}`),r==="provider_unavailable"&&(a+=` (${e} server-side, not lmctl \u2014 try again later)`));let l=typeof t.provider=="string"?t.provider:"",c=Array.isArray(t.buckets)?t.buckets.filter(iu).map(d=>jD(l,d)):[],u=[];if(iu(t.credits)){let d=t.credits,m=[];typeof d.has_credits=="boolean"&&m.push(`has_credits=${d.has_credits}`),d.unlimited===!0&&m.push("unlimited"),d.balance!==void 0&&d.balance!==null&&m.push(`balance=${String(d.balance)}`),u.push(` credits: ${m.length>0?m.join(" "):"present"}`)}if(iu(t.spend_control)){let d=t.spend_control,m=` spend control: reached=${d.reached===!0}`;d.individual_limit!==void 0&&d.individual_limit!==null&&(m+=` individual_limit=${String(d.individual_limit)}`),u.push(m)}return{head:a,bucketRows:c,footers:u}}function ou(t,e){return t.stderr.write(`error: ${e}
|
|
2845
|
+
${PT}
|
|
2846
|
+
`),2}async function WD(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${PT}
|
|
2847
|
+
`),0;let r=ae(t,["--timeout"],["--json"]);if(r.error!==void 0)return ou(e,r.error);let n=X(r,"--json");for(let p of r.positionals)if(!FT.includes(p))return ou(e,`unknown provider: ${p} (valid targets: ${FT.join(", ")})`);let s=r.positionals.length>0?r.positionals:["all"],i=15,o=W(r,"--timeout");if(o!==void 0){let p=Number(o);if(!Number.isFinite(p)||p<=0)return ou(e,`invalid --timeout "${o}" (expected a positive number of seconds)`);i=p}let a=await yo({targets:s,timeoutSeconds:i,env:e.env??process.env,progress:p=>e.stderr.write(`${p}
|
|
2771
2848
|
`)});if(a.status==="error")return e.stderr.write(`error: ${a.error}
|
|
2772
|
-
`),1;let l=a.readings;if(n)return se(e,{readings:l}),0;let c=new Set(r.positionals),u=l.filter(p=>{let _=typeof p.status=="string"?p.status:"",T=typeof p.reason=="string"?p.reason:"";return _!=="provider_unavailable"||!
|
|
2773
|
-
`),0;let d=["LIMIT","USED","RESET TIME","OVERSTOCK"],m=["left","left","left"],f=u.map(
|
|
2849
|
+
`),1;let l=a.readings;if(n)return se(e,{readings:l}),0;let c=new Set(r.positionals),u=l.filter(p=>{let _=typeof p.status=="string"?p.status:"",T=typeof p.reason=="string"?p.reason:"";return _!=="provider_unavailable"||!UT.has(T)?!0:c.has(typeof p.provider=="string"?p.provider:"")});if(u.length===0)return e.stdout.write(`rate-limit: no readings returned.
|
|
2850
|
+
`),0;let d=["LIMIT","USED","RESET TIME","OVERSTOCK"],m=["left","left","left"],f=u.map(BD),g=(0,Se.measureColumns)([{rows:[],headers:d},...f.map(p=>p.bucketRows)]),y=!1,h=[];for(let p of f){if(h.length>0&&h.push(""),h.push(p.head),p.bucketRows.length>0){let _=!y;y=!0,h.push((0,Se.renderGrid)(p.bucketRows,{widths:g,margin:2,align:m,..._?{headers:d}:{}}))}h.push(...p.footers)}return e.stdout.write(`${h.join(`
|
|
2774
2851
|
`)}
|
|
2775
|
-
`),0}var Se,
|
|
2776
|
-
`),
|
|
2777
|
-
`,"utf8"),
|
|
2852
|
+
`),0}var Se,PT,UT,FT,UD,BT=k(()=>{"use strict";Se=It(gt(),1);ge();dd();PT=["usage: lmctl ratelimit [provider ...] [--json] [--timeout <seconds>]",""," Queries provider subscription rate limits in REAL TIME via the TypeScript"," provider readers -- stateless: nothing is read from or written to any"," database.",""," Providers: all (default), codex, agy, claude, kimi. Multiple allowed.",""," --timeout <seconds> Per-provider reader timeout (default 15).",' --json Emit {"readings": [...]} in the lmratelimit-v1 schema'," with every raw field preserved verbatim -- the same"," shape lmbee's collector parses. Unknown future"," fields pass through.","",' Prints a "querying ..." note on stderr before the readers run.'].join(`
|
|
2853
|
+
`),UT=new Set(["agy_not_found","credentials_missing"]),FT=_o;UD={five_hour:5*36e5,daily:864e5,weekly:7*864e5,monthly:30*864e5}});ct();import{pathToFileURL as HD}from"node:url";import{execFileSync as sw}from"node:child_process";import{existsSync as iw,readFileSync as ow}from"node:fs";import{join as gu}from"node:path";import{fileURLToPath as aw}from"node:url";function _u(){return aw(new URL("../..",import.meta.url))}function Ko(t=_u()){try{let e=JSON.parse(ow(gu(t,"package.json"),"utf8"));if(typeof e.version=="string")return e.version}catch{}return"0.0.0"}function Vo(t,e){try{return sw("git",e,{cwd:t,stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim()}catch{return}}function Yo(t=_u()){let e=Ko(t);if(!iw(gu(t,".git")))return e;let r=Vo(t,["rev-parse","--short","HEAD"]);if(r===void 0)return e;let n=Vo(t,["describe","--tags","--exact-match","HEAD"]),s=Vo(t,["status","--porcelain"]),i=s!==void 0&&s.length>0;return n===`v${e}`&&!i?e:`${e}+${r}${i?".dirty":""}`}V();import{mkdirSync as Tw,readFileSync as ww,renameSync as vw,writeFileSync as Sw}from"node:fs";import{homedir as bw}from"node:os";import{dirname as Iw,join as xw}from"node:path";function xu(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function yw(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function Ew(t,e){return!yw(t)||xu(t)?null:`${e} must use https://: ${t}`}async function ku(t,e){let r=Ew(t,e.description);if(r!==null||!xu(t))throw new Error(r??`${e.description} must use https://: ${t}`);let n=e.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let o;try{o=await fetch(t,{signal:s.signal,redirect:"manual"})}catch(a){throw Iu(t,e.description,n,a)}if(o.type==="opaqueredirect"||o.status>=300&&o.status<400)throw new Error(`refusing to follow redirect from ${e.description} ${t} (https-only: the URL must serve the content directly, not redirect)`);if(!o.ok)throw new Error(`failed to fetch ${e.description} ${t}: HTTP ${o.status}${o.statusText?` ${o.statusText}`:""}`);try{return Buffer.from(await o.arrayBuffer())}catch(a){throw Iu(t,e.description,n,a)}}finally{clearTimeout(i)}}function Iu(t,e,r,n){let i=n instanceof Error&&n.name==="AbortError"?`timed out after ${r}ms`:n instanceof Error?n.message:String(n);return new Error(`failed to fetch ${e} ${t}: ${i}`)}var kw="https://registry.npmjs.org/@lmctl-ai/lmctl/latest",Aw=60*60*1e3,Rw=1500;function Nw(){let t=process.env.HOME??bw();return xw(t,".lmctl",".update-check.json")}function Lw(t){return t.isTTY===!0}function Cw(t,e){let r=i=>{let o=/^(\d+)\.(\d+)\.(\d+)(?:$|[-+])/.exec(i.trim());if(o===null)return null;let a=o.slice(1).map(l=>Number(l));return a.some(l=>!Number.isSafeInteger(l)||l<0)?null:a},n=r(t),s=r(e);if(n===null||s===null)return 0;for(let i=0;i<3;i+=1){if(n[i]>s[i])return 1;if(n[i]<s[i])return-1}return 0}function Qo(t,e){return!!(process.env.LMCTL_NO_UPDATE_NOTIFIER==="1"||!Lw(e.stderr)||t.includes("--json")||t.includes("--help")||t.includes("-h")||t[0]==="help"||t[0]==="mcp")}function Ow(t,e){try{let r=JSON.parse(ww(t,"utf8"));if(typeof r.checkedAt=="number"&&Number.isFinite(r.checkedAt)&&typeof r.latest=="string"&&e-r.checkedAt<Aw)return r.latest}catch{}return null}function Dw(t,e){Tw(Iw(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;Sw(r,`${JSON.stringify(e)}
|
|
2854
|
+
`,"utf8"),vw(r,t)}async function Mw(){let t=await ku(kw,{description:"lmctl npm metadata",timeoutMs:Rw}),e=JSON.parse(t.toString("utf8"));if(typeof e.version!="string"||e.version.trim()==="")throw new Error("registry response missing version");return e.version}async function Au(t,e=[],r={}){try{if(Qo(e,t))return;let n=r.now?.()??Date.now(),s=r.cachePath??Nw();if(Ow(s,n)!==null)return;let o=await(r.fetchLatest??Mw)();try{Dw(s,{checkedAt:n,latest:o})}catch{return}let a=r.currentVersion?.()??Ko();Cw(o,a)>0&&t.stderr.write(`update available: ${a} \u2192 ${o} run: npm i -g @lmctl-ai/lmctl@latest
|
|
2778
2855
|
`)}catch{}}ea();Ws();var wn=`usage: lmctl [--db PATH] [--debug] <command> [args]
|
|
2779
2856
|
`,au=`${wn}
|
|
2780
2857
|
Onboarding:
|
|
@@ -2811,9 +2888,9 @@ Global flags:
|
|
|
2811
2888
|
write full stack + cause chain and context to that file.
|
|
2812
2889
|
|
|
2813
2890
|
Run 'lmctl help <command>' for command-specific help.
|
|
2814
|
-
`,
|
|
2891
|
+
`,WT=new Set(["init","quickrun","hello","prompt","chat","batch","script","mcp","terminal","tail","export","cost","ls","lint","seed","plan","status","running","ratelimit","db"]);function HT(t,e){return t.stderr.write(`error: ${e}
|
|
2815
2892
|
${wn}Run 'lmctl help' for usage.
|
|
2816
|
-
`),2}function
|
|
2893
|
+
`),2}function qT(t,e){return e==="send"?(t.stderr.write(`error: unknown command: send (use lmctl prompt)
|
|
2817
2894
|
${wn}Run 'lmctl help' for usage.
|
|
2818
2895
|
`),1):e==="recv"?(t.stderr.write(`error: unknown command: recv
|
|
2819
2896
|
${wn}Run 'lmctl help' for usage.
|
|
@@ -2821,23 +2898,23 @@ ${wn}Run 'lmctl help' for usage.
|
|
|
2821
2898
|
${wn}Run 'lmctl help' for usage.
|
|
2822
2899
|
`),1):(t.stderr.write(`error: unknown command: ${e}
|
|
2823
2900
|
${wn}Run 'lmctl help' for usage.
|
|
2824
|
-
`),1)}async function
|
|
2825
|
-
`),0;if(i==="--help"||i==="-h"||i===void 0)return e.stdout.write(au),0;if(i==="help"){let[c,...u]=r.slice(1);return c===void 0||c==="--help"||c==="-h"?(e.stdout.write(au),0):
|
|
2901
|
+
`),1)}async function XD(t,e={stdout:process.stdout,stderr:process.stderr}){let r=vu();try{return await qD(t,e)}finally{Su(r)}}async function qD(t,e={stdout:process.stdout,stderr:process.stderr}){let r=[],n,s=0;for(;s<t.length;s+=1){let c=t[s];if(c==="--db"){let u=t[++s];if(u===void 0||u.startsWith("--"))return HT(e,"missing value for --db");n=u;continue}if(c==="--debug"){wu();continue}if(c==="--allow-schema-skew"){process.env.LMCTL_ALLOW_SCHEMA_SKEW="1";continue}break}if(r.push(...t.slice(s)),n!==void 0){let c=r[0];if($s()&&c!==void 0&&Fs(c))return HT(e,"--db cannot be combined with an infra command (lmctl and lmauto use separate databases)");process.env.LMCTL_DB=n}let i=r[0];if(i==="--version"||i==="-v"||i==="-V")return e.stdout.write(`lmctl ${Yo()}
|
|
2902
|
+
`),0;if(i==="--help"||i==="-h"||i===void 0)return e.stdout.write(au),0;if(i==="help"){let[c,...u]=r.slice(1);return c===void 0||c==="--help"||c==="-h"?(e.stdout.write(au),0):WT.has(c)?XT(c,[...u,"--help"],e):qT(e,c)}Jo(pe(),e.stderr);let[o,...a]=r;if(o===void 0)return e.stdout.write(au),0;let l=Date.now();lu(o,a,{phase:"start",started_at:new Date(l).toISOString()});try{let c=await XT(o,a,e);return lu(o,a,{phase:"finish",outcome:c===0?"ok":"error",exit_code:c,duration_ms:Date.now()-l}),WT.has(o)&&!Qo(r,e)&&await Au(e,r),c}catch(c){let u=c instanceof Error?c:new Error(String(c));return lu(o,a,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-l,error_class:u.name,error_message:u.message,error_stack:u.stack??null,causes:JD(u)}),GD(c,o,a,e)}}function lu(t,e,r){Ie({event:t,record_kind:"cli_action",command:t,argv:e,cwd:process.cwd(),db_path:pe(),lmctl_version:Yo(),node_version:process.version,...r})}function GD(t,e,r,n){let s=t instanceof Error?t:new Error(String(t));return s instanceof jt&&r.includes("--json")?(n.stdout.write(`${JSON.stringify({error:s.message,schema_skew:{db_version:s.dbVersion,build_version:s.buildVersion,mode:"refused"}},null,2)}
|
|
2826
2903
|
`),1):(n.stderr.write(`error: ${s.message}
|
|
2827
2904
|
`),bu()?(n.stderr.write(`(debug details written to ~/.lmctl/debug-*.log)
|
|
2828
2905
|
`),1):(n.stderr.write(`(re-run with --debug for the full stack trace and context in ~/.lmctl/debug-*.log)
|
|
2829
|
-
`),1))}function
|
|
2830
|
-
`);let{runChat:n}=await Promise.resolve().then(()=>(wo(),_d));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(
|
|
2906
|
+
`),1))}function JD(t){let e=[],r=t.cause,n=0;for(;r!=null&&n<8;){let s=r instanceof Error?r:new Error(String(r));e.push({error_class:s.name,error_message:s.message,error_stack:s.stack??null}),r=s.cause,n+=1}return e}async function XT(t,e,r){switch(t){case"batch":{let{runBatch:n}=await Promise.resolve().then(()=>(Cg(),Lg));return n(e,r)}case"script":{let{runScript:n}=await Promise.resolve().then(()=>(Oy(),Cy));return n(e,r)}case"prompt":{let{runChat:n}=await Promise.resolve().then(()=>(wo(),_d)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(Co(),Lo));return s(r,"prompt",e,i=>n(i,r))}case"chat":{process.stderr.write(`warning: 'lmctl chat' is being phased out -- use 'lmctl prompt' (same behaviour; a prompt is answered, it is not a conversation)
|
|
2907
|
+
`);let{runChat:n}=await Promise.resolve().then(()=>(wo(),_d));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(bE(),SE));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(FE(),$E));return n(e,r)}case"export":{let{runExport:n}=await Promise.resolve().then(()=>(jE(),UE));return n(e,r)}case"cost":{let{runCost:n}=await Promise.resolve().then(()=>(WE(),BE));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(qE(),XE));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>($t(),cd));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>($t(),cd)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(Co(),Lo));return s(r,"seed",e,i=>n(i,r))}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(As(),pE)),{runWithSaveScript:s}=await Promise.resolve().then(()=>(Co(),Lo));return s(r,"plan",e,i=>n(i,r),{ownsForce:!0,extension:".txt"})}case"init":{let{runInit:n}=await Promise.resolve().then(()=>(JE(),GE));return n(e,r)}case"quickrun":{let{runQuickrun:n}=await Promise.resolve().then(()=>(sT(),nT));return n(e,r)}case"hello":{let{runHello:n}=await Promise.resolve().then(()=>(aT(),oT));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(Dd(),tT));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Qd(),AT));return n(e,r)}case"running":{let{runRunning:n}=await Promise.resolve().then(()=>($T(),MT));return n(e,r)}case"ratelimit":{let{runRatelimit:n}=await Promise.resolve().then(()=>(BT(),jT));return n(e,r)}case"db":return VD(e,r);default:if($s()&&Fs(t)){let{runInfraCommand:n}=await Promise.resolve().then(()=>(ea(),Nu));return n(t,e,r)}return qT(r,t)}}async function VD(t,e){let[r,...n]=t;return r==="--help"||r==="-h"||r==="help"?(e.stdout.write(`usage: lmctl db <subcommand>
|
|
2831
2908
|
|
|
2832
2909
|
backfill-events Replay the legacy tables into the event-log
|
|
2833
2910
|
(with --db <copy>) substrate and rebuild projections. Idempotent;
|
|
2834
2911
|
run against a COPY of the DB, never the live file.
|
|
2835
2912
|
downgrade --to <version> --confirm Documented stub (restore from backup).
|
|
2836
|
-
`),0):r==="backfill-events"
|
|
2913
|
+
`),0):r==="backfill-events"?KD(n,e):r==="downgrade"?(e.stderr.write(`not yet implemented; restore from backup, or run lmctl migrate (forward-migrates ok)
|
|
2837
2914
|
`),1):(e.stderr.write(`usage: lmctl db <subcommand> (backfill-events | downgrade)
|
|
2838
|
-
`),1)}async function
|
|
2915
|
+
`),1)}async function KD(t,e){let{resolveDbPath:r}=await Promise.resolve().then(()=>(ct(),hu)),n=r();if(!((process.env.LMCTL_DB??"").length>0)&&!t.includes("--allow-live"))return e.stderr.write(`refusing to backfill the default live DB.
|
|
2839
2916
|
resolved target: ${n}
|
|
2840
2917
|
run against a COPY: cp <state.db> copy.db && lmctl --db copy.db db backfill-events
|
|
2841
2918
|
(or pass --allow-live to target the resolved DB deliberately).
|
|
2842
2919
|
`),1;let{migrate:i}=await Promise.resolve().then(()=>(Ws(),ju)),{backfillEventLog:o}=await Promise.resolve().then(()=>(la(),Cu)),a=i({dbPath:n});try{let l=o(a);return e.stdout.write(`${JSON.stringify(l,null,2)}
|
|
2843
|
-
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===
|
|
2920
|
+
`),0}finally{a.close()}}if(process.argv[1]!==void 0&&import.meta.url===HD(process.argv[1]).href){let t=await XD(process.argv.slice(2));process.exitCode=t}export{WT as COMMANDS,XD as runCli};
|