@lmctl-ai/lmctl 0.1.111 → 0.1.113
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/README.md +6 -5
- package/dist/cli/index.js +67 -61
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -14,7 +14,7 @@ var Xk=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>{f
|
|
|
14
14
|
`).filter(i=>i.length>0),o=s.slice(Math.max(0,s.length-r));return{source_path:e,tail_lines:o.length,tail:Yn(o.join(`
|
|
15
15
|
`)),note:null}}catch(n){return n.code==="ENOENT"?{source_path:e,tail_lines:0,tail:"",note:"no intent log present (status never run on this host)"}:{source_path:e,tail_lines:0,tail:"",note:`intent log unreadable: ${n instanceof Error?n.message:String(n)}`}}}var wo,hI,xl,zn=T(()=>{"use strict";yo();wo=["serve","db","runs","jobs","attentions","env","intents"];hI=["LMCTL_DB","LMCTL_API_URL","LMCTL_API_TOKEN","LMCTL_PID_FILE","LMCTL_SERVE_LOG","LMCTL_SESSIONDIR","LMCTL_DAEMON_INTERVAL_MS","LMCTL_SESSION_SIZE_DISABLED","NODE_ENV","PATH"];xl=["id","job_id","workflow_id","team_id","current_state","terminal_state","started_at","ended_at","paused_at","parent_run_id","blocker"].join(", ")});import{readFileSync as qm,appendFileSync as kI,mkdirSync as II,existsSync as vX,readdirSync as kX,unlinkSync as IX}from"node:fs";import{join as To,dirname as NI}from"node:path";import{homedir as AI}from"node:os";function Ll(){return To(AI(),".lmctl")}function Hm(){Yr=!0,process.env.LMCTL_DEBUG="1"}function Jm(){return{cliDebug:Yr,lmctlDebugEnv:process.env.LMCTL_DEBUG}}function Xm(t){Yr=t.cliDebug,t.lmctlDebugEnv===void 0?delete process.env.LMCTL_DEBUG:process.env.LMCTL_DEBUG=t.lmctlDebugEnv}function ue(){if(Yr||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-Bm>=xI&&(Wm=$I(),Bm=t),Wm}function Gm(){return Yr||process.env.LMCTL_DEBUG==="1"}function RI(){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 Oe(t,e){if(e?.verbose){if(!Yr)return}else if(!e?.always&&!ue())return;try{LI();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};kI(Eo,JSON.stringify(r)+`
|
|
16
16
|
`)}catch{}}function LI(){if(!Eo){let e=RI().slice(0,13).replace("T","-");Eo=To(Ll(),`debug-${e}.log`)}II(NI(Eo),{recursive:!0})}function je(...t){Oe({event:"legacy",msg:t.join(" ")})}function bt(...t){Oe({event:"legacy",msg:t.join(" ")},{verbose:!0})}function Z(t){Oe(t,{always:!0})}function $I(){return OI()||jI()}function OI(){try{let t=qm(To(Ll(),"config.toml"),"utf-8");for(let e of t.split(`
|
|
17
|
-
`)){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 jI(){try{let t=qm(To(Ll(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Yr,Wm,Bm,xI,Eo,ve=T(()=>{"use strict";Yr=!1,Wm=!1,Bm=0,xI=5e3;Eo=null});function Zn(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function $l(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function Qn(t,e){return!$l(t)||Zn(t)?null:`${e} must use https://: ${t}`}async function bo(t,e){let r=Qn(t,e.description);if(r!==null||!Zn(t))throw new Error(r??`${e.description} must use https://: ${t}`);let n=e.timeoutMs??15e3,s=new AbortController,o=setTimeout(()=>s.abort(),n);try{let i;try{i=await fetch(t,{signal:s.signal,redirect:"manual"})}catch(a){throw Km(t,e.description,n,a)}if(i.type==="opaqueredirect"||i.status>=300&&i.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(!i.ok)throw new Error(`failed to fetch ${e.description} ${t}: HTTP ${i.status}${i.statusText?` ${i.statusText}`:""}`);try{return Buffer.from(await i.arrayBuffer())}catch(a){throw Km(t,e.description,n,a)}}finally{clearTimeout(o)}}function Km(t,e,r,n){let o=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}: ${o}`)}var Ol=T(()=>{"use strict"});function rr(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 So=T(()=>{"use strict"});import{hostname as zI}from"node:os";function nr(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},o=t.getAgentInflight(e.receiver_teamfile,e.receiver_alias),i=o===null||o.holder_pid===null,a=t.tryAcquireAgentInflight(s,{...i?{stale_before:n}:{},force:e.force});if(a.acquired){let c=o===null?null:e.force===!0?"force":o.holder_pid===null&&o.started_at<n?"stale":null;return{acquired:!0,lease:a.current??s,previous:o,reclaimReason:c}}if(!Zm(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}});return l.acquired?{acquired:!0,lease:l.current??s,previous:a.current,reclaimReason:a.current.holder_pid===null?"stale":"dead-pid"}:{acquired:!1,current:l.current}}function zr(t,e,r){let n=t.getTerminalLock(e,r);if(n!==null&&ZI(n))return!0;let s=t.getAgentInflight(e,r);if(s===null)return!1;let o=new Date(Date.now()-QI()).toISOString();return!Zm(s,o)}function ZI(t){if(t.holder_host===zI())return rr(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=
|
|
17
|
+
`)){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 jI(){try{let t=qm(To(Ll(),"config.json"),"utf-8"),e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.debug===!0}catch{}return!1}var Yr,Wm,Bm,xI,Eo,ve=T(()=>{"use strict";Yr=!1,Wm=!1,Bm=0,xI=5e3;Eo=null});function Zn(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function $l(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function Qn(t,e){return!$l(t)||Zn(t)?null:`${e} must use https://: ${t}`}async function bo(t,e){let r=Qn(t,e.description);if(r!==null||!Zn(t))throw new Error(r??`${e.description} must use https://: ${t}`);let n=e.timeoutMs??15e3,s=new AbortController,o=setTimeout(()=>s.abort(),n);try{let i;try{i=await fetch(t,{signal:s.signal,redirect:"manual"})}catch(a){throw Km(t,e.description,n,a)}if(i.type==="opaqueredirect"||i.status>=300&&i.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(!i.ok)throw new Error(`failed to fetch ${e.description} ${t}: HTTP ${i.status}${i.statusText?` ${i.statusText}`:""}`);try{return Buffer.from(await i.arrayBuffer())}catch(a){throw Km(t,e.description,n,a)}}finally{clearTimeout(o)}}function Km(t,e,r,n){let o=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}: ${o}`)}var Ol=T(()=>{"use strict"});function rr(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 So=T(()=>{"use strict"});import{hostname as zI}from"node:os";function nr(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},o=t.getAgentInflight(e.receiver_teamfile,e.receiver_alias),i=o===null||o.holder_pid===null,a=t.tryAcquireAgentInflight(s,{...i?{stale_before:n}:{},force:e.force});if(a.acquired){let c=o===null?null:e.force===!0?"force":o.holder_pid===null&&o.started_at<n?"stale":null;return{acquired:!0,lease:a.current??s,previous:o,reclaimReason:c}}if(!Zm(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}});return l.acquired?{acquired:!0,lease:l.current??s,previous:a.current,reclaimReason:a.current.holder_pid===null?"stale":"dead-pid"}:{acquired:!1,current:l.current}}function zr(t,e,r){let n=t.getTerminalLock(e,r);if(n!==null&&ZI(n))return!0;let s=t.getAgentInflight(e,r);if(s===null)return!1;let o=new Date(Date.now()-QI()).toISOString();return!Zm(s,o)}function ZI(t){if(t.holder_host===zI())return rr(t.holder_pid);let e=Date.parse(t.last_heartbeat);return Number.isFinite(e)?Date.now()-e<=eN():!1}function Zm(t,e){return t.holder_pid===null?t.started_at<e:!rr(t.holder_pid)}function QI(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 eN(t=process.env){let e=t.LMCTL_TERMINAL_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return zm;let r=Number(e);return!Number.isFinite(r)||r<=0?zm:r}var Ym,zm,es=T(()=>{"use strict";So();Ym=8*60*60*1e3,zm=12e4});import{existsSync as tN}from"node:fs";import{createRequire as rN}from"node:module";function nN(){return Cl===null&&(Cl=rN(import.meta.url)("node:sqlite").DatabaseSync),Cl}function Ml(t){return t.length===1&&sN(t[0])?[t[0]]:t}function sN(t){if(!Fl(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Fl(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Cl,Dl,vo,Pl,Ul=T(()=>{"use strict";Cl=null;Dl=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!tN(e))throw new Error("unable to open database file");this.name=e,this.handle=new(nN())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new Pl(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)}}},vo=Dl,Pl=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...Ml(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...Ml(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...Ml(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&Fl(e)?Object.values(e):Fl(e)?{...e}:e}}});import{existsSync as oN,mkdirSync as iN,readFileSync as ep}from"node:fs";import{homedir as aN}from"node:os";import{dirname as tp,join as lN,resolve as rp}from"node:path";import{fileURLToPath as cN,pathToFileURL as uN}from"node:url";function Bl(t){t.dbPath!==":memory:"&&iN(tp(t.dbPath),{recursive:!0});let e=new vo(t.dbPath);e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=op(e);return r===0&&(e.exec(ep(sp,"utf8")),e.pragma(`user_version = ${Wl}`)),fN(e,r),e}function fN(t,e){let r=e;if(r<2&&r!==0&&(t.exec(`
|
|
18
18
|
CREATE TABLE IF NOT EXISTS session_size (
|
|
19
19
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
20
20
|
team_name TEXT NOT NULL,
|
|
@@ -583,7 +583,7 @@ var Xk=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>{f
|
|
|
583
583
|
notified_at = COALESCE(ended_at, started_at)
|
|
584
584
|
WHERE status IN ('done', 'error', 'busy', 'cancelled')
|
|
585
585
|
AND notified_by IS NULL;
|
|
586
|
-
`),t.pragma("user_version = 49"),r=49),
|
|
586
|
+
`),t.pragma("user_version = 49"),r=49),oN(dN)}function de(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function ts(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ko(t,e){if(!ts(t,e)&&(t.exec(ep(sp,"utf8")),!ts(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function Qm(t){let e=de(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
587
587
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
588
588
|
CREATE TABLE team_chat_log_v46 (
|
|
589
589
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -612,7 +612,7 @@ var Xk=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>{f
|
|
|
612
612
|
FROM team_chat_log;
|
|
613
613
|
DROP TABLE team_chat_log;
|
|
614
614
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
615
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function op(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function
|
|
615
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function op(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function mN(){return process.env.LMCTL_DB??lN(aN(),".lmctl","state.db")}var np,sp,dN,Wl,ql=T(()=>{"use strict";Ul();np=tp(cN(import.meta.url)),sp=rp(np,"schema.sql"),dN=rp(np,"migrations"),Wl=49;if(process.argv[1]&&import.meta.url===uN(process.argv[1]).href){let t=Bl({dbPath:process.argv[2]??mN()});try{process.stdout.write(`migrated user_version=${op(t)}
|
|
616
616
|
`)}finally{t.close()}}});function ip(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(`
|
|
617
617
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
618
618
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
@@ -886,8 +886,8 @@ var Xk=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>{f
|
|
|
886
886
|
AND delivering_at IS NULL
|
|
887
887
|
ORDER BY receiver_teamfile ASC, receiver_alias ASC, id ASC
|
|
888
888
|
`),deleteMailboxMessage:t.prepare("DELETE FROM agent_mailbox WHERE id = ?")}}function Hl(t){if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(dp,"utf8"),n=Math.max(0,65536-r),s=Buffer.from(t,"utf8"),o=n;for(;o>0&&(s[o]&192)===128;)o-=1;return`${s.subarray(0,o).toString("utf8")}${dp}`}var dp,mp=T(()=>{"use strict";dp=`
|
|
889
|
-
...[truncated]`});function ss(t,e){return JSON.stringify([t,e])}function pp(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 rs,ns,_p=T(()=>{"use strict";rs="terminal_lock",ns="member"});function Zr(t){return typeof t=="string"&&
|
|
890
|
-
`)}var hp,Io,
|
|
889
|
+
...[truncated]`});function ss(t,e){return JSON.stringify([t,e])}function pp(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 rs,ns,_p=T(()=>{"use strict";rs="terminal_lock",ns="member"});function Zr(t){return typeof t=="string"&&pN.has(t)}function yp(t){return["Decide the workflow outcome. Reply with a final line:",` STANCE: <one of: ${t.length>0?t.join(" | "):"(this step declares no outcomes \u2014 escalate)"}>`,"If you cannot pick one of those declared outcomes, escalate to a","human instead \u2014 reply with exactly one of:",` STANCE: ${Io[0]}`,` STANCE: ${Io[1]}`,` STANCE: ${Io[2]}`,` STANCE: ${hp}: <one short sentence: why no declared outcome fits>`,"Never invent a different outcome; never leave the STANCE line out."].join(`
|
|
890
|
+
`)}var hp,Io,pN,os,gp,Jl,No,is=T(()=>{"use strict";hp="other",Io=["not_enough_information","dont_know","other_work"],pN=new Set([hp,...Io]),os="@abort",gp="invalid_decision",Jl="escalation_aborted",No="workflow_escalation"});import{randomUUID as wp}from"node:crypto";import{hostname as as}from"node:os";function xe(t){return t.provider_resolved??t.provider}function M(){return new Date().toISOString()}function he(t){return new Xl(Bl({dbPath:t.path}))}function Ep(t,e,r){let n=Tp(e);if(n.length===0)return;let s=new Set,o=[],i=l=>{if(l===t)return n;let c=r(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Tp(c.definition)},a=l=>{let c=o.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...o.slice(c),l].join(" -> ")}`);if(!s.has(l)){o.push(l);try{for(let u of i(l))a(u)}finally{o.pop()}s.add(l)}};a(t)}function Tp(t){let e=_N(t),r=e===null?null:hN(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))Ao(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function _N(t){try{let e=JSON.parse(t);return Ao(e)?e:null}catch{return null}}function hN(t,e){let r=t[e];return Ao(r)?r:null}function Ao(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gN(t){try{let e=JSON.parse(t);return!Ao(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 yN(t,e){return t===null?!0:t.holder_host===as()?!rr(t.holder_pid):t.last_heartbeat<e}function wN(t,e){return t.delivering_at===null?!1:t.delivery_holder_host===as()&&EN(t.delivery_holder_pid)?!rr(t.delivery_holder_pid):t.delivering_at<e}function EN(t){return Number.isInteger(t)&&(t??0)>0}function TN(t){return{...fp(t),getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
891
891
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
892
892
|
VALUES (?, ?, ?, ?, ?)
|
|
893
893
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1287,52 +1287,52 @@ var Xk=Object.defineProperty;var T=(t,e)=>()=>(t&&(e=t(t=0)),e);var se=(t,e)=>{f
|
|
|
1287
1287
|
error_detail = ?,
|
|
1288
1288
|
truncated = ?
|
|
1289
1289
|
WHERE id = ?
|
|
1290
|
-
`),...cp(t),...ip(t)}}function b0(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Xl,Me=T(()=>{"use strict";ql();ap();up();mp();_p();So();is();Xl=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=T0(e),this.claimTxn=e.transaction((r,n,s)=>{let o=this.stmts.selectClaimableJob.get(s,s,s);return o===void 0||this.stmts.claimJob.run(r,n,s,o.id,s,s,s).changes!==1?null:this.getJob(o.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,o)=>{let i=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of i){let l=this.getJob(a.id);if(l===null)continue;let c=o(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,o,i)=>{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>=o)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<=o,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<o;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=i(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,o,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,o,a.id,o,o,o).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=o?"locked":"not_claimable",job_id:r,status:p?.status??a.status,locked_by:p?.locked_by??a.locked_by,locked_until:p?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>b0("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,o)=>{let i=this.getInteractiveSessionByStepId(r);if(i===null)return{resumed:!1,reason:"not_found"};if(i.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(i.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(),i.id),this.stmts.resumeRunState.run(i.state_name,a.id),this.stmts.requeuePausedJob.run(o,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 o=this.stmts.getAttention.get(r);if(o===void 0)return{resumed:!1,reason:"not_found"};if(o.kind!==No)return{resumed:!1,reason:"wrong_kind"};if(o.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(o.run_id===null)return{resumed:!1,reason:"run_not_found"};let i=null,a=[];if(o.payload!==null)try{let u=JSON.parse(o.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(i=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(i===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(o.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==os&&!a.includes(n))return{resumed:!1,reason:gp};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[i]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(i,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=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:s?.sender_teamfile??null,reclaim_observed_sender_alias:s?.sender_alias??null,reclaim_observed_started_at:s?.started_at??null,reclaim_observed_holder_pid:typeof s?.holder_pid=="number"?s.holder_pid:null}),i=o!==void 0?{acquired:!0,current:o}:{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"),i}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}},this.recvMailboxMessagesTxn=e.transaction((r,n)=>{let s=this.stmts.listAllMailboxMessagesForReceiver.all(r,n);for(let o of s)this.stmts.deleteMailboxMessage.run(o.id);return 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){Ep(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,M()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,M());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 o=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),o}upsertWorkflow(e){Ep(e.name,e.definition,i=>this.getWorkflowByName(i));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,o=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,M());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(o.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,M())}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 o=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,i=this.stmts.insertWorkflowVersion.run(e,o,r,n??null,M());return this.stmts.getWorkflowVersion.get(i.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let o=JSON.parse(n.definition);typeof o.definition_schema_version=="number"&&(s=o.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,M()),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,M(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(M(),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 o of s){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.length===0||typeof i.type!="string"||i.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:i.id,trigger_type:i.type,parameters:JSON.stringify(i.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,M());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,M());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,M(),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"),o=Object.prototype.hasOwnProperty.call(r,"model"),i=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,o?r.model??null:n.model,i?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,M());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",M());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"),o=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),i=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,o?r.durable_memory_mode:n.durable_memory_mode,i?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,M());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=M(),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,M(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,M(),e)??null}closeIssue(e,r,n){let s=M(),o=this.stmts.closeIssue.get(r,n??null,s,s,e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,M(),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"),o=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),i=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,o?r.ai_test_path??null:n.ai_test_path,M(),e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=M();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,o){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,o,M(),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,M(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=wp(),s=M();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 o=M(),i=this.stmts.insertChatbotMessage.run(e,r,n,s??null,o);return this.stmts.touchChatbotSession.run(o,e),this.stmts.getChatbotMessage.get(i.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,M())}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??M(),e.dedupe_key??null,e.concurrency_key??null,M());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=M(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=M(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=M(),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:M();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,M()),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,M()),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??M(),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,M());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=M(),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),o=this.getWebProject(s);if(o===null)throw new Error(`web_project ${s} missing after insert`);return o}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,M(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(M(),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){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.created_at);return Number(r.lastInsertRowid)}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){let r=e.started_at??M(),n=e.holder_host??as(),s=e.last_heartbeat_at??r,o=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,Pt(e.command),r,e.holder_pid??null,n,s,Pt(e.meta));return this.getTrackedInvocation(Number(o.lastInsertRowid))}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){let n=r.ended_at??M();return this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Pt(r.result_summary),Pt(r.error),r.team_chat_log_id??null,Pt(r.meta),n,e).changes!==1?null:this.getTrackedInvocation(e)}reclaimTrackedInvocationIfUnchanged(e,r,n){let s=n.ended_at??M();return this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Pt(n.result_summary),Pt(n.error),n.team_chat_log_id??null,Pt(n.meta),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1?null:this.getTrackedInvocation(e)}heartbeatTrackedInvocation(e,r=M()){return this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1?null:this.getTrackedInvocation(e)}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled')","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=M()){return this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1?null:this.getTrackedInvocation(e)}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 o=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${o} 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 ")}`,o=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(o?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}enqueueMail(e){return this.sendMailboxMessage(e)}sendMailboxMessage(e){let r=this.stmts.insertMailboxMessage.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile??null,e.sender_alias??null,e.root_teamfile??null,Hl(e.payload),e.created_at??M(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null);return this.getMailboxMessage(Number(r.lastInsertRowid))}listEnqueuedMailFromSender(e,r,n,s){return this.stmts.listEnqueuedMailFromSender.all(e,r,n,s)}markMailDelivered(e,r,n){let s=[...new Set(e.map(i=>Math.trunc(i)).filter(i=>Number.isInteger(i)&&i>0))];if(s.length===0)return 0;let o=Hl(r);this.db.exec("BEGIN IMMEDIATE");try{let i=0;for(let a of s)i+=this.stmts.markMailboxMessageDelivered.run(n,o,a).changes;return this.db.exec("COMMIT"),i}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}claimMailForDelivery(e,r,n=process.pid,s=as()){let o=[...new Set(e.map(i=>Math.trunc(i)).filter(i=>Number.isInteger(i)&&i>0))];if(o.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let i=[];for(let a of o)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,a).changes===1){let c=this.getMailboxMessage(a);c!==null&&i.push(c)}return this.db.exec("COMMIT"),i}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearMailDelivery(e){let r=[...new Set(e.map(n=>Math.trunc(n)).filter(n=>Number.isInteger(n)&&n>0))];if(r.length===0)return 0;this.db.exec("BEGIN IMMEDIATE");try{let n=0;for(let s of r)n+=this.stmts.clearMailboxMessageDelivery.run(s).changes;return this.db.exec("COMMIT"),n}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}reclaimMailboxDeliveryIfUnchanged(e){return this.stmts.clearMailboxMessageDeliveryIfUnchanged.run(e.id,e.delivering_at,e.delivery_holder_pid,e.delivery_holder_host).changes!==1?null:this.getMailboxMessage(e.id)}reclaimStaleMailboxDeliveries(e){let r=this.stmts.listInFlightMailboxDeliveries.all(),n=[];this.db.exec("BEGIN IMMEDIATE");try{for(let s of r){if(!w0(s,e))continue;let o=this.reclaimMailboxDeliveryIfUnchanged(s);o!==null&&n.push(o)}return this.db.exec("COMMIT"),n}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}listDeliveredReceiptsForSender(e,r){return this.stmts.listDeliveredReceiptsForSender.all(e,r)}listOutboundPendingForSender(e,r){return this.stmts.listOutboundPendingForSender.all(e,r)}getMailboxMessage(e){return this.stmts.getMailboxMessage.get(e)??null}peekMailboxMessages(e,r=1e3){return this.stmts.listMailboxMessagesForReceiver.all(e.receiver_teamfile,e.receiver_alias,Math.max(1,Math.min(1e3,Math.trunc(r))))}recvMailboxMessages(e){return this.recvMailboxMessagesTxn(e.receiver_teamfile,e.receiver_alias)}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)}clearAgentInflight(e,r){this.stmts.clearAgentInflight.run(e,r)}clearObservedTerminalAgentInflight(e,r,n){return 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}).changes===1}releaseAgentInflight(e){this.db.exec("BEGIN IMMEDIATE");try{let r=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(r===null||r.sender_teamfile!==e.sender_teamfile||r.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r.active_count<=1)return this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias),this.db.exec("COMMIT"),!0;let n=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),n.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.stmts.clearAgentInflightOlderThan.run(e).changes}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(rs,ss(e,r),ns);return n===void 0?null:pp(n.data)}setTerminalLock(e){this.stmts.upsertRuntimeState.run(rs,ss(e.teamfile,e.alias),ns,JSON.stringify(e),e.last_heartbeat)}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getTerminalLock(e,r);if(o===null||o.lock_id!==n)return this.db.exec("COMMIT"),!1;let i={...o,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(rs,ss(e,r),ns,JSON.stringify(i),s),this.db.exec("COMMIT"),!0}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}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 o=this.stmts.deleteRuntimeState.run(rs,ss(e,r),ns);return this.db.exec("COMMIT"),o.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:g0(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,o=M()){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i!==null&&!y0(i,s))return this.db.exec("COMMIT"),{acquired:!1,current:i};let a={lock_id:wp(),holder_pid:process.pid,holder_host:as(),started_at:o,last_heartbeat:o};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),o),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:i}}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o===null||o.lock_id!==s)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),i.changes===1}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}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,M(),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,M())}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,M());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,M(),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??M(),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,M());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,M()).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,M()),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,M());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(M(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=M();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:o,type:i,updated_at:a})=>({name:s,description:o,type:i,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:o,updated_at:i})=>({name:n,description:s,type:o,updated_at:i}))}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??M());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,o=0;for(let i of r)try{let a=JSON.parse(i.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),o+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:o}}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,M())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,M())}}});async function R(t,e){if(t.dal!==void 0)return e(t.dal);let r=he({path:le()});try{return await e(r)}finally{r.close()}}function F(t,e,r=["--json"]){let n=new Set(e),s=new Set(r),o=[],i={};for(let a=0;a<t.length;a+=1){let l=t[a];if(!l.startsWith("--")){o.push(l);continue}if(s.has(l)){i[l]=!0;continue}if(!n.has(l))return{positionals:o,flags:i,error:`unknown flag: ${l}`};let c=t[a+1];if(c===void 0||c.startsWith("--"))return{positionals:o,flags:i,error:`missing value for ${l}`};i[l]=c,a+=1}return{positionals:o,flags:i}}function L(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function D(t,e){return t.flags[e]===!0}function W(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1290
|
+
`),...cp(t),...ip(t)}}function bN(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var Xl,Me=T(()=>{"use strict";ql();ap();up();mp();_p();So();is();Xl=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=TN(e),this.claimTxn=e.transaction((r,n,s)=>{let o=this.stmts.selectClaimableJob.get(s,s,s);return o===void 0||this.stmts.claimJob.run(r,n,s,o.id,s,s,s).changes!==1?null:this.getJob(o.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,o)=>{let i=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of i){let l=this.getJob(a.id);if(l===null)continue;let c=o(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,o,i)=>{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>=o)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<=o,u=a.status==="running"&&a.locked_until!==null&&a.locked_until<o;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=i(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,o,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,o,a.id,o,o,o).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=o?"locked":"not_claimable",job_id:r,status:p?.status??a.status,locked_by:p?.locked_by??a.locked_by,locked_until:p?.locked_until??a.locked_until}}let m=this.getJob(a.id);return m===null?{claimed:!1,reason:"not_found",job_id:r}:{claimed:!0,job:m}}),this.resumeRunTxn=e.transaction((r,n,s)=>bN("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,o)=>{let i=this.getInteractiveSessionByStepId(r);if(i===null)return{resumed:!1,reason:"not_found"};if(i.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(i.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(),i.id),this.stmts.resumeRunState.run(i.state_name,a.id),this.stmts.requeuePausedJob.run(o,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 o=this.stmts.getAttention.get(r);if(o===void 0)return{resumed:!1,reason:"not_found"};if(o.kind!==No)return{resumed:!1,reason:"wrong_kind"};if(o.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(o.run_id===null)return{resumed:!1,reason:"run_not_found"};let i=null,a=[];if(o.payload!==null)try{let u=JSON.parse(o.payload);u.step!==void 0&&typeof u.step.id=="string"&&u.step.id.length>0&&(i=u.step.id),Array.isArray(u.declared_outcomes)&&(a=u.declared_outcomes.filter(d=>typeof d=="string"))}catch{}if(i===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(o.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==os&&!a.includes(n))return{resumed:!1,reason:gp};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[i]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(i,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=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:s?.sender_teamfile??null,reclaim_observed_sender_alias:s?.sender_alias??null,reclaim_observed_started_at:s?.started_at??null,reclaim_observed_holder_pid:typeof s?.holder_pid=="number"?s.holder_pid:null}),i=o!==void 0?{acquired:!0,current:o}:{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"),i}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}},this.recvMailboxMessagesTxn=e.transaction((r,n)=>{let s=this.stmts.listAllMailboxMessagesForReceiver.all(r,n);for(let o of s)this.stmts.deleteMailboxMessage.run(o.id);return 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){Ep(e.name,e.definition,i=>this.getWorkflowByName(i));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,M()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,M());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 o=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),o}upsertWorkflow(e){Ep(e.name,e.definition,i=>this.getWorkflowByName(i));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,o=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,M());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(o.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,M())}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 o=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,i=this.stmts.insertWorkflowVersion.run(e,o,r,n??null,M());return this.stmts.getWorkflowVersion.get(i.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let o=JSON.parse(n.definition);typeof o.definition_schema_version=="number"&&(s=o.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,M()),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,M(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(M(),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 o of s){if(o===null||typeof o!="object"||Array.isArray(o))continue;let i=o;typeof i.id!="string"||i.id.length===0||typeof i.type!="string"||i.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:i.id,trigger_type:i.type,parameters:JSON.stringify(i.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,M());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,M());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,M(),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"),o=Object.prototype.hasOwnProperty.call(r,"model"),i=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,o?r.model??null:n.model,i?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,M());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",M());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"),o=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),i=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,o?r.durable_memory_mode:n.durable_memory_mode,i?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,M());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=M(),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,M(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,M(),e)??null}closeIssue(e,r,n){let s=M(),o=this.stmts.closeIssue.get(r,n??null,s,s,e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,M(),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"),o=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),i=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,o?r.ai_test_path??null:n.ai_test_path,M(),e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=M();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,o){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,o,M(),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,M(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=wp(),s=M();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 o=M(),i=this.stmts.insertChatbotMessage.run(e,r,n,s??null,o);return this.stmts.touchChatbotSession.run(o,e),this.stmts.getChatbotMessage.get(i.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,M())}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??M(),e.dedupe_key??null,e.concurrency_key??null,M());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=M(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=M(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=M(),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:M();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,M()),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,M()),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??M(),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,M());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=M(),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),o=this.getWebProject(s);if(o===null)throw new Error(`web_project ${s} missing after insert`);return o}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,M(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(M(),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){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.created_at);return Number(r.lastInsertRowid)}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){let r=e.started_at??M(),n=e.holder_host??as(),s=e.last_heartbeat_at??r,o=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,Pt(e.command),r,e.holder_pid??null,n,s,Pt(e.meta));return this.getTrackedInvocation(Number(o.lastInsertRowid))}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){let n=r.ended_at??M();return this.stmts.finishTrackedInvocation.run(r.status,n,r.exit_code??null,r.signal??null,Pt(r.result_summary),Pt(r.error),r.team_chat_log_id??null,Pt(r.meta),n,e).changes!==1?null:this.getTrackedInvocation(e)}reclaimTrackedInvocationIfUnchanged(e,r,n){let s=n.ended_at??M();return this.stmts.reclaimTrackedInvocationIfUnchanged.run(n.status,s,n.exit_code??null,n.signal??null,Pt(n.result_summary),Pt(n.error),n.team_chat_log_id??null,Pt(n.meta),s,e,r.holder_pid,r.holder_host,r.started_at,r.last_heartbeat_at).changes!==1?null:this.getTrackedInvocation(e)}heartbeatTrackedInvocation(e,r=M()){return this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1?null:this.getTrackedInvocation(e)}listClaimableTerminalTrackedInvocations(e){let r=["status IN ('done', 'error', 'busy', 'cancelled')","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=M()){return this.stmts.claimTrackedInvocationNotification.run(r,n,e).changes!==1?null:this.getTrackedInvocation(e)}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 o=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${o} 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 ")}`,o=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(o?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}enqueueMail(e){return this.sendMailboxMessage(e)}sendMailboxMessage(e){let r=this.stmts.insertMailboxMessage.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile??null,e.sender_alias??null,e.root_teamfile??null,Hl(e.payload),e.created_at??M(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null);return this.getMailboxMessage(Number(r.lastInsertRowid))}listEnqueuedMailFromSender(e,r,n,s){return this.stmts.listEnqueuedMailFromSender.all(e,r,n,s)}markMailDelivered(e,r,n){let s=[...new Set(e.map(i=>Math.trunc(i)).filter(i=>Number.isInteger(i)&&i>0))];if(s.length===0)return 0;let o=Hl(r);this.db.exec("BEGIN IMMEDIATE");try{let i=0;for(let a of s)i+=this.stmts.markMailboxMessageDelivered.run(n,o,a).changes;return this.db.exec("COMMIT"),i}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}claimMailForDelivery(e,r,n=process.pid,s=as()){let o=[...new Set(e.map(i=>Math.trunc(i)).filter(i=>Number.isInteger(i)&&i>0))];if(o.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let i=[];for(let a of o)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,a).changes===1){let c=this.getMailboxMessage(a);c!==null&&i.push(c)}return this.db.exec("COMMIT"),i}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearMailDelivery(e){let r=[...new Set(e.map(n=>Math.trunc(n)).filter(n=>Number.isInteger(n)&&n>0))];if(r.length===0)return 0;this.db.exec("BEGIN IMMEDIATE");try{let n=0;for(let s of r)n+=this.stmts.clearMailboxMessageDelivery.run(s).changes;return this.db.exec("COMMIT"),n}catch(n){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),n}}reclaimMailboxDeliveryIfUnchanged(e){return this.stmts.clearMailboxMessageDeliveryIfUnchanged.run(e.id,e.delivering_at,e.delivery_holder_pid,e.delivery_holder_host).changes!==1?null:this.getMailboxMessage(e.id)}reclaimStaleMailboxDeliveries(e){let r=this.stmts.listInFlightMailboxDeliveries.all(),n=[];this.db.exec("BEGIN IMMEDIATE");try{for(let s of r){if(!wN(s,e))continue;let o=this.reclaimMailboxDeliveryIfUnchanged(s);o!==null&&n.push(o)}return this.db.exec("COMMIT"),n}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}listDeliveredReceiptsForSender(e,r){return this.stmts.listDeliveredReceiptsForSender.all(e,r)}listOutboundPendingForSender(e,r){return this.stmts.listOutboundPendingForSender.all(e,r)}getMailboxMessage(e){return this.stmts.getMailboxMessage.get(e)??null}peekMailboxMessages(e,r=1e3){return this.stmts.listMailboxMessagesForReceiver.all(e.receiver_teamfile,e.receiver_alias,Math.max(1,Math.min(1e3,Math.trunc(r))))}recvMailboxMessages(e){return this.recvMailboxMessagesTxn(e.receiver_teamfile,e.receiver_alias)}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)}clearAgentInflight(e,r){this.stmts.clearAgentInflight.run(e,r)}clearObservedTerminalAgentInflight(e,r,n){return 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}).changes===1}releaseAgentInflight(e){this.db.exec("BEGIN IMMEDIATE");try{let r=this.getAgentInflight(e.receiver_teamfile,e.receiver_alias);if(r===null||r.sender_teamfile!==e.sender_teamfile||r.sender_alias!==e.sender_alias)return this.db.exec("COMMIT"),!1;if(r.active_count<=1)return this.stmts.clearAgentInflightIfSender.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias),this.db.exec("COMMIT"),!0;let n=this.stmts.decrementAgentInflight.run(e.receiver_teamfile,e.receiver_alias,e.sender_teamfile,e.sender_alias);return this.db.exec("COMMIT"),n.changes===1}catch(r){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),r}}clearAgentInflightOlderThan(e){return this.stmts.clearAgentInflightOlderThan.run(e).changes}getTerminalLock(e,r){let n=this.stmts.getRuntimeState.get(rs,ss(e,r),ns);return n===void 0?null:pp(n.data)}setTerminalLock(e){this.stmts.upsertRuntimeState.run(rs,ss(e.teamfile,e.alias),ns,JSON.stringify(e),e.last_heartbeat)}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getTerminalLock(e,r);if(o===null||o.lock_id!==n)return this.db.exec("COMMIT"),!1;let i={...o,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(rs,ss(e,r),ns,JSON.stringify(i),s),this.db.exec("COMMIT"),!0}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}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 o=this.stmts.deleteRuntimeState.run(rs,ss(e,r),ns);return this.db.exec("COMMIT"),o.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:gN(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,o=M()){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i!==null&&!yN(i,s))return this.db.exec("COMMIT"),{acquired:!1,current:i};let a={lock_id:wp(),holder_pid:process.pid,holder_host:as(),started_at:o,last_heartbeat:o};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),o),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:i}}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o===null||o.lock_id!==s)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),i.changes===1}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}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,M(),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,M())}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,M());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,M(),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??M(),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,M());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,M()).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,M()),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,M());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(M(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=M();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:o,type:i,updated_at:a})=>({name:s,description:o,type:i,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:o,updated_at:i})=>({name:n,description:s,type:o,updated_at:i}))}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??M());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,o=0;for(let i of r)try{let a=JSON.parse(i.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),o+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:o}}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,M())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,M())}}});async function R(t,e){if(t.dal!==void 0)return e(t.dal);let r=he({path:le()});try{return await e(r)}finally{r.close()}}function F(t,e,r=["--json"]){let n=new Set(e),s=new Set(r),o=[],i={};for(let a=0;a<t.length;a+=1){let l=t[a];if(!l.startsWith("--")){o.push(l);continue}if(s.has(l)){i[l]=!0;continue}if(!n.has(l))return{positionals:o,flags:i,error:`unknown flag: ${l}`};let c=t[a+1];if(c===void 0||c.startsWith("--"))return{positionals:o,flags:i,error:`missing value for ${l}`};i[l]=c,a+=1}return{positionals:o,flags:i}}function L(t,e){let r=t.flags[e];return typeof r=="string"?r:void 0}function D(t,e){return t.flags[e]===!0}function W(t,e){t.stdout.write(`${JSON.stringify(e,null,2)}
|
|
1291
1291
|
`)}function y(t,e){return t.stderr.write(`error: ${e}
|
|
1292
1292
|
`),1}function _e(t,e){let r=e instanceof Error?e.message:String(e);return t.stderr.write(`internal error: ${r}
|
|
1293
1293
|
`),2}var ge=T(()=>{"use strict";Me();Ve()});function bp(t){if(t.length===0||!t.startsWith("---"))throw new St("frontmatter must start at line 1 with `---` on its own line");let e=t.split(`
|
|
1294
|
-
`);if(e[0]!=="---")throw new St("frontmatter must start at line 1 with `---` on its own line");let r={},n=-1;for(let i=1;i<e.length;i++){let a=e[i];if(a==="---"){n=i;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new St(`malformed frontmatter line ${i+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!
|
|
1294
|
+
`);if(e[0]!=="---")throw new St("frontmatter must start at line 1 with `---` on its own line");let r={},n=-1;for(let i=1;i<e.length;i++){let a=e[i];if(a==="---"){n=i;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new St(`malformed frontmatter line ${i+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],u=l[2].trim();if(!SN.has(c))throw new St(`unknown frontmatter key "${c}" \u2014 allowed keys: ${xo.join(", ")}`);r[c]=u}if(n===-1)throw new St("frontmatter not closed (missing trailing `---` on its own line)");for(let i of xo)if(r[i]===void 0)throw new St(`missing required frontmatter key "${i}" \u2014 required: ${xo.join(", ")}`);let s=0;for(let i=0;i<=n;i++)s+=e[i].length+1;s>t.length&&(s=t.length);let o=r.members.split(",").map(i=>i.trim()).filter(Boolean);return{title:r.title,description:r.description,members:o,bodyOffset:s}}var xo,SN,St,Sp=T(()=>{"use strict";xo=["title","description","members"],SN=new Set(xo),St=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as vN,writeFileSync as h4,renameSync as g4,existsSync as kp}from"node:fs";import{basename as kN,resolve as Qr,dirname as Gl}from"node:path";function NN(t){let e={},r=/(\w+)=(?:"([^"]*)"|([\S]*))/g,n;for(;(n=r.exec(t))!==null;){let s=n[1],o=n[2]!==void 0?n[2]:n[3];e[s]=o}return e}function AN(t){return/^\s*_MEMBER_\s+\S/.test(t)}function xN(t){return/^\s*_SESSION_\s+\S/.test(t)}function RN(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function Ro(t){let e=kN(t);return e.endsWith(".lmctl")?e.slice(0,-6):e}function De(t){let e=vN(t,"utf-8"),r=Gl(Qr(t)),n=Vl(e,Ro(t),{baseDir:r,sourcePath:Qr(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Qr(r,s.sessiondir));return n}function Vl(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let o=t;if(o.startsWith("#teamfile:")){let l=o.indexOf(`
|
|
1295
1295
|
`);o=l>=0?o.slice(l+1):""}let i=null;if(o.startsWith("---"))try{i=bp(o)}catch(l){if(l instanceof St)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
1296
|
-
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(
|
|
1297
|
-
allowed keys: ${vp.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}let m={alias:d.alias||`member${n.length+1}`,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:i}}function Yl(t,e){let r=[];for(let o of t.parseErrors)r.push({field:"session",message:o});let n=t.members.filter(o=>o.alias.toLowerCase()===Kl.toLowerCase());n.length>1&&r.push({field:Kl,message:`${n.length} alias=Lead found (max 1)`});let s=new Set;for(let o of t.members){let i=o.alias.toLowerCase();if(s.has(i)&&r.push({field:o.alias,message:`Duplicate alias "${o.alias}" (case-insensitive)`}),s.add(i),o.teamfile){let a=e?Qr(e,o.teamfile):Qr(o.teamfile);if(!kp(a))r.push({field:o.alias,message:`Teamfile not found: ${a}`});else{let l=De(a),c=et(l);c?c.session||r.push({field:o.alias,message:`Team at ${o.teamfile} lead has no session ID. Run: lmctl seed`}):r.push({field:o.alias,message:`Team at ${o.teamfile} has no lead session`})}}else
|
|
1298
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function V(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var ke,or=T(()=>{"use strict";ke=V0()});import{readdir as Oo,stat as qp,unlink as Y0}from"node:fs/promises";import{join as en,basename as Hp}from"node:path";function z0(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function Z0(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return me(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 Jp(t){let e=0,r=0,n=0,s=0,o=0,i=0,a;for await(let l of He(t))if(!l.isSidechain){if(l.type==="user"&&!l.isMeta&&l.message){let c=l.message.content;if(typeof c=="string"){if(c.includes("<command-name>")||c.includes("<local-command-"))continue;e++}}else if(l.type==="assistant"&&l.message){let c=l.message.content;if(Array.isArray(c))for(let d of c)d.type==="text"&&e++;let u=l.message.usage;if(u){let d=u.input_tokens||0,f=u.cache_creation_input_tokens||0,m=u.cache_read_input_tokens||0,p=u.output_tokens||0;r+=d+f+m,n+=m,s+=f,o+=p;let _=d+f+m;_&&(i=_),a={inputTokens:d,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:o,lastInputTokens:i,lastTokenUsage:a}}var jo,Xp=T(()=>{"use strict";or();jo=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||en(ke,".claude"),this.projectsDir=en(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Oo(this.projectsDir)}catch{return e}for(let n of r){let s=en(this.projectsDir,n);if(!(await qp(s).catch(()=>null))?.isDirectory())continue;let i;try{i=await Oo(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let l=Hp(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=en(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,r){let n=await Pe(e,50),s=await Re(e),o="",i,a,l,c,u,d;for(let m of n)if(!z0(m.type)&&(!o&&m.cwd&&(o=m.cwd),!i&&m.slug&&(i=m.slug),!a&&m.version&&(a=m.version),!d&&m.timestamp&&(d=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let p=m.message.content;if(typeof p=="string"){if(p.includes("<command-name>")||p.includes("<local-command-"))continue;c||(c=V(p.trim(),80)),u=V(p.trim(),80)}}if(!o)return null;let f=await Jp(e);return{provider:"claude",sessionId:r,slug:i,cwd:o,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:u,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Re(r),s=[],o="",i,a,l,c,u,d,f,m=e;for await(let _ of He(r))if(_.type!=="file-history-snapshot"&&!_.isSidechain){if(!o&&_.cwd&&(o=_.cwd),!i&&_.slug&&(i=_.slug),!a&&_.version&&(a=_.version),!c&&_.gitBranch&&(c=_.gitBranch),!f&&_.timestamp&&(f=new Date(_.timestamp)),_.sessionId&&(m=_.sessionId),_.type==="system"||_.type==="progress"||_.type==="queue-operation"){s.push({role:"system",timestamp:new Date(_.timestamp||0),content:Z0(_)});continue}if(_.type==="user"&&_.message){if(_.isMeta)continue;let g=new Date(_.timestamp||0),h=_.message.content;if(typeof h=="string"){if(h.includes("<command-name>")||h.includes("<local-command-"))continue;u||(u=V(h.trim(),80)),d=V(h.trim(),80),s.push({role:"user",timestamp:g,content:me(h.trim())})}else if(Array.isArray(h)){for(let E of h)if(E.type==="tool_result"){let w=typeof E.content=="string"?me(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:g,content:w,toolCallId:E.tool_use_id})}}}if(_.type==="assistant"&&_.message){_.message.model&&(l=_.message.model);let g=new Date(_.timestamp||0),h=_.message.content;if(Array.isArray(h))for(let E of h)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:g,content:me(E.text),model:_.message.model}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolCallId:E.id,model:_.message.model}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:g,content:E.thinking})}}if(!o)return null;let p=await Jp(r);return{provider:"claude",sessionId:m,slug:i,cwd:o,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,firstUserMessage:u,lastUserMessage:d,messageCount:p.messageCount,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:p.totalCacheWriteInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,lastInputTokens:p.lastInputTokens||void 0,lastTokenUsage:p.lastTokenUsage,messages:s}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await Y0(r),!0):!1}async resolveSessionFile(e){let r;try{r=await Oo(this.projectsDir)}catch{return null}let n=[];for(let i of r){let a=en(this.projectsDir,i);if(!(await qp(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Oo(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=Hp(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:en(a,u),fileSessionId:d})}}let s=n.find(i=>i.fileSessionId===e);if(s)return s.filePath;let o=n.filter(i=>i.fileSessionId.startsWith(e));if(o.length===1)return o[0].filePath;for(let i of n){let a=await Pe(i.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return i.filePath}return null}}});function Co(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function eN(t,e,r){if(!r)return"";let n=t.tools[e]??ec[e],s=n?.profiles?.[r]?.flags??ec[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 Gp(t,e){return!!t.tools[e]}function Kp(t,e,r,n,s){let o=t.tools[e]??ec[e],i;if(o?.agent){let l=Co(n);i=o.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=Q0[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(Co).join(" ");i=`printf '%s\\n' ${Co(n)} | ${u}`}else i=c.map(Co).join(" ")}let a=eN(t,e,s);return a&&(i+=" "+a),i}var ec,Q0,Vp=T(()=>{"use strict";ec={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:""}}}},Q0={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"]}}});function Yp(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 zp=T(()=>{"use strict"});var tN,Te,Mo,It=T(()=>{"use strict";tN="ACK: waiting for explicit lmctl task.",Te=`lmctl seed initial connection only. Create or pin this provider session, then stop. Do not inspect files, run commands, infer a task, delegate, edit, or begin work. Reply exactly: ${tN}`,Mo=`send this exact lmctl seed instruction: "${Te}"`});function Ft(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function rN(t,e){return e===void 0||e.length===0?t:{...t??process.env,[xr]:e}}function Je(t,e,r){return rN(Ft(t,e),r)}var xr,rt=T(()=>{"use strict";xr="LMCTL_SELF_SESSIONID"});import{spawn as Zp}from"node:child_process";import{mkdirSync as nN}from"node:fs";var tc,Le,Ut=T(()=>{"use strict";Vp();zp();It();rt();tc=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Le=class t{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===Te?r:n)}seed(e,r){return nN(e,{recursive:!0}),new Promise(n=>{let s;try{s=Zp(this.binary,this.seedArgsFor(r),{cwd:e,env:Ft(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let o="";s.stderr?.on("data",a=>{o+=a.toString()});let i=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1299
|
-
`:this.seedStdin;i&&s.stdin?.write(i),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:o.trim().slice(0,200)||`exit code ${a}`})}),s.on("error",a=>{n({success:!1,error:a.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:Mo,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&Gp(r.userConfig,this.name)){let s=r.userConfig.tools[this.name];if(s?.agent)return this.runOneShotAgent(e,r,s.agent)}let n=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return n<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(n,e,r)}withTimeouts(e,r,n){let s=new AbortController,o,i,a="",l,c=()=>{e<=0||(clearTimeout(o),o=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(o)};n.signal&&(n.signal.aborted?(i="external",s.abort()):n.signal.addEventListener("abort",()=>{i="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),n.onProgress?.(p)}},f=this.transportFn(r,d).then(p=>(u(),{...p,status:"ok"})).catch(p=>{throw u(),i==="external"?new tc("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=Kp(r.userConfig,this.name,r.sessionId,e,r.profile),o=Date.now();return new Promise((i,a)=>{let l=Yp(r.env),c=Zp(s,{shell:!0,cwd:r.cwd,env:Je(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,f=setTimeout(()=>{d=!0,c.kill()},l),m="",p="";if(c.stdout?.on("data",_=>{let g=_.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",_=>{p+=_.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",_=>{if(u)return;u=!0,clearTimeout(f);let g=Date.now()-o;d?a(new Error(`Agent command timed out after ${l}ms`)):_===0||_===null?i({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${_}`))}),c.on("error",_=>{u||(u=!0,clearTimeout(f),a(_))})})}}});function Po(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new Bt(t,r,e)}var nt,Ie,Wt,Do,Bt,tn=T(()=>{"use strict";nt=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},Ie=class extends nt{},Wt=class extends nt{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Do=class extends nt{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},Bt=class extends nt{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as nc from"node:child_process";function
|
|
1296
|
+
`);for(let l=0;l<a.length;l++){let c=a[l],u=l+1;if(xN(c))throw new Error(`line ${u}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(RN(c)||!AN(c))continue;let d=NN(c);for(let p of Object.keys(d))if(!vp.includes(p))throw new Error(`line ${u}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
1297
|
+
allowed keys: ${vp.join(", ")}`);if(!d.provider&&!d.teamfile){s.push(`line ${u}: member line missing provider (or teamfile): ${c.trim()}`);continue}let m={alias:d.alias||`member${n.length+1}`,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:i}}function Yl(t,e){let r=[];for(let o of t.parseErrors)r.push({field:"session",message:o});let n=t.members.filter(o=>o.alias.toLowerCase()===Kl.toLowerCase());n.length>1&&r.push({field:Kl,message:`${n.length} alias=Lead found (max 1)`});let s=new Set;for(let o of t.members){let i=o.alias.toLowerCase();if(s.has(i)&&r.push({field:o.alias,message:`Duplicate alias "${o.alias}" (case-insensitive)`}),s.add(i),o.teamfile){let a=e?Qr(e,o.teamfile):Qr(o.teamfile);if(!kp(a))r.push({field:o.alias,message:`Teamfile not found: ${a}`});else{let l=De(a),c=et(l);c?c.session||r.push({field:o.alias,message:`Team at ${o.teamfile} lead has no session ID. Run: lmctl seed`}):r.push({field:o.alias,message:`Team at ${o.teamfile} has no lead session`})}}else IN.has(o.provider)||r.push({field:o.alias,message:`Invalid provider "${o.provider}"`});o.sessiondir!==void 0&&o.sessiondir===""&&r.push({field:o.alias,message:"sessiondir is empty"})}return r}function et(t){return t.members.find(e=>e.alias.toLowerCase()===Kl.toLowerCase())}function zl(t,e,r,n={}){let s=n.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let o=Qr(e,t.teamfile),i=r??new Set;if(i.has(o))throw new Error(`Circular team reference: ${t.alias} \u2192 ${o} (already visited: ${[...i].join(" \u2192 ")})`);if(i.add(o),!kp(o))throw new Error(`Teamfile not found: ${o} (referenced by alias "${t.alias}")`);let a=De(o),l=et(a);if(!l)throw new Error(`Team at ${o} has no lead session`);if(l.teamfile)return zl(l,Gl(o),i,n);if(s&&!l.session)throw new Error(`Team at ${o} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||Gl(o),alias:t.alias,resolvedFrom:o,model:l.model,effort:l.effort}}function Lo(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var Kl,IN,vp,vt=T(()=>{"use strict";Sp();Kl="Lead",IN=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","ClaudeMock"]);vp=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as LN}from"node:crypto";import{existsSync as ls,mkdirSync as $N,readFileSync as Ap,realpathSync as ON,writeFileSync as jN}from"node:fs";import{basename as Ip,dirname as xp,resolve as Rp}from"node:path";function ye(t,e){let r=Rp(t);if(ls(r))return ON(r);if(e!==void 0){let n=DN(t,r,e);if(n!==null)return n}return r}function Np(t,e){let r=xp(e),n=Vl(t,Ro(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=Rp(r,s.sessiondir));return n}function qe(t,e){let r=ye(t,MN(e)?e:void 0);if(e!==void 0){let n=e.getRootTeam(r);if(n!==null)return!ls(r)&&"upsertRootTeam"in e&&($N(xp(r),{recursive:!0}),jN(r,n.raw_text,"utf8")),Np(n.raw_text,r);if(ls(r)){let s=Ap(r,"utf8"),o=Np(s,r);return"upsertRootTeam"in e&&PN(o)&&FN(e,r,o,s),o}throw new Error(`teamfile not found: ${t}`)}if(!ls(r))throw new Error(`teamfile not found: ${t}`);return De(r)}function Lp(t,e,r){let n=ye(t,e),s=e.getRootTeam(n);s===null||!ls(n)||Ap(n,"utf8")===s.raw_text||r(`warning: ${n} differs from the last seeded DB snapshot; runtime is using the seeded snapshot. Run: lmctl seed ${n}`)}function MN(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function DN(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);if(n!==null)return n.teamfile_path;let s=Ip(t),o=Ro(t),i=r.listRootTeams().filter(l=>Ip(l.teamfile_path)===s||l.name===o);if(i.length===0)return null;if(i.length===1)return i[0].teamfile_path;let a=i.map(l=>l.teamfile_path).join(", ");throw new Error(`ambiguous teamfile "${t}" in root-team registry: ${a}; pass an absolute path`)}function PN(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=CN)}function FN(t,e,r,n){let s=new Date().toISOString(),o={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:LN("sha256").update(n).digest("hex"),registered_at:s,last_seeded_at:s};t.upsertRootTeam(o)}var CN,tt=T(()=>{"use strict";vt();CN=5});import{basename as UN}from"node:path";function jp(t,e){let r=new Date(e.now.getTime()-sr()).toISOString(),n=Dp(t,r).filter(f=>!f.sender.teamfile.startsWith("prompt:")),s=qN(e.sender,n),o=HN(e.sender,n);o!==null&&o.teamfile===e.root&&!Op(s[0],o)&&s.unshift({...o,at:null});let i={teamfile:e.receiverTeamfile,alias:e.receiverAlias,at:e.now.getTime()},a=[...s,i],l=s.filter(f=>Op(f,i)),c=l.map(f=>f.at).filter(f=>f!==null).sort((f,m)=>m-f)[0]??null,u=c!==null&&e.now.getTime()-c<WN;return{stop:l.length>=1&&u,chain:JN(a)}}function Cp(t,e){let r=new Date(e.now.getTime()-sr()).toISOString(),n=Dp(t,r),s=Pp(e.sender,n);if(s.length===0)return null;let o=s[0];return o.sender.teamfile.startsWith("prompt:")?o.receiver.teamfile:o.sender.teamfile}function sr(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return $p;let r=Number(e);return!Number.isFinite(r)||r<=0?$p:r}function Mp(t){return`cross-team cycle detected (${t}); stopping to prevent a runaway loop.`}function BN(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 Dp(t,e){return t.clearAgentInflightOlderThan(e),t.listAgentInflight().map(BN).filter(r=>Number.isFinite(r.at)&&new Date(r.at).toISOString()>=e).sort((r,n)=>r.at-n.at)}function qN(t,e,r={}){let n=new Map;for(let a of e)n.set(Ar(a.receiver),a);let s=[{...t,at:null}],o=t,i=new Set([Ar(t)]);for(let a=0;a<64;a+=1){let l=n.get(Ar(o));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=Ar(l.sender);if(i.has(u))break;s.unshift(c),i.add(u),o=l.sender}return s}function Pp(t,e){let r=Ar(t),n=new Set([r]),s=[r],o=[];for(let i=0;s.length>0&&i<128;i+=1){let a=s.shift();for(let l of e){let c=Ar(l.sender),u=Ar(l.receiver);c!==a&&u!==a||(o.includes(l)||o.push(l),n.has(c)||(n.add(c),s.push(c)),n.has(u)||(n.add(u),s.push(u)))}}return o.sort((i,a)=>i.at-a.at)}function HN(t,e){let r=Pp(t,e);if(r.length===0)return null;let n=r[0];return n.sender.teamfile.startsWith("prompt:")?n.receiver:n.sender}function Op(t,e){return t.teamfile===e.teamfile&&t.alias===e.alias}function Ar(t){return`${t.teamfile}\0${t.alias}`}function JN(t){return t.map(e=>`${UN(e.teamfile)}:${e.alias}`).join(" \u2192 ")}var WN,$p,$o=T(()=>{"use strict";WN=6e4,$p=8*60*60*1e3});import{realpathSync as XN}from"node:fs";import{resolve as GN}from"node:path";function Zl(t){let e=GN(t);try{return XN(e)}catch{return e}}var Fp=T(()=>{"use strict"});import{platform as Up}from"node:os";function kt(t){let e=new cs;for(let r of t)e.registerAdapter(r);return e}var cs,Ql=T(()=>{"use strict";Fp();cs=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(i=>i.name===e.provider):this.providers,s=await Promise.all(n.map(i=>i.discoverSessions()));for(let i of s)r.push(...i);let o=r;if(e?.workspace){let i=Zl(e.workspace);o=o.filter(a=>Zl(a.cwd)===i)}if(e?.from){let i=e.from.getTime();o=o.filter(a=>a.modifiedAt.getTime()>=i)}if(e?.to){let i=e.to.getTime();o=o.filter(a=>a.modifiedAt.getTime()<=i)}return o.sort((i,a)=>a.modifiedAt.getTime()-i.modifiedAt.getTime()),e?.limit&&(o=o.slice(0,e.limit)),o}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let o=await s.loadSession(e);if(o)return o}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(o=>o.name===r):this.providers,s=[];for(let o of n){let i=await o.resolveSessionPath(e);i&&s.push({provider:o,filePath:i})}return s}getWatchTargets(){let e=Up()==="darwin"||Up()==="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 Wp}from"node:fs";import{createInterface as Bp}from"node:readline";import{stat as KN}from"node:fs/promises";import{homedir as VN}from"node:os";async function*He(t){let e=Wp(t,{encoding:"utf-8"}),r=Bp({input:e,crlfDelay:1/0});try{for await(let n of r){let s=n.trim();if(s)try{yield JSON.parse(s)}catch{}}}finally{e.destroy()}}async function Pe(t,e){let r=[],n=Wp(t,{encoding:"utf-8"}),s=Bp({input:n,crlfDelay:1/0});try{for await(let o of s){let i=o.trim();if(i){try{r.push(JSON.parse(i))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Re(t){let e=await KN(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function me(t){return t.replace(/\\n/g,`
|
|
1298
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function V(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var ke,or=T(()=>{"use strict";ke=VN()});import{readdir as Oo,stat as qp,unlink as YN}from"node:fs/promises";import{join as en,basename as Hp}from"node:path";function zN(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function ZN(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return me(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 Jp(t){let e=0,r=0,n=0,s=0,o=0,i=0,a;for await(let l of He(t))if(!l.isSidechain){if(l.type==="user"&&!l.isMeta&&l.message){let c=l.message.content;if(typeof c=="string"){if(c.includes("<command-name>")||c.includes("<local-command-"))continue;e++}}else if(l.type==="assistant"&&l.message){let c=l.message.content;if(Array.isArray(c))for(let d of c)d.type==="text"&&e++;let u=l.message.usage;if(u){let d=u.input_tokens||0,f=u.cache_creation_input_tokens||0,m=u.cache_read_input_tokens||0,p=u.output_tokens||0;r+=d+f+m,n+=m,s+=f,o+=p;let _=d+f+m;_&&(i=_),a={inputTokens:d,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:o,lastInputTokens:i,lastTokenUsage:a}}var jo,Xp=T(()=>{"use strict";or();jo=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||en(ke,".claude"),this.projectsDir=en(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Oo(this.projectsDir)}catch{return e}for(let n of r){let s=en(this.projectsDir,n);if(!(await qp(s).catch(()=>null))?.isDirectory())continue;let i;try{i=await Oo(s)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let l=Hp(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=en(s,a);try{let u=await this.extractSummary(c,l);u&&e.push(u)}catch{}}}return e}async extractSummary(e,r){let n=await Pe(e,50),s=await Re(e),o="",i,a,l,c,u,d;for(let m of n)if(!zN(m.type)&&(!o&&m.cwd&&(o=m.cwd),!i&&m.slug&&(i=m.slug),!a&&m.version&&(a=m.version),!d&&m.timestamp&&(d=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let p=m.message.content;if(typeof p=="string"){if(p.includes("<command-name>")||p.includes("<local-command-"))continue;c||(c=V(p.trim(),80)),u=V(p.trim(),80)}}if(!o)return null;let f=await Jp(e);return{provider:"claude",sessionId:r,slug:i,cwd:o,createdAt:d||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:u,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Re(r),s=[],o="",i,a,l,c,u,d,f,m=e;for await(let _ of He(r))if(_.type!=="file-history-snapshot"&&!_.isSidechain){if(!o&&_.cwd&&(o=_.cwd),!i&&_.slug&&(i=_.slug),!a&&_.version&&(a=_.version),!c&&_.gitBranch&&(c=_.gitBranch),!f&&_.timestamp&&(f=new Date(_.timestamp)),_.sessionId&&(m=_.sessionId),_.type==="system"||_.type==="progress"||_.type==="queue-operation"){s.push({role:"system",timestamp:new Date(_.timestamp||0),content:ZN(_)});continue}if(_.type==="user"&&_.message){if(_.isMeta)continue;let g=new Date(_.timestamp||0),h=_.message.content;if(typeof h=="string"){if(h.includes("<command-name>")||h.includes("<local-command-"))continue;u||(u=V(h.trim(),80)),d=V(h.trim(),80),s.push({role:"user",timestamp:g,content:me(h.trim())})}else if(Array.isArray(h)){for(let E of h)if(E.type==="tool_result"){let w=typeof E.content=="string"?me(E.content):JSON.stringify(E.content);s.push({role:"tool_result",timestamp:g,content:w,toolCallId:E.tool_use_id})}}}if(_.type==="assistant"&&_.message){_.message.model&&(l=_.message.model);let g=new Date(_.timestamp||0),h=_.message.content;if(Array.isArray(h))for(let E of h)E.type==="text"&&E.text?s.push({role:"assistant",timestamp:g,content:me(E.text),model:_.message.model}):E.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:E.name||"unknown tool",toolName:E.name,toolInput:JSON.stringify(E.input,null,2),toolCallId:E.id,model:_.message.model}):E.type==="thinking"&&E.thinking&&s.push({role:"thinking",timestamp:g,content:E.thinking})}}if(!o)return null;let p=await Jp(r);return{provider:"claude",sessionId:m,slug:i,cwd:o,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,firstUserMessage:u,lastUserMessage:d,messageCount:p.messageCount,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:p.totalCacheWriteInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,lastInputTokens:p.lastInputTokens||void 0,lastTokenUsage:p.lastTokenUsage,messages:s}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await YN(r),!0):!1}async resolveSessionFile(e){let r;try{r=await Oo(this.projectsDir)}catch{return null}let n=[];for(let i of r){let a=en(this.projectsDir,i);if(!(await qp(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await Oo(a)}catch{continue}for(let u of c){if(!u.endsWith(".jsonl"))continue;let d=Hp(u,".jsonl");/^[0-9a-f]{8}-/.test(d)&&n.push({filePath:en(a,u),fileSessionId:d})}}let s=n.find(i=>i.fileSessionId===e);if(s)return s.filePath;let o=n.filter(i=>i.fileSessionId.startsWith(e));if(o.length===1)return o[0].filePath;for(let i of n){let a=await Pe(i.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return i.filePath}return null}}});function Co(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function e0(t,e,r){if(!r)return"";let n=t.tools[e]??ec[e],s=n?.profiles?.[r]?.flags??ec[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 Gp(t,e){return!!t.tools[e]}function Kp(t,e,r,n,s){let o=t.tools[e]??ec[e],i;if(o?.agent){let l=Co(n);i=o.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=QN[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(Co).join(" ");i=`printf '%s\\n' ${Co(n)} | ${u}`}else i=c.map(Co).join(" ")}let a=e0(t,e,s);return a&&(i+=" "+a),i}var ec,QN,Vp=T(()=>{"use strict";ec={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:""}}}},QN={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"]}}});function Yp(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 zp=T(()=>{"use strict"});var t0,Te,Mo,It=T(()=>{"use strict";t0="ACK: waiting for explicit lmctl task.",Te=`lmctl seed initial connection only. Create or pin this provider session, then stop. Do not inspect files, run commands, infer a task, delegate, edit, or begin work. Reply exactly: ${t0}`,Mo=`send this exact lmctl seed instruction: "${Te}"`});function Ft(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function r0(t,e){return e===void 0||e.length===0?t:{...t??process.env,[xr]:e}}function Je(t,e,r){return r0(Ft(t,e),r)}var xr,rt=T(()=>{"use strict";xr="LMCTL_SELF_SESSIONID"});import{spawn as Zp}from"node:child_process";import{mkdirSync as n0}from"node:fs";var tc,Le,Ut=T(()=>{"use strict";Vp();zp();It();rt();tc=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},Le=class t{name;capabilities;injection;provider;binary;seedArgs;seedStdin;resumeTemplate;startTemplate;transportFn;constructor(e){this.name=e.provider.name,this.provider=e.provider,this.capabilities=e.capabilities,this.injection=e.injection,this.binary=e.binary,this.seedArgs=e.seedArgs,this.seedStdin=e.seedStdin,this.resumeTemplate=e.resumeTemplate,this.startTemplate=e.startTemplate,this.transportFn=e.transport}discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return this.provider.getWatchPaths?.()??[]}seedArgsFor(e){let r=e?.prompt;return r===void 0?this.seedArgs:this.seedArgs.map(n=>n===Te?r:n)}seed(e,r){return n0(e,{recursive:!0}),new Promise(n=>{let s;try{s=Zp(this.binary,this.seedArgsFor(r),{cwd:e,env:Ft(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let o="";s.stderr?.on("data",a=>{o+=a.toString()});let i=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1299
|
+
`:this.seedStdin;i&&s.stdin?.write(i),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:o.trim().slice(0,200)||`exit code ${a}`})}),s.on("error",a=>{n({success:!1,error:a.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:Mo,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&Gp(r.userConfig,this.name)){let s=r.userConfig.tools[this.name];if(s?.agent)return this.runOneShotAgent(e,r,s.agent)}let n=r.timeoutMs??t.DEFAULT_IDLE_TIMEOUT_MS;return n<=0&&!r.signal?this.transportFn(e,{...r,binary:this.binary}):this.withTimeouts(n,e,r)}withTimeouts(e,r,n){let s=new AbortController,o,i,a="",l,c=()=>{e<=0||(clearTimeout(o),o=setTimeout(()=>{n.onIdleWarning?.(e),u(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},u=()=>{clearTimeout(o)};n.signal&&(n.signal.aborted?(i="external",s.abort()):n.signal.addEventListener("abort",()=>{i="external",s.abort()},{once:!0})),c();let d={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),n.onProgress?.(p)}},f=this.transportFn(r,d).then(p=>(u(),{...p,status:"ok"})).catch(p=>{throw u(),i==="external"?new tc("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=Kp(r.userConfig,this.name,r.sessionId,e,r.profile),o=Date.now();return new Promise((i,a)=>{let l=Yp(r.env),c=Zp(s,{shell:!0,cwd:r.cwd,env:Je(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),u=!1,d=!1,f=setTimeout(()=>{d=!0,c.kill()},l),m="",p="";if(c.stdout?.on("data",_=>{let g=_.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",_=>{p+=_.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",_=>{if(u)return;u=!0,clearTimeout(f);let g=Date.now()-o;d?a(new Error(`Agent command timed out after ${l}ms`)):_===0||_===null?i({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${_}`))}),c.on("error",_=>{u||(u=!0,clearTimeout(f),a(_))})})}}});function Po(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new Bt(t,r,e)}var nt,Ie,Wt,Do,Bt,tn=T(()=>{"use strict";nt=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},Ie=class extends nt{},Wt=class extends nt{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},Do=class extends nt{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},Bt=class extends nt{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as nc from"node:child_process";function o0(t){if(typeof nc.spawnSync=="function")try{nc.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function Qp(t){return t.exitCode!==null||t.signalCode!==null}function rc(t,e){return Qp(t)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(o),r(!0))},o=setTimeout(()=>{n||(n=!0,t.removeListener("exit",s),r(!1))},e);t.once("exit",s)})}async function dt(t,e={}){let r=Date.now(),n=e.stdinEnd!==!1,s=e.softDelayMs??5e3,o=e.killDelayMs??5e3,i=e.platform??process.platform,a=e.runTaskkill??o0;if(Qp(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await rc(t,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(i==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await rc(t,o))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(i!=="win32")try{t.kill("SIGKILL")}catch{}return await rc(t,s0)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var s0,Fo=T(()=>{"use strict";s0=1e3});function e_(t){ue()&&Oe({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function ir(t,e){let r=a0[t];if(r)return r[e]??r.yolo}function c0(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 ft(t,e,r="yolo"){if(l0.has(t)){e_(`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)":"protocol/config (out-of-band)"} \u2014 no argv flag`);return}let n=r==="plan"?ir(t,"plan"):i0[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 Z({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new Ie(s)}if(!c0(e,n)){let s=n.join(" "),o=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(i=>JSON.stringify(i)).join(", ")}]`;throw Z({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:o}),new Ie(o)}e_(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var i0,a0,l0,rn=T(()=>{"use strict";tn();ve();i0={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},a0={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"]}};l0=new Set(["codex","opencode"])});import{spawn as u0}from"node:child_process";import{existsSync as d0}from"node:fs";function m0(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(`
|
|
1300
1300
|
|
|
1301
1301
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1302
1302
|
|
|
1303
|
-
`+t[r]);return e.join("")}function
|
|
1303
|
+
`+t[r]);return e.join("")}function p0(t={}){let e=[],r="",n=!1;return{processLine(s){if(!s.trim())return;let o;try{o=JSON.parse(s)}catch{return}t.onEvent?.(o);let i=o.type;if(i==="system"&&o.subtype==="init"&&(r=o.session_id||r),i==="assistant"){let a=o.message;if(a){let l=a.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&t.onText?.(c.text)}}i==="result"&&(n=!0,e.push(o))},sawResult(){return n},finalize(){if(!n)return null;let s=_0(e);return{result:m0(s.resultTexts),sessionId:s.sessionId||r,durationMs:s.durationMs,numTurns:s.numTurns}}}}function _0(t){let e=[],r=0,n=0,s="";for(let o of t){e.push(o.result||"");let i=o.duration_ms;typeof i=="number"&&Number.isFinite(i)&&(r+=i);let a=o.num_turns;typeof a=="number"&&Number.isFinite(a)&&(n=a);let l=o.session_id;typeof l=="string"&&l&&(s=l)}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s}}function h0(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1304
1304
|
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:
|
|
1305
1305
|
${e}
|
|
1306
1306
|
|
|
1307
|
-
${r}`:r}function t_(t,e){return new Promise((r,n)=>{let s=e.tool||"claude",o=e.binaryPath||
|
|
1308
|
-
`);f=h.pop()||"";for(let E of h)m(E)});let p="";c.stderr?.on("data",g=>{p+=g.toString()}),c.on("error",g=>{Z({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:g.message}),n(new Ie(`Failed to spawn ${o}: ${g.message}`,{cause:g}))}),c.on("exit",g=>{if(u)return;f.trim()&&m(f);let h=d.finalize();h?(bt(`stream-json: result ${h.result.slice(0,80)}${h.result.length>80?"...":""} (${h.durationMs}ms)`),r({...h,exitCode:g})):(Z({event:"transport_error",provider:s,error_class:"Error",reason:"provider_no_result",exit_code:g,stderr_tail:p.slice(0,500)}),n(new Error(
|
|
1309
|
-
`),bt(`stream-json: prompt sent (${t.length} chars)`)})}var
|
|
1307
|
+
${r}`:r}function t_(t,e){return new Promise((r,n)=>{let s=e.tool||"claude",o=e.binaryPath||f0[s]||"claude",i=["-p","","--output-format","stream-json","--input-format","stream-json"];s==="claude"&&i.push("--verbose"),e.sessionId&&i.push("--resume",e.sessionId),e.model&&i.push("--model",e.model);let a=e.permissionMode??"yolo",l=ir(s,a)??g0[s]??["--dangerously-skip-permissions"];i.push(...l);try{ft(s,i,a)}catch(g){return n(g)}if(e.cwd&&!d0(e.cwd))return Z({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),n(new Ie(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let c=u0(o,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:Je(e.env,e.cwd,e.sessionId)}),u=!1;if(e.signal){if(e.signal.aborted)return u=!0,Z({event:"transport_abort",provider:s,phase:"pre_spawn"}),dt(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,Z({event:"transport_abort",provider:s}),dt(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let d=p0({onEvent:e.onEvent,onText:e.onText}),f="";function m(g){let h=d.sawResult();d.processLine(g),!h&&d.sawResult()&&c.stdin?.end()}c.stdout?.on("data",g=>{f+=g.toString();let h=f.split(`
|
|
1308
|
+
`);f=h.pop()||"";for(let E of h)m(E)});let p="";c.stderr?.on("data",g=>{p+=g.toString()}),c.on("error",g=>{Z({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:g.message}),n(new Ie(`Failed to spawn ${o}: ${g.message}`,{cause:g}))}),c.on("exit",g=>{if(u)return;f.trim()&&m(f);let h=d.finalize();h?(bt(`stream-json: result ${h.result.slice(0,80)}${h.result.length>80?"...":""} (${h.durationMs}ms)`),r({...h,exitCode:g})):(Z({event:"transport_error",provider:s,error_class:"Error",reason:"provider_no_result",exit_code:g,stderr_tail:p.slice(0,500)}),n(new Error(h0({tool:s,exitCode:g,stderr:p}))))});let _=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(_+`
|
|
1309
|
+
`),bt(`stream-json: prompt sent (${t.length} chars)`)})}var f0,g0,r_=T(()=>{"use strict";tn();Fo();rn();ve();rt();f0={claude:"claude",qwen:"qwen"};g0={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function Uo(t={}){return[]}var sc=T(()=>{"use strict"});import{spawn as y0}from"node:child_process";import{createInterface as w0}from"node:readline";import{existsSync as E0,readFileSync as T0}from"node:fs";import{fileURLToPath as b0}from"node:url";function S0(t){return t==="plan"?"read-only":"danger-full-access"}function k0(){return{clientInfo:{name:"lmctl",title:"lmctl",version:v0},capabilities:{experimentalApi:!1}}}function ar(t,e){bt(`[codex:${t}] ${JSON.stringify(e)}`)}function I0(){return{agentItems:new Map,resultText:""}}function n_(t,e,r,n){let s=t.method;if(!s)return!1;let o=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let i=o?.item;if(i?.type==="agentMessage"&&typeof i.id=="string"){let a=typeof i.phase=="string"?i.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(i.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let i=o?.delta||"",a=typeof o?.itemId=="string"?o.itemId:void 0;if(!i)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=i),r?.(i),l.phase&&o&&(o._lmctlItemPhase=l.phase)):(e.resultText+=i,r?.(i)),!0}if(s==="item/completed"){let i=o?.item;if(i?.type==="agentMessage"&&typeof i.id=="string"){let a=e.agentItems.get(i.id);if(a){if(a.phase!=="commentary"){let l=typeof i.text=="string"?i.text:a.buffer;if(n&&typeof i.text=="string"&&i.text!==a.buffer){let c=typeof o?.threadId=="string"?o.threadId:void 0,u=typeof o?.turnId=="string"?o.turnId:void 0;n({itemId:i.id,threadId:c,turnId:u,expectedFromItemText:i.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(i.id)}return!0}return!1}return!1}function N0(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function A0(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 x0(){return{pendingCodexError:null}}function R0(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1310
1310
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1311
1311
|
${e}
|
|
1312
1312
|
|
|
1313
|
-
${r}`:r}function
|
|
1313
|
+
${r}`:r}function L0(t,e){let r=A0(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function $0(t,e){if(e.pendingCodexError){let o=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:o}}let n=t.params?.turn;if((typeof n?.status=="string"?n.status:void 0)==="failed"){let o=n?.error,i=typeof o?.message=="string"?o.message:void 0,a=i&&i.length>0?i:"(no message)";return{shouldReject:!0,turnError:new Error(`Turn errored: ${a}`)}}return{shouldReject:!1}}function s_(t,e){return new Promise((r,n)=>{let s=e.binaryPath||"codex",o=["app-server","--listen","stdio://"];e.model&&o.push("-c",`model=${JSON.stringify(e.model)}`);let i=e.isLead??e.alias?.toLowerCase()==="lead",a=i?Uo():[];o.push(...a),ue()&&je(JSON.stringify({event:"codex_mcp_inject",alias:e.alias??null,isLead:i,injected:a.length>0}));let l=e.permissionMode??"yolo",c=S0(l);try{ft("codex",o,l)}catch(U){return n(U)}if(e.cwd&&!E0(e.cwd))return Z({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`}),n(new Ie(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let u=y0(s,o,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:Je(e.env,e.cwd,e.threadId)}),d=!1;if(e.signal){if(e.signal.aborted)return d=!0,Z({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),dt(u).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,Z({event:"transport_abort",provider:"codex"}),dt(u).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let f=w0({input:u.stdout}),m=new Map,p=1,_=e.threadId||"",g="",h=!1,E=!1,w=Date.now(),v=I0(),x=x0();function k(U,$={}){return new Promise((A,J)=>{let B=p++;m.set(B,{resolve:A,reject:J});let I=JSON.stringify({jsonrpc:"2.0",id:B,method:U,params:$});u.stdin?.write(I+`
|
|
1314
1314
|
`)})}function j(U,$={}){let A=JSON.stringify({jsonrpc:"2.0",method:U,params:$});u.stdin?.write(A+`
|
|
1315
|
-
`)}f.on("line",U=>{let $;try{$=JSON.parse(U)}catch{return}if(typeof $.id=="number"&&m.has($.id)){let B=m.get($.id);if(m.delete($.id),$.error){let I=$.error,N=typeof I?.message=="string"&&I.message.length>0?I.message:JSON.stringify($.error);B.reject(Po(`codex app-server error: ${N}`,I))}else B.resolve($);e.onEvent?.($);return}let A=$.method;if(!A){e.onEvent?.($);return}if(A==="thread/started"){let I=$.params?.thread;I?.id&&(_=I.id)}let J=ue()?B=>{ar("item.text/buffer-mismatch",{itemId:B.itemId,threadId:B.threadId??null,turnId:B.turnId??null,expectedFromItemText:B.expectedFromItemText,gotFromBuffer:B.gotFromBuffer,expectedLen:B.expectedFromItemText.length,gotLen:B.gotFromBuffer.length})}:void 0;if(A==="turn/started"){let B=$.params,I=B?.turn;I?.id&&(g=I.id),n_($,v,e.onDelta,J),ue()&&ar("turn/started",{params:B??null})}if(ue()&&(A==="item/started"||A==="item/completed")){let B=$.params;B?.item?.type==="agentMessage"&&ar(A,{params:B??null})}if(A==="item/started"||A==="item/agentMessage/delta"||A==="item/completed"){if(A==="item/agentMessage/delta"){let B=$.params;ue()&&ar("agentMessage/delta",{params:B??null})}n_($,v,e.onDelta,J)}if(A==="turn/completed"){let B=$.params;if(ue())for(let[N,C]of v.agentItems.entries())C.buffer&&ar("turn/completed/unflushed-item",{itemId:N,phase:C.phase,bufferLen:C.buffer.length});
|
|
1316
|
-
`);let $=(await k("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;$?.id&&(_=$.id)}else{let $=(await k("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;$?.id&&(_=$.id)}await k("turn/start",{threadId:_,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(U){dt(u).catch(()=>{}),n(U instanceof Error?U:new Error(String(U)))}})()})}var
|
|
1317
|
-
`;)o+=1;o<t.length&&(e+=t[o]);continue}if(i==="/"&&a==="*"){for(o+=2;o<t.length&&!(t[o]==="*"&&t[o+1]==="/");)o+=1;o+=1;continue}e+=i}return e.replace(/,\s*([}\]])/g,"$1")}function Wo(t,e={}){let r=us(t,".opencode"),n=us(r,"opencode.json");if(!l_(n)){
|
|
1315
|
+
`)}f.on("line",U=>{let $;try{$=JSON.parse(U)}catch{return}if(typeof $.id=="number"&&m.has($.id)){let B=m.get($.id);if(m.delete($.id),$.error){let I=$.error,N=typeof I?.message=="string"&&I.message.length>0?I.message:JSON.stringify($.error);B.reject(Po(`codex app-server error: ${N}`,I))}else B.resolve($);e.onEvent?.($);return}let A=$.method;if(!A){e.onEvent?.($);return}if(A==="thread/started"){let I=$.params?.thread;I?.id&&(_=I.id)}let J=ue()?B=>{ar("item.text/buffer-mismatch",{itemId:B.itemId,threadId:B.threadId??null,turnId:B.turnId??null,expectedFromItemText:B.expectedFromItemText,gotFromBuffer:B.gotFromBuffer,expectedLen:B.expectedFromItemText.length,gotLen:B.gotFromBuffer.length})}:void 0;if(A==="turn/started"){let B=$.params,I=B?.turn;I?.id&&(g=I.id),n_($,v,e.onDelta,J),ue()&&ar("turn/started",{params:B??null})}if(ue()&&(A==="item/started"||A==="item/completed")){let B=$.params;B?.item?.type==="agentMessage"&&ar(A,{params:B??null})}if(A==="item/started"||A==="item/agentMessage/delta"||A==="item/completed"){if(A==="item/agentMessage/delta"){let B=$.params;ue()&&ar("agentMessage/delta",{params:B??null})}n_($,v,e.onDelta,J)}if(A==="turn/completed"){let B=$.params;if(ue())for(let[N,C]of v.agentItems.entries())C.buffer&&ar("turn/completed/unflushed-item",{itemId:N,phase:C.phase,bufferLen:C.buffer.length});N0(v),ue()&&ar("turn/completed",{params:B??null});let I=$0($,x);I.shouldReject?(ue()&&ar("turn/completed/terminal-reject",{message:I.turnError.message}),E=!0,h=!0,u.stdin?.end(),n(I.turnError)):(h=!0,u.stdin?.end())}if(A==="error"){let B=L0($,x);if(ue()){let I=$.params,N=I?.error,C=typeof N?.message=="string"?N.message:"(no message)";ar(B.willRetry?"error/retry":"error/terminal-deferred",{message:C,willRetry:B.willRetry,params:I??null})}}e.onEvent?.($)});let K="";u.stderr?.on("data",U=>{K+=U.toString()}),u.on("error",U=>{Z({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:U.message}),n(new Ie(`Failed to spawn codex app-server: ${U.message}`,{cause:U}))}),u.on("exit",U=>{if(!d&&!E){if(h){r({result:v.resultText,threadId:_,turnId:g,durationMs:Date.now()-w,exitCode:U});return}if(x.pendingCodexError){n(x.pendingCodexError);return}Z({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:U,stderr_tail:K.slice(0,500)}),n(new Error(R0({exitCode:U,stderr:K})))}}),(async()=>{try{if(await k("initialize",k0()),j("initialized",{}),e.threadId)try{let U=k("thread/resume",{threadId:e.threadId,sandbox:c,approvalPolicy:"never",...e.model?{model:e.model}:{}}),$=new Promise((A,J)=>setTimeout(()=>J(new Error("resume timeout")),5e3));await Promise.race([U,$]),_=e.threadId}catch{process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1316
|
+
`);let $=(await k("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;$?.id&&(_=$.id)}else{let $=(await k("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;$?.id&&(_=$.id)}await k("turn/start",{threadId:_,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(U){dt(u).catch(()=>{}),n(U instanceof Error?U:new Error(String(U)))}})()})}var v0,o_=T(()=>{"use strict";ve();ve();tn();Fo();rn();sc();ve();rt();v0=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(T0(b0(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});import{existsSync as l_,mkdirSync as O0,readFileSync as c_,writeFileSync as i_}from"node:fs";import{join as us,resolve as j0}from"node:path";function u_(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 oc(t,e,r={existsSync:l_,readFileSync:c_}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let o=j0(e,s.sessiondir??e);for(let i of C0(o)){let a=M0(i,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(u_(a.permission)||n.push(`[${s.alias}] ${i} 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 C0(t){return[us(t,".opencode","opencode.jsonc"),us(t,"opencode.jsonc"),us(t,"opencode.json")]}function M0(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(D0(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function D0(t){let e="",r=!1,n="",s=!1;for(let o=0;o<t.length;o+=1){let i=t[o],a=t[o+1];if(r){e+=i,s?s=!1:i==="\\"?s=!0:i===n&&(r=!1,n="");continue}if(i==='"'||i==="'"){r=!0,n=i,e+=i;continue}if(i==="/"&&a==="/"){for(;o<t.length&&t[o]!==`
|
|
1317
|
+
`;)o+=1;o<t.length&&(e+=t[o]);continue}if(i==="/"&&a==="*"){for(o+=2;o<t.length&&!(t[o]==="*"&&t[o+1]==="/");)o+=1;o+=1;continue}e+=i}return e.replace(/,\s*([}\]])/g,"$1")}function Wo(t,e={}){let r=us(t,".opencode"),n=us(r,"opencode.json");if(!l_(n)){O0(r,{recursive:!0});let i=JSON.stringify({permission:"allow"},null,2);return i_(n,i+`
|
|
1318
1318
|
`,"utf-8"),!0}let s;try{s=JSON.parse(c_(n,"utf-8"))}catch{return console.log(a_.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(a_.yellow(` .opencode/opencode.json at ${n} is not an object \u2014 skipping opencode config install.`)),!1;let o=!1;return s.permission===void 0&&(s.permission="allow",o=!0),u_(s.permission)||Z({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.`}),o&&i_(n,JSON.stringify(s,null,2)+`
|
|
1319
|
-
`,"utf-8"),o}var a_,Bo=T(()=>{"use strict";ve();a_={yellow:t=>t}});import{spawn as
|
|
1319
|
+
`,"utf-8"),o}var a_,Bo=T(()=>{"use strict";ve();a_={yellow:t=>t}});import{spawn as P0}from"node:child_process";import{existsSync as F0}from"node:fs";import{createInterface as U0}from"node:readline";function W0(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1320
1320
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1321
1321
|
${e}
|
|
1322
1322
|
|
|
1323
|
-
${r}`:r}function
|
|
1323
|
+
${r}`:r}function V0(t){let e=[...t.matchAll(H0)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return d_(t.slice(n).trimStart())}return d_(Y0(t.replace(J0,"")))}function Y0(t){let e=X0.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(G0)];if(n.length<2)return t;let s=n[0],o=(s.index??0)+s[0].length;return r.slice(o).trimStart()}function d_(t){let e=[...t.matchAll(K0)];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 m_(t,e){let r=B0[e.tool];return r?new Promise((n,s)=>{let o=e.binaryPath||r.binary;if(e.tool==="opencode")try{Wo(e.cwd)}catch(k){Z({event:"opencode_config_install_failed",cwd:e.cwd,error_message:k instanceof Error?k.message:String(k)})}let i=e.permissionMode??"yolo",a=[...r.args];if(i==="plan")if(e.tool==="gemini"){let k=ir("gemini","plan"),j=ir("gemini","yolo");a=a.filter(K=>!(j??[]).includes(K)),k&&a.push(...k)}else e.tool==="copilot"&&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.
|
|
1324
1324
|
`);e.model&&e.tool==="gemini"&&a.push("--model",e.model);let l=e.tool==="copilot"?"yolo":i;try{ft(e.tool,a,l)}catch(k){return s(k)}if(e.model&&e.tool==="copilot"&&process.stderr.write(`[acp] copilot does not support per-session model selection in --acp mode (model="${e.model}" ignored). Set the default via copilot's /model slash command in an interactive \`lmctl terminal\` session.
|
|
1325
|
-
`),e.cwd&&!
|
|
1325
|
+
`),e.cwd&&!F0(e.cwd))return Z({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),s(new Ie(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let c=P0(o,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:Je(e.env,e.cwd,e.sessionId)}),u=Date.now(),d=!1;if(e.signal){if(e.signal.aborted)return d=!0,Z({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),dt(c).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,Z({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-u}),dt(c).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let f=U0({input:c.stdout}),m=new Map,p=e.sessionId||"",_="",g="",h=!1,E=!1;function w(k,j={}){return new Promise((K,U)=>{let $=q0++;m.set($,{resolve:K,reject:U});let A=JSON.stringify({jsonrpc:"2.0",id:$,method:k,params:j});Oe({event:"acp_send",direction:"SEND",provider:e.tool,method:k,id:$,params:j}),c.stdin?.write(A+`
|
|
1326
1326
|
`)})}f.on("line",k=>{let j;try{j=JSON.parse(k)}catch{return}if(Oe({event:"acp_recv",direction:"RECV",provider:e.tool,id:typeof j.id=="number"?j.id:void 0,method:typeof j.method=="string"?j.method:void 0,preview:JSON.stringify(j).slice(0,300)}),e.onEvent?.(j),typeof j.id=="number"&&m.has(j.id)){let U=m.get(j.id);if(m.delete(j.id),j.error){let $=j.error,A=typeof $?.message=="string"&&$.message.length>0?$.message:JSON.stringify(j.error);U.reject(Po(`ACP RPC error: ${A}`,$))}else U.resolve(j);return}let K=j.method;if(K){if(typeof j.id=="number"){Z({event:"acp_unhandled_request",provider:e.tool,method:K,id:j.id,params:j.params});let U=JSON.stringify({jsonrpc:"2.0",id:j.id,error:{code:-32601,message:`Method not found: ${K} (lmctl does not implement server-side ACP methods)`}});Oe({event:"acp_send",direction:"SEND",provider:e.tool,replyTo:j.id,error:"method not found"}),c.stdin?.write(U+`
|
|
1327
|
-
`);return}if(K==="session/update"){let $=j.params?.update;if($?.sessionUpdate==="agent_message_chunk"){let J=$.content?.text||"";J&&E&&(_+=J,e.onDelta?.(J))}}}});let v="";c.stderr?.on("data",k=>{v+=k.toString()}),c.on("error",k=>{Z({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:k.message,elapsed_ms:Date.now()-u}),s(new Ie(`Failed to spawn ${r.binary} ${r.args.join(" ")}: ${k.message}`,{cause:k}))}),c.on("exit",k=>{d||(h?n({result:e.tool==="gemini"?
|
|
1327
|
+
`);return}if(K==="session/update"){let $=j.params?.update;if($?.sessionUpdate==="agent_message_chunk"){let J=$.content?.text||"";J&&E&&(_+=J,e.onDelta?.(J))}}}});let v="";c.stderr?.on("data",k=>{v+=k.toString()}),c.on("error",k=>{Z({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:k.message,elapsed_ms:Date.now()-u}),s(new Ie(`Failed to spawn ${r.binary} ${r.args.join(" ")}: ${k.message}`,{cause:k}))}),c.on("exit",k=>{d||(h?n({result:e.tool==="gemini"?V0(_):_,sessionId:p,durationMs:Date.now()-u,stopReason:g,exitCode:k}):(Z({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:k,stderr_tail:v.slice(0,500),elapsed_ms:Date.now()-u}),s(new Error(W0({tool:e.tool,exitCode:k,stderr:v})))))});function x(k,j={}){let K=JSON.stringify({jsonrpc:"2.0",method:k,params:j});c.stdin?.write(K+`
|
|
1328
1328
|
`)}(async()=>{try{if(await w("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),x("notifications/initialized"),e.sessionId)try{p=(await w("session/load",{sessionId:e.sessionId,cwd:e.cwd,mcpServers:[]})).result?.sessionId||e.sessionId}catch(j){if(e.requireResume)throw new Error(`Cannot resume session ${e.sessionId} via ACP: ${j instanceof Error?j.message:String(j)}`);process.stderr.write(`[acp] session/load failed for ${e.sessionId}, creating new session
|
|
1329
1329
|
`),p=(await w("session/new",{cwd:e.cwd,mcpServers:[]})).result?.sessionId||""}else p=(await w("session/new",{cwd:e.cwd,mcpServers:[]})).result?.sessionId||"";if(e.model&&e.tool==="opencode")try{await w("session/set_config_option",{sessionId:p,configId:"model",value:e.model}),bt(`acp: set_config_option(model=${e.model}) ok`)}catch(j){let K=j instanceof Error?j.message:String(j);process.stderr.write(`[acp] set_config_option(model=${e.model}) failed: ${K}
|
|
1330
1330
|
`)}if(e.effort&&e.tool==="opencode")try{await w("session/set_config_option",{sessionId:p,configId:"effort",value:e.effort}),bt(`acp: set_config_option(effort=${e.effort}) ok`)}catch(j){let K=j instanceof Error?j.message:String(j);process.stderr.write(`[acp] set_config_option(effort=${e.effort}) failed: ${K}
|
|
1331
|
-
`)}_="",E=!0,bt(`acp: prompt sent (${t.length} chars)`),g=(await w("session/prompt",{sessionId:p,prompt:[{type:"text",text:t}]})).result?.stopReason||"",h=!0,bt(`acp: result received (${_.length} chars, stopReason=${g})`),c.stdin?.end()}catch(k){dt(c).catch(()=>{}),s(k instanceof Error?k:new Error(String(k)))}})()}):Promise.reject(new Error(`No ACP config for tool "${e.tool}"`))}var
|
|
1331
|
+
`)}_="",E=!0,bt(`acp: prompt sent (${t.length} chars)`),g=(await w("session/prompt",{sessionId:p,prompt:[{type:"text",text:t}]})).result?.stopReason||"",h=!0,bt(`acp: result received (${_.length} chars, stopReason=${g})`),c.stdin?.end()}catch(k){dt(c).catch(()=>{}),s(k instanceof Error?k:new Error(String(k)))}})()}):Promise.reject(new Error(`No ACP config for tool "${e.tool}"`))}var B0,q0,f_,H0,J0,X0,G0,K0,p_=T(()=>{"use strict";ve();tn();Fo();rn();Bo();ve();rt();B0={gemini:{binary:"gemini",args:["--acp","-y","--skip-trust"]},copilot:{binary:"copilot",args:["--acp","--yolo"]},opencode:{binary:"opencode",args:["acp"]}},q0=1,f_="(?:png|jpe?g|webp|heic|pdf)",H0=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${f_}\\s*`,"gi"),J0=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${f_}\\s*`,"i"),X0=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,G0=/^STANCE:\s+\S+\s*$/gim,K0=/\[Thought:\s*true\]\s*/gi});function we(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function __(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=z0){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 Z0(){let t=new Map;return(e,r)=>{Q0(e,__(t,r))}}function Q0(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,o=typeof t.max_retries=="number"?t.max_retries:void 0,i=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(o!==void 0?`attempt ${s}/${o}`:`attempt ${s}`),i!==void 0&&c.push(`HTTP ${i}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(we(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,o=typeof t.error=="string"?t.error:void 0,i=["api_error"];s!==void 0&&i.push(`HTTP ${s}`),o&&i.push(we(o,80)),e({kind:"other",summary:i.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 o of s){let i=o.type;if(i==="text"){let a=o.text||"";a&&e({kind:"text",summary:we(a),raw:o})}else if(i==="tool_use"){let a=o.name||"tool",l=typeof o.id=="string"?o.id:void 0,c=o.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=we(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:we(u),id:l,raw:o})}else if(i==="thinking"){let a=o.thinking||"";e({kind:"thinking",summary:we(a),raw:o})}else if(i==="tool_result"){let l=o.is_error===!0?"error":"ok",c=typeof o.tool_use_id=="string"?o.tool_use_id:void 0,u,d=o.content;if(typeof d=="string")u=`${d.split(`
|
|
1332
1332
|
`).length} lines, ${d.length} chars`;else if(Array.isArray(d)){let f=d.map(m=>typeof m=="object"&&m&&"text"in m?m.text:"").filter(Boolean).join("");f&&(u=`${f.split(`
|
|
1333
|
-
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:o})}else i&&e({kind:"other",summary:i,raw:o})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function qo(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?
|
|
1333
|
+
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:u,id:c,raw:o})}else i&&e({kind:"other",summary:i,raw:o})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function qo(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?Z0():void 0,s=await t_(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?o=>n(o,e.onProgress):void 0,signal:e.signal});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,numTurns:s.numTurns}}function eA(){let t=new Map;return(e,r)=>{tA(e,__(t,r))}}function tA(t,e){if(t.method!=="session/update")return;let s=t.params?.update;if(!s)return;let o=s.sessionUpdate;if(o){if(o==="agent_message_chunk"){let a=s.content?.text||"";a&&e({kind:"text",summary:we(a)});return}if(o==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:we(a)});return}if(o==="tool_call"){let i=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=we(JSON.stringify(c))),e({kind:"tool_use",tool:i,summary:we(l),id:a});return}if(o==="tool_call_update"){let i=s.status||"",a=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(i==="completed"||i==="failed")e({kind:"tool_result",summary:i,status:i==="failed"?"error":"ok",id:a});else if(i==="in_progress"){let l=s.content,c=typeof l=="string"?l:typeof l?.text=="string"?l.text:"",u=c?`running\u2026 ${we(c,80)}`:"running\u2026";e({kind:"other",summary:u,id:a})}return}e({kind:"other",summary:o})}}async function nn(t,e){let r=e.acpTool||e.binary;e.model&&r==="copilot"&&Oe({event:"model_ignored",provider:r,model:e.model,reason:"copilot --acp does not implement per-session model selection"});let n=e.onProgress?eA():void 0,s=await m_(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,onDelta:e.onDelta,onEvent:n?o=>n(o,e.onProgress):void 0,signal:e.signal});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason}}function rA(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,o=typeof s?.message=="string"?s.message:void 0,i=o&&o.length>0?o:"(no message)",a=n?.willRetry===!0;e(a?{kind:"api_retry",summary:`codex retry: ${we(i,120)}`}:{kind:"other",summary:`codex error: ${we(i,120)}`});return}if(r==="item/started"||r==="item/completed"){let s=n?.item;if(!s)return;let o=s.type,i=r==="item/started";switch(o){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(i)e({kind:"tool_use",tool:"Bash",summary:we(c||"(command)"),id:a});else{let u=s.exitCode,d=s.status||"",f=typeof s.durationMs=="number"?s.durationMs:void 0,m=typeof u=="number"?`exit ${u}`:d||"done",p=[];typeof u=="number"?p.push(`exit ${u}`):d&&p.push(d),typeof f=="number"&&p.push(`${Math.round(f/1e3)}s`),e({kind:"tool_result",summary:p.join(", ")||"done",status:m,elapsedMs:f,id:a})}return}case"fileChange":{let a=typeof s.id=="string"?s.id:void 0;if(i){let l=s.changes,c=Array.isArray(l)?l.map(u=>u.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:we(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(i)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(i?{kind:"tool_use",tool:"WebSearch",summary:we(s.query||""),id:a}:{kind:"tool_result",summary:"done",status:"done",id:a});return}case"reasoning":{i&&e({kind:"thinking",summary:""});return}case"agentMessage":case"userMessage":return;default:{o&&e({kind:i?"tool_use":"tool_result",tool:o,summary:""});return}}}if(r==="item/agentMessage/delta"){let s=n?.delta||"";if(s){let o=typeof n?._lmctlItemPhase=="string"?n._lmctlItemPhase:void 0;e(o==="commentary"?{kind:"thinking",summary:we(s)}:{kind:"text",summary:we(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:we(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let o=s.split(`
|
|
1334
1334
|
`).filter(l=>l.length>0),i=o[o.length-1]||"",a=o.length>1?`${o.length} lines: ${we(i,60)}`:we(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 o=s.split(`
|
|
1335
|
-
`).filter(l=>l.length>0),i=o[o.length-1]||"",a=o.length>1?`${o.length} lines: ${we(i,60)}`:we(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 h_(t,e){let r=await s_(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=>rA(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}var
|
|
1335
|
+
`).filter(l=>l.length>0),i=o[o.length-1]||"",a=o.length>1?`${o.length} lines: ${we(i,60)}`:we(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 h_(t,e){let r=await s_(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=>rA(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}var z0,Rr=T(()=>{"use strict";r_();o_();p_();ve();z0=256});function ac(t){return new ic(t)}var ic,lc=T(()=>{"use strict";Xp();Ut();Rr();It();ic=class extends Le{constructor(e){super({provider:new jo(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",Te,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:qo})}}});import{readdir as nA,stat as g_,unlink as sA}from"node:fs/promises";import{join as ds,basename as oA}from"node:path";function iA(t,e,r){return`${t}|${e.toISOString()}|${r}`}function fs(t,e,r){let n=iA(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function y_(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function aA(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 Ho(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 Ho(r)}).filter(r=>r.length>0).join(`
|
|
1336
1336
|
`);try{return JSON.stringify(t)}catch{return String(t)}}async function w_(t){let e=0,r=0,n=0,s=0,o=0,i,a;for await(let l of He(t)){if(l.type==="response_item"&&l.payload){let c=l.payload;if(c.type==="message"&&c.role==="user"&&c.content)for(let u of c.content)u.type==="input_text"&&typeof u.text=="string"&&u.text&&e++;else if(c.type==="message"&&c.role==="assistant"&&c.content)for(let u of c.content)u.type==="output_text"&&typeof u.text=="string"&&u.text&&e++}if(l.payload&&typeof l.payload.model_context_window=="number"&&(a=l.payload.model_context_window),l.type==="event_msg"&&l.payload?.type==="token_count"&&l.payload.info?.total_token_usage){let c=l.payload.info.total_token_usage;r=c.input_tokens??r,n=c.cached_input_tokens??c.cache_read_input_tokens??n,s=c.output_tokens??s,o=c.reasoning_output_tokens??o;let u=aA(l.payload.info.last_token_usage);u&&(i=u),typeof l.payload.info.model_context_window=="number"&&(a=l.payload.info.model_context_window)}}return{messageCount:e,totalInputTokens:r,totalCachedInputTokens:n,totalOutputTokens:s,totalReasoningOutputTokens:o,lastTokenUsage:i,modelContextWindow:a}}var Jo,E_=T(()=>{"use strict";or();Jo=class{name="codex";codexDirs;constructor(e={}){let r=[ds(ke,".codex"),ds(ke,".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:ds(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=ds(r,"sessions");try{await g_(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 o of s)try{let i=await this.extractSummary(o);i&&e.push(i)}catch{}}return e}async findSessionFiles(e){let r=[],n;try{n=await nA(e)}catch{return r}for(let s of n){let o=ds(e,s),i=await g_(o).catch(()=>null);if(i)if(i.isDirectory()){let a=await this.findSessionFiles(o);r.push(...a)}else s.endsWith(".jsonl")&&r.push(o)}return r}extractSessionIdFromFilename(e){let r=oA(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 Pe(e,30),n=await Re(e),s=this.extractSessionIdFromFilename(e),o="",i,a,l,c,u,d,f;for(let p of r){if(p.type==="session_meta"&&p.payload&&(p.payload.id&&(s=p.payload.id),p.payload.cwd&&(o=p.payload.cwd),p.payload.cli_version&&(i=p.payload.cli_version),p.payload.timestamp&&(l=new Date(p.payload.timestamp)),p.payload.originator&&(d=p.payload.originator),p.payload.source&&(f=p.payload.source)),p.type==="turn_context"&&p.payload&&(p.payload.model&&(a=p.payload.model),!o&&p.payload.cwd&&(o=p.payload.cwd)),p.type==="event_msg"&&p.payload?.type==="user_message"){let _=p.payload.message||p.payload.text;_&&(c||(c=V(_.trim(),80)),u=V(_.trim(),80))}if(p.type==="response_item"&&p.payload?.type==="message"&&p.payload.role==="user"&&p.payload.content){let _=p.payload.content.find(g=>g.type==="input_text"&&typeof g.text=="string"&&g.text);typeof _?.text=="string"&&(c||(c=V(_.text.trim(),80)),u=V(_.text.trim(),80))}}if(!o)return null;let m=await w_(e);return{provider:"codex",sessionId:s,cwd:o,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:i,startCommand:y_(d,f),firstUserMessage:c,lastUserMessage:u,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:m.lastTokenUsage,modelContextWindow:m.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Re(r),s=[],o="",i,a,l,c,u,d=e,f,m=new Set;for await(let _ of He(r)){let g=_.timestamp?new Date(_.timestamp):new Date;if(_.type==="session_meta"&&_.payload){_.payload.id&&(d=_.payload.id),_.payload.cwd&&(o=_.payload.cwd),_.payload.cli_version&&(i=_.payload.cli_version),_.payload.timestamp&&(l=new Date(_.payload.timestamp)),f=y_(_.payload.originator,_.payload.source);continue}if(_.type==="turn_context"&&_.payload){_.payload.model&&(a=_.payload.model),!o&&_.payload.cwd&&(o=_.payload.cwd);continue}if(_.type==="response_item"&&_.payload){let h=_.payload;if(h.type==="message"){if(h.role==="user"&&h.content){for(let E of h.content)if(E.type==="input_text"&&typeof E.text=="string"&&E.text){let w=E.text.trim();c||(c=V(w,80)),u=V(w,80),fs(s,m,{role:"user",timestamp:g,content:me(w)})}continue}if(h.role==="assistant"&&h.content){for(let E of h.content)E.type==="output_text"&&typeof E.text=="string"&&E.text&&fs(s,m,{role:"assistant",timestamp:g,content:me(E.text),model:a});continue}if(h.role!=="user"&&h.role!=="assistant"&&h.content){for(let E of h.content)(E.type==="input_text"||E.type==="output_text")&&typeof E.text=="string"&&E.text&&fs(s,m,{role:"system",timestamp:g,content:me(E.text.trim())});continue}}if(h.type==="function_call"){s.push({role:"tool_use",timestamp:g,content:h.name||"unknown tool",toolName:h.name,toolInput:h.arguments!==void 0?me(Ho(h.arguments)):void 0,toolCallId:h.call_id});continue}if(h.type==="function_call_output"){s.push({role:"tool_result",timestamp:g,content:me(Ho(h.output)),toolCallId:h.call_id});continue}if(h.type==="reasoning"&&h.summary){let E=h.summary.map(w=>Ho(w.text)).join(`
|
|
1337
1337
|
`);E.trim()&&fs(s,m,{role:"thinking",timestamp:g,content:me(E)});continue}}if(_.type==="event_msg"&&_.payload&&_.payload.type==="agent_reasoning"){let h=_.payload.message||_.payload.text;h&&fs(s,m,{role:"thinking",timestamp:g,content:me(h)})}}if(!o)return null;let p=await w_(r);return{provider:"codex",sessionId:d,cwd:o,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:i,startCommand:f,firstUserMessage:c,lastUserMessage:u,messageCount:p.messageCount,filePath:r,totalInputTokens:p.totalInputTokens||void 0,totalCachedInputTokens:p.totalCachedInputTokens||void 0,totalOutputTokens:p.totalOutputTokens||void 0,totalReasoningOutputTokens:p.totalReasoningOutputTokens||void 0,lastInputTokens:p.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:p.lastTokenUsage,modelContextWindow:p.modelContextWindow,messages:s}}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await sA(r),!0):!1}async resolveSessionFile(e){let r=await this.getSessionsDirs(),n=[];for(let o of r){let i=await this.findSessionFiles(o);n.push(...i)}for(let o of n)if(this.extractSessionIdFromFilename(o)===e)return o;let s=[];for(let o of n)this.extractSessionIdFromFilename(o).startsWith(e)&&s.push(o);if(s.length===1)return s[0];for(let o of n){let i=await Pe(o,1);if(i.length>0&&i[0].type==="session_meta"){let a=i[0].payload?.id;if(a===e||a&&a.startsWith(e))return o}}return null}}});function uc(t){return new cc(t)}var cc,dc=T(()=>{"use strict";E_();Ut();Rr();It();cc=class extends Le{constructor(e){super({provider:new Jo(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:`${Te}
|
|
1338
1338
|
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:h_})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r.slice(0,-1),"--model",e.model,r[r.length-1]]:r}}});function ms(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 Xo(t){let e=ms(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(`
|
|
@@ -1376,9 +1376,9 @@ ${hs(t)}`}function ii(t,e){let r=[];for(let n of t){if(n==="--from"||n.startsWit
|
|
|
1376
1376
|
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(fx(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.
|
|
1377
1377
|
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}".
|
|
1378
1378
|
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 i={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(i.provider=s.provider),i}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
1379
|
-
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var be,ux,dx,ai,xt=T(()=>{"use strict";vt();tt();be=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},ux=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dx=/^ses_[A-Za-z0-9_-]+$/,ai=/^[A-Za-z][A-Za-z0-9_-]*$/});function ys(t){let e=jr(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var Xc=T(()=>{"use strict";xt()});var Qc={};se(Qc,{deliveryLockKey:()=>zc,runDeliveryWorker:()=>jx,
|
|
1380
|
-
`),2}function bx(t,e){return{session_id:t[xr]??null,identity:e?.value??null,teamfile:e?.teamfile??null,alias:e?.alias??null}}function Sx(t){Oe({event:"
|
|
1381
|
-
`),i.push(l)}return i}async function Rx(t,e,r,n){let s=new Date(Date.now()-Fx(n)).toISOString(),o=await R(r,l=>l.tryAcquireRuntimeProcessLock(ih,t.value,Es,s));if(!o.acquired)return{acquired:!1,current:o.current};await R(r,l=>l.clearRuntimeProcessLock(ih,t.value,Es,o.lock.lock_id)).catch(()=>{});let i=zc(t.value,e),a=await R(r,l=>l.tryAcquireRuntimeProcessLock(Gc,i,Es,s));return a.acquired?{acquired:!0,scope:Gc,key:i,id:a.lock.lock_id}:{acquired:!1,current:a.current}}function zc(t,e){return`${t}\0${e}`}async function Lx(t,e,r,n,s){let o=`${n.receiverTeamfile}:${n.receiverAlias}`,i=n.rows.length;if(await R(t,u=>zr(u,n.receiverTeamfile,n.receiverAlias)))return{receiver:o,status:"skipped-busy",pending_count:i};let l=await Rx(r,o,t,e);if(!l.acquired)return{receiver:o,status:"skipped-active",pending_count:i};let c=null;try{let u=await R(t,m=>Fe(n.receiverTeamfile,n.receiverAlias,m));c=(await R(t,m=>m.startTrackedInvocation({kind:"chat",origin:"agent",scope_teamfile:n.receiverTeamfile,from_identity:r.value,target_teamfile:n.receiverTeamfile,target_alias:n.receiverAlias,root_teamfile:r.teamfile,cwd:u.sessiondir??null,command:`lmctl chat ${JSON.stringify(n.receiverTeamfile)} ${n.receiverAlias} ${JSON.stringify("[queued mail]")}`,holder_pid:null,holder_host:Yc(),meta:JSON.stringify({
|
|
1379
|
+
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var be,ux,dx,ai,xt=T(()=>{"use strict";vt();tt();be=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},ux=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dx=/^ses_[A-Za-z0-9_-]+$/,ai=/^[A-Za-z][A-Za-z0-9_-]*$/});function ys(t){let e=jr(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var Xc=T(()=>{"use strict";xt()});var Qc={};se(Qc,{deliveryLockKey:()=>zc,runDeliveryWorker:()=>jx,runNotifyMe:()=>Tx});import{spawn as mx}from"node:child_process";import{hostname as Yc}from"node:os";async function Tx(t,e={stdout:process.stdout,stderr:process.stderr},r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(px),0;let n=ii(t,"notify_me");if(n.error!==void 0)return cn(e,n.error);let s=F(n.args,["--interval","--timeout"],["--json"]);if(s.error!==void 0)return cn(e,s.error);if(s.positionals.length>1)return cn(e,`unexpected positional: ${s.positionals[1]}`);let o=uh(L(s,"--interval"),"--interval",_x);if(typeof o=="string")return cn(e,o);let i=uh(L(s,"--timeout"),"--timeout",hx);if(typeof i=="string")return cn(e,i);let a=e.env??process.env,l,c;try{l=await Ix(e,{teamfile:s.positionals[0]}),c=await Nx(e,l)}catch($){return cn(e,$ instanceof Error?$.message:String($))}let u=D(s,"--json"),d=bx(a,c),f=[],m=!1;c!==null&&(f=await xx(c,e,r.spawnDelivery),m=f.some($=>$.status==="error"));let p=await R(e,$=>ws($,l,c));sR(e,{identity:c?.value??null,sending:p.sending,working:p.working,queued:p.queued,finished:[],receipts:[]},u);let _=r.sleep??($=>new Promise(A=>setTimeout(A,$))),g=r.now??(()=>Date.now()),h=r.appearanceGraceMs??uR(),E=r.reclaimStaleMs??cR("LMCTL_NOTIFY_ME_RECLAIM_STALE_MS",yx),w=g(),v=new Date(w).toISOString(),x=zx(l,v),k=w+i,j=w+h,K=new Set;await R(e,$=>Jx($,g(),E)),Oe({event:"notify_me",record_kind:"notify_me_detail",phase:"start",actor:d,scope:l,started_at:v,notifier:x,intervalMs:o,timeoutMs:i,appearanceGraceMs:h,reclaimStaleMs:E,dbPath:le()});let U=($,A)=>(Sx({actor:d,scope:l,startedAtMs:w,now:g,delivery:f,result:$,exitCode:A,deliveryHadError:m}),A);for(;;){let $=await R(e,A=>Ux(A,{scope:l,snapshotIds:K,nowMs:g(),notifyMeStartedAt:v,notifier:x,reclaimStaleMs:E,mailboxSender:c}));if($.finished!==null||$.receipts.length>0){let A=await R(e,B=>ws(B,l,c)),J={status:"completed",identity:c?.value??null,sending:A.sending,working:A.working,queued:A.queued,finished:tR($.finished,$.receipts),in_flight:A.working,receipts:$.receipts.map(_h)};return li(e,J,u,!u),U(J,m?1:0)}if(K.size>0||$.hasComingMail){if(g()>=k){let A=await R(e,B=>ws(B,l,c)),J={status:"timeout",identity:c?.value??null,sending:A.sending,working:A.working,queued:A.queued,finished:[],in_flight:A.working,receipts:[]};return li(e,J,u,!u),U(J,1)}await _(dh(g(),o,k));continue}if(g()>=k){let A=await R(e,B=>ws(B,l,c)),J={status:"timeout",identity:c?.value??null,sending:A.sending,working:A.working,queued:A.queued,finished:[],in_flight:[],receipts:[]};return li(e,J,u,!u),U(J,1)}if(g()>=j){let A=await R(e,B=>ws(B,l,c)),J={status:"idle",identity:c?.value??null,sending:A.sending,working:A.working,queued:A.queued,finished:[],in_flight:[],receipts:[]};return li(e,J,u,!u),U(J,m?1:0)}await _(dh(g(),o,j,k))}}function cn(t,e){return t.stderr.write(`error: ${e}
|
|
1380
|
+
`),2}function bx(t,e){return{session_id:t[xr]??null,identity:e?.value??null,teamfile:e?.teamfile??null,alias:e?.alias??null}}function Sx(t){Oe({event:"notify_me",record_kind:"notify_me_detail",phase:"finish",actor:t.actor,scope:t.scope,outcome:t.result.status,exit_code:t.exitCode,duration_ms:Math.max(0,t.now()-t.startedAtMs),delivery_had_error:t.deliveryHadError,flush:vx(t.delivery),returned:kx(t.result)})}function vx(t){let e=0,r=0,n=0,s=0,o=0,i=0;for(let a of t)e+=a.pending_count,a.status==="delivered"?r+=a.delivered_ids.length:a.status==="spawned"?n+=1:a.status==="skipped-busy"?s+=1:a.status==="skipped-active"?o+=1:a.status==="error"&&(i+=1);return{lane_count:t.length,pending_count:e,delivered_count:r,spawned_count:n,skipped_busy_count:s,skipped_active_count:o,error_count:i,lanes:t}}function kx(t){return{status:t.status,identity:t.identity,sending_count:t.sending.length,working_count:t.working.length,queued_count:t.queued.length,finished_count:t.finished.length,receipt_count:t.receipts.length,finished:t.finished}}async function Ix(t,e){if(e.teamfile!==void 0)return await R(t,n=>({kind:"team",teamfile:ye(e.teamfile,n)}));let r=t.env??process.env;return await R(t,n=>{let s=ln(r,n);if(s.ok)return{kind:"from",from:s.identity};throw s.reason==="unset"?new Error(hs("notify_me")):new Error(an("notify_me"))})}async function Nx(t,e){if(e.kind==="from")return ys(e.from);let r=t.env??process.env;return await R(t,n=>{try{let s=Jc(r,n);return s.ok?ys(s.identity):null}catch{return null}})}function ws(t,e,r){let n=Vc(t,e).sort((i,a)=>i.id-a.id),s=n.filter(ch).map(Zx),o=new Set(r===null?[]:s.filter(i=>i.from_identity===r.value).map(i=>i.receiver));return{sending:s,working:n.filter(i=>!ch(i)).map(Qx),queued:r===null?[]:Ax(r.value,t.listOutboundPendingForSender(r.teamfile,r.alias),t).filter(i=>!o.has(i.receiver))}}function Ax(t,e,r){return Kc(e).map(n=>({sender:t,receiver:`${n.receiverTeamfile}:${n.receiverAlias}`,pending_count:n.rows.length,busy:zr(r,n.receiverTeamfile,n.receiverAlias),oldest_created_at:n.rows[0].created_at,newest_created_at:n.rows[n.rows.length-1].created_at,ids:n.rows.map(s=>s.id)}))}async function xx(t,e,r=Ox){let n=e.env??process.env;if((await R(e,a=>Kc(a.listOutboundPendingForSender(t.teamfile,t.alias)))).length===0)return[];let o=await R(e,a=>Kc(a.listOutboundPendingForSender(t.teamfile,t.alias))),i=[];for(let a of o){let l=await Lx(e,n,t,a,r);l.status==="error"&&e.stderr.write(`warning: notify_me delivery trigger failed for ${l.receiver}: ${l.error}
|
|
1381
|
+
`),i.push(l)}return i}async function Rx(t,e,r,n){let s=new Date(Date.now()-Fx(n)).toISOString(),o=await R(r,l=>l.tryAcquireRuntimeProcessLock(ih,t.value,Es,s));if(!o.acquired)return{acquired:!1,current:o.current};await R(r,l=>l.clearRuntimeProcessLock(ih,t.value,Es,o.lock.lock_id)).catch(()=>{});let i=zc(t.value,e),a=await R(r,l=>l.tryAcquireRuntimeProcessLock(Gc,i,Es,s));return a.acquired?{acquired:!0,scope:Gc,key:i,id:a.lock.lock_id}:{acquired:!1,current:a.current}}function zc(t,e){return`${t}\0${e}`}async function Lx(t,e,r,n,s){let o=`${n.receiverTeamfile}:${n.receiverAlias}`,i=n.rows.length;if(await R(t,u=>zr(u,n.receiverTeamfile,n.receiverAlias)))return{receiver:o,status:"skipped-busy",pending_count:i};let l=await Rx(r,o,t,e);if(!l.acquired)return{receiver:o,status:"skipped-active",pending_count:i};let c=null;try{let u=await R(t,m=>Fe(n.receiverTeamfile,n.receiverAlias,m));c=(await R(t,m=>m.startTrackedInvocation({kind:"chat",origin:"agent",scope_teamfile:n.receiverTeamfile,from_identity:r.value,target_teamfile:n.receiverTeamfile,target_alias:n.receiverAlias,root_teamfile:r.teamfile,cwd:u.sessiondir??null,command:`lmctl chat ${JSON.stringify(n.receiverTeamfile)} ${n.receiverAlias} ${JSON.stringify("[queued mail]")}`,holder_pid:null,holder_host:Yc(),meta:JSON.stringify({lmctl_notify_me_delivery:!0,pending_count:i,provider:u.provider,model:u.model??null,sessionid:u.sessionid??null})}))).id;let f=await s({trackedId:c,sender:r,receiverTeamfile:n.receiverTeamfile,receiverAlias:n.receiverAlias,lockKey:l.key,lockId:l.id,env:e});if(f===null)throw new Error("delivery worker spawn failed");return await $x(t,c,f),{receiver:o,status:"spawned",pending_count:i,tracked_invocation_id:c}}catch(u){return c!==null&&await R(t,d=>d.finishTrackedInvocation(c,{status:"error",error:u instanceof Error?u.message:String(u),result_summary:u instanceof Error?u.message:String(u),exit_code:1})).catch(()=>{}),await R(t,d=>d.clearRuntimeProcessLock(l.scope,l.key,Es,l.id)).catch(()=>{}),{receiver:o,status:"error",pending_count:i,error:u instanceof Error?u.message:String(u)}}}async function $x(t,e,r){let n=new Date().toISOString();await R(t,s=>{s.db.prepare(`
|
|
1382
1382
|
UPDATE tracked_invocation
|
|
1383
1383
|
SET holder_pid = ?,
|
|
1384
1384
|
holder_host = ?,
|
|
@@ -1387,14 +1387,14 @@ ${hs(t)}`}function ii(t,e){let r=[];for(let n of t){if(n==="--from"||n.startsWit
|
|
|
1387
1387
|
AND status = 'running'
|
|
1388
1388
|
`).run(r,Yc(),n,e)}).catch(()=>{})}async function Ox(t){let e=process.argv[1];if(e===void 0||e.length===0)return null;let r=mx(process.execPath,[e,"__deliver-lane",String(t.trackedId),t.sender.teamfile,t.sender.alias,t.receiverTeamfile,t.receiverAlias,t.lockId],{detached:!0,env:t.env,stdio:"ignore"});return r.unref(),r.pid??null}async function jx(t,e={stdout:process.stdout,stderr:process.stderr}){let r=Cx(t);if(r===null)return e.stderr.write(`error: invalid delivery worker arguments
|
|
1389
1389
|
`),2;let{trackedIdRaw:n,senderTeamfile:s,senderAlias:o,receiverTeamfile:i,receiverAlias:a,lockId:l}=r,c=Number(n);if(!Number.isInteger(c)||c<=0)return e.stderr.write(`error: invalid delivery worker arguments
|
|
1390
|
-
`),2;let u=zc(`${s}:${o}`,`${i}:${a}`),d=e.env??process.env,f=Dx(e,c),m="error",p="",_=null,g=1,h=[];try{let E=await Px(e,d,{teamfile:s,alias:o,value:`${s}:${o}`},{receiverTeamfile:i,receiverAlias:a,rows:[]});E.status==="delivered"?(m="done",p=E.receipt,h=E.delivered_ids,g=0):E.status==="skipped-busy"?(m="busy",p=`receiver busy: ${E.receiver}`,g=1):E.status==="error"?(m="error",_=E.error,p=E.error,g=1):(m="error",_=`unexpected delivery worker result: ${E.status}`,p=_,g=1)}catch(E){m="error",_=E instanceof Error?E.message:String(E),p=_,g=1}finally{f!==void 0&&clearInterval(f),await Mx(e,c,{status:m,result_summary:p,error:_,exit_code:g},h),await R(e,E=>E.clearRuntimeProcessLock(Gc,u,Es,l)).catch(()=>{})}return g===0?0:1}function Cx(t){if(t.length
|
|
1390
|
+
`),2;let u=zc(`${s}:${o}`,`${i}:${a}`),d=e.env??process.env,f=Dx(e,c),m="error",p="",_=null,g=1,h=[];try{let E=await Px(e,d,{teamfile:s,alias:o,value:`${s}:${o}`},{receiverTeamfile:i,receiverAlias:a,rows:[]});E.status==="delivered"?(m="done",p=E.receipt,h=E.delivered_ids,g=0):E.status==="skipped-busy"?(m="busy",p=`receiver busy: ${E.receiver}`,g=1):E.status==="error"?(m="error",_=E.error,p=E.error,g=1):(m="error",_=`unexpected delivery worker result: ${E.status}`,p=_,g=1)}catch(E){m="error",_=E instanceof Error?E.message:String(E),p=_,g=1}finally{f!==void 0&&clearInterval(f),await Mx(e,c,{status:m,result_summary:p,error:_,exit_code:g},h),await R(e,E=>E.clearRuntimeProcessLock(Gc,u,Es,l)).catch(()=>{})}return g===0?0:1}function Cx(t){if(t.length!==6||t.some(a=>a.includes("\0")))return null;let[e,r,n,s,o,i]=t;return e===void 0||r===void 0||n===void 0||s===void 0||o===void 0||i===void 0?null:{trackedIdRaw:e,senderTeamfile:r,senderAlias:n,receiverTeamfile:s,receiverAlias:o,lockId:i}}async function Mx(t,e,r,n){await R(t,s=>{if(r.status!=="done"||n.length===0){s.finishTrackedInvocation(e,r);return}let o=[...new Set(n.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))],i=new Date().toISOString();s.db.exec("BEGIN IMMEDIATE");try{if(s.finishTrackedInvocation(e,r)!==null){let l=s.db.prepare(`
|
|
1391
1391
|
UPDATE agent_mailbox
|
|
1392
1392
|
SET waited_at = ?,
|
|
1393
1393
|
waited_by = ?
|
|
1394
1394
|
WHERE id = ?
|
|
1395
1395
|
AND delivered_at IS NOT NULL
|
|
1396
1396
|
AND waited_at IS NULL
|
|
1397
|
-
`);for(let c of o)l.run(i,`chat:${e}`,c)}s.db.exec("COMMIT")}catch(a){throw s.db.inTransaction&&s.db.exec("ROLLBACK"),a}}).catch(()=>{})}function Dx(t,e){let r=setInterval(()=>{R(t,n=>n.heartbeatTrackedInvocation(e)).catch(()=>{})},wx);return r.unref?.(),r}async function Px(t,e,r,n){let s=`${n.receiverTeamfile}:${n.receiverAlias}`,o=n.rows.length;if(await R(t,l=>zr(l,n.receiverTeamfile,n.receiverAlias)))return{receiver:s,status:"skipped-busy",pending_count:o};let a=null;try{let l=await R(t,d=>Fe(n.receiverTeamfile,n.receiverAlias,d)),c=await R(t,d=>nr(d,{receiver_teamfile:n.receiverTeamfile,receiver_alias:n.receiverAlias,sender_teamfile:r.teamfile,sender_alias:r.alias,ttlMs:sr()}));if(!c.acquired)return{receiver:s,status:"skipped-busy",pending_count:o};a=c.lease;let u=await oi({sender:r,receiver:{teamfile:n.receiverTeamfile,alias:n.receiverAlias,provider:l.provider,sessionId:l.sessionid,cwd:l.sessiondir,...l.model!==void 0?{model:l.model}:{},...l.effort!==void 0?{effort:l.effort}:{},...l.isLead!==void 0?{isLead:l.isLead}:{}},io:t,permissionMode:"yolo",env:e});return u.status==="stalled"?{receiver:s,status:"error",pending_count:o,error:"provider stalled"}:{receiver:s,status:"delivered",pending_count:o,delivered_ids:u.deliveredIds,receipt:u.receipt}}catch(l){return{receiver:s,status:"error",pending_count:o,error:l instanceof Error?l.message:String(l)}}finally{a!==null&&await R(t,l=>l.releaseAgentInflight(a)).catch(()=>{})}}function Kc(t){let e=new Map;for(let r of t){let n=`${r.receiver_teamfile}\0${r.receiver_alias}`,s=e.get(n);s===void 0?e.set(n,[r]):s.push(r)}return[...e.values()].map(r=>({receiverTeamfile:r[0].receiver_teamfile,receiverAlias:r[0].receiver_alias,rows:r.sort((n,s)=>n.id-s.id)})).sort((r,n)=>r.rows[0].id-n.rows[0].id)}function Fx(t){let e=t.
|
|
1397
|
+
`);for(let c of o)l.run(i,`chat:${e}`,c)}s.db.exec("COMMIT")}catch(a){throw s.db.inTransaction&&s.db.exec("ROLLBACK"),a}}).catch(()=>{})}function Dx(t,e){let r=setInterval(()=>{R(t,n=>n.heartbeatTrackedInvocation(e)).catch(()=>{})},wx);return r.unref?.(),r}async function Px(t,e,r,n){let s=`${n.receiverTeamfile}:${n.receiverAlias}`,o=n.rows.length;if(await R(t,l=>zr(l,n.receiverTeamfile,n.receiverAlias)))return{receiver:s,status:"skipped-busy",pending_count:o};let a=null;try{let l=await R(t,d=>Fe(n.receiverTeamfile,n.receiverAlias,d)),c=await R(t,d=>nr(d,{receiver_teamfile:n.receiverTeamfile,receiver_alias:n.receiverAlias,sender_teamfile:r.teamfile,sender_alias:r.alias,ttlMs:sr()}));if(!c.acquired)return{receiver:s,status:"skipped-busy",pending_count:o};a=c.lease;let u=await oi({sender:r,receiver:{teamfile:n.receiverTeamfile,alias:n.receiverAlias,provider:l.provider,sessionId:l.sessionid,cwd:l.sessiondir,...l.model!==void 0?{model:l.model}:{},...l.effort!==void 0?{effort:l.effort}:{},...l.isLead!==void 0?{isLead:l.isLead}:{}},io:t,permissionMode:"yolo",env:e});return u.status==="stalled"?{receiver:s,status:"error",pending_count:o,error:"provider stalled"}:{receiver:s,status:"delivered",pending_count:o,delivered_ids:u.deliveredIds,receipt:u.receipt}}catch(l){return{receiver:s,status:"error",pending_count:o,error:l instanceof Error?l.message:String(l)}}finally{a!==null&&await R(t,l=>l.releaseAgentInflight(a)).catch(()=>{})}}function Kc(t){let e=new Map;for(let r of t){let n=`${r.receiver_teamfile}\0${r.receiver_alias}`,s=e.get(n);s===void 0?e.set(n,[r]):s.push(r)}return[...e.values()].map(r=>({receiverTeamfile:r[0].receiver_teamfile,receiverAlias:r[0].receiver_alias,rows:r.sort((n,s)=>n.id-s.id)})).sort((r,n)=>r.rows[0].id-n.rows[0].id)}function Fx(t){let e=t.LMCTL_NOTIFY_ME_DELIVERY_LOCK_STALE_MS??t.LMCTL_PUSH_LOCK_STALE_MS;if(e===void 0||e.trim()==="")return ah;let r=Number(e);return!Number.isFinite(r)||r<=0?ah:r}function Ux(t,e){let r=new Set(t.reclaimStaleMailboxDeliveries(new Date(e.nowMs-e.reclaimStaleMs).toISOString()).map(l=>l.id)),n=Wx(t,e.mailboxSender,e.scope,e.notifier,r),s=lh(t,e);if(s!==null)return{finished:s,running:Vc(t,e.scope),receipts:n.receipts,hasComingMail:n.hasComingMail};if(e.snapshotIds.size===0)for(let l of Vc(t,e.scope))e.snapshotIds.add(l.id);let i=[...e.snapshotIds].map(l=>Xx(t,l,e.nowMs,e.reclaimStaleMs)).filter(l=>l!==null).filter(Vx).sort((l,c)=>l.id-c.id);e.snapshotIds.clear();for(let l of i)e.snapshotIds.add(l.id);return{finished:lh(t,e),running:i,receipts:n.receipts,hasComingMail:n.hasComingMail}}function lh(t,e){for(let r of Hx(t,e.scope)){let n=t.claimTrackedInvocationNotification(r.id,e.notifier);if(n!==null)return n}return null}function Wx(t,e,r,n,s){if(e===null)return{receipts:[],hasComingMail:!1};let o=new Date().toISOString();t.db.exec("BEGIN IMMEDIATE");try{let i=t.db.prepare(`
|
|
1398
1398
|
SELECT id FROM agent_mailbox
|
|
1399
1399
|
WHERE sender_teamfile = ?
|
|
1400
1400
|
AND sender_alias = ?
|
|
@@ -1432,11 +1432,11 @@ ${hs(t)}`}function ii(t,e){let r=[];for(let n of t){if(n==="--from"||n.startsWit
|
|
|
1432
1432
|
WHERE from_identity = ?
|
|
1433
1433
|
AND status = 'running'
|
|
1434
1434
|
LIMIT 1
|
|
1435
|
-
`).get(e.from)!=null}function Vc(t,e){return e.kind==="team"?t.listRunningTrackedInvocations({scope_teamfile:e.teamfile,limit:1e3}):t.listRunningTrackedInvocations({from:e.from,limit:1e3})}function Hx(t,e){return e.kind==="team"?t.listClaimableTerminalTrackedInvocations({scope_teamfile:e.teamfile,limit:1e3}):t.listClaimableTerminalTrackedInvocations({from:e.from,limit:1e3})}function Jx(t,e,r){let n=[];for(let s of t.listAllRunningTrackedInvocations()){if(!mh(s,e,r))continue;let o=fh(t,s);o!==null&&Yx(o)&&n.push(o)}return n}function Xx(t,e,r,n){let s=t.getTrackedInvocation(e);return s===null||s.status!=="running"||!mh(s,r,n)?s:fh(t,s)??t.getTrackedInvocation(s.id)}function fh(t,e){return t.reclaimTrackedInvocationIfUnchanged(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},{status:"error",error:oh,result_summary:oh})}function mh(t,e,r){return t.holder_host===Yc()&&Kx(t.holder_pid)?!rr(t.holder_pid):Gx(t,e,r)}function Gx(t,e,r){let n=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(n)&&e-n>r}function Kx(t){return Number.isInteger(t)&&(t??0)>0}function Vx(t){return t.status==="running"}function Yx(t){return Ex.has(t.status)}function Zc(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function ph(t){if(t.meta===null||t.meta.trim()==="")return{};try{let e=JSON.parse(t.meta);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function ch(t){return t.kind==="chat"&&ph(t).
|
|
1435
|
+
`).get(e.from)!=null}function Vc(t,e){return e.kind==="team"?t.listRunningTrackedInvocations({scope_teamfile:e.teamfile,limit:1e3}):t.listRunningTrackedInvocations({from:e.from,limit:1e3})}function Hx(t,e){return e.kind==="team"?t.listClaimableTerminalTrackedInvocations({scope_teamfile:e.teamfile,limit:1e3}):t.listClaimableTerminalTrackedInvocations({from:e.from,limit:1e3})}function Jx(t,e,r){let n=[];for(let s of t.listAllRunningTrackedInvocations()){if(!mh(s,e,r))continue;let o=fh(t,s);o!==null&&Yx(o)&&n.push(o)}return n}function Xx(t,e,r,n){let s=t.getTrackedInvocation(e);return s===null||s.status!=="running"||!mh(s,r,n)?s:fh(t,s)??t.getTrackedInvocation(s.id)}function fh(t,e){return t.reclaimTrackedInvocationIfUnchanged(e.id,{holder_pid:e.holder_pid,holder_host:e.holder_host,started_at:e.started_at,last_heartbeat_at:e.last_heartbeat_at},{status:"error",error:oh,result_summary:oh})}function mh(t,e,r){return t.holder_host===Yc()&&Kx(t.holder_pid)?!rr(t.holder_pid):Gx(t,e,r)}function Gx(t,e,r){let n=Date.parse(t.last_heartbeat_at??t.started_at);return Number.isFinite(n)&&e-n>r}function Kx(t){return Number.isInteger(t)&&(t??0)>0}function Vx(t){return t.status==="running"}function Yx(t){return Ex.has(t.status)}function Zc(t){return t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`}function ph(t){if(t.meta===null||t.meta.trim()==="")return{};try{let e=JSON.parse(t.meta);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function ch(t){return t.kind==="chat"&&ph(t).lmctl_notify_me_delivery===!0}function zx(t,e){let r=t.kind==="team"?t.teamfile:t.from;return`notify_me:${process.pid}:${t.kind}:${r}:${e}`}function Zx(t){let e=ph(t),r=typeof e.pending_count=="number"&&Number.isFinite(e.pending_count)?e.pending_count:null;return{id:t.id,kind:t.kind,status:"running",from_identity:t.from_identity,receiver:Zc(t)??"(unknown)",pending_count:r,started_at:t.started_at}}function Qx(t){return{id:t.id,kind:t.kind,status:"running",from_identity:t.from_identity,target:Zc(t),target_alias:t.target_alias,started_at:t.started_at}}function eR(t){let e=nR(t);return{source:"tracked",id:t.id,kind:t.kind,status:t.status,from_identity:t.from_identity,scope_teamfile:t.scope_teamfile,target_teamfile:t.target_teamfile,target_alias:t.target_alias,target:Zc(t),result_summary:e,result:e,completed_at:t.ended_at}}function tR(t,e){let r=[];return t!==null&&r.push(eR(t)),r.push(...e.map(_h)),r}function _h(t){let e=rR(t.receipt??"");return{source:"receipt",id:t.id,receiver:`${t.receiver_teamfile}:${t.receiver_alias}`,delivered_at:t.delivered_at??t.created_at,receipt:e,result:e}}function rR(t){let e=t.replace(/\s+/g," ").trim();return e.length===0?"(empty)":e.length<=240?e:`${e.slice(0,239)}\u2026`}function nR(t){let r=(t.result_summary??t.error??t.status).replace(/\s+/g," ").trim();return r.length===0?"(empty)":r.length<=240?r:`${r.slice(0,239)}\u2026`}function sR(t,e,r){if(r){t.stderr.write(`${JSON.stringify({event:"status",...e})}
|
|
1436
1436
|
`);return}let n={...t,stdout:t.stderr};e.identity!==null&&n.stdout.write(`identity: ${e.identity}
|
|
1437
1437
|
`),hh(n,e.sending,e.working,e.queued,e.finished)}function li(t,e,r,n=!0){if(r){W(t,e);return}if(n&&(e.identity!==null&&t.stdout.write(`identity: ${e.identity}
|
|
1438
|
-
`),hh(t,e.sending,e.working,e.queued,e.finished)),e.status==="idle"){t.stdout.write(`
|
|
1439
|
-
`);return}if(e.status==="timeout"){let s=e.sending.length+e.working.length;t.stdout.write(`
|
|
1438
|
+
`),hh(t,e.sending,e.working,e.queued,e.finished)),e.status==="idle"){t.stdout.write(`notify_me: idle (nothing landed)
|
|
1439
|
+
`);return}if(e.status==="timeout"){let s=e.sending.length+e.working.length;t.stdout.write(`notify_me: timeout; ${s} invocation(s) still running
|
|
1440
1440
|
`);return}n||gh(t,e.finished)}function hh(t,e,r,n,s){oR(t,e),iR(t,r),aR(t,n),gh(t,s)}function oR(t,e){if(t.stdout.write(`SENDING:
|
|
1441
1441
|
`),e.length===0){t.stdout.write(` none
|
|
1442
1442
|
`);return}for(let r of e){let n=r.pending_count===null?"pending unknown":`${r.pending_count} pending`;t.stdout.write(` ${r.id} chat ${r.receiver} ${n}
|
|
@@ -1450,10 +1450,16 @@ ${hs(t)}`}function ii(t,e){let r=[];for(let n of t){if(n==="--from"||n.startsWit
|
|
|
1450
1450
|
`),e.length===0){t.stdout.write(` none
|
|
1451
1451
|
`);return}for(let r of e)r.source==="receipt"?t.stdout.write(` receipt ${r.id} to ${r.receiver} ${r.result}
|
|
1452
1452
|
`):(t.stdout.write(` job ${r.id} ${r.status} ${r.kind}`),r.target!==null&&t.stdout.write(` ${r.target}`),t.stdout.write(` ${r.result}
|
|
1453
|
-
`))}function uh(t,e,r){return t===void 0?r:lR(t,e)}function lR(t,e){let r=Number(t);return!Number.isFinite(r)||r<=0?`${e} must be a positive number of seconds`:Math.max(1,Math.ceil(r*1e3))}function cR(t,e){let r=process.env[t];if(r===void 0||r.trim()==="")return e;let n=Number(r);return!Number.isFinite(n)||n<=0?e:Math.max(1,Math.ceil(n))}function uR(){let t=process.env.
|
|
1453
|
+
`))}function uh(t,e,r){return t===void 0?r:lR(t,e)}function lR(t,e){let r=Number(t);return!Number.isFinite(r)||r<=0?`${e} must be a positive number of seconds`:Math.max(1,Math.ceil(r*1e3))}function cR(t,e){let r=process.env[t];if(r===void 0||r.trim()==="")return e;let n=Number(r);return!Number.isFinite(n)||n<=0?e:Math.max(1,Math.ceil(n))}function uR(){let t=process.env.LMCTL_NOTIFY_ME_APPEARANCE_GRACE_MS;if(t===void 0||t.trim()==="")return sh;let e=Number(t);return Number.isFinite(e)?Math.min(gx,Math.max(0,Math.ceil(e))):sh}function dh(t,e,...r){let n=Math.min(...r);return Math.min(e,Math.max(1,n-t))}var px,_x,hx,sh,gx,yx,wx,Ex,oh,Gc,ih,Es,ah,eu=T(()=>{"use strict";es();So();ge();Ve();tt();$o();qc();gs();Xc();xt();ve();rt();px=`usage: lmctl notify_me [teamfile] [--interval <seconds>] [--timeout <seconds>] [--json]
|
|
1454
1454
|
|
|
1455
|
-
|
|
1456
|
-
|
|
1455
|
+
I'm done with this round; my delegations are all running in the background;
|
|
1456
|
+
I'm taking a break \u2014 notify me when something lands.
|
|
1457
|
+
|
|
1458
|
+
Call this in the FOREGROUND; it holds your process and returns when a member
|
|
1459
|
+
finishes.
|
|
1460
|
+
|
|
1461
|
+
Flush this member's outbound queued mail, show current jobs/queue status, then
|
|
1462
|
+
return the first finished tracked invocation or delivered receipt.
|
|
1457
1463
|
Default scope is the calling member, inferred from LMCTL_SELF_SESSIONID;
|
|
1458
1464
|
use a teamfile positional to watch invocations targeting that team.
|
|
1459
1465
|
|
|
@@ -1461,7 +1467,7 @@ Exit codes:
|
|
|
1461
1467
|
0 completed or idle (inspect status in output/JSON)
|
|
1462
1468
|
1 timeout
|
|
1463
1469
|
2 usage or scope error
|
|
1464
|
-
`,_x=3e3,hx=8*60*60*1e3,sh=0,gx=3e4,yx=8*60*60*1e3,wx=3e4,Ex=new Set(["done","error","busy","cancelled"]),oh="reclaimed: holder process not alive",Gc="cli:
|
|
1470
|
+
`,_x=3e3,hx=8*60*60*1e3,sh=0,gx=3e4,yx=8*60*60*1e3,wx=3e4,Ex=new Set(["done","error","busy","cancelled"]),oh="reclaimed: holder process not alive",Gc="cli:notify_me-delivery",ih="cli:push",Es="lock",ah=12e4});function dR(){return tu===null&&(tu=kt(Nt())),tu}async function dn(t){let{dal:e,team_member_id:r}=t,n=e!==void 0&&r!==void 0;n&&e.setMemberState(r,"in_chat");let s=!1,o;try{return await mR(t)}catch(i){throw s=!0,o=i,i}finally{if(n)if(!s)un.delete(r),e.setMemberState(r,"idle");else{let i=fR(o,r);e.setMemberState(r,i!==null?"attention_needed":"idle",i)}}}function fR(t,e){if(!(t instanceof Ne))return un.delete(e),null;if(t.kind==="sessiondir_missing")return"sessiondir_missing";if(t.kind==="enoent")return"binary_missing";if(t.kind==="nonzero_exit"&&(t.exit_status===137||t.exit_status===139))return"oom_exit";if(t.kind==="timeout"){let r=(un.get(e)??0)+1;return r>=3?(un.delete(e),"consecutive_timeouts"):(un.set(e,r),null)}return un.delete(e),null}async function mR(t){let e=t.timeoutMs,r=typeof e=="number"&&e>0,n=dR(),s;try{let u=await n.resolveSession(t.sessionid);if(!u)return Promise.reject(new Ne("other",null,`library: sessionid "${t.sessionid}" matched no registered provider`,ru(t.sessionid,t.sessiondir,"unresolved")));s=u.provider.name}catch(u){return Promise.reject(new Ne("other",null,`library: session resolution failed: ${yh(u)}`,ru(t.sessionid,t.sessiondir,"unresolved")))}let o=ru(t.sessionid,t.sessiondir,s),i=new AbortController,a=r?setTimeout(()=>i.abort(),e):null,l=!1;i.signal.addEventListener("abort",()=>{l=!0},{once:!0});let c=Date.now();try{let u=await Ht({provider:s,sessionId:t.sessionid,cwd:t.sessiondir,prompt:t.prompt,timeoutMs:0,signal:i.signal,registry:n,onProgress:t.onProgress,permissionMode:t.permissionMode});if(u.status==="stalled")throw new Ne("timeout",null,`library: stalled after ${u.stalledAfterMs??0}ms`,o);return{text:u.text,ms:Date.now()-c,exit_status:0,argv:o}}catch(u){throw l?new Ne("timeout",null,`library: wall-clock timeout after ${e??0}ms`,o):pR(u,o)}finally{a!==null&&clearTimeout(a)}}function ru(t,e,r){return["<library>","chat",t,e,"--provider",r]}function yh(t){return t instanceof Error?t.message:String(t)}function pR(t,e){if(t instanceof Ne)return t;if(t instanceof Ie){let r=t.cause;return r?.code==="ENOENT_CWD"?new Ne("sessiondir_missing",null,t.message,e):r?.code==="ENOENT"?new Ne("enoent",null,t.message,e):new Ne("other",null,t.message,e)}return t instanceof Wt?new Ne("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Bt?new Ne("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof nt?new Ne("other",null,t.message,e):new Ne("other",null,yh(t),e)}var Ne,tu,un,Ts=T(()=>{"use strict";At();Ne=class extends Error{kind;exit_status;stderr;argv;constructor(e,r,n,s){super(`lmctl chat failed: ${e}`),this.kind=e,this.exit_status=r,this.stderr=n,this.argv=s,this.name="ChatError"}},tu=null;un=new Map});function wh(){return nu===null&&(nu=kt(Nt())),nu}function hR(t,e){if(!_R.test(t))return t;let r=e.getConfig(`workspace.${t}`);if(r===null||r.length===0)throw new Ae("other",null,`workspace has no mapping for ${t}; run \`lmctl workspace init\` (or set workspace.${t} in lmctl_config)`,["<library>","seed","--provider",t]);return r}async function fn(t){let e=hR(t.member.provider,t.dal),r=e===t.member.provider?t.member:{...t.member,provider:e},n=await gR({member:r});return t.dal.setMemberProviderResolved(t.member.id,e),{sessionid:n.sessionid,provider_resolved:e}}async function gR(t){let e=t.member.provider,r=t.member.sessiondir,n=su("seed",r,e);try{let s=await Fc({provider:e,cwd:r,registry:wh()});if(!s.success)throw wR(s.error,n);if(!s.sessionId)throw new Ae("parse",0,"",n);return{sessionid:s.sessionId}}catch(s){throw s instanceof Ae?s:ou(s,n)}}async function Eh(t){return yR(t)}async function yR(t){let e=wh(),r=su("tokens",t.sessionid,"unresolved"),n;try{let o=await e.resolveSession(t.sessionid);if(!o)throw new Ae("parse",0,`library: sessionid "${t.sessionid}" matched no registered provider`,r);n=o.provider.name}catch(o){throw o instanceof Ae?o:ou(o,r)}let s=su("tokens",t.sessionid,n);try{let o=await Wc({sessionId:t.sessionid,provider:n,registry:e});return{input_tokens:o.input,cache_tokens:o.cachedInput+o.cacheWriteInput,output_tokens:o.output,total_tokens:o.total}}catch(o){throw o instanceof Ae?o:ou(o,s)}}function su(t,e,r){return["<library>",t,e,"--provider",r]}function wR(t,e){let r=t??"";if(/\bENOENT\b/i.test(r))return new Ae("enoent",null,r,e);if(/timed?\s*out/i.test(r))return new Ae("timeout",null,r,e);if(/\bexit code\s+(-?\d+)\b/i.test(r)){let n=/\bexit code\s+(-?\d+)\b/i.exec(r);return new Ae("nonzero_exit",Number(n[1]),r,e)}return new Ae("other",null,r,e)}function ou(t,e){return t instanceof Ae?t:t instanceof Ie?t.cause?.code==="ENOENT"?new Ae("enoent",null,t.message,e):new Ae("other",null,t.message,e):t instanceof Wt?new Ae("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Bt?new Ae("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof nt?new Ae("other",null,t.message,e):new Ae("other",null,t instanceof Error?t.message:String(t),e)}var Ae,nu,_R,ci=T(()=>{"use strict";At();Ae=class extends Error{kind;exit_status;stderr;argv;constructor(e,r,n,s){super(`lmctl seed failed: ${e}`),this.kind=e,this.exit_status=r,this.stderr=n,this.argv=s,this.name="SeedError"}},nu=null;_R=/^provider[123]$/});function ui(t){return Buffer.from(t,"utf8").toString("base64url")}function Ss(t){return Buffer.from(t,"base64url").toString("utf8")}async function Th(t,e=r=>Eh({sessionid:r})){if(process.env.LMCTL_SESSION_SIZE_DISABLED==="1")return{recorded:0,failed:0};let r=0,n=0;for(let s of ER(t)){let o=s.member.sessionid;if(o!==null)try{let i=await e(o);t.recordSessionSize({team_name:s.team_name,alias:s.member.alias,sessionid:o,...i}),r+=1}catch(i){n+=1;try{t.raiseAttention({kind:"daemon_session_size_failed",severity:"warn",payload:JSON.stringify({team_name:s.team_name,alias:s.member.alias,sessionid:o,error:i instanceof Error?i.message:String(i)})})}catch{}}}return{recorded:r,failed:n}}async function bh(t,e,r){let n=Sh(t,e,r);if(n===null||n.member.sessionid===null)throw new Error("session member not found");if(n.member.state!=="idle")throw new bs(r,n.member.state);t.setMemberState(n.member.id,"in_chat","compacting");try{return await dn({sessionid:n.member.sessionid,sessiondir:n.member.sessiondir,prompt:"/compact"}),t.setMemberState(n.member.id,"idle",null),{ok:!0,row:vh(t,e,r)}}catch(s){throw t.setMemberState(n.member.id,"attention_needed",`compact failed: ${s instanceof Error?s.message:String(s)}`),s}}async function iu(t,e,r){let n=Sh(t,e,r);if(n===null)throw new Error("session member not found");let s=await fn({member:n.member,dal:t});return t.updateTeamMemberSession(n.member.id,s.sessionid),{ok:!0,sessionid:s.sessionid,row:vh(t,e,r)}}function ER(t){return t.listTeams().flatMap(e=>t.listTeamMembers(e.id).filter(r=>r.sessionid!==null).map(r=>({team_name:e.name,member:r})))}function Sh(t,e,r){let n=t.findTeamByName(e);if(n===null)return null;let s=t.findTeamMemberByAlias(n.id,r);return s===null?null:{team_name:n.name,member:s}}function vh(t,e,r){return t.sessionSizeHistory(e,r,1)[0]??null}var bs,di=T(()=>{"use strict";Ts();ci();bs=class extends Error{constructor(e,r){super(`member ${e} is currently ${r}; cannot compact while busy`),this.name="MemberBusyError"}}});async function au(t){let e=t.dal,r=t.nowMs??Date.now(),n=t.thresholdMs??bR(e),s=r-n,o=e.query(`
|
|
1465
1471
|
SELECT
|
|
1466
1472
|
isess.id AS interactive_session_id,
|
|
1467
1473
|
isess.run_id,
|
|
@@ -2058,28 +2064,28 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2058
2064
|
WHERE w.name = ?
|
|
2059
2065
|
ORDER BY pw.id DESC`,"newspaper")}function kE(t,e){for(let r of[...e.steps].reverse()){let n=t.getInteractiveSessionByStepId(r.id);if(n!==null)return n}return null}function IE(t,e){let r=Number(Qe(e.project_id));return Number.isInteger(r)?t.getProject(r):null}function MP(t){let e=Qe(t.schedule)||"daily";return e==="weekly"?{preset:e,cron:"0 6 * * 1"}:e==="custom"?{preset:e,cron:Qe(t.cron).trim()||"0 6 * * *"}:{preset:"daily",cron:"0 6 * * *"}}function yE(t){let e=t.req.param("workflow");return Ad.includes(e)?e:null}function Cn(t){return Ia.find(e=>e.name===t)?.title??t}function DP(t){return t.split(/[_:-]/).filter(Boolean).map(e=>`${e[0]?.toUpperCase()??""}${e.slice(1)}`).join(" ")}function Rd(t){return _P.parse(t,{async:!1})}function PP(t){return t==="done"||t==="pr_ready"||t==="merged"}function FP(t){return t.replace(/\n*STANCE:\s+\S+\s*$/,"").trimEnd()}function UP(t,e){return t.split(`
|
|
2060
2066
|
`).slice(0,e).join(`
|
|
2061
|
-
`)}function WP(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Qe(t){return typeof t=="string"?t:""}function BP(t){if(t===null)return{};try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{return{}}return{}}function Nd(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ka(t,e){return Number(t.req.param(e))}var Ia,Ad,NE=T(()=>{"use strict";Ks();Jt();ld();Ia=[{name:"info-qa",title:"Ask a Question",description:"Get a grounded answer from multiple researchers and one consolidator."},{name:"document-creation",title:"Create a Document",description:"Draft, review, and render a polished document with an interactive wizard."},{name:"newspaper",title:"Daily Newspaper",description:"Subscribe to recurring digests for topics you care about."}],Ad=Ia.map(t=>t.name)});function HP(t){return t.replace(/^\/+/,"")}function AE(t){return typeof t=="string"&&t!==""&&!t.includes("/")&&!t.includes("\\")}function Mn(t){if(t.mailboxKey!==void 0&&t.mailboxKey!==null&&t.mailboxKey!==""){let e=HP(t.mailboxKey),r=e.lastIndexOf("/");return(r>=0?e.slice(r+1):e).includes(".")&&(e=r>=0?e.slice(0,r+1):""),e!==""&&!e.endsWith("/")&&(e+="/"),e}return AE(t.userId)&&AE(t.deviceId)?`${t.userId}/${t.deviceId}/`:`${qP}/${t.identityId}/`}function XP(t){return String(Math.max(0,Math.floor(t))).padStart(JP,"0")}function Ld(t,e,r){return`${t}${e}${XP(r)}.json`}function Na(t,e){return`${t}${e}`}function Aa(t,e,r){let n=`${e}${r}`;if(!t.startsWith(n))return;let s=t.slice(n.length).match(/^(\d+)\.json$/);if(s===null)return;let o=Number(s[1]);return Number.isSafeInteger(o)?o:void 0}var qP,JP,xa=T(()=>{"use strict";qP="mailbox";JP=12});function Zt(t,e){let r=Math.floor(t),n="",s=r;for(let u=0;u<12;u++)n=Ra[s&15]+n,s=Math.floor(s/16);let o=Math.floor(e()*4096)&4095,i="",a=o;for(let u=0;u<3;u++)i=Ra[a&15]+i,a=a>>4;let l=Ra[8|Math.floor(e()*4)&3],c="";for(let u=0;u<15;u++)c+=Ra[Math.floor(e()*16)&15];return n.slice(0,8)+"-"+n.slice(8,12)+"-7"+i+"-"+l+c.slice(0,3)+"-"+c.slice(3,15)}var Ra,La=T(()=>{"use strict";Ra="0123456789abcdef"});function Od(t,e){return!Number.isFinite(t)||t<=0?e:t}function jd(t){if(t===null||typeof t!="object")return!1;let e=t;return e.name==="NoSuchKey"||e.name==="NotFound"||e.Code==="NoSuchKey"||e.code==="NoSuchKey"||e.$metadata!==void 0&&e.$metadata.httpStatusCode===404}function OE(t){return t.conversation_id===$E&&VP(t.payload)}function VP(t){return typeof t=="object"&&t!==null&&t.kind==="heartbeat"}function YP(t){let e=typeof t.hb=="string"&&t.hb!==""?t.hb:OE(t)?t.timestamp:void 0;if(e===void 0)return;let r=Date.parse(e);return Number.isFinite(r)?r:void 0}var xE,RE,LE,GP,$E,KP,$d,Hr,$a=T(()=>{"use strict";xa();La();xE=3e3,RE=1e4,LE=12e3,GP=1e3,$E="__lmctl_heartbeat__",KP={kind:"heartbeat"},$d={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Hr=class{opts;basePrefix;ownStream;peerStream;cursor;ownSeq;bootstrapped=!1;bootstrapInFlight=null;bootstrapPromise=null;writeChain=Promise.resolve();readIntervalMs;heartbeatIdleMs;backoffReadIntervalMs;running=!1;stopped=!1;stopRequested=!1;timerHandle=null;heartbeatTimerHandle=null;lastWriteMs;lastPeerHeartbeatMs;tickInFlight=null;constructor(e){this.opts=e,this.basePrefix=Mn({identityId:e.identityId,userId:e.userId,deviceId:e.deviceId,mailboxKey:e.mailboxKey}),this.ownStream=e.selfRole==="agent"?"local":"web",this.peerStream=e.selfRole==="agent"?"web":"local",this.cursor=e.cursor,this.readIntervalMs=Od(e.readIntervalMs??e.pollIntervalMs??xE,xE),this.heartbeatIdleMs=Od(e.heartbeatIdleMs??RE,RE),this.backoffReadIntervalMs=Od(e.backoffReadIntervalMs??e.pollIntervalMs??LE,LE)}start(){if(this.stopped)throw new Error("SequentialMailboxClient: cannot start after stop()");this.running||(this.running=!0,this.bootstrapInFlight=this.bootstrapThenRun())}async stop(){this.stopped=!0,this.stopRequested=!0;let e=this.opts.timers??$d;if(this.timerHandle!==null&&(e.clearTimeout(this.timerHandle),this.timerHandle=null),this.heartbeatTimerHandle!==null&&(e.clearTimeout(this.heartbeatTimerHandle),this.heartbeatTimerHandle=null),this.bootstrapInFlight!==null)try{await this.bootstrapInFlight}catch{}if(this.tickInFlight!==null)try{await this.tickInFlight}catch{}this.running=!1}async putMessage(e){return this.putEnvelope(e.conversation_id,e.payload)}getCursor(){return this.cursor}getMailboxBasePrefix(){return this.basePrefix}setPollIntervalMs(e){if(!Number.isFinite(e)||e<=0)throw new Error(`SequentialMailboxClient.setPollIntervalMs: invalid ms=${e}`);this.readIntervalMs=e}isPeerOn(){return this.peerIsOn((this.opts.now??Date.now)())}async bootstrapThenRun(){if(await this.ensureBootstrapped(),this.stopRequested){this.running=!1;return}this.runTick(),this.writeHeartbeat()}ensureBootstrapped(){return this.bootstrapped?Promise.resolve():(this.bootstrapPromise===null&&(this.bootstrapPromise=this.runColdStart()),this.bootstrapPromise)}async runColdStart(){try{let e=await this.maxSeq(this.ownStream);this.ownSeq=e,this.cursor===void 0&&(this.cursor=await this.maxSeq(this.peerStream)),this.bootstrapped=!0}catch(e){throw this.bootstrapPromise=null,this.emitError(e,"list"),e}}async maxSeq(e){let r=Na(this.basePrefix,e),n=0,s;do{let o=await this.opts.s3.send(new this.opts.commands.ListObjectsV2Command({Bucket:this.opts.bucket,Prefix:r,MaxKeys:GP,...s!==void 0&&{ContinuationToken:s}}));this.opts.onS3Op?.("list");for(let i of o.Contents??[]){let a=Aa(i.Key??"",this.basePrefix,e);a!==void 0&&a>n&&(n=a)}s=o.IsTruncated===!0?o.NextContinuationToken:void 0}while(s!==void 0);return n}async putEnvelope(e,r){let n=this.writeChain.then(()=>this.doPut(e,r));return this.writeChain=n.catch(()=>{}),n}async doPut(e,r){await this.ensureBootstrapped();let n=(this.opts.now??Date.now)(),s=new Date(n).toISOString(),o={message_id:Zt(n,this.opts.random??Math.random),from:this.opts.selfRole,timestamp:s,hb:s,conversation_id:e,payload:r},i=(this.ownSeq??0)+1,a=Ld(this.basePrefix,this.ownStream,i);return await this.opts.s3.send(new this.opts.commands.PutObjectCommand({Bucket:this.opts.bucket,Key:a,Body:JSON.stringify(o),ContentType:"application/json"})),this.opts.onS3Op?.("put"),this.ownSeq=i,this.recordWrite(n),a}scheduleNextTick(e){if(this.stopRequested)return;let r=this.opts.timers??$d;this.timerHandle=r.setTimeout(()=>{this.timerHandle=null,this.runTick()},e)}runTick(){this.stopRequested||(this.tickInFlight=(async()=>{try{await this.pollOnce()}finally{this.tickInFlight=null,this.stopRequested||this.scheduleNextTick(this.nextReadDelayMs())}})())}async pollOnce(){for(;!this.stopRequested;){let e=(this.cursor??0)+1,r=Ld(this.basePrefix,this.peerStream,e),n;try{let o=await this.opts.s3.send(new this.opts.commands.GetObjectCommand({Bucket:this.opts.bucket,Key:r}));if(this.opts.onS3Op?.("get"),o.Body===void 0){this.emitError(new Error(`GetObject ${r}: empty body`),"get"),this.advanceCursor(e);continue}n=await o.Body.transformToString("utf-8")}catch(o){if(jd(o)){this.opts.onS3Op?.("get");return}this.emitError(o,"get");return}let s;try{s=JSON.parse(n)}catch(o){this.emitError(o,"get"),this.advanceCursor(e);continue}if(this.recordPeerHeartbeat(s),OE(s)){this.advanceCursor(e);continue}try{await this.opts.onMessage(s)}catch(o){this.emitError(o,"handle");return}this.advanceCursor(e)}}advanceCursor(e){this.cursor=e,this.notifyCursorAdvance(e)}nextReadDelayMs(){return this.peerIsOn((this.opts.now??Date.now)())?this.readIntervalMs:this.backoffReadIntervalMs}peerIsOn(e){return this.lastPeerHeartbeatMs!==void 0&&e-this.lastPeerHeartbeatMs<=this.heartbeatIdleMs}recordPeerHeartbeat(e){let r=YP(e);r!==void 0&&(this.lastPeerHeartbeatMs=r)}recordWrite(e){this.lastWriteMs=e,this.scheduleHeartbeatCheck(this.heartbeatIdleMs)}scheduleHeartbeatCheck(e){if(this.stopRequested)return;let r=this.opts.timers??$d;this.heartbeatTimerHandle!==null&&r.clearTimeout(this.heartbeatTimerHandle),this.heartbeatTimerHandle=r.setTimeout(()=>{this.heartbeatTimerHandle=null,this.maybeWriteHeartbeat()},e)}async maybeWriteHeartbeat(){if(this.stopRequested)return;let e=(this.opts.now??Date.now)();if(this.lastWriteMs!==void 0){let r=e-this.lastWriteMs;if(r<this.heartbeatIdleMs){this.scheduleHeartbeatCheck(this.heartbeatIdleMs-r);return}}await this.writeHeartbeat()}async writeHeartbeat(){try{await this.putEnvelope($E,KP)}catch(e){this.emitError(e,"put"),this.scheduleHeartbeatCheck(this.heartbeatIdleMs)}}notifyCursorAdvance(e){if(this.opts.onCursorAdvance!==void 0)try{this.opts.onCursorAdvance(e)}catch(r){this.emitError(r,"handle")}}emitError(e,r){if(this.opts.onError!==void 0)try{this.opts.onError(e,r)}catch{}else console.error(`SequentialMailboxClient[${r}]`,e)}}});import{getConnInfo as zP}from"@hono/node-server/conninfo";function jE(t,e){let r=e.bucket??ZP,n=e.remoteAddressOf??(o=>e1(o)),s=o=>{let i=n(o);return t1(i)?null:o.json({error:"forbidden",message:"local-mailbox is loopback-only"},403)};t.get("/local-mailbox/object",async o=>{let i=s(o);if(i!==null)return i;let a=Cd(o.req.query("key"));if(typeof a!="string")return o.json({error:"bad_request",message:a.error},400);try{let l=await e.s3.send(new e.commands.GetObjectCommand({Bucket:r,Key:a}));if(l.Body===void 0)return o.json({error:"empty_body"},404);let c=await l.Body.transformToString("utf-8");return o.body(c,200,{"Content-Type":"application/octet-stream"})}catch(l){return jd(l)?o.json({error:"not_found"},404):o.json({error:"internal",message:Md(l)},500)}}),t.put("/local-mailbox/object",async o=>{let i=s(o);if(i!==null)return i;let a=Cd(o.req.query("key"));if(typeof a!="string")return o.json({error:"bad_request",message:a.error},400);let l=new Uint8Array(await o.req.arrayBuffer());try{return await e.s3.send(new e.commands.PutObjectCommand({Bucket:r,Key:a,Body:l})),o.json({ok:!0})}catch(c){return o.json({error:"internal",message:Md(c)},500)}}),t.get("/local-mailbox/list",async o=>{let i=s(o);if(i!==null)return i;let a=o.req.query("prefix")??"",l=Cd(a,{allowEmpty:!0});if(typeof l!="string")return o.json({error:"bad_request",message:l.error},400);let c=QP(o.req.query("maxKeys")),u=o.req.query("token");try{let d=await e.s3.send(new e.commands.ListObjectsV2Command({Bucket:r,Prefix:l,...c!==void 0?{MaxKeys:c}:{},...u!==void 0&&u!==""?{ContinuationToken:u}:{}}));return o.json({Contents:(d.Contents??[]).map(f=>({Key:f.Key,LastModified:f.LastModified instanceof Date?f.LastModified.toISOString():f.LastModified})),IsTruncated:d.IsTruncated??!1,...d.NextContinuationToken!==void 0?{NextContinuationToken:d.NextContinuationToken}:{}})}catch(d){return o.json({error:"internal",message:Md(d)},500)}})}function Cd(t,e={}){if(t===void 0||t==="")return e.allowEmpty===!0?"":{error:"key required"};let r=t.replace(/^\/+/,"");return r.split("/").includes("..")?{error:"key must not contain '..'"}:r}function QP(t){if(t===void 0||t==="")return;let e=Number(t);return Number.isInteger(e)&&e>0?e:void 0}function e1(t){try{return zP(t).remote.address}catch{return}}function t1(t){return t===void 0||t===""?!1:!!(t==="127.0.0.1"||t==="::1"||t.startsWith("::ffff:127.")||t.startsWith("127."))}function Md(t){return t instanceof Error?t.message:String(t)}var ZP,CE=T(()=>{"use strict";$a();ZP="local"});function ME(t,e){t.get("/mailbox/workspace",r=>s1(r,e)),t.get("/mailbox/projects",r=>o1(r,e)),t.get("/mailbox/projects/:id",r=>i1(r,e)),t.post("/mailbox/projects",r=>a1(r,e)),t.patch("/mailbox/projects/:id",r=>l1(r,e)),t.delete("/mailbox/projects/:id",r=>c1(r,e)),t.post("/mailbox/projects/:project_id/prompts",r=>u1(r,e)),t.get("/mailbox/prompts/:id",r=>d1(r,e))}function s1(t,e){e.dal.ensureWorkspace({id:Pn,name:Dd});let r=DE(e.dal),n={id:Pn,name:Dd,created_at:n1,projects:r};return t.json({workspace:n})}function o1(t,e){return t.json({projects:DE(e.dal)})}function i1(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);if(r.startsWith(Dn)){let s=Pd(e.dal,r);return s===null||s.deleted_at!==null?t.json({project:null},404):t.json({project:Ca(s)})}let n=FE(e.dal,r);return n===null?t.json({project:null},404):t.json({project:PE(n)})}async function a1(t,e){let r;try{r=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let n=r.input;if(n===void 0||typeof n!="object")return t.json({error:"bad_request",message:"input is required"},400);if(typeof n.name!="string"||n.name==="")return t.json({error:"bad_request",message:"input.name is required"},400);if(typeof n.repo_path!="string"||n.repo_path==="")return t.json({error:"bad_request",message:"input.repo_path is required"},400);e.dal.ensureWorkspace({id:Pn,name:Dd});let s=e.dal.insertWebProject({workspace_id:Pn,name:n.name,repo_path:n.repo_path,config_json:n.config_json===void 0?null:JSON.stringify(n.config_json)});return t.json({project:Ca(s)},201)}async function l1(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.input??{};if(r.startsWith(Dn)){let o=Pd(e.dal,r);if(o===null||o.deleted_at!==null)return t.json({error:"project_not_found",message:`project not found: ${r}`},404);let i=e.dal.updateWebProject({id:o.id,name:s.name===void 0?void 0:s.name,config_json:s.config_json===void 0?void 0:JSON.stringify(s.config_json)});return i===null?t.json({error:"project_not_found",message:`project not found: ${r}`},404):t.json({project:Ca(i)})}return t.json({error:"project_not_found",message:`project not found: ${r}`},404)}function c1(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);if(r.startsWith(Dn)){let n=Pd(e.dal,r);if(n===null)return t.json({deleted:!1});let s=e.dal.softDeleteWebProject(n.id);return t.json({deleted:s})}return t.json({deleted:!1})}async function u1(t,e){let r=t.req.param("project_id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project_id required in path"},400);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.input;if(s===void 0||typeof s!="object")return t.json({error:"bad_request",message:"input is required"},400);let o=s.project_id??r;if(typeof s.text!="string"||s.text==="")return t.json({error:"bad_request",message:"input.text is required"},400);let i=FE(e.dal,o);if(i===null)return t.json({error:"project_not_found",message:`project not found: ${o}`},404);if(e.dal.getWorkflowByName(i.workflow_name)===null)return t.json({error:"workflow_not_registered",message:`project ${i.name} has no registered workflow "${i.workflow_name}"`},400);let l=`${r1}${crypto.randomUUID()}`,c={text:s.text,context_json:s.context_json??null},u;e.enqueueProjectJob!==void 0?u=e.enqueueProjectJob({dal:e.dal,project_id:i.id,source_ref:l,payload:c}):u=await f1({dal:e.dal,project_id:i.id,source_ref:l,payload:c}),e.dal.insertPromptDispatch({prompt_id:l,project_id:i.id,job_id:u.id,text:s.text,context_json:s.context_json===void 0?null:JSON.stringify(s.context_json)});let d={id:l,project_id:`${ja}${i.id}`,text:s.text,status:"pending",created_at:new Date().toISOString(),completed_at:null};return t.json({prompt:d},201)}function d1(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"prompt id required"},400);let n=m1(e.dal,r);return t.json({result:n})}function DE(t){let e=t.listProjects().map(PE),r=t.listWebProjectsActive(Pn).map(Ca);return[...e,...r].sort(S1)}function PE(t){return{id:`${ja}${t.id}`,workspace_id:Pn,name:t.name,repo_path:t.local_path,config_json:{workflow_name:t.workflow_name,team_id:t.team_id,durable_memory_mode:t.durable_memory_mode},last_active_at:null,created_at:t.created_at}}function Ca(t){let e={};if(t.config_json!==null)try{let r=JSON.parse(t.config_json);r!==null&&typeof r=="object"&&(e=r)}catch{}return t.linked_v4_project_id!==null&&(e={...e,linked_v4_project_id:t.linked_v4_project_id}),{id:`${Dn}${t.id}`,workspace_id:t.workspace_id,name:t.name,repo_path:t.repo_path,config_json:e,last_active_at:t.last_active_at,created_at:t.created_at}}function Pd(t,e){if(!e.startsWith(Dn))return null;let r=e.slice(Dn.length),n=Number.parseInt(r,10);return!Number.isFinite(n)||String(n)!==r?null:t.getWebProject(n)}function FE(t,e){if(e.startsWith(ja)){let n=e.slice(ja.length),s=Number.parseInt(n,10);if(Number.isFinite(s)&&String(s)===n)return t.getProject(s)}let r=Number.parseInt(e,10);return Number.isFinite(r)&&String(r)===e?t.getProject(r):null}async function f1(t){let{enqueueManual:e}=await Promise.resolve().then(()=>(Yu(),fy));return{id:e(t.dal,{project_id:t.project_id,source_ref:t.source_ref,payload:t.payload}).id}}function m1(t,e){let r=t.getPromptDispatch(e);if(r===null)return{prompt_id:e,data:{status:"unknown"},errors_json:{error:"prompt_not_found"},duration_ms:null};let n=t.getJob(r.job_id);if(n===null)return{prompt_id:e,data:null,errors_json:{error:"job_missing",job_id:r.job_id},duration_ms:null};let s=n.run_id===null?null:t.getRun(n.run_id),o=t.getProject(r.project_id),i=E1(t,o?.team_id??null),a=w1(s),l=T1(n,a,i.length>0),c=b1(r.created_at,s),u=o===null?{totalEstimatedMs:void 0,perStep:new Map}:p1(t,o.workflow_name),d=u.totalEstimatedMs,f=UE(r.created_at),m=o?.workflow_name,p=u.perStep.size>0?u.perStep.size:void 0,_=s===null?[]:_1(t,s.id),g=h1(s,a,_,u.perStep,i),h=g1(_,u.perStep),E=y1(g,h,d,f,m,p);return l==="error"?{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,...Oa(d,f),...E},errors_json:{error:n.last_error??"job_failed",job_id:n.id,run_id:s?.id??null},duration_ms:c}:l==="done"?(r.completed_at===null&&t.setPromptDispatchCompleted(e),{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,terminal_state:s?.terminal_state??null,text:r.text,...Oa(d,f),...E},errors_json:null,duration_ms:c}):l==="paused"?{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,attempt_count:n.attempt_count,paused_step:a,attention_needed:i,...Oa(d,f),...E},errors_json:null,duration_ms:c}:{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,attempt_count:n.attempt_count,...Oa(d,f),...E},errors_json:null,duration_ms:c}}function p1(t,e){let r={totalEstimatedMs:void 0,perStep:new Map},n=t.getWorkflowByName(e);if(n===null)return r;let s;try{s=JSON.parse(n.definition)}catch{return r}if(s===null||typeof s!="object")return r;let o=s,i=typeof o.estimated_duration_ms=="number"&&Number.isFinite(o.estimated_duration_ms)&&o.estimated_duration_ms>=0?o.estimated_duration_ms:void 0,a=new Map;if(Array.isArray(o.steps))for(let l of o.steps){if(l===null||typeof l!="object")continue;let c=l;if(typeof c.id!="string"||c.id.length===0)continue;let u=typeof c.name=="string"&&c.name.length>0?c.name:c.id,d=typeof c.estimated_duration_ms=="number"&&Number.isFinite(c.estimated_duration_ms)&&c.estimated_duration_ms>=0?c.estimated_duration_ms:void 0;a.set(c.id,d===void 0?{name:u}:{name:u,estimated_duration_ms:d})}if(o.steps===void 0&&o.states!==null&&typeof o.states=="object")for(let[l,c]of Object.entries(o.states)){if(c===null||typeof c!="object")continue;let u=c,d=typeof u.estimated_duration_ms=="number"&&Number.isFinite(u.estimated_duration_ms)&&u.estimated_duration_ms>=0?u.estimated_duration_ms:void 0;a.set(l,d===void 0?{name:l}:{name:l,estimated_duration_ms:d})}return{totalEstimatedMs:i,perStep:a}}function _1(t,e){try{return t.listStepsForRun(e)}catch{return[]}}function h1(t,e,r,n,s){if(t===null||t.terminal_state!==null)return;let o=e!==null?e:t.current_state;if(o===null||o.length===0)return;let a=[...r].reverse().find(f=>f.state_name===o&&f.ended_at===null)?.started_at??t.paused_at??t.started_at,l=n.get(o),c=l?.name??o,u=UE(a),d={id:o,name:c,started_at:a,elapsed_ms:u};return l?.estimated_duration_ms!==void 0&&(d.estimated_duration_ms=l.estimated_duration_ms),s.length>0&&(d.attention_needed=s),d}function g1(t,e){let r=[];for(let n of t){if(n.ended_at===null)continue;let s=Date.parse(n.started_at),o=Date.parse(n.ended_at),i=Number.isFinite(s)&&Number.isFinite(o)?Math.max(0,o-s):0,a=e.get(n.state_name)?.name??n.state_name,l=n.outcome==="failed"?"failed":"done";r.push({id:n.state_name,name:a,duration_ms:i,status:l})}return r}function y1(t,e,r,n,s,o){let i={completed_steps:e,total_elapsed_ms:n};return t!==void 0&&(i.current_step=t),r!==void 0&&(i.total_estimated_ms=r),s!==void 0&&s.length>0&&(i.workflow_name=s),o!==void 0&&(i.total_steps=o),i}function UE(t){let e=Date.parse(t);return Number.isNaN(e)?0:Math.max(0,Date.now()-e)}function Oa(t,e){return t===void 0?{elapsed_ms:e}:{elapsed_ms:e,estimated_duration_ms:t}}function w1(t){if(t===null)return null;let e=t.current_state;if(e===null)return null;let r="__paused__:";return e.startsWith(r)?e.slice(r.length):null}function E1(t,e){if(e===null)return[];let r;try{r=t.listTeamMembers(e)}catch{return[]}return r.filter(n=>n.state==="attention_needed").map(n=>({alias:n.alias,reason:n.state_reason}))}function T1(t,e,r){return t.status==="queued"?"pending":t.status==="done"?"done":t.status==="failed"?"error":e!==null||r||t.status==="paused"?"paused":t.status==="running"?"running":"error"}function b1(t,e){let r=Date.parse(t);if(Number.isNaN(r))return null;let n=e?.ended_at??null,s=n===null?Date.now():Date.parse(n);return Number.isNaN(s)?null:Math.max(0,s-r)}function S1(t,e){let r=Date.parse(t.last_active_at??""),n=Date.parse(e.last_active_at??""),s=(Number.isNaN(n)?0:n)-(Number.isNaN(r)?0:r);return s===0?t.name.localeCompare(e.name):s}var ja,Dn,r1,Pn,Dd,n1,WE=T(()=>{"use strict";ja="project:",Dn="web_project:",r1="prompt:",Pn="default",Dd="Default workspace",n1=new Date(0).toISOString()});import{Buffer as BE}from"node:buffer";function qE(t,e,r){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(e!==void 0&&e!==""){let n=Number(e);if(Number.isFinite(n)&&n>0)return n}return r}function HE(t){return I1[t]}function JE(t){let e=t.trim();if(e==="")return;let r=e.split(/\s+/),n=r.shift();if(!(n===void 0||n===""))return{cmd:n,args:r}}var v1,k1,Ma,I1,Fd=T(()=>{"use strict";v1=1e4,k1=256*1024,Ma=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=qE(e.pushWindowMs,process.env.LMCTL_TERMINAL_PUSH_WINDOW_MS,v1),this.pushByteCap=qE(e.pushByteCap,process.env.LMCTL_TERMINAL_PUSH_BYTE_CAP,k1),this.timers=e.timers??{setTimeout:(r,n)=>globalThis.setTimeout(r,n),clearTimeout:r=>globalThis.clearTimeout(r)}}startSession(e){if(this.sessions.has(e.session_id))throw new Error(`terminal_session_already_exists: ${e.session_id}`);let r=this.opts.pty.spawn(e.command,e.args,{name:"xterm-256color",cols:e.cols??120,rows:e.rows??30,cwd:e.cwd??process.cwd(),env:e.env??process.env}),n={session_id:e.session_id,pty:r,pendingOutput:[],pendingBytes:0,pushTimer:void 0,closed:!1};return this.sessions.set(e.session_id,n),r.onData(s=>{this.onPtyData(n,s)}),r.onExit(s=>{this.onPtyExit(n,s)}),this.opts.log?.(`[dt-2] terminal session ${e.session_id} started pid=${r.pid} cmd=${e.command}`),{pid:r.pid}}endSession(e){let r=this.sessions.get(e);if(r!==void 0)try{r.pty.kill()}catch{}}onInbound(e){if(e.direction!=="user_to_agent")return;let r=this.sessions.get(e.session_id);if(r===void 0){this.opts.log?.(`[dt-2] inbound terminal data for unknown session ${e.session_id}; dropping`);return}if(r.closed){this.opts.log?.(`[dt-2] inbound terminal data for closed session ${e.session_id}; dropping`);return}try{r.pty.write(e.data)}catch(n){this.opts.log?.(`[dt-2] pty.write failed for session ${e.session_id}: ${n instanceof Error?n.message:String(n)}`)}}setPublish(e){this.opts={...this.opts,publish:e}}listSessions(){return Array.from(this.sessions.values()).map(e=>({session_id:e.session_id,pid:e.pty.pid}))}pendingBytesFor(e){return this.sessions.get(e)?.pendingBytes}async stop(){for(let e of Array.from(this.sessions.values()))try{e.pty.kill()}catch{}for(let e of Array.from(this.sessions.values()))e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0)}onPtyData(e,r){if(!e.closed){if(e.pendingOutput.push(r),e.pendingBytes+=BE.byteLength(r,"utf8"),e.pendingBytes>=this.pushByteCap){this.flush(e,"byte_cap");return}e.pushTimer===void 0&&(e.pushTimer=this.timers.setTimeout(()=>{this.flush(e,"window_idle")},this.pushWindowMs))}}async flush(e,r){if(e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0),e.pendingOutput.length===0)return;let n=e.pendingOutput.join("");e.pendingOutput=[],e.pendingBytes=0;let s={kind:"terminal",session_id:e.session_id,direction:"agent_to_user",data:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s),this.opts.log?.(`[dt-2] flushed session=${e.session_id} reason=${r} bytes=${BE.byteLength(n,"utf8")}`)}catch(o){this.opts.log?.(`[dt-2] publish failed session=${e.session_id} reason=${r}: ${o instanceof Error?o.message:String(o)}`)}}async onPtyExit(e,r){if(e.closed)return;await this.flush(e,"pty_exit");let n=`\r
|
|
2067
|
+
`)}function WP(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Qe(t){return typeof t=="string"?t:""}function BP(t){if(t===null)return{};try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{return{}}return{}}function Nd(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ka(t,e){return Number(t.req.param(e))}var Ia,Ad,NE=T(()=>{"use strict";Ks();Jt();ld();Ia=[{name:"info-qa",title:"Ask a Question",description:"Get a grounded answer from multiple researchers and one consolidator."},{name:"document-creation",title:"Create a Document",description:"Draft, review, and render a polished document with an interactive wizard."},{name:"newspaper",title:"Daily Newspaper",description:"Subscribe to recurring digests for topics you care about."}],Ad=Ia.map(t=>t.name)});function HP(t){return t.replace(/^\/+/,"")}function AE(t){return typeof t=="string"&&t!==""&&!t.includes("/")&&!t.includes("\\")}function Mn(t){if(t.mailboxKey!==void 0&&t.mailboxKey!==null&&t.mailboxKey!==""){let e=HP(t.mailboxKey),r=e.lastIndexOf("/");return(r>=0?e.slice(r+1):e).includes(".")&&(e=r>=0?e.slice(0,r+1):""),e!==""&&!e.endsWith("/")&&(e+="/"),e}return AE(t.userId)&&AE(t.deviceId)?`${t.userId}/${t.deviceId}/`:`${qP}/${t.identityId}/`}function XP(t){return String(Math.max(0,Math.floor(t))).padStart(JP,"0")}function Ld(t,e,r){return`${t}${e}${XP(r)}.json`}function Na(t,e){return`${t}${e}`}function Aa(t,e,r){let n=`${e}${r}`;if(!t.startsWith(n))return;let s=t.slice(n.length).match(/^(\d+)\.json$/);if(s===null)return;let o=Number(s[1]);return Number.isSafeInteger(o)?o:void 0}var qP,JP,xa=T(()=>{"use strict";qP="mailbox";JP=12});function Zt(t,e){let r=Math.floor(t),n="",s=r;for(let u=0;u<12;u++)n=Ra[s&15]+n,s=Math.floor(s/16);let o=Math.floor(e()*4096)&4095,i="",a=o;for(let u=0;u<3;u++)i=Ra[a&15]+i,a=a>>4;let l=Ra[8|Math.floor(e()*4)&3],c="";for(let u=0;u<15;u++)c+=Ra[Math.floor(e()*16)&15];return n.slice(0,8)+"-"+n.slice(8,12)+"-7"+i+"-"+l+c.slice(0,3)+"-"+c.slice(3,15)}var Ra,La=T(()=>{"use strict";Ra="0123456789abcdef"});function Od(t,e){return!Number.isFinite(t)||t<=0?e:t}function jd(t){if(t===null||typeof t!="object")return!1;let e=t;return e.name==="NoSuchKey"||e.name==="NotFound"||e.Code==="NoSuchKey"||e.code==="NoSuchKey"||e.$metadata!==void 0&&e.$metadata.httpStatusCode===404}function OE(t){return t.conversation_id===$E&&VP(t.payload)}function VP(t){return typeof t=="object"&&t!==null&&t.kind==="heartbeat"}function YP(t){let e=typeof t.hb=="string"&&t.hb!==""?t.hb:OE(t)?t.timestamp:void 0;if(e===void 0)return;let r=Date.parse(e);return Number.isFinite(r)?r:void 0}var xE,RE,LE,GP,$E,KP,$d,Hr,$a=T(()=>{"use strict";xa();La();xE=3e3,RE=1e4,LE=12e3,GP=1e3,$E="__lmctl_heartbeat__",KP={kind:"heartbeat"},$d={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Hr=class{opts;basePrefix;ownStream;peerStream;cursor;ownSeq;bootstrapped=!1;bootstrapInFlight=null;bootstrapPromise=null;writeChain=Promise.resolve();readIntervalMs;heartbeatIdleMs;backoffReadIntervalMs;running=!1;stopped=!1;stopRequested=!1;timerHandle=null;heartbeatTimerHandle=null;lastWriteMs;lastPeerHeartbeatMs;tickInFlight=null;constructor(e){this.opts=e,this.basePrefix=Mn({identityId:e.identityId,userId:e.userId,deviceId:e.deviceId,mailboxKey:e.mailboxKey}),this.ownStream=e.selfRole==="agent"?"local":"web",this.peerStream=e.selfRole==="agent"?"web":"local",this.cursor=e.cursor,this.readIntervalMs=Od(e.readIntervalMs??e.pollIntervalMs??xE,xE),this.heartbeatIdleMs=Od(e.heartbeatIdleMs??RE,RE),this.backoffReadIntervalMs=Od(e.backoffReadIntervalMs??e.pollIntervalMs??LE,LE)}start(){if(this.stopped)throw new Error("SequentialMailboxClient: cannot start after stop()");this.running||(this.running=!0,this.bootstrapInFlight=this.bootstrapThenRun())}async stop(){this.stopped=!0,this.stopRequested=!0;let e=this.opts.timers??$d;if(this.timerHandle!==null&&(e.clearTimeout(this.timerHandle),this.timerHandle=null),this.heartbeatTimerHandle!==null&&(e.clearTimeout(this.heartbeatTimerHandle),this.heartbeatTimerHandle=null),this.bootstrapInFlight!==null)try{await this.bootstrapInFlight}catch{}if(this.tickInFlight!==null)try{await this.tickInFlight}catch{}this.running=!1}async putMessage(e){return this.putEnvelope(e.conversation_id,e.payload)}getCursor(){return this.cursor}getMailboxBasePrefix(){return this.basePrefix}setPollIntervalMs(e){if(!Number.isFinite(e)||e<=0)throw new Error(`SequentialMailboxClient.setPollIntervalMs: invalid ms=${e}`);this.readIntervalMs=e}isPeerOn(){return this.peerIsOn((this.opts.now??Date.now)())}async bootstrapThenRun(){if(await this.ensureBootstrapped(),this.stopRequested){this.running=!1;return}this.runTick(),this.writeHeartbeat()}ensureBootstrapped(){return this.bootstrapped?Promise.resolve():(this.bootstrapPromise===null&&(this.bootstrapPromise=this.runColdStart()),this.bootstrapPromise)}async runColdStart(){try{let e=await this.maxSeq(this.ownStream);this.ownSeq=e,this.cursor===void 0&&(this.cursor=await this.maxSeq(this.peerStream)),this.bootstrapped=!0}catch(e){throw this.bootstrapPromise=null,this.emitError(e,"list"),e}}async maxSeq(e){let r=Na(this.basePrefix,e),n=0,s;do{let o=await this.opts.s3.send(new this.opts.commands.ListObjectsV2Command({Bucket:this.opts.bucket,Prefix:r,MaxKeys:GP,...s!==void 0&&{ContinuationToken:s}}));this.opts.onS3Op?.("list");for(let i of o.Contents??[]){let a=Aa(i.Key??"",this.basePrefix,e);a!==void 0&&a>n&&(n=a)}s=o.IsTruncated===!0?o.NextContinuationToken:void 0}while(s!==void 0);return n}async putEnvelope(e,r){let n=this.writeChain.then(()=>this.doPut(e,r));return this.writeChain=n.catch(()=>{}),n}async doPut(e,r){await this.ensureBootstrapped();let n=(this.opts.now??Date.now)(),s=new Date(n).toISOString(),o={message_id:Zt(n,this.opts.random??Math.random),from:this.opts.selfRole,timestamp:s,hb:s,conversation_id:e,payload:r},i=(this.ownSeq??0)+1,a=Ld(this.basePrefix,this.ownStream,i);return await this.opts.s3.send(new this.opts.commands.PutObjectCommand({Bucket:this.opts.bucket,Key:a,Body:JSON.stringify(o),ContentType:"application/json"})),this.opts.onS3Op?.("put"),this.ownSeq=i,this.recordWrite(n),a}scheduleNextTick(e){if(this.stopRequested)return;let r=this.opts.timers??$d;this.timerHandle=r.setTimeout(()=>{this.timerHandle=null,this.runTick()},e)}runTick(){this.stopRequested||(this.tickInFlight=(async()=>{try{await this.pollOnce()}finally{this.tickInFlight=null,this.stopRequested||this.scheduleNextTick(this.nextReadDelayMs())}})())}async pollOnce(){for(;!this.stopRequested;){let e=(this.cursor??0)+1,r=Ld(this.basePrefix,this.peerStream,e),n;try{let o=await this.opts.s3.send(new this.opts.commands.GetObjectCommand({Bucket:this.opts.bucket,Key:r}));if(this.opts.onS3Op?.("get"),o.Body===void 0){this.emitError(new Error(`GetObject ${r}: empty body`),"get"),this.advanceCursor(e);continue}n=await o.Body.transformToString("utf-8")}catch(o){if(jd(o)){this.opts.onS3Op?.("get");return}this.emitError(o,"get");return}let s;try{s=JSON.parse(n)}catch(o){this.emitError(o,"get"),this.advanceCursor(e);continue}if(this.recordPeerHeartbeat(s),OE(s)){this.advanceCursor(e);continue}try{await this.opts.onMessage(s)}catch(o){this.emitError(o,"handle");return}this.advanceCursor(e)}}advanceCursor(e){this.cursor=e,this.notifyCursorAdvance(e)}nextReadDelayMs(){return this.peerIsOn((this.opts.now??Date.now)())?this.readIntervalMs:this.backoffReadIntervalMs}peerIsOn(e){return this.lastPeerHeartbeatMs!==void 0&&e-this.lastPeerHeartbeatMs<=this.heartbeatIdleMs}recordPeerHeartbeat(e){let r=YP(e);r!==void 0&&(this.lastPeerHeartbeatMs=r)}recordWrite(e){this.lastWriteMs=e,this.scheduleHeartbeatCheck(this.heartbeatIdleMs)}scheduleHeartbeatCheck(e){if(this.stopRequested)return;let r=this.opts.timers??$d;this.heartbeatTimerHandle!==null&&r.clearTimeout(this.heartbeatTimerHandle),this.heartbeatTimerHandle=r.setTimeout(()=>{this.heartbeatTimerHandle=null,this.maybeWriteHeartbeat()},e)}async maybeWriteHeartbeat(){if(this.stopRequested)return;let e=(this.opts.now??Date.now)();if(this.lastWriteMs!==void 0){let r=e-this.lastWriteMs;if(r<this.heartbeatIdleMs){this.scheduleHeartbeatCheck(this.heartbeatIdleMs-r);return}}await this.writeHeartbeat()}async writeHeartbeat(){try{await this.putEnvelope($E,KP)}catch(e){this.emitError(e,"put"),this.scheduleHeartbeatCheck(this.heartbeatIdleMs)}}notifyCursorAdvance(e){if(this.opts.onCursorAdvance!==void 0)try{this.opts.onCursorAdvance(e)}catch(r){this.emitError(r,"handle")}}emitError(e,r){if(this.opts.onError!==void 0)try{this.opts.onError(e,r)}catch{}else console.error(`SequentialMailboxClient[${r}]`,e)}}});import{getConnInfo as zP}from"@hono/node-server/conninfo";function jE(t,e){let r=e.bucket??ZP,n=e.remoteAddressOf??(o=>eF(o)),s=o=>{let i=n(o);return tF(i)?null:o.json({error:"forbidden",message:"local-mailbox is loopback-only"},403)};t.get("/local-mailbox/object",async o=>{let i=s(o);if(i!==null)return i;let a=Cd(o.req.query("key"));if(typeof a!="string")return o.json({error:"bad_request",message:a.error},400);try{let l=await e.s3.send(new e.commands.GetObjectCommand({Bucket:r,Key:a}));if(l.Body===void 0)return o.json({error:"empty_body"},404);let c=await l.Body.transformToString("utf-8");return o.body(c,200,{"Content-Type":"application/octet-stream"})}catch(l){return jd(l)?o.json({error:"not_found"},404):o.json({error:"internal",message:Md(l)},500)}}),t.put("/local-mailbox/object",async o=>{let i=s(o);if(i!==null)return i;let a=Cd(o.req.query("key"));if(typeof a!="string")return o.json({error:"bad_request",message:a.error},400);let l=new Uint8Array(await o.req.arrayBuffer());try{return await e.s3.send(new e.commands.PutObjectCommand({Bucket:r,Key:a,Body:l})),o.json({ok:!0})}catch(c){return o.json({error:"internal",message:Md(c)},500)}}),t.get("/local-mailbox/list",async o=>{let i=s(o);if(i!==null)return i;let a=o.req.query("prefix")??"",l=Cd(a,{allowEmpty:!0});if(typeof l!="string")return o.json({error:"bad_request",message:l.error},400);let c=QP(o.req.query("maxKeys")),u=o.req.query("token");try{let d=await e.s3.send(new e.commands.ListObjectsV2Command({Bucket:r,Prefix:l,...c!==void 0?{MaxKeys:c}:{},...u!==void 0&&u!==""?{ContinuationToken:u}:{}}));return o.json({Contents:(d.Contents??[]).map(f=>({Key:f.Key,LastModified:f.LastModified instanceof Date?f.LastModified.toISOString():f.LastModified})),IsTruncated:d.IsTruncated??!1,...d.NextContinuationToken!==void 0?{NextContinuationToken:d.NextContinuationToken}:{}})}catch(d){return o.json({error:"internal",message:Md(d)},500)}})}function Cd(t,e={}){if(t===void 0||t==="")return e.allowEmpty===!0?"":{error:"key required"};let r=t.replace(/^\/+/,"");return r.split("/").includes("..")?{error:"key must not contain '..'"}:r}function QP(t){if(t===void 0||t==="")return;let e=Number(t);return Number.isInteger(e)&&e>0?e:void 0}function eF(t){try{return zP(t).remote.address}catch{return}}function tF(t){return t===void 0||t===""?!1:!!(t==="127.0.0.1"||t==="::1"||t.startsWith("::ffff:127.")||t.startsWith("127."))}function Md(t){return t instanceof Error?t.message:String(t)}var ZP,CE=T(()=>{"use strict";$a();ZP="local"});function ME(t,e){t.get("/mailbox/workspace",r=>sF(r,e)),t.get("/mailbox/projects",r=>oF(r,e)),t.get("/mailbox/projects/:id",r=>iF(r,e)),t.post("/mailbox/projects",r=>aF(r,e)),t.patch("/mailbox/projects/:id",r=>lF(r,e)),t.delete("/mailbox/projects/:id",r=>cF(r,e)),t.post("/mailbox/projects/:project_id/prompts",r=>uF(r,e)),t.get("/mailbox/prompts/:id",r=>dF(r,e))}function sF(t,e){e.dal.ensureWorkspace({id:Pn,name:Dd});let r=DE(e.dal),n={id:Pn,name:Dd,created_at:nF,projects:r};return t.json({workspace:n})}function oF(t,e){return t.json({projects:DE(e.dal)})}function iF(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);if(r.startsWith(Dn)){let s=Pd(e.dal,r);return s===null||s.deleted_at!==null?t.json({project:null},404):t.json({project:Ca(s)})}let n=FE(e.dal,r);return n===null?t.json({project:null},404):t.json({project:PE(n)})}async function aF(t,e){let r;try{r=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let n=r.input;if(n===void 0||typeof n!="object")return t.json({error:"bad_request",message:"input is required"},400);if(typeof n.name!="string"||n.name==="")return t.json({error:"bad_request",message:"input.name is required"},400);if(typeof n.repo_path!="string"||n.repo_path==="")return t.json({error:"bad_request",message:"input.repo_path is required"},400);e.dal.ensureWorkspace({id:Pn,name:Dd});let s=e.dal.insertWebProject({workspace_id:Pn,name:n.name,repo_path:n.repo_path,config_json:n.config_json===void 0?null:JSON.stringify(n.config_json)});return t.json({project:Ca(s)},201)}async function lF(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.input??{};if(r.startsWith(Dn)){let o=Pd(e.dal,r);if(o===null||o.deleted_at!==null)return t.json({error:"project_not_found",message:`project not found: ${r}`},404);let i=e.dal.updateWebProject({id:o.id,name:s.name===void 0?void 0:s.name,config_json:s.config_json===void 0?void 0:JSON.stringify(s.config_json)});return i===null?t.json({error:"project_not_found",message:`project not found: ${r}`},404):t.json({project:Ca(i)})}return t.json({error:"project_not_found",message:`project not found: ${r}`},404)}function cF(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project id required"},400);if(r.startsWith(Dn)){let n=Pd(e.dal,r);if(n===null)return t.json({deleted:!1});let s=e.dal.softDeleteWebProject(n.id);return t.json({deleted:s})}return t.json({deleted:!1})}async function uF(t,e){let r=t.req.param("project_id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"project_id required in path"},400);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.input;if(s===void 0||typeof s!="object")return t.json({error:"bad_request",message:"input is required"},400);let o=s.project_id??r;if(typeof s.text!="string"||s.text==="")return t.json({error:"bad_request",message:"input.text is required"},400);let i=FE(e.dal,o);if(i===null)return t.json({error:"project_not_found",message:`project not found: ${o}`},404);if(e.dal.getWorkflowByName(i.workflow_name)===null)return t.json({error:"workflow_not_registered",message:`project ${i.name} has no registered workflow "${i.workflow_name}"`},400);let l=`${rF}${crypto.randomUUID()}`,c={text:s.text,context_json:s.context_json??null},u;e.enqueueProjectJob!==void 0?u=e.enqueueProjectJob({dal:e.dal,project_id:i.id,source_ref:l,payload:c}):u=await fF({dal:e.dal,project_id:i.id,source_ref:l,payload:c}),e.dal.insertPromptDispatch({prompt_id:l,project_id:i.id,job_id:u.id,text:s.text,context_json:s.context_json===void 0?null:JSON.stringify(s.context_json)});let d={id:l,project_id:`${ja}${i.id}`,text:s.text,status:"pending",created_at:new Date().toISOString(),completed_at:null};return t.json({prompt:d},201)}function dF(t,e){let r=t.req.param("id");if(r===void 0||r==="")return t.json({error:"bad_request",message:"prompt id required"},400);let n=mF(e.dal,r);return t.json({result:n})}function DE(t){let e=t.listProjects().map(PE),r=t.listWebProjectsActive(Pn).map(Ca);return[...e,...r].sort(SF)}function PE(t){return{id:`${ja}${t.id}`,workspace_id:Pn,name:t.name,repo_path:t.local_path,config_json:{workflow_name:t.workflow_name,team_id:t.team_id,durable_memory_mode:t.durable_memory_mode},last_active_at:null,created_at:t.created_at}}function Ca(t){let e={};if(t.config_json!==null)try{let r=JSON.parse(t.config_json);r!==null&&typeof r=="object"&&(e=r)}catch{}return t.linked_v4_project_id!==null&&(e={...e,linked_v4_project_id:t.linked_v4_project_id}),{id:`${Dn}${t.id}`,workspace_id:t.workspace_id,name:t.name,repo_path:t.repo_path,config_json:e,last_active_at:t.last_active_at,created_at:t.created_at}}function Pd(t,e){if(!e.startsWith(Dn))return null;let r=e.slice(Dn.length),n=Number.parseInt(r,10);return!Number.isFinite(n)||String(n)!==r?null:t.getWebProject(n)}function FE(t,e){if(e.startsWith(ja)){let n=e.slice(ja.length),s=Number.parseInt(n,10);if(Number.isFinite(s)&&String(s)===n)return t.getProject(s)}let r=Number.parseInt(e,10);return Number.isFinite(r)&&String(r)===e?t.getProject(r):null}async function fF(t){let{enqueueManual:e}=await Promise.resolve().then(()=>(Yu(),fy));return{id:e(t.dal,{project_id:t.project_id,source_ref:t.source_ref,payload:t.payload}).id}}function mF(t,e){let r=t.getPromptDispatch(e);if(r===null)return{prompt_id:e,data:{status:"unknown"},errors_json:{error:"prompt_not_found"},duration_ms:null};let n=t.getJob(r.job_id);if(n===null)return{prompt_id:e,data:null,errors_json:{error:"job_missing",job_id:r.job_id},duration_ms:null};let s=n.run_id===null?null:t.getRun(n.run_id),o=t.getProject(r.project_id),i=EF(t,o?.team_id??null),a=wF(s),l=TF(n,a,i.length>0),c=bF(r.created_at,s),u=o===null?{totalEstimatedMs:void 0,perStep:new Map}:pF(t,o.workflow_name),d=u.totalEstimatedMs,f=UE(r.created_at),m=o?.workflow_name,p=u.perStep.size>0?u.perStep.size:void 0,_=s===null?[]:_F(t,s.id),g=hF(s,a,_,u.perStep,i),h=gF(_,u.perStep),E=yF(g,h,d,f,m,p);return l==="error"?{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,...Oa(d,f),...E},errors_json:{error:n.last_error??"job_failed",job_id:n.id,run_id:s?.id??null},duration_ms:c}:l==="done"?(r.completed_at===null&&t.setPromptDispatchCompleted(e),{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,terminal_state:s?.terminal_state??null,text:r.text,...Oa(d,f),...E},errors_json:null,duration_ms:c}):l==="paused"?{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,attempt_count:n.attempt_count,paused_step:a,attention_needed:i,...Oa(d,f),...E},errors_json:null,duration_ms:c}:{prompt_id:e,data:{status:l,job_id:n.id,project_id:r.project_id,run_id:s?.id??null,attempt_count:n.attempt_count,...Oa(d,f),...E},errors_json:null,duration_ms:c}}function pF(t,e){let r={totalEstimatedMs:void 0,perStep:new Map},n=t.getWorkflowByName(e);if(n===null)return r;let s;try{s=JSON.parse(n.definition)}catch{return r}if(s===null||typeof s!="object")return r;let o=s,i=typeof o.estimated_duration_ms=="number"&&Number.isFinite(o.estimated_duration_ms)&&o.estimated_duration_ms>=0?o.estimated_duration_ms:void 0,a=new Map;if(Array.isArray(o.steps))for(let l of o.steps){if(l===null||typeof l!="object")continue;let c=l;if(typeof c.id!="string"||c.id.length===0)continue;let u=typeof c.name=="string"&&c.name.length>0?c.name:c.id,d=typeof c.estimated_duration_ms=="number"&&Number.isFinite(c.estimated_duration_ms)&&c.estimated_duration_ms>=0?c.estimated_duration_ms:void 0;a.set(c.id,d===void 0?{name:u}:{name:u,estimated_duration_ms:d})}if(o.steps===void 0&&o.states!==null&&typeof o.states=="object")for(let[l,c]of Object.entries(o.states)){if(c===null||typeof c!="object")continue;let u=c,d=typeof u.estimated_duration_ms=="number"&&Number.isFinite(u.estimated_duration_ms)&&u.estimated_duration_ms>=0?u.estimated_duration_ms:void 0;a.set(l,d===void 0?{name:l}:{name:l,estimated_duration_ms:d})}return{totalEstimatedMs:i,perStep:a}}function _F(t,e){try{return t.listStepsForRun(e)}catch{return[]}}function hF(t,e,r,n,s){if(t===null||t.terminal_state!==null)return;let o=e!==null?e:t.current_state;if(o===null||o.length===0)return;let a=[...r].reverse().find(f=>f.state_name===o&&f.ended_at===null)?.started_at??t.paused_at??t.started_at,l=n.get(o),c=l?.name??o,u=UE(a),d={id:o,name:c,started_at:a,elapsed_ms:u};return l?.estimated_duration_ms!==void 0&&(d.estimated_duration_ms=l.estimated_duration_ms),s.length>0&&(d.attention_needed=s),d}function gF(t,e){let r=[];for(let n of t){if(n.ended_at===null)continue;let s=Date.parse(n.started_at),o=Date.parse(n.ended_at),i=Number.isFinite(s)&&Number.isFinite(o)?Math.max(0,o-s):0,a=e.get(n.state_name)?.name??n.state_name,l=n.outcome==="failed"?"failed":"done";r.push({id:n.state_name,name:a,duration_ms:i,status:l})}return r}function yF(t,e,r,n,s,o){let i={completed_steps:e,total_elapsed_ms:n};return t!==void 0&&(i.current_step=t),r!==void 0&&(i.total_estimated_ms=r),s!==void 0&&s.length>0&&(i.workflow_name=s),o!==void 0&&(i.total_steps=o),i}function UE(t){let e=Date.parse(t);return Number.isNaN(e)?0:Math.max(0,Date.now()-e)}function Oa(t,e){return t===void 0?{elapsed_ms:e}:{elapsed_ms:e,estimated_duration_ms:t}}function wF(t){if(t===null)return null;let e=t.current_state;if(e===null)return null;let r="__paused__:";return e.startsWith(r)?e.slice(r.length):null}function EF(t,e){if(e===null)return[];let r;try{r=t.listTeamMembers(e)}catch{return[]}return r.filter(n=>n.state==="attention_needed").map(n=>({alias:n.alias,reason:n.state_reason}))}function TF(t,e,r){return t.status==="queued"?"pending":t.status==="done"?"done":t.status==="failed"?"error":e!==null||r||t.status==="paused"?"paused":t.status==="running"?"running":"error"}function bF(t,e){let r=Date.parse(t);if(Number.isNaN(r))return null;let n=e?.ended_at??null,s=n===null?Date.now():Date.parse(n);return Number.isNaN(s)?null:Math.max(0,s-r)}function SF(t,e){let r=Date.parse(t.last_active_at??""),n=Date.parse(e.last_active_at??""),s=(Number.isNaN(n)?0:n)-(Number.isNaN(r)?0:r);return s===0?t.name.localeCompare(e.name):s}var ja,Dn,rF,Pn,Dd,nF,WE=T(()=>{"use strict";ja="project:",Dn="web_project:",rF="prompt:",Pn="default",Dd="Default workspace",nF=new Date(0).toISOString()});import{Buffer as BE}from"node:buffer";function qE(t,e,r){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(e!==void 0&&e!==""){let n=Number(e);if(Number.isFinite(n)&&n>0)return n}return r}function HE(t){return IF[t]}function JE(t){let e=t.trim();if(e==="")return;let r=e.split(/\s+/),n=r.shift();if(!(n===void 0||n===""))return{cmd:n,args:r}}var vF,kF,Ma,IF,Fd=T(()=>{"use strict";vF=1e4,kF=256*1024,Ma=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=qE(e.pushWindowMs,process.env.LMCTL_TERMINAL_PUSH_WINDOW_MS,vF),this.pushByteCap=qE(e.pushByteCap,process.env.LMCTL_TERMINAL_PUSH_BYTE_CAP,kF),this.timers=e.timers??{setTimeout:(r,n)=>globalThis.setTimeout(r,n),clearTimeout:r=>globalThis.clearTimeout(r)}}startSession(e){if(this.sessions.has(e.session_id))throw new Error(`terminal_session_already_exists: ${e.session_id}`);let r=this.opts.pty.spawn(e.command,e.args,{name:"xterm-256color",cols:e.cols??120,rows:e.rows??30,cwd:e.cwd??process.cwd(),env:e.env??process.env}),n={session_id:e.session_id,pty:r,pendingOutput:[],pendingBytes:0,pushTimer:void 0,closed:!1};return this.sessions.set(e.session_id,n),r.onData(s=>{this.onPtyData(n,s)}),r.onExit(s=>{this.onPtyExit(n,s)}),this.opts.log?.(`[dt-2] terminal session ${e.session_id} started pid=${r.pid} cmd=${e.command}`),{pid:r.pid}}endSession(e){let r=this.sessions.get(e);if(r!==void 0)try{r.pty.kill()}catch{}}onInbound(e){if(e.direction!=="user_to_agent")return;let r=this.sessions.get(e.session_id);if(r===void 0){this.opts.log?.(`[dt-2] inbound terminal data for unknown session ${e.session_id}; dropping`);return}if(r.closed){this.opts.log?.(`[dt-2] inbound terminal data for closed session ${e.session_id}; dropping`);return}try{r.pty.write(e.data)}catch(n){this.opts.log?.(`[dt-2] pty.write failed for session ${e.session_id}: ${n instanceof Error?n.message:String(n)}`)}}setPublish(e){this.opts={...this.opts,publish:e}}listSessions(){return Array.from(this.sessions.values()).map(e=>({session_id:e.session_id,pid:e.pty.pid}))}pendingBytesFor(e){return this.sessions.get(e)?.pendingBytes}async stop(){for(let e of Array.from(this.sessions.values()))try{e.pty.kill()}catch{}for(let e of Array.from(this.sessions.values()))e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0)}onPtyData(e,r){if(!e.closed){if(e.pendingOutput.push(r),e.pendingBytes+=BE.byteLength(r,"utf8"),e.pendingBytes>=this.pushByteCap){this.flush(e,"byte_cap");return}e.pushTimer===void 0&&(e.pushTimer=this.timers.setTimeout(()=>{this.flush(e,"window_idle")},this.pushWindowMs))}}async flush(e,r){if(e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0),e.pendingOutput.length===0)return;let n=e.pendingOutput.join("");e.pendingOutput=[],e.pendingBytes=0;let s={kind:"terminal",session_id:e.session_id,direction:"agent_to_user",data:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s),this.opts.log?.(`[dt-2] flushed session=${e.session_id} reason=${r} bytes=${BE.byteLength(n,"utf8")}`)}catch(o){this.opts.log?.(`[dt-2] publish failed session=${e.session_id} reason=${r}: ${o instanceof Error?o.message:String(o)}`)}}async onPtyExit(e,r){if(e.closed)return;await this.flush(e,"pty_exit");let n=`\r
|
|
2062
2068
|
[process exited with code ${r.exitCode}${r.signal!==void 0?` signal ${r.signal}`:""}]\r
|
|
2063
|
-
`,s={kind:"terminal",session_id:e.session_id,direction:"agent_to_user",data:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s)}catch(o){this.opts.log?.(`[dt-2] publish (exit) failed session=${e.session_id}: ${o instanceof Error?o.message:String(o)}`)}e.closed=!0,this.sessions.delete(e.session_id)}};I1={claude:{cmd:"claude",args:["--dangerously-skip-permissions"]},codex:{cmd:"codex",args:["--yolo","--sandbox","danger-full-access"]},gemini:{cmd:"gemini",args:["-y","--skip-trust"]},copilot:{cmd:"copilot",args:["--yolo"]},qwen:{cmd:"qwen",args:["--approval-mode","yolo"]},opencode:{cmd:"opencode",args:[]}}});function GE(t,e){t.post("/mailbox/terminal/launch",r=>N1(r,e)),t.post("/mailbox/terminal/end/:session_id",r=>A1(r,e)),t.get("/mailbox/terminal/sessions",r=>x1(r,e))}async function N1(t,e){let r=e.terminalSessionManager;if(r===void 0)return t.json({error:"terminal_unavailable",message:"terminal session manager not configured (mailbox runtime missing)"},503);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.session_id;if(typeof s!="string"||!XE.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let o=n.provider;if(typeof o!="string"||o==="")return t.json({error:"bad_request",message:"provider is required"},400);let i;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(i=JE(n.command_line),i===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=HE(o);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no TERMINAL_LAUNCH_DEFAULTS entry for provider "${o}"`},400);i={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=r.startSession({session_id:s,command:i.cmd,args:i.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,pid:a,command:i.cmd,args:i.args},201)}catch(a){let l=a instanceof Error?a.message:String(a);return l.startsWith("terminal_session_already_exists")?t.json({error:"session_exists",message:l},409):t.json({error:"spawn_failed",message:l},500)}}function A1(t,e){let r=e.terminalSessionManager;if(r===void 0)return t.json({error:"terminal_unavailable",message:"terminal session manager not configured"},503);let n=t.req.param("session_id");return n===void 0||!XE.test(n)?t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400):(r.endSession(n),t.json({session_id:n,ended:!0}))}function x1(t,e){let r=e.terminalSessionManager;return r===void 0?t.json({sessions:[],note:"terminal session manager not configured"}):t.json({sessions:r.listSessions()})}var XE,KE=T(()=>{"use strict";Fd();XE=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});import{Buffer as R1}from"node:buffer";function O1(t){try{return R1.byteLength(JSON.stringify(t),"utf8")}catch{return 256}}function VE(t,e,r){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(e!==void 0&&e!==""){let n=Number(e);if(Number.isFinite(n)&&n>0)return n}return r}function YE(t){return j1[t]}function zE(t){let e=t.trim();if(e==="")return;let r=[],n=0;for(;n<e.length;){let o=e[n];if(o===" "||o===" "){n+=1;continue}if(o==='"'){let a=n+1,l="";for(;a<e.length&&e[a]!=='"';)l+=e[a],a+=1;r.push(l),n=a+1;continue}let i=n;for(;i<e.length&&e[i]!==" "&&e[i]!==" ";)i+=1;r.push(e.slice(n,i)),n=i}if(r.length===0)return;let s=r.shift();if(!(s===void 0||s===""))return{cmd:s,args:r}}var L1,$1,Da,j1,Ud=T(()=>{"use strict";L1=2e3,$1=64*1024,Da=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=VE(e.pushWindowMs,process.env.LMCTL_PROVIDER_PUSH_WINDOW_MS,L1),this.pushByteCap=VE(e.pushByteCap,process.env.LMCTL_PROVIDER_PUSH_BYTE_CAP,$1),this.timers=e.timers??{setTimeout:(r,n)=>globalThis.setTimeout(r,n),clearTimeout:r=>globalThis.clearTimeout(r)}}async startSession(e){if(this.sessions.has(e.session_id))throw new Error(`persistent_session_already_exists: ${e.session_id}`);let r=this.opts.adapterFactory(e.provider),n={session_id:e.session_id,provider:e.provider,adapter:r,child:void 0,pendingEvents:[],pendingBytes:0,pushTimer:void 0,generation:1,turnMap:new Map,closed:!1};this.sessions.set(e.session_id,n);let s=this.makeAdapterContext(n);try{let o=await r.start(e,s);return n.child=o,this.wireChildExit(n,o),this.opts.log?.(`[dt-3] persistent session ${e.session_id} started provider=${e.provider} pid=${o.pid??"?"}`),{pid:o.pid}}catch(o){throw this.sessions.delete(e.session_id),o}}async endSession(e){let r=this.sessions.get(e);if(r!==void 0){r.generation+=1;try{await r.adapter.stop()}catch{}if(r.child!==void 0)try{r.child.kill("SIGTERM")}catch{}await this.flush(r,"session_end"),r.closed=!0,this.sessions.delete(e)}}async onInbound(e){if(e.direction!=="user_to_agent")return;let r=this.sessions.get(e.session_id);if(r===void 0){this.opts.log?.(`[dt-3] inbound provider data for unknown session ${e.session_id}; dropping`);return}if(r.closed){this.opts.log?.(`[dt-3] inbound provider data for closed session ${e.session_id}; dropping`);return}let n=e.user_input??"";if(n!=="")try{await r.adapter.sendTurn(n)}catch(s){let o=s instanceof Error?s.message:String(s);this.opts.log?.(`[dt-3] adapter.sendTurn failed session=${e.session_id}: ${o}`),this.appendEvent(r,{event_type:"error",payload:{message:`sendTurn failed: ${o}`}})}}setPublish(e){this.opts={...this.opts,publish:e}}listSessions(){return Array.from(this.sessions.values()).map(e=>({session_id:e.session_id,provider:e.provider,pid:e.child?.pid}))}pendingEventCountFor(e){return this.sessions.get(e)?.pendingEvents.length}generationFor(e){return this.sessions.get(e)?.generation}_testBumpGeneration(e){let r=this.sessions.get(e);r!==void 0&&(r.generation+=1)}async stop(){for(let e of Array.from(this.sessions.values())){e.generation+=1;try{await e.adapter.stop()}catch{}if(e.child!==void 0)try{e.child.kill("SIGTERM")}catch{}}for(let e of Array.from(this.sessions.values()))e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0)}makeAdapterContext(e){let r=e.generation,n=this;return{generation:r,currentGeneration(){return e.generation},emit(s){r===e.generation&&(e.closed||n.appendEvent(e,s))},...n.opts.log!==void 0?{log:n.opts.log}:{},turnMap:e.turnMap}}appendEvent(e,r){e.pendingEvents.push(r);let n=O1(r);if(e.pendingBytes+=n,e.pendingBytes>=this.pushByteCap){this.flush(e,"byte_cap");return}e.pushTimer===void 0&&(e.pushTimer=this.timers.setTimeout(()=>{this.flush(e,"window_idle")},this.pushWindowMs))}async flush(e,r){if(e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0),e.pendingEvents.length===0)return;let n=e.pendingEvents;e.pendingEvents=[],e.pendingBytes=0;let s={kind:"provider",session_id:e.session_id,direction:"agent_to_user",events:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s),this.opts.log?.(`[dt-3] flushed session=${e.session_id} reason=${r} events=${n.length}`)}catch(o){this.opts.log?.(`[dt-3] publish failed session=${e.session_id} reason=${r}: ${o instanceof Error?o.message:String(o)}`)}}wireChildExit(e,r){let n=e.generation;r.on("exit",(s,o)=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child exited code=${s??"?"} signal=${o??""}; session ended. Click Reset to start a new chat.`}}),this.flush(e,"child_exit"),e.closed=!0))}),r.on("error",s=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child error: ${s.message}`}}),this.flush(e,"child_exit")))})}};j1={codex:{cmd:"codex",args:["app-server","--listen","stdio://"]},claude:{cmd:"claude",args:["-p","","--output-format","stream-json","--input-format","stream-json","--verbose","--dangerously-skip-permissions"]},gemini:{cmd:"gemini",args:["--acp","-y","--skip-trust"]},copilot:{cmd:"copilot",args:["--acp","--yolo"]},opencode:{cmd:"opencode",args:["acp"]},qwen:{cmd:"qwen",args:["-p","","--output-format","stream-json","--input-format","stream-json","--approval-mode","yolo"]}}});function QE(t,e){t.post("/mailbox/chat/launch",r=>C1(r,e)),t.post("/mailbox/chat/end/:session_id",r=>M1(r,e)),t.get("/mailbox/chat/sessions",r=>D1(r,e))}async function C1(t,e){let r=e.persistentSessionManager;if(r===void 0)return t.json({error:"chat_unavailable",message:"persistent session manager not configured (mailbox runtime missing)"},503);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.session_id;if(typeof s!="string"||!ZE.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let o=n.provider;if(typeof o!="string"||o==="")return t.json({error:"bad_request",message:"provider is required"},400);let i;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(i=zE(n.command_line),i===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=YE(o);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no PERSISTENT_LAUNCH_DEFAULTS entry for provider "${o}"`},400);i={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=await r.startSession({session_id:s,provider:o,command:i.cmd,args:i.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,provider:o,pid:a,command:i.cmd,args:i.args},201)}catch(a){let l=a instanceof Error?a.message:String(a);return l.startsWith("persistent_session_already_exists")?t.json({error:"session_exists",message:l},409):l.startsWith("no_persistent_adapter_for_provider")?t.json({error:"no_adapter",message:l},400):t.json({error:"spawn_failed",message:l},500)}}async function M1(t,e){let r=e.persistentSessionManager;if(r===void 0)return t.json({error:"chat_unavailable",message:"persistent session manager not configured"},503);let n=t.req.param("session_id");return n===void 0||!ZE.test(n)?t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400):(await r.endSession(n),t.json({session_id:n,ended:!0}))}function D1(t,e){let r=e.persistentSessionManager;return r===void 0?t.json({sessions:[],note:"persistent session manager not configured"}):t.json({sessions:r.listSessions()})}var ZE,eT=T(()=>{"use strict";Ud();ZE=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});import{readFileSync as P1}from"node:fs";function rT(t){let e=t.artifacts.find(r=>r.kind===`${t.state_name}_transcript`);if(e?.content!==void 0&&e.content!==null)return tT(e.content);if(e?.path===void 0||e.path===null)return[];try{let r=P1(e.path,{encoding:"utf8"});return tT(r)}catch{return[]}}function tT(t){let e=t.split(/\r?\n/).filter(r=>r.trim().length>0);return e.length===0?[]:e.map(r=>{let n=/^(user|assistant|system|tool)\s*:\s*(.*)$/i.exec(r);return n===null?{role:"transcript",text:r}:{role:n[1].toLowerCase(),text:n[2]}})}var nT=T(()=>{"use strict"});function sT(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 i=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(i.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(i.length>1){let l=i.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=i[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 Pa(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2069
|
+
`,s={kind:"terminal",session_id:e.session_id,direction:"agent_to_user",data:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s)}catch(o){this.opts.log?.(`[dt-2] publish (exit) failed session=${e.session_id}: ${o instanceof Error?o.message:String(o)}`)}e.closed=!0,this.sessions.delete(e.session_id)}};IF={claude:{cmd:"claude",args:["--dangerously-skip-permissions"]},codex:{cmd:"codex",args:["--yolo","--sandbox","danger-full-access"]},gemini:{cmd:"gemini",args:["-y","--skip-trust"]},copilot:{cmd:"copilot",args:["--yolo"]},qwen:{cmd:"qwen",args:["--approval-mode","yolo"]},opencode:{cmd:"opencode",args:[]}}});function GE(t,e){t.post("/mailbox/terminal/launch",r=>NF(r,e)),t.post("/mailbox/terminal/end/:session_id",r=>AF(r,e)),t.get("/mailbox/terminal/sessions",r=>xF(r,e))}async function NF(t,e){let r=e.terminalSessionManager;if(r===void 0)return t.json({error:"terminal_unavailable",message:"terminal session manager not configured (mailbox runtime missing)"},503);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.session_id;if(typeof s!="string"||!XE.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let o=n.provider;if(typeof o!="string"||o==="")return t.json({error:"bad_request",message:"provider is required"},400);let i;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(i=JE(n.command_line),i===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=HE(o);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no TERMINAL_LAUNCH_DEFAULTS entry for provider "${o}"`},400);i={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=r.startSession({session_id:s,command:i.cmd,args:i.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,pid:a,command:i.cmd,args:i.args},201)}catch(a){let l=a instanceof Error?a.message:String(a);return l.startsWith("terminal_session_already_exists")?t.json({error:"session_exists",message:l},409):t.json({error:"spawn_failed",message:l},500)}}function AF(t,e){let r=e.terminalSessionManager;if(r===void 0)return t.json({error:"terminal_unavailable",message:"terminal session manager not configured"},503);let n=t.req.param("session_id");return n===void 0||!XE.test(n)?t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400):(r.endSession(n),t.json({session_id:n,ended:!0}))}function xF(t,e){let r=e.terminalSessionManager;return r===void 0?t.json({sessions:[],note:"terminal session manager not configured"}):t.json({sessions:r.listSessions()})}var XE,KE=T(()=>{"use strict";Fd();XE=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});import{Buffer as RF}from"node:buffer";function OF(t){try{return RF.byteLength(JSON.stringify(t),"utf8")}catch{return 256}}function VE(t,e,r){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(e!==void 0&&e!==""){let n=Number(e);if(Number.isFinite(n)&&n>0)return n}return r}function YE(t){return jF[t]}function zE(t){let e=t.trim();if(e==="")return;let r=[],n=0;for(;n<e.length;){let o=e[n];if(o===" "||o===" "){n+=1;continue}if(o==='"'){let a=n+1,l="";for(;a<e.length&&e[a]!=='"';)l+=e[a],a+=1;r.push(l),n=a+1;continue}let i=n;for(;i<e.length&&e[i]!==" "&&e[i]!==" ";)i+=1;r.push(e.slice(n,i)),n=i}if(r.length===0)return;let s=r.shift();if(!(s===void 0||s===""))return{cmd:s,args:r}}var LF,$F,Da,jF,Ud=T(()=>{"use strict";LF=2e3,$F=64*1024,Da=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=VE(e.pushWindowMs,process.env.LMCTL_PROVIDER_PUSH_WINDOW_MS,LF),this.pushByteCap=VE(e.pushByteCap,process.env.LMCTL_PROVIDER_PUSH_BYTE_CAP,$F),this.timers=e.timers??{setTimeout:(r,n)=>globalThis.setTimeout(r,n),clearTimeout:r=>globalThis.clearTimeout(r)}}async startSession(e){if(this.sessions.has(e.session_id))throw new Error(`persistent_session_already_exists: ${e.session_id}`);let r=this.opts.adapterFactory(e.provider),n={session_id:e.session_id,provider:e.provider,adapter:r,child:void 0,pendingEvents:[],pendingBytes:0,pushTimer:void 0,generation:1,turnMap:new Map,closed:!1};this.sessions.set(e.session_id,n);let s=this.makeAdapterContext(n);try{let o=await r.start(e,s);return n.child=o,this.wireChildExit(n,o),this.opts.log?.(`[dt-3] persistent session ${e.session_id} started provider=${e.provider} pid=${o.pid??"?"}`),{pid:o.pid}}catch(o){throw this.sessions.delete(e.session_id),o}}async endSession(e){let r=this.sessions.get(e);if(r!==void 0){r.generation+=1;try{await r.adapter.stop()}catch{}if(r.child!==void 0)try{r.child.kill("SIGTERM")}catch{}await this.flush(r,"session_end"),r.closed=!0,this.sessions.delete(e)}}async onInbound(e){if(e.direction!=="user_to_agent")return;let r=this.sessions.get(e.session_id);if(r===void 0){this.opts.log?.(`[dt-3] inbound provider data for unknown session ${e.session_id}; dropping`);return}if(r.closed){this.opts.log?.(`[dt-3] inbound provider data for closed session ${e.session_id}; dropping`);return}let n=e.user_input??"";if(n!=="")try{await r.adapter.sendTurn(n)}catch(s){let o=s instanceof Error?s.message:String(s);this.opts.log?.(`[dt-3] adapter.sendTurn failed session=${e.session_id}: ${o}`),this.appendEvent(r,{event_type:"error",payload:{message:`sendTurn failed: ${o}`}})}}setPublish(e){this.opts={...this.opts,publish:e}}listSessions(){return Array.from(this.sessions.values()).map(e=>({session_id:e.session_id,provider:e.provider,pid:e.child?.pid}))}pendingEventCountFor(e){return this.sessions.get(e)?.pendingEvents.length}generationFor(e){return this.sessions.get(e)?.generation}_testBumpGeneration(e){let r=this.sessions.get(e);r!==void 0&&(r.generation+=1)}async stop(){for(let e of Array.from(this.sessions.values())){e.generation+=1;try{await e.adapter.stop()}catch{}if(e.child!==void 0)try{e.child.kill("SIGTERM")}catch{}}for(let e of Array.from(this.sessions.values()))e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0)}makeAdapterContext(e){let r=e.generation,n=this;return{generation:r,currentGeneration(){return e.generation},emit(s){r===e.generation&&(e.closed||n.appendEvent(e,s))},...n.opts.log!==void 0?{log:n.opts.log}:{},turnMap:e.turnMap}}appendEvent(e,r){e.pendingEvents.push(r);let n=OF(r);if(e.pendingBytes+=n,e.pendingBytes>=this.pushByteCap){this.flush(e,"byte_cap");return}e.pushTimer===void 0&&(e.pushTimer=this.timers.setTimeout(()=>{this.flush(e,"window_idle")},this.pushWindowMs))}async flush(e,r){if(e.pushTimer!==void 0&&(this.timers.clearTimeout(e.pushTimer),e.pushTimer=void 0),e.pendingEvents.length===0)return;let n=e.pendingEvents;e.pendingEvents=[],e.pendingBytes=0;let s={kind:"provider",session_id:e.session_id,direction:"agent_to_user",events:n,ts:(this.opts.now??Date.now)()};try{await this.opts.publish(s),this.opts.log?.(`[dt-3] flushed session=${e.session_id} reason=${r} events=${n.length}`)}catch(o){this.opts.log?.(`[dt-3] publish failed session=${e.session_id} reason=${r}: ${o instanceof Error?o.message:String(o)}`)}}wireChildExit(e,r){let n=e.generation;r.on("exit",(s,o)=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child exited code=${s??"?"} signal=${o??""}; session ended. Click Reset to start a new chat.`}}),this.flush(e,"child_exit"),e.closed=!0))}),r.on("error",s=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child error: ${s.message}`}}),this.flush(e,"child_exit")))})}};jF={codex:{cmd:"codex",args:["app-server","--listen","stdio://"]},claude:{cmd:"claude",args:["-p","","--output-format","stream-json","--input-format","stream-json","--verbose","--dangerously-skip-permissions"]},gemini:{cmd:"gemini",args:["--acp","-y","--skip-trust"]},copilot:{cmd:"copilot",args:["--acp","--yolo"]},opencode:{cmd:"opencode",args:["acp"]},qwen:{cmd:"qwen",args:["-p","","--output-format","stream-json","--input-format","stream-json","--approval-mode","yolo"]}}});function QE(t,e){t.post("/mailbox/chat/launch",r=>CF(r,e)),t.post("/mailbox/chat/end/:session_id",r=>MF(r,e)),t.get("/mailbox/chat/sessions",r=>DF(r,e))}async function CF(t,e){let r=e.persistentSessionManager;if(r===void 0)return t.json({error:"chat_unavailable",message:"persistent session manager not configured (mailbox runtime missing)"},503);let n;try{n=await t.req.json()}catch{return t.json({error:"bad_request",message:"invalid JSON body"},400)}let s=n.session_id;if(typeof s!="string"||!ZE.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let o=n.provider;if(typeof o!="string"||o==="")return t.json({error:"bad_request",message:"provider is required"},400);let i;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(i=zE(n.command_line),i===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=YE(o);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no PERSISTENT_LAUNCH_DEFAULTS entry for provider "${o}"`},400);i={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=await r.startSession({session_id:s,provider:o,command:i.cmd,args:i.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,provider:o,pid:a,command:i.cmd,args:i.args},201)}catch(a){let l=a instanceof Error?a.message:String(a);return l.startsWith("persistent_session_already_exists")?t.json({error:"session_exists",message:l},409):l.startsWith("no_persistent_adapter_for_provider")?t.json({error:"no_adapter",message:l},400):t.json({error:"spawn_failed",message:l},500)}}async function MF(t,e){let r=e.persistentSessionManager;if(r===void 0)return t.json({error:"chat_unavailable",message:"persistent session manager not configured"},503);let n=t.req.param("session_id");return n===void 0||!ZE.test(n)?t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400):(await r.endSession(n),t.json({session_id:n,ended:!0}))}function DF(t,e){let r=e.persistentSessionManager;return r===void 0?t.json({sessions:[],note:"persistent session manager not configured"}):t.json({sessions:r.listSessions()})}var ZE,eT=T(()=>{"use strict";Ud();ZE=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i});import{readFileSync as PF}from"node:fs";function rT(t){let e=t.artifacts.find(r=>r.kind===`${t.state_name}_transcript`);if(e?.content!==void 0&&e.content!==null)return tT(e.content);if(e?.path===void 0||e.path===null)return[];try{let r=PF(e.path,{encoding:"utf8"});return tT(r)}catch{return[]}}function tT(t){let e=t.split(/\r?\n/).filter(r=>r.trim().length>0);return e.length===0?[]:e.map(r=>{let n=/^(user|assistant|system|tool)\s*:\s*(.*)$/i.exec(r);return n===null?{role:"transcript",text:r}:{role:n[1].toLowerCase(),text:n[2]}})}var nT=T(()=>{"use strict"});function sT(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 i=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(i.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(i.length>1){let l=i.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=i[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 Pa(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2064
2070
|
WHERE run_id = ?
|
|
2065
2071
|
AND acknowledged_at IS NULL
|
|
2066
2072
|
AND requires_user = 1
|
|
2067
|
-
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var Fa=T(()=>{"use strict"});function pT(t,e){t.all("/runtime/*",r=>F1(r.req.raw,e))}async function F1(t,e){try{return Response.json(await U1(t,e))}catch(r){if(r instanceof ie)return Response.json({error:r.message},{status:r.status});let n=r instanceof Error?r.message:String(r);return Response.json({error:n},{status:500})}}async function U1(t,e){let r=new URL(t.url),n=G1(e),s=r.pathname.split("/").filter(Boolean).map(decodeURIComponent);if(t.method==="GET"&&r.pathname==="/runtime/workspaces")return Wd(t),[{id:n.id,name:n.name}];if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="workspaces")return Ua(t,n.id,s[2]),W1(e.dal,n);if(t.method==="GET"&&s.length===5&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"){Ua(t,n.id,s[2]);let o=iT(e.dal,s[4]);return oT(e.dal,n,o)}if(t.method==="GET"&&r.pathname==="/runtime/lead-teams")return Wd(t),e.dal.listTeams().map(o=>X1(o));if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="chat"){let o=aT(e.dal,lT(s[2])),i=await t.json();if(i.teamId!==`team:${o.name}`)throw new ie(400,"runtime lead chat body does not match route team");return uT(t,n.id,i.context),cT(o,i.context)}if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="messages"){let o=aT(e.dal,lT(s[2])),i=await t.json();if(i.teamId!==`team:${o.name}`)throw new ie(400,"runtime lead message body does not match route team");uT(t,n.id,i.context);let a=i.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime lead message requires draft.body");return cT(o,i.context,a)}if(t.method==="POST"&&s.length===6&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"&&s[5]==="workflow-message"){Ua(t,n.id,s[2]);let o=iT(e.dal,s[4]),i=await t.json();if(i.workspaceId!==n.id||i.projectId!==o.name)throw new ie(400,"runtime request body does not match route workspace/project");let a=i.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime workflow message requires draft.body");return H1(e.dal,o,a),oT(e.dal,n,o)}if(t.method==="GET"&&r.pathname==="/runtime/templates")return Vs(t,n.id),e.dal.listWorkflows().map(o=>K1(o));if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="templates"){Vs(t,n.id);let o=Y1(e.dal,s[2]);return V1(o)}if(t.method==="GET"&&r.pathname==="/runtime/runs"){Vs(t,n.id);let o=r.searchParams.get("project"),i=r.searchParams.get("template");if(o!==null&&i!==null)throw new ie(400,"conflicting_filters: ?project= and ?template= are mutually exclusive");return z1(e.dal,o,i).map(l=>fT(e.dal,l))}if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="runs"){Vs(t,n.id);let o=dT(e.dal,s[2]);return fT(e.dal,o)}if(t.method==="GET"&&s.length===4&&s[0]==="runtime"&&s[1]==="runs"&&s[3]==="events"){Vs(t,n.id);let o=dT(e.dal,s[2]),i=Q1(e.dal,o);return{runId:Xd(o),events:i,...i.length>0?{cursor:i[i.length-1].id}:{}}}throw new ie(404,`unknown runtime request: ${t.method} ${r.pathname}`)}function W1(t,e){return{id:e.id,name:e.name,projects:t.listProjects().map(r=>_T(t,e,r))}}function oT(t,e,r){let n=_T(t,e,r);return{...n,managedWorkflow:{...n.managedWorkflow,instance:B1(t,r),composerTarget:{kind:"workflow-initial",label:`Project Workflow: ${r.workflow_name}`,templateId:`template:${r.workflow_name}`,runId:n.managedWorkflow.runId}},workflowMessages:q1(t,r)}}function _T(t,e,r){let n=hT(t,r.id),s=qd(n);return{id:r.name,workspaceId:e.id,name:r.name,...r.description===null?{}:{description:r.description},status:s,managedWorkflow:{templateId:`template:${r.workflow_name}`,templateName:r.workflow_name,runId:n===null?`project:${r.id}:no-run`:`run:${n.id}`,status:s}}}function B1(t,e){let r=hT(t,e.id),n=r?.current_state??null;return{id:r===null?`project:${e.id}:no-run`:`run:${r.id}`,templateId:`template:${e.workflow_name}`,label:e.workflow_name,status:qd(r),currentStepIds:n===null?[]:[n],...r?.started_at===void 0?{}:{createdAt:r.started_at},...r?.ended_at===null||r?.ended_at===void 0?{}:{updatedAt:r.ended_at}}}function q1(t,e){return t.query("SELECT * FROM attention WHERE project_id = ? ORDER BY id ASC LIMIT 50",e.id).map(n=>({id:`attention:${n.id}`,role:"event",author:"lmctl",timestamp:n.created_at,body:n.kind}))}function H1(t,e,r){let n=J1(t,e.id);if(n!==null){let s=Pa(t,n.id);if(s?.kind==="workflow_escalation"){let o=t.resumeEscalation(s.attention_id,r);if(!o.resumed)throw new ie(409,`workflow escalation resume failed: ${o.reason}`);return}if(s?.kind==="interactive_waiting_operator"){let o=Rt(t,s.attention_id);if(o?.step_id===null||o?.step_id===void 0)throw new ie(409,"interactive resume failed: missing step");let i=t.resumeInteractive(o.step_id,r,!0);if(!i.resumed)throw new ie(409,`interactive resume failed: ${i.reason}`);return}}t.enqueueJob({project_id:e.id,source:"runtime-workflow-message",payload:JSON.stringify({prompt:r}),priority:0})}function hT(t,e){return t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? ORDER BY r.id DESC LIMIT 1",e)[0]??null}function J1(t,e){return t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? AND r.terminal_state IS NULL ORDER BY r.id DESC LIMIT 1",e)[0]??null}function qd(t){return t===null?"queued":t.terminal_state===null?"running":t.terminal_state==="done"||t.terminal_state==="success"?"succeeded":t.terminal_state==="cancelled"||t.terminal_state==="aborted"?"cancelled":"failed"}function iT(t,e){let r=t.findProjectByName(e);if(r===null)throw new ie(404,`project not found: ${e}`);return r}function aT(t,e){let r=t.listTeams().find(n=>n.name===e);if(r===void 0)throw new ie(404,`team not found: ${e}`);return r}function lT(t){return t.startsWith("team:")?t.slice(5):t}function X1(t){return{id:`team:${t.name}`,name:t.name,teamfile:"",hasLead:!0,kind:t.name.toLowerCase().includes("manager")?"global-manager":"custom-ai-led"}}function cT(t,e,r){let n=new Date().toISOString(),s=r===void 0?[]:[{id:`lead:${t.id}:user:${Date.now()}`,role:"user",author:"operator",timestamp:n,body:r},{id:`lead:${t.id}:event:${Date.now()}`,role:"event",author:"lmctl",timestamp:n,body:"Lead-team mailbox request accepted by the runtime dispatcher."}];return{id:`lead-chat:${t.name}:${e?.scope??"global-admin"}:${e?.workspaceId??mT}`,teamId:`team:${t.name}`,title:`${t.name} Lead`,messages:s,...e===void 0?{}:{context:e}}}function G1(t){let e=t.workspaceName??Kn()??Ir.default;return{id:e,name:e}}function Wd(t){if(t.headers.get("x-lmctl-workspace-id")!==mT)throw new ie(400,"runtime request requires global-admin workspace identity")}function Ua(t,e,r){let n=t.headers.get("x-lmctl-workspace-id");if(n===null)throw new ie(400,"runtime request requires workspace identity");if(r!==e||n!==e)throw new ie(400,"runtime workspace identity does not match route")}function Vs(t,e){let r=t.headers.get("x-lmctl-workspace-id");if(r===null)throw new ie(400,"runtime request requires workspace identity");if(r!==e)throw new ie(400,"runtime workspace identity does not match server workspace")}function uT(t,e,r){if(r?.scope==="workspace"){if(r.workspaceId===void 0)throw new ie(400,"workspace manager context requires workspace identity");Ua(t,e,r.workspaceId);return}Wd(t)}function Hd(t){return`${Fn}${Jd(t.name)}`}function Jd(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"item"}function Xd(t){return`${Bd}${t.id}`}function K1(t){let e=Wa(t.definition);return{id:Hd(t),name:t.name,...e.description===null?{}:{description:e.description}}}function V1(t){let e=Wa(t.definition);return{id:Hd(t),name:t.name,...e.description===null?{}:{description:e.description},graph:e.graph}}function Wa(t){let e;try{e=JSON.parse(t)}catch{return{description:null,graph:null,stepIds:[],nameToId:new Map}}if(e===null||typeof e!="object")return{description:null,graph:e,stepIds:[],nameToId:new Map};let r=e,n=typeof r.description=="string"?r.description:null,s=[],o=new Map;if(r.schema_version==="lmctl/v3"&&Array.isArray(r.steps)){let i=typeof r.entry_step_id=="string"?r.entry_step_id:null;for(let a of r.steps){let l=typeof a.id=="string"?a.id:null;l!==null&&(s.push(l),typeof a.name=="string"&&a.name.length>0&&o.set(a.name,l))}i!==null&&s.includes(i)&&s.sort((a,l)=>a===i?-1:l===i?1:0)}return{description:n,graph:e,stepIds:s,nameToId:o}}function Y1(t,e){if(!e.startsWith(Fn))throw new ie(404,`template not found: ${e}`);let r=e.slice(Fn.length),n=t.listWorkflows().filter(s=>Jd(s.name)===r);if(n.length===0)throw new ie(404,`template not found: ${e}`);if(n.length>1){let s=n.map(o=>o.name).join(", ");throw new ie(409,`template_id_ambiguous: ${e} matches multiple workflow names [${s}]; rename to ensure unique slugs`)}return n[0]}function dT(t,e){if(!e.startsWith(Bd))throw new ie(404,`run not found: ${e}`);let r=e.slice(Bd.length);if(!/^[1-9]\d*$/.test(r))throw new ie(404,`run not found: ${e}`);let n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0||String(n)!==r)throw new ie(404,`run not found: ${e}`);let s=t.getRun(n);if(s===null)throw new ie(404,`run not found: ${e}`);return s}function z1(t,e,r){if(r!==null){if(!r.startsWith(Fn))return[];let s=r.slice(Fn.length),o=t.listWorkflows().filter(a=>Jd(a.name)===s).map(a=>a.id);if(o.length===0)return[];let i=o.map(()=>"?").join(", ");return t.query(`SELECT * FROM run WHERE workflow_id IN (${i}) ORDER BY id DESC LIMIT 200`,...o)}if(e===null)return t.query("SELECT * FROM run ORDER BY id DESC LIMIT 200");let n=t.findProjectByName(e);return n===null?[]:t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? ORDER BY r.id DESC LIMIT 200",n.id)}function fT(t,e){let r=t.getWorkflow(e.workflow_id),n=qd(e),s=Z1(r,e);return{id:Xd(e),templateId:r===null?`${Fn}unknown`:Hd(r),label:r===null?`run ${e.id}`:`${r.name} #${e.id}`,status:n,createdAt:e.started_at,...e.ended_at===null?{}:{updatedAt:e.ended_at},currentStepIds:s}}function Z1(t,e){if(e.current_state===null)return[];let r=e.current_state.startsWith("__paused__:")?e.current_state.slice(11):e.current_state;return t===null?[r]:[Wa(t.definition).nameToId.get(r)??r]}function Q1(t,e){let r=t.getWorkflow(e.workflow_id),n=r===null?{stepIds:[],nameToId:new Map}:Wa(r.definition),s=c=>n.nameToId.get(c)??c,o=Xd(e),i=[];i.push({timestamp:e.started_at,type:"run.started",message:"Run started"});let a=t.listStepsForRun(e.id);for(let c of a){let u=s(c.state_name);if(i.push({timestamp:c.started_at,type:"step.started",stepId:u,message:`step ${c.state_name} started`}),c.ended_at!==null){let d=eF(c);i.push({timestamp:c.ended_at,type:d,stepId:u,...c.outcome===null?{}:{message:c.outcome},...c.status_detail===null?{}:{payload:{status_detail:c.status_detail}}})}else e.paused_at!==null&&c.id===a[a.length-1]?.id&&i.push({timestamp:e.paused_at,type:"step.paused",stepId:u})}let l=t.listSessionEvents(e.id);for(let c of l){let u=c.step_id===null?void 0:(()=>{let m=a.find(p=>p.id===c.step_id);return m===void 0?void 0:s(m.state_name)})(),d=new Date(c.timestamp_ms).toISOString(),f={kind:c.kind,session_event_id:c.id};if(c.payload.length>0)try{let m=JSON.parse(c.payload);m!==null&&typeof m=="object"&&!Array.isArray(m)&&(f={...f,...m})}catch{}i.push({timestamp:d,type:"message",...u===void 0?{}:{stepId:u},payload:f})}if(e.terminal_state!==null){let c=e.terminal_state==="done"||e.terminal_state==="success"?"run.completed":e.terminal_state==="cancelled"||e.terminal_state==="aborted"?"run.cancelled":"run.failed";i.push({timestamp:e.ended_at??e.started_at,type:c,message:e.terminal_state})}return i.sort((c,u)=>c.timestamp.localeCompare(u.timestamp)),i.map((c,u)=>({id:`${o}:evt:${u+1}`,runId:o,sequence:u+1,timestamp:c.timestamp,type:c.type,...c.stepId===void 0?{}:{stepId:c.stepId},...c.message===void 0?{}:{message:c.message},...c.payload===void 0?{}:{payload:c.payload}}))}function eF(t){if(t.outcome===null)return"step.failed";let e=t.status_detail;return e==="failed"||e==="error"||e==="aborted"?"step.failed":"step.completed"}var mT,Fn,Bd,ie,gT=T(()=>{"use strict";Ve();Fa();Jt();mT="global-admin";Fn="template:",Bd="run:";ie=class extends Error{status;constructor(e,r){super(r),this.status=e}}});import{mkdirSync as tF,writeFileSync as rF}from"node:fs";import{randomUUID as yT}from"node:crypto";import{dirname as nF,resolve as Ba,sep as wT}from"node:path";async function TT(t,e){let r;try{r=await t.req.parseBody({all:!1})}catch{return t.text("invalid multipart body",400)}let n=r.image;if(!lF(n))return t.text("missing image file",400);if(n.size>sF)return t.text("upload too large",413);let s=Buffer.from(await n.arrayBuffer()),o=cF(s);if(o===null||!(o in ET))return t.text("unsupported upload MIME type",415);if(n.type.length>0&&n.type!==o)return t.text("upload MIME type does not match file content",415);let i=oF(e,r.project);if(typeof i=="string")return t.text(i,404);let a=i===null?Ba(aF()):Ba(i.local_path),l=Ba(a,"uploads",yT()),c=Ba(l,`${yT()}${ET[o]}`);if(!iF(c,a))return t.text("invalid upload path",400);tF(l,{recursive:!0});let u=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);rF(c,u);let d={path:c,size:s.byteLength,mime:o,project:i?.name??null};return t.json(d)}function oF(t,e){return e==null||e===""?null:typeof e!="string"?"invalid project":t.findProjectByName(e)??`project not found: ${e}`}function iF(t,e){let r=e.endsWith(wT)?e:`${e}${wT}`;return t.startsWith(r)}function aF(){return nF(le())}function lF(t){return typeof File<"u"&&t instanceof File}function cF(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP"?"image/webp":t.length>=12&&t.subarray(4,8).toString("ascii")==="ftyp"&&["heic","heix","hevc","hevx","mif1","msf1"].includes(t.subarray(8,12).toString("ascii"))?"image/heic":t.length>=5&&t.subarray(0,5).toString("ascii")==="%PDF-"?"application/pdf":null}var sF,ET,bT=T(()=>{"use strict";Ve();sF=10*1024*1024,ET={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}});import{existsSync as qa}from"node:fs";import{basename as uF,dirname as dF,extname as fF,isAbsolute as mF,join as pF,relative as _F}from"node:path";import{fileURLToPath as hF}from"node:url";import{Hono as gF}from"hono";import{serveStatic as Ot}from"@hono/node-server/serve-static";function xT(t){let e=new gF,r=[],n=t.localWebui!==void 0?Kd(t.localWebui.webuiDir):yF();if(t.localWebui!==void 0&&jE(e,{s3:t.localWebui.localMailbox.s3,commands:t.localWebui.localMailbox.commands}),n!==null){let s=wF();t.localWebui!==void 0?e.get("/config.json",s,o=>o.json({workspaceFetchMode:"local-mailbox",localMailbox:{base:"/local-mailbox",userId:"local",deviceId:"local"},mailboxPolling:{readIntervalSeconds:1,heartbeatIdleSeconds:1,backoffReadIntervalSeconds:1}})):t.webuiRuntimeConfig!==void 0&&e.get("/config.json",s,o=>o.json(t.webuiRuntimeConfig)),e.use("/dist/*",s,Ot({root:n})),e.use("/vendor/*",s,Ot({root:n})),e.use("/src/*",s,Ot({root:n})),e.get("/",s,Ot({root:n,path:"index.html"})),e.get("/admin",s,Ot({root:n,path:"index.html"})),e.get("/admin/*",s,Ot({root:n,path:"index.html"})),e.get("/terminal",s,Ot({root:n,path:"index.html"})),e.get("/terminal/*",s,Ot({root:n,path:"index.html"})),e.get("/chat",s,Ot({root:n,path:"index.html"})),e.get("/chat/*",s,Ot({root:n,path:"index.html"}))}else e.get("/",s=>s.html('<!doctype html><meta charset="utf-8"><title>lmctl</title><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5"><h1>lmctl daemon</h1><p>This build does not bundle the local web console; the HTTP API is running on this port.</p><p>Open the hosted console at <a href="https://lmctl.ai/">https://lmctl.ai/</a> \u2014 it connects to this daemon via the cloud mailbox.</p></body>'));return e.use("*",wy()),e.get("/login",s=>s.html($e("Login",`
|
|
2073
|
+
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var Fa=T(()=>{"use strict"});function pT(t,e){t.all("/runtime/*",r=>FF(r.req.raw,e))}async function FF(t,e){try{return Response.json(await UF(t,e))}catch(r){if(r instanceof ie)return Response.json({error:r.message},{status:r.status});let n=r instanceof Error?r.message:String(r);return Response.json({error:n},{status:500})}}async function UF(t,e){let r=new URL(t.url),n=GF(e),s=r.pathname.split("/").filter(Boolean).map(decodeURIComponent);if(t.method==="GET"&&r.pathname==="/runtime/workspaces")return Wd(t),[{id:n.id,name:n.name}];if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="workspaces")return Ua(t,n.id,s[2]),WF(e.dal,n);if(t.method==="GET"&&s.length===5&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"){Ua(t,n.id,s[2]);let o=iT(e.dal,s[4]);return oT(e.dal,n,o)}if(t.method==="GET"&&r.pathname==="/runtime/lead-teams")return Wd(t),e.dal.listTeams().map(o=>XF(o));if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="chat"){let o=aT(e.dal,lT(s[2])),i=await t.json();if(i.teamId!==`team:${o.name}`)throw new ie(400,"runtime lead chat body does not match route team");return uT(t,n.id,i.context),cT(o,i.context)}if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="messages"){let o=aT(e.dal,lT(s[2])),i=await t.json();if(i.teamId!==`team:${o.name}`)throw new ie(400,"runtime lead message body does not match route team");uT(t,n.id,i.context);let a=i.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime lead message requires draft.body");return cT(o,i.context,a)}if(t.method==="POST"&&s.length===6&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"&&s[5]==="workflow-message"){Ua(t,n.id,s[2]);let o=iT(e.dal,s[4]),i=await t.json();if(i.workspaceId!==n.id||i.projectId!==o.name)throw new ie(400,"runtime request body does not match route workspace/project");let a=i.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime workflow message requires draft.body");return HF(e.dal,o,a),oT(e.dal,n,o)}if(t.method==="GET"&&r.pathname==="/runtime/templates")return Vs(t,n.id),e.dal.listWorkflows().map(o=>KF(o));if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="templates"){Vs(t,n.id);let o=YF(e.dal,s[2]);return VF(o)}if(t.method==="GET"&&r.pathname==="/runtime/runs"){Vs(t,n.id);let o=r.searchParams.get("project"),i=r.searchParams.get("template");if(o!==null&&i!==null)throw new ie(400,"conflicting_filters: ?project= and ?template= are mutually exclusive");return zF(e.dal,o,i).map(l=>fT(e.dal,l))}if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="runs"){Vs(t,n.id);let o=dT(e.dal,s[2]);return fT(e.dal,o)}if(t.method==="GET"&&s.length===4&&s[0]==="runtime"&&s[1]==="runs"&&s[3]==="events"){Vs(t,n.id);let o=dT(e.dal,s[2]),i=QF(e.dal,o);return{runId:Xd(o),events:i,...i.length>0?{cursor:i[i.length-1].id}:{}}}throw new ie(404,`unknown runtime request: ${t.method} ${r.pathname}`)}function WF(t,e){return{id:e.id,name:e.name,projects:t.listProjects().map(r=>_T(t,e,r))}}function oT(t,e,r){let n=_T(t,e,r);return{...n,managedWorkflow:{...n.managedWorkflow,instance:BF(t,r),composerTarget:{kind:"workflow-initial",label:`Project Workflow: ${r.workflow_name}`,templateId:`template:${r.workflow_name}`,runId:n.managedWorkflow.runId}},workflowMessages:qF(t,r)}}function _T(t,e,r){let n=hT(t,r.id),s=qd(n);return{id:r.name,workspaceId:e.id,name:r.name,...r.description===null?{}:{description:r.description},status:s,managedWorkflow:{templateId:`template:${r.workflow_name}`,templateName:r.workflow_name,runId:n===null?`project:${r.id}:no-run`:`run:${n.id}`,status:s}}}function BF(t,e){let r=hT(t,e.id),n=r?.current_state??null;return{id:r===null?`project:${e.id}:no-run`:`run:${r.id}`,templateId:`template:${e.workflow_name}`,label:e.workflow_name,status:qd(r),currentStepIds:n===null?[]:[n],...r?.started_at===void 0?{}:{createdAt:r.started_at},...r?.ended_at===null||r?.ended_at===void 0?{}:{updatedAt:r.ended_at}}}function qF(t,e){return t.query("SELECT * FROM attention WHERE project_id = ? ORDER BY id ASC LIMIT 50",e.id).map(n=>({id:`attention:${n.id}`,role:"event",author:"lmctl",timestamp:n.created_at,body:n.kind}))}function HF(t,e,r){let n=JF(t,e.id);if(n!==null){let s=Pa(t,n.id);if(s?.kind==="workflow_escalation"){let o=t.resumeEscalation(s.attention_id,r);if(!o.resumed)throw new ie(409,`workflow escalation resume failed: ${o.reason}`);return}if(s?.kind==="interactive_waiting_operator"){let o=Rt(t,s.attention_id);if(o?.step_id===null||o?.step_id===void 0)throw new ie(409,"interactive resume failed: missing step");let i=t.resumeInteractive(o.step_id,r,!0);if(!i.resumed)throw new ie(409,`interactive resume failed: ${i.reason}`);return}}t.enqueueJob({project_id:e.id,source:"runtime-workflow-message",payload:JSON.stringify({prompt:r}),priority:0})}function hT(t,e){return t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? ORDER BY r.id DESC LIMIT 1",e)[0]??null}function JF(t,e){return t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? AND r.terminal_state IS NULL ORDER BY r.id DESC LIMIT 1",e)[0]??null}function qd(t){return t===null?"queued":t.terminal_state===null?"running":t.terminal_state==="done"||t.terminal_state==="success"?"succeeded":t.terminal_state==="cancelled"||t.terminal_state==="aborted"?"cancelled":"failed"}function iT(t,e){let r=t.findProjectByName(e);if(r===null)throw new ie(404,`project not found: ${e}`);return r}function aT(t,e){let r=t.listTeams().find(n=>n.name===e);if(r===void 0)throw new ie(404,`team not found: ${e}`);return r}function lT(t){return t.startsWith("team:")?t.slice(5):t}function XF(t){return{id:`team:${t.name}`,name:t.name,teamfile:"",hasLead:!0,kind:t.name.toLowerCase().includes("manager")?"global-manager":"custom-ai-led"}}function cT(t,e,r){let n=new Date().toISOString(),s=r===void 0?[]:[{id:`lead:${t.id}:user:${Date.now()}`,role:"user",author:"operator",timestamp:n,body:r},{id:`lead:${t.id}:event:${Date.now()}`,role:"event",author:"lmctl",timestamp:n,body:"Lead-team mailbox request accepted by the runtime dispatcher."}];return{id:`lead-chat:${t.name}:${e?.scope??"global-admin"}:${e?.workspaceId??mT}`,teamId:`team:${t.name}`,title:`${t.name} Lead`,messages:s,...e===void 0?{}:{context:e}}}function GF(t){let e=t.workspaceName??Kn()??Ir.default;return{id:e,name:e}}function Wd(t){if(t.headers.get("x-lmctl-workspace-id")!==mT)throw new ie(400,"runtime request requires global-admin workspace identity")}function Ua(t,e,r){let n=t.headers.get("x-lmctl-workspace-id");if(n===null)throw new ie(400,"runtime request requires workspace identity");if(r!==e||n!==e)throw new ie(400,"runtime workspace identity does not match route")}function Vs(t,e){let r=t.headers.get("x-lmctl-workspace-id");if(r===null)throw new ie(400,"runtime request requires workspace identity");if(r!==e)throw new ie(400,"runtime workspace identity does not match server workspace")}function uT(t,e,r){if(r?.scope==="workspace"){if(r.workspaceId===void 0)throw new ie(400,"workspace manager context requires workspace identity");Ua(t,e,r.workspaceId);return}Wd(t)}function Hd(t){return`${Fn}${Jd(t.name)}`}function Jd(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"item"}function Xd(t){return`${Bd}${t.id}`}function KF(t){let e=Wa(t.definition);return{id:Hd(t),name:t.name,...e.description===null?{}:{description:e.description}}}function VF(t){let e=Wa(t.definition);return{id:Hd(t),name:t.name,...e.description===null?{}:{description:e.description},graph:e.graph}}function Wa(t){let e;try{e=JSON.parse(t)}catch{return{description:null,graph:null,stepIds:[],nameToId:new Map}}if(e===null||typeof e!="object")return{description:null,graph:e,stepIds:[],nameToId:new Map};let r=e,n=typeof r.description=="string"?r.description:null,s=[],o=new Map;if(r.schema_version==="lmctl/v3"&&Array.isArray(r.steps)){let i=typeof r.entry_step_id=="string"?r.entry_step_id:null;for(let a of r.steps){let l=typeof a.id=="string"?a.id:null;l!==null&&(s.push(l),typeof a.name=="string"&&a.name.length>0&&o.set(a.name,l))}i!==null&&s.includes(i)&&s.sort((a,l)=>a===i?-1:l===i?1:0)}return{description:n,graph:e,stepIds:s,nameToId:o}}function YF(t,e){if(!e.startsWith(Fn))throw new ie(404,`template not found: ${e}`);let r=e.slice(Fn.length),n=t.listWorkflows().filter(s=>Jd(s.name)===r);if(n.length===0)throw new ie(404,`template not found: ${e}`);if(n.length>1){let s=n.map(o=>o.name).join(", ");throw new ie(409,`template_id_ambiguous: ${e} matches multiple workflow names [${s}]; rename to ensure unique slugs`)}return n[0]}function dT(t,e){if(!e.startsWith(Bd))throw new ie(404,`run not found: ${e}`);let r=e.slice(Bd.length);if(!/^[1-9]\d*$/.test(r))throw new ie(404,`run not found: ${e}`);let n=Number.parseInt(r,10);if(!Number.isFinite(n)||n<=0||String(n)!==r)throw new ie(404,`run not found: ${e}`);let s=t.getRun(n);if(s===null)throw new ie(404,`run not found: ${e}`);return s}function zF(t,e,r){if(r!==null){if(!r.startsWith(Fn))return[];let s=r.slice(Fn.length),o=t.listWorkflows().filter(a=>Jd(a.name)===s).map(a=>a.id);if(o.length===0)return[];let i=o.map(()=>"?").join(", ");return t.query(`SELECT * FROM run WHERE workflow_id IN (${i}) ORDER BY id DESC LIMIT 200`,...o)}if(e===null)return t.query("SELECT * FROM run ORDER BY id DESC LIMIT 200");let n=t.findProjectByName(e);return n===null?[]:t.query("SELECT r.* FROM run r JOIN job j ON j.id = r.job_id WHERE j.project_id = ? ORDER BY r.id DESC LIMIT 200",n.id)}function fT(t,e){let r=t.getWorkflow(e.workflow_id),n=qd(e),s=ZF(r,e);return{id:Xd(e),templateId:r===null?`${Fn}unknown`:Hd(r),label:r===null?`run ${e.id}`:`${r.name} #${e.id}`,status:n,createdAt:e.started_at,...e.ended_at===null?{}:{updatedAt:e.ended_at},currentStepIds:s}}function ZF(t,e){if(e.current_state===null)return[];let r=e.current_state.startsWith("__paused__:")?e.current_state.slice(11):e.current_state;return t===null?[r]:[Wa(t.definition).nameToId.get(r)??r]}function QF(t,e){let r=t.getWorkflow(e.workflow_id),n=r===null?{stepIds:[],nameToId:new Map}:Wa(r.definition),s=c=>n.nameToId.get(c)??c,o=Xd(e),i=[];i.push({timestamp:e.started_at,type:"run.started",message:"Run started"});let a=t.listStepsForRun(e.id);for(let c of a){let u=s(c.state_name);if(i.push({timestamp:c.started_at,type:"step.started",stepId:u,message:`step ${c.state_name} started`}),c.ended_at!==null){let d=e1(c);i.push({timestamp:c.ended_at,type:d,stepId:u,...c.outcome===null?{}:{message:c.outcome},...c.status_detail===null?{}:{payload:{status_detail:c.status_detail}}})}else e.paused_at!==null&&c.id===a[a.length-1]?.id&&i.push({timestamp:e.paused_at,type:"step.paused",stepId:u})}let l=t.listSessionEvents(e.id);for(let c of l){let u=c.step_id===null?void 0:(()=>{let m=a.find(p=>p.id===c.step_id);return m===void 0?void 0:s(m.state_name)})(),d=new Date(c.timestamp_ms).toISOString(),f={kind:c.kind,session_event_id:c.id};if(c.payload.length>0)try{let m=JSON.parse(c.payload);m!==null&&typeof m=="object"&&!Array.isArray(m)&&(f={...f,...m})}catch{}i.push({timestamp:d,type:"message",...u===void 0?{}:{stepId:u},payload:f})}if(e.terminal_state!==null){let c=e.terminal_state==="done"||e.terminal_state==="success"?"run.completed":e.terminal_state==="cancelled"||e.terminal_state==="aborted"?"run.cancelled":"run.failed";i.push({timestamp:e.ended_at??e.started_at,type:c,message:e.terminal_state})}return i.sort((c,u)=>c.timestamp.localeCompare(u.timestamp)),i.map((c,u)=>({id:`${o}:evt:${u+1}`,runId:o,sequence:u+1,timestamp:c.timestamp,type:c.type,...c.stepId===void 0?{}:{stepId:c.stepId},...c.message===void 0?{}:{message:c.message},...c.payload===void 0?{}:{payload:c.payload}}))}function e1(t){if(t.outcome===null)return"step.failed";let e=t.status_detail;return e==="failed"||e==="error"||e==="aborted"?"step.failed":"step.completed"}var mT,Fn,Bd,ie,gT=T(()=>{"use strict";Ve();Fa();Jt();mT="global-admin";Fn="template:",Bd="run:";ie=class extends Error{status;constructor(e,r){super(r),this.status=e}}});import{mkdirSync as t1,writeFileSync as r1}from"node:fs";import{randomUUID as yT}from"node:crypto";import{dirname as n1,resolve as Ba,sep as wT}from"node:path";async function TT(t,e){let r;try{r=await t.req.parseBody({all:!1})}catch{return t.text("invalid multipart body",400)}let n=r.image;if(!l1(n))return t.text("missing image file",400);if(n.size>s1)return t.text("upload too large",413);let s=Buffer.from(await n.arrayBuffer()),o=c1(s);if(o===null||!(o in ET))return t.text("unsupported upload MIME type",415);if(n.type.length>0&&n.type!==o)return t.text("upload MIME type does not match file content",415);let i=o1(e,r.project);if(typeof i=="string")return t.text(i,404);let a=i===null?Ba(a1()):Ba(i.local_path),l=Ba(a,"uploads",yT()),c=Ba(l,`${yT()}${ET[o]}`);if(!i1(c,a))return t.text("invalid upload path",400);t1(l,{recursive:!0});let u=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);r1(c,u);let d={path:c,size:s.byteLength,mime:o,project:i?.name??null};return t.json(d)}function o1(t,e){return e==null||e===""?null:typeof e!="string"?"invalid project":t.findProjectByName(e)??`project not found: ${e}`}function i1(t,e){let r=e.endsWith(wT)?e:`${e}${wT}`;return t.startsWith(r)}function a1(){return n1(le())}function l1(t){return typeof File<"u"&&t instanceof File}function c1(t){return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?"image/png":t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":t.length>=12&&t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP"?"image/webp":t.length>=12&&t.subarray(4,8).toString("ascii")==="ftyp"&&["heic","heix","hevc","hevx","mif1","msf1"].includes(t.subarray(8,12).toString("ascii"))?"image/heic":t.length>=5&&t.subarray(0,5).toString("ascii")==="%PDF-"?"application/pdf":null}var s1,ET,bT=T(()=>{"use strict";Ve();s1=10*1024*1024,ET={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}});import{existsSync as qa}from"node:fs";import{basename as u1,dirname as d1,extname as f1,isAbsolute as m1,join as p1,relative as _1}from"node:path";import{fileURLToPath as h1}from"node:url";import{Hono as g1}from"hono";import{serveStatic as Ot}from"@hono/node-server/serve-static";function xT(t){let e=new g1,r=[],n=t.localWebui!==void 0?Kd(t.localWebui.webuiDir):y1();if(t.localWebui!==void 0&&jE(e,{s3:t.localWebui.localMailbox.s3,commands:t.localWebui.localMailbox.commands}),n!==null){let s=w1();t.localWebui!==void 0?e.get("/config.json",s,o=>o.json({workspaceFetchMode:"local-mailbox",localMailbox:{base:"/local-mailbox",userId:"local",deviceId:"local"},mailboxPolling:{readIntervalSeconds:1,heartbeatIdleSeconds:1,backoffReadIntervalSeconds:1}})):t.webuiRuntimeConfig!==void 0&&e.get("/config.json",s,o=>o.json(t.webuiRuntimeConfig)),e.use("/dist/*",s,Ot({root:n})),e.use("/vendor/*",s,Ot({root:n})),e.use("/src/*",s,Ot({root:n})),e.get("/",s,Ot({root:n,path:"index.html"})),e.get("/admin",s,Ot({root:n,path:"index.html"})),e.get("/admin/*",s,Ot({root:n,path:"index.html"})),e.get("/terminal",s,Ot({root:n,path:"index.html"})),e.get("/terminal/*",s,Ot({root:n,path:"index.html"})),e.get("/chat",s,Ot({root:n,path:"index.html"})),e.get("/chat/*",s,Ot({root:n,path:"index.html"}))}else e.get("/",s=>s.html('<!doctype html><meta charset="utf-8"><title>lmctl</title><body style="font-family:system-ui;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5"><h1>lmctl daemon</h1><p>This build does not bundle the local web console; the HTTP API is running on this port.</p><p>Open the hosted console at <a href="https://lmctl.ai/">https://lmctl.ai/</a> \u2014 it connects to this daemon via the cloud mailbox.</p></body>'));return e.use("*",wy()),e.get("/login",s=>s.html($e("Login",`
|
|
2068
2074
|
<h1>Login</h1>
|
|
2069
2075
|
<form method="post" action="/login">
|
|
2070
2076
|
<label>Token <input name="token" type="password"></label>
|
|
2071
2077
|
<button type="submit">Login</button>
|
|
2072
2078
|
</form>
|
|
2073
|
-
`))),e.post("/login",async s=>{let o=await s.req.parseBody(),i=typeof o.token=="string"?o.token:"";return Ty(i)?(rd(s,i),s.redirect("/",302)):s.html($e("Login","<p>Invalid token</p>"),401)}),e.post("/logout",s=>(by(s),s.redirect("/login",302))),wE(e,{dal:t.dal}),pT(e,{dal:t.dal}),ME(e,{dal:t.dal}),GE(e,{terminalSessionManager:t.terminalSessionManager}),QE(e,{persistentSessionManager:t.persistentSessionManager}),e.post("/api/teams/:team_name/refresh",async s=>{let o=Ss(s.req.param("team_name")),i=t.dal.findTeamByName(o);if(i===null)return s.notFound();let a=[],c=t.dal.db.transaction(()=>{let f=t.dal.listTeamMembers(i.id),m=f.filter(p=>p.state!=="idle");if(m.length>0)return{ok:!1,nonIdle:m.map(p=>({alias:p.alias,state:p.state}))};for(let p of f)t.dal.setMemberState(p.id,"in_chat","refreshing");return a=f.map(p=>({id:p.id,alias:p.alias})),{ok:!0}})();if(!c.ok){let f=c.nonIdle.map(m=>`${m.alias}:${m.state}`).join(", ");return s.text(`refresh refused: non-idle members: ${f}`,409)}let u=[],d=[];for(let f of a)try{await iu(t.dal,o,f.alias),t.dal.setMemberState(f.id,"idle",null),u.push(f.alias)}catch(m){let p=m instanceof Error?m.message:String(m);t.dal.setMemberState(f.id,"attention_needed",`refresh failed: ${p}`),d.push({alias:f.alias,error:p})}return H(s,{team:o,seeded:u,failed:d},f=>`<p>refreshed team ${S(f.team)}: seeded [${f.seeded.map(m=>S(m)).join(", ")}]${f.failed.length>0?` failed [${f.failed.map(m=>`${S(m.alias)}: ${S(m.error)}`).join(", ")}]`:""}</p>`)}),xy(e,{dal:t.dal}),My(e,{dal:t.dal}),e.get("/api/status",s=>H(s,_i(t.dal),IF)),e.get("/api/projects",s=>H(s,hi(t.dal),NF)),e.get("/api/teams",s=>H(s,xh(t.dal),RF)),e.get("/api/workflows",s=>H(s,gi(t.dal),LF)),e.get("/api/workflows/verify",s=>{let o=nE();return s.req.header("accept")?.includes("text/plain")?s.text(oE(o)):s.json(o)}),e.get("/api/jobs",s=>H(s,Rh(t.dal,{status:s.req.query("status")}),$F)),e.post("/api/uploads",s=>TT(s,t.dal)),e.get("/api/jobs/:id",s=>{let o=yi(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/jobs",async s=>{let o;try{o=await s.req.json()}catch{return s.text("invalid JSON body",400)}let i=null;if(typeof o.project_id=="number")i=o.project_id;else if(typeof o.project=="string"){let f=t.dal.findProjectByName(o.project);if(f===null)return s.text(`project not found: ${o.project}`,404);i=f.id}else{let f=t.dal.listProjects();f.length===1&&(i=f[0].id)}if(i===null)return s.text("missing project or project_id",400);let a=typeof o.workflow_id_override=="number"?o.workflow_id_override:null;if(a===null&&typeof o.workflow=="string"){let f=t.dal.getWorkflowByName(o.workflow);if(f===null)return s.text(`workflow not found: ${o.workflow}`,404);a=f.id}let l=typeof o.source=="string"?o.source:"manual",c=o.payload,u=c==null?null:typeof c=="string"?c:JSON.stringify(c),d=t.dal.enqueueJob({project_id:i,workflow_id_override:a,source:l,source_ref:typeof o.source_ref=="string"?o.source_ref:null,payload:u,priority:typeof o.priority=="number"?o.priority:0,dedupe_key:typeof o.dedupe_key=="string"?o.dedupe_key:null});return H(s,d,fe)}),e.post("/api/jobs/:id/run",async s=>{let{runJobById:o}=await Promise.resolve().then(()=>(Ks(),_E)),i=yi(t.dal,re(s,"id"));if(i===null)return s.notFound();let a=await o({dal:t.dal,worker_id:`api-job-run-${process.pid}-${Date.now()}`,job_id:i.id});return a.claimed?s.json({job_id:a.job_id,run_id:a.run_id,status:a.status,terminal_state:a.terminal_state,ms:a.ms}):s.json(a,409)}),e.get("/api/workflows/:name",s=>{let o=t.dal.getWorkflowByName(s.req.param("name"));return o===null?s.notFound():H(s,o,fe)}),e.get("/api/projects/:name/workflows",s=>{let o=t.dal.findProjectByName(s.req.param("name"));return o===null?s.notFound():H(s,t.dal.listProjectWorkflows(o.id),AF)}),e.post("/api/projects/:name/workflows",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.text(i,400);let a=typeof i.workflow=="string"?i.workflow:null,l=typeof i.workflow_id=="number"?i.workflow_id:null,c=l!==null?t.dal.getWorkflow(l):a!==null?t.dal.getWorkflowByName(a):null;if(c===null)return s.text("workflow not found",404);let u=typeof i.condition=="string"&&i.condition.length>0?i.condition:null;if(u!==null)try{hr(u)}catch{return s.text("invalid condition",400)}let d=bF(i.parameters_override??i.params);if(typeof d=="string"&&d.startsWith("error:"))return s.text(d.slice(6),400);let f=typeof i.priority=="number"&&Number.isInteger(i.priority)?i.priority:100,m=t.dal.insertProjectWorkflow({project_id:o.id,workflow_id:c.id,condition:u,parameters_override:d,priority:f});return H(s,m,fe)}),e.get("/api/projects/workflows/:id",s=>{let o=t.dal.getProjectWorkflow(re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.delete("/api/projects/workflows/:id",s=>t.dal.removeProjectWorkflow(re(s,"id"))?H(s,{removed:!0},fe):s.notFound()),e.post("/api/projects/workflows/:id/enable",s=>{let o=t.dal.setProjectWorkflowEnabled(re(s,"id"),!0);return o===null?s.notFound():H(s,o,fe)}),e.post("/api/projects/workflows/:id/disable",s=>{let o=t.dal.setProjectWorkflowEnabled(re(s,"id"),!1);return o===null?s.notFound():H(s,o,fe)}),e.get("/api/projects/:name/issues",s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=vT(s.req.query("status"),SF);if(typeof i=="string")return s.text(i,400);let a=vT(s.req.query("severity"),LT);return typeof a=="string"?s.text(a,400):H(s,t.dal.listIssues(o.id,{...i!==void 0?{status:i}:{},...a!==void 0?{severity:a}:{},...s.req.query("ai_test_path")!==void 0?{ai_test_path:s.req.query("ai_test_path")}:{}}),xF)}),e.post("/api/projects/:name/issues",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.text(i,400);let a=typeof i.title=="string"&&i.title.trim().length>0?i.title:null,l=typeof i.body=="string"?i.body:null;if(a===null||l===null)return s.text("missing title or body",400);let c=vF(i.severity);if(typeof c=="object")return s.text(c.error,400);let u=kF(i.labels);if(typeof u=="string"&&u.startsWith("error:"))return s.text(u.slice(6),400);let d=t.dal.createIssue({project_id:o.id,title:a,body:l,...c!==void 0?{severity:c}:{},labels:u,ai_test_path:typeof i.ai_test_path=="string"?i.ai_test_path:null,source_run_id:typeof i.source_run_id=="number"?i.source_run_id:null});return H(s,d,fe)}),e.get("/api/issues/:id",s=>{let o=t.dal.getIssue(re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/issues/:id/claim",async s=>{let o=re(s,"id"),i=t.dal.getIssue(o);if(i===null)return s.notFound();let a=await Un(s);if(typeof a=="string")return s.json({error:a},400);let l=typeof a.assigned_run_id=="number"?a.assigned_run_id:null;if(l===null)return s.json({error:"missing assigned_run_id"},400);let c=t.dal.claimIssue(o,l);return c===null?s.json({error:`issue ${o} is not in a claimable state (status=${i.status})`},400):H(s,c,fe)}),e.post("/api/projects/:name/issues/claim-next",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.json({error:"project_not_found"},404);let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.assigned_run_id=="number"?i.assigned_run_id:null;if(a===null)return s.json({error:"missing assigned_run_id"},400);let l=t.dal.claimNextIssue(o.id,a);return l===null?s.json({status:"queue_empty"},404):H(s,l,fe)}),e.post("/api/issues/:id/close",async s=>{let o=t.dal.getIssue(re(s,"id"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.closed_run_id=="number"?i.closed_run_id:o.assigned_run_id;if(a===null)return s.json({error:"missing closed_run_id"},400);try{return H(s,t.dal.closeIssue(re(s,"id"),a,typeof i.commit_hash=="string"?i.commit_hash:null),fe)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.post("/api/issues/:id/reopen",async s=>{let o=t.dal.getIssue(re(s,"id"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.source_run_id=="number"?i.source_run_id:o.closed_run_id??o.source_run_id;if(a===null)return s.json({error:"missing source_run_id"},400);try{return H(s,t.dal.reopenIssue(re(s,"id"),a),fe)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.get("/api/projects/:name",s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=o.name.indexOf("/"),a=i>0?o.name.slice(0,i):null,l=i>0?o.name.slice(i+1):o.name;return H(s,{...o,owner:a,repo:l},fe)}),e.get("/api/runs/:run_id/artifacts",s=>{let o=re(s,"run_id"),i=s.req.query("kind"),a=Dr(t.dal,o,i);return H(s,a,fe)}),e.get("/api/runs/:run_id/artifacts/:kind",async s=>{let o=re(s,"run_id"),i=s.req.param("kind"),a=Dr(t.dal,o,i);if(a.length===0)return s.notFound();let l=a[a.length-1],c=s.req.query("raw")==="true";if(l.content!==null&&l.content!==void 0)return c?s.text(l.content):H(s,l,fe);if(l.path!==null&&l.path!==void 0){if(c)try{let{readFileSync:u}=await import("node:fs"),d=EF(l.path);if(TF(d)){let _=u(l.path,"utf8");return s.body(_,200,{"Content-Type":d})}let f=u(l.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),p=uF(l.path);return s.body(m,200,{"Content-Type":d,"Content-Disposition":`attachment; filename="${p}"`})}catch(u){return s.text(`failed to read artifact path: ${u.message}`,500)}return H(s,l,fe)}return H(s,l,fe)}),e.get("/api/runs",s=>H(s,mn(t.dal,{limit:Gd(s,"limit")??100}),OF)),e.get("/api/runs/:id",s=>{let o=Mr(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,jF)}),e.get("/api/runs/:id/where",s=>{let o=pn(t.dal,re(s,"id"));return o===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(Ei(o)):s.json(o)}),e.get("/api/runs/:id/timeline",s=>{let o=Ti(t.dal,re(s,"id"));return o===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(bi(o)):s.json(o)}),e.post("/api/runs/:id/resume",async s=>{let o=s.req.query("outcome");if(o===void 0||o.length===0){let a=s.req.header("content-type")??"";if(a.includes("application/x-www-form-urlencoded")||a.includes("multipart/form-data")){let c=(await s.req.parseBody().catch(()=>({}))).outcome;typeof c=="string"&&c.length>0&&(o=c)}}if(o===void 0||o.length===0)return s.text("missing outcome",400);let i=t.dal.resumeRun(re(s,"id"),o);return!i.resumed&&i.reason==="run_not_found"?s.notFound():i.resumed?(Ha(t.daemon),H(s,i,kT)):H(s,i,kT,400)}),e.post("/api/interactive/:step_id/respond",async s=>{let o=re(s,"step_id"),i,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let u=await s.req.json();typeof u.input=="string"&&(i=u.input),u.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let u=await s.req.parseBody().catch(()=>({}));typeof u.input=="string"&&(i=u.input),(u.done==="true"||u.done===!0)&&(a=!0)}if(i===void 0)return s.text("missing input",400);let c=t.dal.resumeInteractive(o,i,a);return!c.resumed&&c.reason==="not_found"?s.notFound():c.resumed?(Ha(t.daemon),s.json({resumed:!0,session_status:c.session.status})):s.json({resumed:!1,reason:c.reason},400)}),e.get("/api/runs/:id/steps/:step_id",s=>ST(s,t.dal,o=>H(s,o,MF))),e.get("/api/runs/:id/steps/:step_id/transcript",s=>{let o=jh(t.dal,re(s,"id"),re(s,"step_id"));return o===null?s.notFound():RT(s)?s.html(`<pre>${S(o)}</pre>`):s.req.header("accept")?.includes("text/plain")?s.text(o):s.json({transcript:o})}),e.get("/api/runs/:id/steps/:step_id/messages",s=>ST(s,t.dal,o=>{let i=rT(o);return H(s,i,a=>pe(["role","text"],a.map(l=>[S(l.role),S(l.text)])))})),e.get("/api/external-objects",s=>H(s,Ch(t.dal,{type:s.req.query("type")}),DF)),e.get("/api/external-signals",s=>H(s,Mh(t.dal,{unhandled:s.req.query("unhandled")==="true"}),PF)),e.get("/api/attentions",s=>H(s,fr(t.dal,{unacked:s.req.query("unacked")==="true"}),FF)),e.post("/api/attentions/:id/ack",s=>{let o=t.dal.acknowledgeAttention(re(s,"id"));return o===null?s.notFound():H(s,o,i=>`<p>acknowledged attention ${S(i.id)}</p>`)}),e.get("/api/escalations",s=>{let o=s.req.query("project"),i=s.req.query("all")==="true",a=s.req.query("since"),l={all:i};o!==void 0&&(l.project=o),a!==void 0&&(l.since=a);let c=wi(t.dal,l);return H(s,c,u=>`<h1>Escalations</h1>${pe(["attention_id","project","run","workflow","state","prompt"],u.map(d=>[S(d.attention_id),S(d.project),S(d.run_id),S(d.workflow_name),S(d.state_name),S((d.prompt??"").slice(0,120))]))}`)}),e.get("/api/escalations/:id",s=>{let o=Rt(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/escalations/:id/respond",async s=>{let o=re(s,"id"),i,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let m=await s.req.json();typeof m.input=="string"&&(i=m.input),m.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let m=await s.req.parseBody().catch(()=>({}));typeof m.input=="string"&&(i=m.input),(m.done==="true"||m.done===!0)&&(a=!0)}if(i===void 0)return s.text("missing input",400);let c=Rt(t.dal,o);if(c===null)return s.notFound();let u=fr(t.dal).find(m=>m.id===o);if(u===void 0)return s.notFound();if(u.kind==="workflow_escalation"){let m=t.dal.resumeEscalation(o,i);if(!m.resumed)return s.json({ok:!1,reason:m.reason},400);Ha(t.daemon);let p=fr(t.dal).find(_=>_.id===o);return s.json({ok:!0,attention_id:o,run_id:m.run.id,decision:i,session_status:"escalation_resumed",acknowledged_at:p?.acknowledged_at??null})}if(u.kind!=="interactive_waiting_operator")return s.json({ok:!1,reason:"wrong_kind",kind:u.kind},400);if(u.acknowledged_at!==null)return s.json({ok:!1,reason:"already_acked"},400);if(c.step_id===null)return s.json({ok:!1,reason:"no_step"},400);let d=t.dal.resumeInteractive(c.step_id,i,a);if(!d.resumed)return s.json({ok:!1,reason:d.reason,step_id:c.step_id},400);let f=t.dal.acknowledgeAttention(o);return Ha(t.daemon),s.json({ok:!0,attention_id:o,step_id:c.step_id,session_status:d.session.status,acknowledged_at:f?.acknowledged_at??null})}),e.get("/api/submitted-prs",s=>{let o=s.req.query("pr_url"),i=s.req.query("status"),a=Lh(t.dal,{status:i,pr_url:o});return H(s,a,UF)}),e.get("/api/submitted-prs/:id",s=>{let o=re(s,"id"),i=$h(t.dal,o);return i===null?s.notFound():H(s,i,WF)}),e.get("/api/sessions",s=>H(s,t.dal.latestSessionSizes(),IT)),e.get("/api/sessions/:team_name/:alias/history",s=>{let o=Ss(s.req.param("team_name"));return H(s,t.dal.sessionSizeHistory(o,s.req.param("alias")),IT)}),e.post("/api/sessions/:team_name/:alias/compact",async s=>{let o=Ss(s.req.param("team_name"));try{let i=await bh(t.dal,o,s.req.param("alias"));return H(s,i,a=>NT("compacted",a.row))}catch(i){if(i instanceof bs)return s.text(i.message,409);throw i}}),e.post("/api/sessions/:team_name/:alias/refresh",async s=>{let o=Ss(s.req.param("team_name")),i=await iu(t.dal,o,s.req.param("alias"));return H(s,i,a=>NT(`refreshed ${a.sessionid}`,a.row))}),e.get("/api/intake/state",s=>H(s,r,AT)),e.post("/api/intake/scan",async s=>(r=await Rn(t.dal),H(s,r,AT))),e.get("/api/stats/run-throughput",s=>H(s,Fh(t.dal),BF)),e.get("/api/daemon/state",s=>H(s,t.daemon?.state??null,qF)),e.post("/api/daemon/cycle",async s=>{if(t.daemon===void 0)return H(s,{disabled:!0},fe);let o=await t.daemon.runCycle();return H(s,{state:t.daemon.state,result:o},fe)}),e.get("/metrics/:project_id",s=>{let o=re(s,"project_id"),i=t.dal.getProject(o);if(i===null)return s.notFound();let a=mu(t.dal,o),l=pu(t.dal,{project_id:o});return s.html($e(`Metrics \u2014 ${i.name}`,HF(i.name,a,l)))}),e.get("/api/metrics/reviewer/:project_id",s=>{let o=re(s,"project_id");if(t.dal.getProject(o)===null)return s.notFound();let i=Gd(s,"since_days");return s.json(mu(t.dal,o,i))}),e.get("/api/metrics/tools/:project_id",s=>{let o=re(s,"project_id");if(t.dal.getProject(o)===null)return s.notFound();let i=Gd(s,"since_days");return s.json(pu(t.dal,{project_id:o,since_days:i}))}),e.post("/api/drift/:id/ack",s=>{let o=t.dal.acknowledgeDriftSignal(re(s,"id"));return o===null?s.notFound():s.json({id:o.id,acknowledged_at:o.acknowledged_at})}),e}function ST(t,e,r){let n=fu(e,re(t,"id"),re(t,"step_id"));return n===null?t.notFound():r(n)}function Ha(t){t!==void 0&&t.runCycle().catch(()=>{})}function H(t,e,r,n=200){return RT(t)?n===200?t.html(r(e)):t.html(r(e),400):new Response(JSON.stringify(e),{status:n,headers:{"Content-Type":"application/json; charset=UTF-8"}})}function RT(t){let e=t.req.header("accept")??"";return e.includes("text/html")&&!e.includes("application/json")}function yF(){let t=process.env.LMCTL_WEBUI_DIST;if(t!==void 0)return qa(`${t}/index.html`)?Kd(t):null;let e="src/serve/webui-dist";if(qa(`${e}/index.html`))return e;let r="dist/serve/webui-dist";if(qa(`${r}/index.html`))return r;let n=pF(dF(hF(import.meta.url)),"webui-dist");return qa(`${n}/index.html`)?Kd(n):null}function Kd(t){if(!mF(t))return t;let e=_F(process.cwd(),t);return e.length===0?".":e}function wF(){return async(t,e)=>{await e(),t.header("Cache-Control","no-store")}}function re(t,e){return Number(t.req.param(e))}function Gd(t,e){let r=t.req.query(e);if(r===void 0)return;let n=Number(r);return Number.isInteger(n)&&n>0?n:void 0}function EF(t){switch(fF(t).toLowerCase()){case".txt":return"text/plain; charset=utf-8";case".md":return"text/markdown; charset=utf-8";case".html":case".htm":return"text/html; charset=utf-8";case".css":return"text/css; charset=utf-8";case".csv":return"text/csv; charset=utf-8";case".json":return"application/json; charset=utf-8";case".xml":return"application/xml; charset=utf-8";case".yaml":case".yml":return"text/yaml; charset=utf-8";case".js":case".mjs":case".cjs":return"text/javascript; charset=utf-8";case".ts":return"text/x-typescript; charset=utf-8";case".log":return"text/plain; charset=utf-8";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".pdf":return"application/pdf";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".zip":return"application/zip";case".gz":return"application/gzip";default:return"application/octet-stream"}}function TF(t){return!!(t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/xml"))}async function Un(t){try{let e=await t.req.json();return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:"invalid JSON body"}catch{return"invalid JSON body"}}function bF(t){if(t==null)return null;if(typeof t=="string"){try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return JSON.stringify(e)}catch{return"error:invalid parameters_override JSON"}return"error:parameters_override must be a JSON object"}return typeof t=="object"&&!Array.isArray(t)?JSON.stringify(t):"error:parameters_override must be a JSON object"}function vT(t,e){if(t===void 0||t.length===0)return;let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(r.length!==0){for(let n of r)if(!e.includes(n))return`invalid value: ${n}`;return r}}function vF(t){if(t!=null)return typeof t=="string"&<.includes(t)?t:{error:`invalid severity: ${String(t)}`}}function kF(t){if(t==null)return null;if(typeof t=="string")try{let e=JSON.parse(t);return Array.isArray(e)&&e.every(r=>typeof r=="string")?JSON.stringify(e):"error:labels must be a JSON string array"}catch{return"error:invalid labels JSON"}return Array.isArray(t)&&t.every(e=>typeof e=="string")?JSON.stringify(t):"error:labels must be a JSON string array"}function IF(t){return`<h1>Status</h1><div class="grid">
|
|
2079
|
+
`))),e.post("/login",async s=>{let o=await s.req.parseBody(),i=typeof o.token=="string"?o.token:"";return Ty(i)?(rd(s,i),s.redirect("/",302)):s.html($e("Login","<p>Invalid token</p>"),401)}),e.post("/logout",s=>(by(s),s.redirect("/login",302))),wE(e,{dal:t.dal}),pT(e,{dal:t.dal}),ME(e,{dal:t.dal}),GE(e,{terminalSessionManager:t.terminalSessionManager}),QE(e,{persistentSessionManager:t.persistentSessionManager}),e.post("/api/teams/:team_name/refresh",async s=>{let o=Ss(s.req.param("team_name")),i=t.dal.findTeamByName(o);if(i===null)return s.notFound();let a=[],c=t.dal.db.transaction(()=>{let f=t.dal.listTeamMembers(i.id),m=f.filter(p=>p.state!=="idle");if(m.length>0)return{ok:!1,nonIdle:m.map(p=>({alias:p.alias,state:p.state}))};for(let p of f)t.dal.setMemberState(p.id,"in_chat","refreshing");return a=f.map(p=>({id:p.id,alias:p.alias})),{ok:!0}})();if(!c.ok){let f=c.nonIdle.map(m=>`${m.alias}:${m.state}`).join(", ");return s.text(`refresh refused: non-idle members: ${f}`,409)}let u=[],d=[];for(let f of a)try{await iu(t.dal,o,f.alias),t.dal.setMemberState(f.id,"idle",null),u.push(f.alias)}catch(m){let p=m instanceof Error?m.message:String(m);t.dal.setMemberState(f.id,"attention_needed",`refresh failed: ${p}`),d.push({alias:f.alias,error:p})}return H(s,{team:o,seeded:u,failed:d},f=>`<p>refreshed team ${S(f.team)}: seeded [${f.seeded.map(m=>S(m)).join(", ")}]${f.failed.length>0?` failed [${f.failed.map(m=>`${S(m.alias)}: ${S(m.error)}`).join(", ")}]`:""}</p>`)}),xy(e,{dal:t.dal}),My(e,{dal:t.dal}),e.get("/api/status",s=>H(s,_i(t.dal),I1)),e.get("/api/projects",s=>H(s,hi(t.dal),N1)),e.get("/api/teams",s=>H(s,xh(t.dal),R1)),e.get("/api/workflows",s=>H(s,gi(t.dal),L1)),e.get("/api/workflows/verify",s=>{let o=nE();return s.req.header("accept")?.includes("text/plain")?s.text(oE(o)):s.json(o)}),e.get("/api/jobs",s=>H(s,Rh(t.dal,{status:s.req.query("status")}),$1)),e.post("/api/uploads",s=>TT(s,t.dal)),e.get("/api/jobs/:id",s=>{let o=yi(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/jobs",async s=>{let o;try{o=await s.req.json()}catch{return s.text("invalid JSON body",400)}let i=null;if(typeof o.project_id=="number")i=o.project_id;else if(typeof o.project=="string"){let f=t.dal.findProjectByName(o.project);if(f===null)return s.text(`project not found: ${o.project}`,404);i=f.id}else{let f=t.dal.listProjects();f.length===1&&(i=f[0].id)}if(i===null)return s.text("missing project or project_id",400);let a=typeof o.workflow_id_override=="number"?o.workflow_id_override:null;if(a===null&&typeof o.workflow=="string"){let f=t.dal.getWorkflowByName(o.workflow);if(f===null)return s.text(`workflow not found: ${o.workflow}`,404);a=f.id}let l=typeof o.source=="string"?o.source:"manual",c=o.payload,u=c==null?null:typeof c=="string"?c:JSON.stringify(c),d=t.dal.enqueueJob({project_id:i,workflow_id_override:a,source:l,source_ref:typeof o.source_ref=="string"?o.source_ref:null,payload:u,priority:typeof o.priority=="number"?o.priority:0,dedupe_key:typeof o.dedupe_key=="string"?o.dedupe_key:null});return H(s,d,fe)}),e.post("/api/jobs/:id/run",async s=>{let{runJobById:o}=await Promise.resolve().then(()=>(Ks(),_E)),i=yi(t.dal,re(s,"id"));if(i===null)return s.notFound();let a=await o({dal:t.dal,worker_id:`api-job-run-${process.pid}-${Date.now()}`,job_id:i.id});return a.claimed?s.json({job_id:a.job_id,run_id:a.run_id,status:a.status,terminal_state:a.terminal_state,ms:a.ms}):s.json(a,409)}),e.get("/api/workflows/:name",s=>{let o=t.dal.getWorkflowByName(s.req.param("name"));return o===null?s.notFound():H(s,o,fe)}),e.get("/api/projects/:name/workflows",s=>{let o=t.dal.findProjectByName(s.req.param("name"));return o===null?s.notFound():H(s,t.dal.listProjectWorkflows(o.id),A1)}),e.post("/api/projects/:name/workflows",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.text(i,400);let a=typeof i.workflow=="string"?i.workflow:null,l=typeof i.workflow_id=="number"?i.workflow_id:null,c=l!==null?t.dal.getWorkflow(l):a!==null?t.dal.getWorkflowByName(a):null;if(c===null)return s.text("workflow not found",404);let u=typeof i.condition=="string"&&i.condition.length>0?i.condition:null;if(u!==null)try{hr(u)}catch{return s.text("invalid condition",400)}let d=b1(i.parameters_override??i.params);if(typeof d=="string"&&d.startsWith("error:"))return s.text(d.slice(6),400);let f=typeof i.priority=="number"&&Number.isInteger(i.priority)?i.priority:100,m=t.dal.insertProjectWorkflow({project_id:o.id,workflow_id:c.id,condition:u,parameters_override:d,priority:f});return H(s,m,fe)}),e.get("/api/projects/workflows/:id",s=>{let o=t.dal.getProjectWorkflow(re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.delete("/api/projects/workflows/:id",s=>t.dal.removeProjectWorkflow(re(s,"id"))?H(s,{removed:!0},fe):s.notFound()),e.post("/api/projects/workflows/:id/enable",s=>{let o=t.dal.setProjectWorkflowEnabled(re(s,"id"),!0);return o===null?s.notFound():H(s,o,fe)}),e.post("/api/projects/workflows/:id/disable",s=>{let o=t.dal.setProjectWorkflowEnabled(re(s,"id"),!1);return o===null?s.notFound():H(s,o,fe)}),e.get("/api/projects/:name/issues",s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=vT(s.req.query("status"),S1);if(typeof i=="string")return s.text(i,400);let a=vT(s.req.query("severity"),LT);return typeof a=="string"?s.text(a,400):H(s,t.dal.listIssues(o.id,{...i!==void 0?{status:i}:{},...a!==void 0?{severity:a}:{},...s.req.query("ai_test_path")!==void 0?{ai_test_path:s.req.query("ai_test_path")}:{}}),x1)}),e.post("/api/projects/:name/issues",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.text(i,400);let a=typeof i.title=="string"&&i.title.trim().length>0?i.title:null,l=typeof i.body=="string"?i.body:null;if(a===null||l===null)return s.text("missing title or body",400);let c=v1(i.severity);if(typeof c=="object")return s.text(c.error,400);let u=k1(i.labels);if(typeof u=="string"&&u.startsWith("error:"))return s.text(u.slice(6),400);let d=t.dal.createIssue({project_id:o.id,title:a,body:l,...c!==void 0?{severity:c}:{},labels:u,ai_test_path:typeof i.ai_test_path=="string"?i.ai_test_path:null,source_run_id:typeof i.source_run_id=="number"?i.source_run_id:null});return H(s,d,fe)}),e.get("/api/issues/:id",s=>{let o=t.dal.getIssue(re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/issues/:id/claim",async s=>{let o=re(s,"id"),i=t.dal.getIssue(o);if(i===null)return s.notFound();let a=await Un(s);if(typeof a=="string")return s.json({error:a},400);let l=typeof a.assigned_run_id=="number"?a.assigned_run_id:null;if(l===null)return s.json({error:"missing assigned_run_id"},400);let c=t.dal.claimIssue(o,l);return c===null?s.json({error:`issue ${o} is not in a claimable state (status=${i.status})`},400):H(s,c,fe)}),e.post("/api/projects/:name/issues/claim-next",async s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.json({error:"project_not_found"},404);let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.assigned_run_id=="number"?i.assigned_run_id:null;if(a===null)return s.json({error:"missing assigned_run_id"},400);let l=t.dal.claimNextIssue(o.id,a);return l===null?s.json({status:"queue_empty"},404):H(s,l,fe)}),e.post("/api/issues/:id/close",async s=>{let o=t.dal.getIssue(re(s,"id"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.closed_run_id=="number"?i.closed_run_id:o.assigned_run_id;if(a===null)return s.json({error:"missing closed_run_id"},400);try{return H(s,t.dal.closeIssue(re(s,"id"),a,typeof i.commit_hash=="string"?i.commit_hash:null),fe)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.post("/api/issues/:id/reopen",async s=>{let o=t.dal.getIssue(re(s,"id"));if(o===null)return s.notFound();let i=await Un(s);if(typeof i=="string")return s.json({error:i},400);let a=typeof i.source_run_id=="number"?i.source_run_id:o.closed_run_id??o.source_run_id;if(a===null)return s.json({error:"missing source_run_id"},400);try{return H(s,t.dal.reopenIssue(re(s,"id"),a),fe)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.get("/api/projects/:name",s=>{let o=t.dal.findProjectByName(s.req.param("name"));if(o===null)return s.notFound();let i=o.name.indexOf("/"),a=i>0?o.name.slice(0,i):null,l=i>0?o.name.slice(i+1):o.name;return H(s,{...o,owner:a,repo:l},fe)}),e.get("/api/runs/:run_id/artifacts",s=>{let o=re(s,"run_id"),i=s.req.query("kind"),a=Dr(t.dal,o,i);return H(s,a,fe)}),e.get("/api/runs/:run_id/artifacts/:kind",async s=>{let o=re(s,"run_id"),i=s.req.param("kind"),a=Dr(t.dal,o,i);if(a.length===0)return s.notFound();let l=a[a.length-1],c=s.req.query("raw")==="true";if(l.content!==null&&l.content!==void 0)return c?s.text(l.content):H(s,l,fe);if(l.path!==null&&l.path!==void 0){if(c)try{let{readFileSync:u}=await import("node:fs"),d=E1(l.path);if(T1(d)){let _=u(l.path,"utf8");return s.body(_,200,{"Content-Type":d})}let f=u(l.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),p=u1(l.path);return s.body(m,200,{"Content-Type":d,"Content-Disposition":`attachment; filename="${p}"`})}catch(u){return s.text(`failed to read artifact path: ${u.message}`,500)}return H(s,l,fe)}return H(s,l,fe)}),e.get("/api/runs",s=>H(s,mn(t.dal,{limit:Gd(s,"limit")??100}),O1)),e.get("/api/runs/:id",s=>{let o=Mr(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,j1)}),e.get("/api/runs/:id/where",s=>{let o=pn(t.dal,re(s,"id"));return o===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(Ei(o)):s.json(o)}),e.get("/api/runs/:id/timeline",s=>{let o=Ti(t.dal,re(s,"id"));return o===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(bi(o)):s.json(o)}),e.post("/api/runs/:id/resume",async s=>{let o=s.req.query("outcome");if(o===void 0||o.length===0){let a=s.req.header("content-type")??"";if(a.includes("application/x-www-form-urlencoded")||a.includes("multipart/form-data")){let c=(await s.req.parseBody().catch(()=>({}))).outcome;typeof c=="string"&&c.length>0&&(o=c)}}if(o===void 0||o.length===0)return s.text("missing outcome",400);let i=t.dal.resumeRun(re(s,"id"),o);return!i.resumed&&i.reason==="run_not_found"?s.notFound():i.resumed?(Ha(t.daemon),H(s,i,kT)):H(s,i,kT,400)}),e.post("/api/interactive/:step_id/respond",async s=>{let o=re(s,"step_id"),i,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let u=await s.req.json();typeof u.input=="string"&&(i=u.input),u.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let u=await s.req.parseBody().catch(()=>({}));typeof u.input=="string"&&(i=u.input),(u.done==="true"||u.done===!0)&&(a=!0)}if(i===void 0)return s.text("missing input",400);let c=t.dal.resumeInteractive(o,i,a);return!c.resumed&&c.reason==="not_found"?s.notFound():c.resumed?(Ha(t.daemon),s.json({resumed:!0,session_status:c.session.status})):s.json({resumed:!1,reason:c.reason},400)}),e.get("/api/runs/:id/steps/:step_id",s=>ST(s,t.dal,o=>H(s,o,M1))),e.get("/api/runs/:id/steps/:step_id/transcript",s=>{let o=jh(t.dal,re(s,"id"),re(s,"step_id"));return o===null?s.notFound():RT(s)?s.html(`<pre>${S(o)}</pre>`):s.req.header("accept")?.includes("text/plain")?s.text(o):s.json({transcript:o})}),e.get("/api/runs/:id/steps/:step_id/messages",s=>ST(s,t.dal,o=>{let i=rT(o);return H(s,i,a=>pe(["role","text"],a.map(l=>[S(l.role),S(l.text)])))})),e.get("/api/external-objects",s=>H(s,Ch(t.dal,{type:s.req.query("type")}),D1)),e.get("/api/external-signals",s=>H(s,Mh(t.dal,{unhandled:s.req.query("unhandled")==="true"}),P1)),e.get("/api/attentions",s=>H(s,fr(t.dal,{unacked:s.req.query("unacked")==="true"}),F1)),e.post("/api/attentions/:id/ack",s=>{let o=t.dal.acknowledgeAttention(re(s,"id"));return o===null?s.notFound():H(s,o,i=>`<p>acknowledged attention ${S(i.id)}</p>`)}),e.get("/api/escalations",s=>{let o=s.req.query("project"),i=s.req.query("all")==="true",a=s.req.query("since"),l={all:i};o!==void 0&&(l.project=o),a!==void 0&&(l.since=a);let c=wi(t.dal,l);return H(s,c,u=>`<h1>Escalations</h1>${pe(["attention_id","project","run","workflow","state","prompt"],u.map(d=>[S(d.attention_id),S(d.project),S(d.run_id),S(d.workflow_name),S(d.state_name),S((d.prompt??"").slice(0,120))]))}`)}),e.get("/api/escalations/:id",s=>{let o=Rt(t.dal,re(s,"id"));return o===null?s.notFound():H(s,o,fe)}),e.post("/api/escalations/:id/respond",async s=>{let o=re(s,"id"),i,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let m=await s.req.json();typeof m.input=="string"&&(i=m.input),m.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let m=await s.req.parseBody().catch(()=>({}));typeof m.input=="string"&&(i=m.input),(m.done==="true"||m.done===!0)&&(a=!0)}if(i===void 0)return s.text("missing input",400);let c=Rt(t.dal,o);if(c===null)return s.notFound();let u=fr(t.dal).find(m=>m.id===o);if(u===void 0)return s.notFound();if(u.kind==="workflow_escalation"){let m=t.dal.resumeEscalation(o,i);if(!m.resumed)return s.json({ok:!1,reason:m.reason},400);Ha(t.daemon);let p=fr(t.dal).find(_=>_.id===o);return s.json({ok:!0,attention_id:o,run_id:m.run.id,decision:i,session_status:"escalation_resumed",acknowledged_at:p?.acknowledged_at??null})}if(u.kind!=="interactive_waiting_operator")return s.json({ok:!1,reason:"wrong_kind",kind:u.kind},400);if(u.acknowledged_at!==null)return s.json({ok:!1,reason:"already_acked"},400);if(c.step_id===null)return s.json({ok:!1,reason:"no_step"},400);let d=t.dal.resumeInteractive(c.step_id,i,a);if(!d.resumed)return s.json({ok:!1,reason:d.reason,step_id:c.step_id},400);let f=t.dal.acknowledgeAttention(o);return Ha(t.daemon),s.json({ok:!0,attention_id:o,step_id:c.step_id,session_status:d.session.status,acknowledged_at:f?.acknowledged_at??null})}),e.get("/api/submitted-prs",s=>{let o=s.req.query("pr_url"),i=s.req.query("status"),a=Lh(t.dal,{status:i,pr_url:o});return H(s,a,U1)}),e.get("/api/submitted-prs/:id",s=>{let o=re(s,"id"),i=$h(t.dal,o);return i===null?s.notFound():H(s,i,W1)}),e.get("/api/sessions",s=>H(s,t.dal.latestSessionSizes(),IT)),e.get("/api/sessions/:team_name/:alias/history",s=>{let o=Ss(s.req.param("team_name"));return H(s,t.dal.sessionSizeHistory(o,s.req.param("alias")),IT)}),e.post("/api/sessions/:team_name/:alias/compact",async s=>{let o=Ss(s.req.param("team_name"));try{let i=await bh(t.dal,o,s.req.param("alias"));return H(s,i,a=>NT("compacted",a.row))}catch(i){if(i instanceof bs)return s.text(i.message,409);throw i}}),e.post("/api/sessions/:team_name/:alias/refresh",async s=>{let o=Ss(s.req.param("team_name")),i=await iu(t.dal,o,s.req.param("alias"));return H(s,i,a=>NT(`refreshed ${a.sessionid}`,a.row))}),e.get("/api/intake/state",s=>H(s,r,AT)),e.post("/api/intake/scan",async s=>(r=await Rn(t.dal),H(s,r,AT))),e.get("/api/stats/run-throughput",s=>H(s,Fh(t.dal),B1)),e.get("/api/daemon/state",s=>H(s,t.daemon?.state??null,q1)),e.post("/api/daemon/cycle",async s=>{if(t.daemon===void 0)return H(s,{disabled:!0},fe);let o=await t.daemon.runCycle();return H(s,{state:t.daemon.state,result:o},fe)}),e.get("/metrics/:project_id",s=>{let o=re(s,"project_id"),i=t.dal.getProject(o);if(i===null)return s.notFound();let a=mu(t.dal,o),l=pu(t.dal,{project_id:o});return s.html($e(`Metrics \u2014 ${i.name}`,H1(i.name,a,l)))}),e.get("/api/metrics/reviewer/:project_id",s=>{let o=re(s,"project_id");if(t.dal.getProject(o)===null)return s.notFound();let i=Gd(s,"since_days");return s.json(mu(t.dal,o,i))}),e.get("/api/metrics/tools/:project_id",s=>{let o=re(s,"project_id");if(t.dal.getProject(o)===null)return s.notFound();let i=Gd(s,"since_days");return s.json(pu(t.dal,{project_id:o,since_days:i}))}),e.post("/api/drift/:id/ack",s=>{let o=t.dal.acknowledgeDriftSignal(re(s,"id"));return o===null?s.notFound():s.json({id:o.id,acknowledged_at:o.acknowledged_at})}),e}function ST(t,e,r){let n=fu(e,re(t,"id"),re(t,"step_id"));return n===null?t.notFound():r(n)}function Ha(t){t!==void 0&&t.runCycle().catch(()=>{})}function H(t,e,r,n=200){return RT(t)?n===200?t.html(r(e)):t.html(r(e),400):new Response(JSON.stringify(e),{status:n,headers:{"Content-Type":"application/json; charset=UTF-8"}})}function RT(t){let e=t.req.header("accept")??"";return e.includes("text/html")&&!e.includes("application/json")}function y1(){let t=process.env.LMCTL_WEBUI_DIST;if(t!==void 0)return qa(`${t}/index.html`)?Kd(t):null;let e="src/serve/webui-dist";if(qa(`${e}/index.html`))return e;let r="dist/serve/webui-dist";if(qa(`${r}/index.html`))return r;let n=p1(d1(h1(import.meta.url)),"webui-dist");return qa(`${n}/index.html`)?Kd(n):null}function Kd(t){if(!m1(t))return t;let e=_1(process.cwd(),t);return e.length===0?".":e}function w1(){return async(t,e)=>{await e(),t.header("Cache-Control","no-store")}}function re(t,e){return Number(t.req.param(e))}function Gd(t,e){let r=t.req.query(e);if(r===void 0)return;let n=Number(r);return Number.isInteger(n)&&n>0?n:void 0}function E1(t){switch(f1(t).toLowerCase()){case".txt":return"text/plain; charset=utf-8";case".md":return"text/markdown; charset=utf-8";case".html":case".htm":return"text/html; charset=utf-8";case".css":return"text/css; charset=utf-8";case".csv":return"text/csv; charset=utf-8";case".json":return"application/json; charset=utf-8";case".xml":return"application/xml; charset=utf-8";case".yaml":case".yml":return"text/yaml; charset=utf-8";case".js":case".mjs":case".cjs":return"text/javascript; charset=utf-8";case".ts":return"text/x-typescript; charset=utf-8";case".log":return"text/plain; charset=utf-8";case".docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case".xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case".pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case".pdf":return"application/pdf";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".webp":return"image/webp";case".zip":return"application/zip";case".gz":return"application/gzip";default:return"application/octet-stream"}}function T1(t){return!!(t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/xml"))}async function Un(t){try{let e=await t.req.json();return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:"invalid JSON body"}catch{return"invalid JSON body"}}function b1(t){if(t==null)return null;if(typeof t=="string"){try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return JSON.stringify(e)}catch{return"error:invalid parameters_override JSON"}return"error:parameters_override must be a JSON object"}return typeof t=="object"&&!Array.isArray(t)?JSON.stringify(t):"error:parameters_override must be a JSON object"}function vT(t,e){if(t===void 0||t.length===0)return;let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(r.length!==0){for(let n of r)if(!e.includes(n))return`invalid value: ${n}`;return r}}function v1(t){if(t!=null)return typeof t=="string"&<.includes(t)?t:{error:`invalid severity: ${String(t)}`}}function k1(t){if(t==null)return null;if(typeof t=="string")try{let e=JSON.parse(t);return Array.isArray(e)&&e.every(r=>typeof r=="string")?JSON.stringify(e):"error:labels must be a JSON string array"}catch{return"error:invalid labels JSON"}return Array.isArray(t)&&t.every(e=>typeof e=="string")?JSON.stringify(t):"error:labels must be a JSON string array"}function I1(t){return`<h1>Status</h1><div class="grid">
|
|
2074
2080
|
<div class="metric"><strong>${t.jobs.queued}</strong><br>queued jobs</div>
|
|
2075
2081
|
<div class="metric"><strong>${t.jobs.done}</strong><br>done jobs</div>
|
|
2076
2082
|
<div class="metric"><strong>${t.runs.active}</strong><br>active runs</div>
|
|
2077
2083
|
<div class="metric"><strong>${t.attentions.unacked}</strong><br>unacked attentions</div>
|
|
2078
|
-
</div><p class="muted">generated ${S(t.generated_at)}</p>`}function
|
|
2084
|
+
</div><p class="muted">generated ${S(t.generated_at)}</p>`}function N1(t){return`<h1>Projects</h1>${pe(["id","name","workflow","team","path"],t.map(e=>[S(e.id),S(e.name),S(e.workflow_name),S(e.team_id),S(e.local_path)]))}`}function A1(t){return`<h1>Project Workflows</h1>${pe(["id","workflow","condition","priority","enabled"],t.map(e=>[S(e.id),S(e.workflow_id),S(e.condition),S(e.priority),S(e.enabled)]))}`}function x1(t){return`<h1>Issues</h1>${pe(["id","status","severity","title","ai test"],t.map(e=>[S(e.id),S(e.status),S(e.severity),S(e.title),S(e.ai_test_path)]))}`}function R1(t){return`<h1>Teams</h1>${pe(["id","name","members"],t.map(e=>[S(e.id),S(e.name),S(e.members.map(r=>r.alias).join(", "))]))}`}function L1(t){return`<h1>Workflows</h1>${pe(["id","name","version"],t.map(e=>[S(e.id),`<a href="/workflows/${encodeURIComponent(e.name)}">${S(e.name)}</a>`,S(e.version)]))}`}function $1(t){return`<h1>Jobs</h1>${pe(["id","status","source","source_ref","run"],t.map(e=>[S(e.id),S(e.status),S(e.source),S(e.source_ref),S(e.run_id)]))}`}function O1(t){return`<h1>Runs</h1>${pe(["id","job","current","terminal","started"],t.map(e=>[`<a href="/runs/${e.id}">${S(e.id)}</a>`,S(e.job_id),S(e.current_state),S(e.terminal_state),S(e.started_at)]))}`}function j1(t){let e=C1(t);return`<h1>Run ${S(t.id)}</h1>
|
|
2079
2085
|
${fe({id:t.id,terminal_state:t.terminal_state,current_state:t.current_state,job_id:t.job_id})}
|
|
2080
2086
|
${e}
|
|
2081
2087
|
<h2>Steps</h2>
|
|
2082
|
-
${pe(["id","state","outcome","detail"],t.steps.map(r=>[`<span hx-get="/api/runs/${t.id}/steps/${r.id}" hx-target="#step-${r.id}" hx-swap="innerHTML">${S(r.id)}</span><div id="step-${r.id}"></div>`,S(r.state_name),S(r.outcome),S(r.status_detail)]))}`}function
|
|
2088
|
+
${pe(["id","state","outcome","detail"],t.steps.map(r=>[`<span hx-get="/api/runs/${t.id}/steps/${r.id}" hx-target="#step-${r.id}" hx-swap="innerHTML">${S(r.id)}</span><div id="step-${r.id}"></div>`,S(r.state_name),S(r.outcome),S(r.status_detail)]))}`}function C1(t){let e="__paused__:";if(typeof t.current_state!="string"||!t.current_state.startsWith(e)||t.workflow===null)return"";let r=t.current_state.slice(e.length),n;try{n=JSON.parse(t.workflow.definition)}catch{return`<section class="pause"><h2>Paused at ${S(r)}</h2><p>(workflow definition unparseable)</p></section>`}let s=n.states?.[r],o=s?.schema?.outcomes??[];if(o.length===0)return`<section class="pause"><h2>Paused at ${S(r)}</h2><p>(state has no declared outcomes)</p></section>`;let i=typeof s?.prompt=="string"?s.prompt:"",l=[...t.steps].reverse().find(f=>f.state_name===r)?.artifacts.find(f=>f.kind==="pause_context"),c="";if(l?.content!==null&&l?.content!==void 0)try{let f=JSON.parse(l.content);typeof f.prompt=="string"&&(c=f.prompt)}catch{}let u=c!==""?c:i,d=o.map((f,m)=>`<label class="pause-outcome"><input type="radio" name="outcome" value="${S(f)}"${m===0?" checked":""}/> <code>${S(f)}</code></label>`).join(" ");return`<section class="pause" id="pause-section" style="border:2px solid #d28e00;background:#fff8e6;padding:1em;margin:1em 0;">
|
|
2083
2089
|
<h2 style="margin-top:0;">\u2605 Paused at <code>${S(r)}</code> \u2014 operator decision required</h2>
|
|
2084
2090
|
${u!==""?`<blockquote style="border-left:3px solid #888;padding-left:0.8em;margin-left:0;color:#444;white-space:pre-wrap;">${S(u)}</blockquote>`:""}
|
|
2085
2091
|
<form hx-post="/api/runs/${S(t.id)}/resume" hx-target="#pause-result" hx-swap="innerHTML">
|
|
@@ -2090,11 +2096,11 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2090
2096
|
</fieldset>
|
|
2091
2097
|
</form>
|
|
2092
2098
|
<div id="pause-result" style="margin-top:0.6em;"></div>
|
|
2093
|
-
</section>`}function
|
|
2099
|
+
</section>`}function M1(t){return`<section><h3>${S(t.state_name)}</h3>${fe(t)}<p><a hx-get="/api/runs/${t.run_id}/steps/${t.id}/transcript" hx-target="closest section" hx-swap="beforeend">Transcript</a> <a hx-get="/api/runs/${t.run_id}/steps/${t.id}/messages" hx-target="closest section" hx-swap="beforeend">Messages</a></p></section>`}function kT(t){return t.resumed?`<p>resumed run ${S(t.run.id)}</p>`:`<p>resume failed: ${S(t.reason)}</p>`}function D1(t){return`<h1>External Objects</h1>${pe(["id","type","provider","external_id","status","url"],t.map(e=>[S(e.id),S(e.type),S(e.provider),S(e.external_id),S(e.status),S(e.url)]))}`}function P1(t){return`<h1>External Signals</h1>${pe(["id","object","kind","handled"],t.map(e=>[S(e.id),S(e.object_id),S(e.kind),S(e.handled_at)]))}`}function F1(t){let e=`<style>
|
|
2094
2100
|
@keyframes attn-flicker { 0%,100%{background:#fff8e6;} 50%{background:#ffd766;} }
|
|
2095
2101
|
tr.requires-user { animation: attn-flicker 1.4s ease-in-out infinite; font-weight:600; }
|
|
2096
2102
|
tr.requires-user td:first-child::before { content:"\u2605 "; color:#d28e00; }
|
|
2097
|
-
</style>`,r=t.map(n=>{let s=(n.requires_user??0)===1&&n.acknowledged_at===null,o=n.run_id!==null?`<a href="/runs/${S(n.run_id)}">${S(n.id)}</a>`:S(n.id),i=n.acknowledged_at===null?`<button hx-post="/api/attentions/${n.id}/ack" hx-swap="outerHTML">Ack</button>`:S(n.acknowledged_at),a=[o,S(n.kind),S(n.severity),i];return`<tr${s?' class="requires-user"':""}>${a.map(l=>`<td>${l}</td>`).join("")}</tr>`}).join("");return`<h1>Attentions</h1>${e}<table><thead><tr><th>id</th><th>kind</th><th>severity</th><th>ack</th></tr></thead><tbody>${r}</tbody></table>`}function
|
|
2103
|
+
</style>`,r=t.map(n=>{let s=(n.requires_user??0)===1&&n.acknowledged_at===null,o=n.run_id!==null?`<a href="/runs/${S(n.run_id)}">${S(n.id)}</a>`:S(n.id),i=n.acknowledged_at===null?`<button hx-post="/api/attentions/${n.id}/ack" hx-swap="outerHTML">Ack</button>`:S(n.acknowledged_at),a=[o,S(n.kind),S(n.severity),i];return`<tr${s?' class="requires-user"':""}>${a.map(l=>`<td>${l}</td>`).join("")}</tr>`}).join("");return`<h1>Attentions</h1>${e}<table><thead><tr><th>id</th><th>kind</th><th>severity</th><th>ack</th></tr></thead><tbody>${r}</tbody></table>`}function U1(t){return`<h1>Submitted PRs</h1>${pe(["id","repo","pr","status","last state","submitted","last scan"],t.map(e=>[`<a href="/api/submitted-prs/${S(e.id)}">${S(e.id)}</a>`,S(e.repo),`<a href="${S(e.pr_url)}" target="_blank" rel="noreferrer">${S(e.pr_url.replace(/^https:\/\/github\.com\//,""))}</a>`,S(e.status),S(e.last_known_state??""),S(e.submitted_at),S(e.last_scanned_at??"")]))}`}function W1(t){return t===null?"<p>not found</p>":`<h1>PR ${S(t.id)}</h1><dl>
|
|
2098
2104
|
<dt>repo</dt><dd>${S(t.repo)}</dd>
|
|
2099
2105
|
<dt>pr</dt><dd><a href="${S(t.pr_url)}" target="_blank" rel="noreferrer">${S(t.pr_url)}</a></dd>
|
|
2100
2106
|
<dt>issue</dt><dd>${t.issue_url===null?"\u2014":`<a href="${S(t.issue_url)}" target="_blank" rel="noreferrer">${S(t.issue_url)}</a>`}</dd>
|
|
@@ -2104,7 +2110,7 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2104
2110
|
<dt>submitted_at</dt><dd>${S(t.submitted_at)}</dd>
|
|
2105
2111
|
<dt>last_scanned_at</dt><dd>${S(t.last_scanned_at??"\u2014")}</dd>
|
|
2106
2112
|
<dt>last_known_state</dt><dd>${S(t.last_known_state??"\u2014")}</dd>
|
|
2107
|
-
</dl>`}function IT(t){return`<h1>Sessions</h1>${pe(["team","alias","session","input","cache","output","total","observed","actions"],t.map(e=>{let r=ui(e.team_name),n=encodeURIComponent(e.alias);return[S(e.team_name),S(e.alias),S(e.sessionid),S(e.input_tokens),S(e.cache_tokens),S(e.output_tokens),S(e.total_tokens),S(e.observed_at),`<button hx-post="/api/sessions/${r}/${n}/compact" hx-swap="outerHTML">Compact</button> <button hx-post="/api/sessions/${r}/${n}/refresh" hx-swap="outerHTML">Refresh</button>`]}))}`}function NT(t,e){return e===null?`<span>${S(t)}</span>`:`<span>${S(t)} ${S(e.team_name)}/${S(e.alias)}</span>`}function
|
|
2113
|
+
</dl>`}function IT(t){return`<h1>Sessions</h1>${pe(["team","alias","session","input","cache","output","total","observed","actions"],t.map(e=>{let r=ui(e.team_name),n=encodeURIComponent(e.alias);return[S(e.team_name),S(e.alias),S(e.sessionid),S(e.input_tokens),S(e.cache_tokens),S(e.output_tokens),S(e.total_tokens),S(e.observed_at),`<button hx-post="/api/sessions/${r}/${n}/compact" hx-swap="outerHTML">Compact</button> <button hx-post="/api/sessions/${r}/${n}/refresh" hx-swap="outerHTML">Refresh</button>`]}))}`}function NT(t,e){return e===null?`<span>${S(t)}</span>`:`<span>${S(t)} ${S(e.team_name)}/${S(e.alias)}</span>`}function B1(t){return`<h1>Run Throughput</h1>${pe(["workflow","terminal","count"],t.map(e=>[S(e.workflow_name),S(e.terminal_state),S(e.count)]))}`}function AT(t){return`<h1>Intake</h1><button hx-post="/api/intake/scan" hx-target="main" hx-swap="innerHTML">Scan now</button>${pe(["project","scanned","new jobs","error"],t.map(e=>[S(e.project_name),S(e.scanned),S(e.new_jobs),S(e.error)]))}`}function q1(t){return`<h1>Daemon</h1>${t===null?"<p>disabled</p>":`${fe(t)}<button hx-post="/api/daemon/cycle" hx-target="main" hx-swap="beforeend">Run cycle now</button>`}`}function H1(t,e,r){let n=e.request_changes_rate,s=n.by_state.map(l=>[S(l.state_name),S(l.total),S(l.request_changes),S(l.rate_pct)]),o=e.step_duration_histogram.map(l=>[S(l.state_name),S(l.lt_5min),S(l.btw_5_15min),S(l.btw_15_60min),S(l.gt_60min),S(l.no_end)]),i=e.retry_counts.map(l=>[S(l.state_name),S(l.retried_runs),S(l.avg_retries)]),a=r.map(l=>[S(l.tool_name),S(l.invocations),S(l.successes),S(l.hit_rate_pct),S(l.avg_latency_ms??"n/a"),S(l.p50_latency_ms??"n/a"),S(l.p95_latency_ms??"n/a")]);return`<h1>Metrics \u2014 ${S(t)}</h1>
|
|
2108
2114
|
<h2>Request-changes rate</h2>
|
|
2109
2115
|
<p>Total: ${S(n.request_changes)} of ${S(n.total)} steps (${S(n.rate_pct)})</p>
|
|
2110
2116
|
${pe(["state","total steps","request_changes","rate"],s)}
|
|
@@ -2113,13 +2119,13 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2113
2119
|
<h2>Retry counts (runs with >1 attempt per state)</h2>
|
|
2114
2120
|
${pe(["state","retried runs","avg attempts"],i)}
|
|
2115
2121
|
<h2>Tool efficacy</h2>
|
|
2116
|
-
${pe(["tool","invocations","successes (status=ok)","hit rate","avg latency ms","p50 ms","p95 ms"],a)}`}var
|
|
2122
|
+
${pe(["tool","invocations","successes (status=ok)","hit rate","avg latency ms","p50 ms","p95 ms"],a)}`}var S1,LT,$T=T(()=>{"use strict";oa();kn();vy();Ry();Dy();Jt();ld();NE();CE();WE();KE();eT();nT();gT();di();bT();ba();S1=["open","assigned","closed","reopened"],LT=["low","medium","high","critical"]});function J1(t){return Math.floor(t/6e4)*6e4}function X1(t){t.db.transaction(()=>{let e=t.getRollupCursor(),r=t.listSessionEventsSince(e);if(r.length!==0){for(let n of r)G1(t,n);t.setRollupCursor(r[r.length-1].id)}})()}function G1(t,e){let r=Date.now(),n=J1(e.timestamp_ms),s=n+6e4;if(e.kind==="tool_use"){t.addRollupValue({run_id:e.run_id,step_id:e.step_id,metric_kind:"tool_calls_count",value:1,bucket_start_ms:n,bucket_end_ms:s,updated_at:r});return}if(e.kind==="tool_result"){let o={};try{o=JSON.parse(e.payload)}catch{}let i=typeof o.elapsedMs=="number"&&o.elapsedMs>0?o.elapsedMs:0;i>0&&t.addRollupValue({run_id:e.run_id,step_id:e.step_id,metric_kind:"time_in_tool_use_ms",value:i,bucket_start_ms:n,bucket_end_ms:s,updated_at:r});return}if(e.kind==="text"){let o=Buffer.byteLength(e.payload,"utf8");t.addRollupValue({run_id:e.run_id,step_id:e.step_id,metric_kind:"message_delta_bytes",value:o,bucket_start_ms:n,bucket_end_ms:s,updated_at:r})}}function OT(t,e=250){let r=setInterval(()=>{try{X1(t)}catch{}},e);return{stop(){clearInterval(r)}}}var jT=T(()=>{"use strict"});function V1({dal:t}){let e=t.listProjects();for(let r of e){let n=t.query(`SELECT r.id, r.team_id
|
|
2117
2123
|
FROM run r
|
|
2118
2124
|
JOIN job j ON j.id = r.job_id
|
|
2119
2125
|
WHERE j.project_id = ?
|
|
2120
2126
|
AND r.terminal_state IS NOT NULL
|
|
2121
2127
|
ORDER BY r.id DESC
|
|
2122
|
-
LIMIT ?`,r.id,3);if(n.length<3||!n.every(l=>t.query("SELECT 1 FROM step WHERE run_id = ? AND outcome = ? LIMIT 1",l.id,KF).length>0))continue;let o=n[0].team_id,i=t.listTeamMembers(o),a=i.find(l=>l.alias.toLowerCase().includes("coder"))??i[0];a!==void 0&&(t.hasUnackedDriftSignal(a.id,r.id,CT)||t.insertDriftSignal({team_member_id:a.id,project_id:r.id,signal_kind:CT,severity:"high",description:`3+ consecutive reviewer rejections (request_changes) for project ${r.name}`,detected_at:Date.now(),payload:JSON.stringify({run_ids:n.map(l=>l.id),consecutive_threshold:3})}))}}function MT(t){for(let e of YF)try{e(t)}catch{}}var KF,CT,YF,DT=T(()=>{"use strict";KF="request_changes",CT="reviewer_rejection_rate_high";YF=[VF]});function Ys(){let t=process.env.LMCTL_DAEMON_INTERVAL_MS;if(t===void 0||t.trim().length===0)return 5e3;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e3}function PT(t){let e=t.intervalMs??Ys(),r=t.runOnceFn??qr,n={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,cycles:0,jobs_processed:0,last_jobs_processed:0,last_started_at:null,last_finished_at:null,last_error:null,last_session_sizes_recorded:0,last_session_size_failures:0,last_intake_scanned:0,last_intake_new_jobs:0,last_intake_failures:0,last_session_hung_detected:0,last_session_monitor_checked_at:null,last_session_monitor_error:null},s=null,o=null,i=null,a=null,l=null;t.startRollupUpdaterFn!==!1&&(l=(t.startRollupUpdaterFn??OT)(t.dal));let c=f=>{n.running&&(s=setTimeout(()=>{d.runCycle().finally(()=>c(e))},f))},u=f=>{n.running&&(o=setTimeout(()=>{a===null&&(a=FT(t.dal,t.monitorSessionActivityFn??au,e,n).finally(()=>{a=null})),a.finally(()=>u(lu(t.dal,e)))},f))},d={state:n,runCycle:async()=>(i!==null||(i=zF(t.dal,r,t.collectSessionSizesFn??Th,t.scanIntakeFn??Rn,t.monitorSessionActivityFn??au,t.worker_id??"daemon",e,n).finally(()=>{i=null})),i),stop:async()=>{n.running=!1,s!==null&&clearTimeout(s),o!==null&&clearTimeout(o),l?.stop(),i!==null&&await i.catch(()=>{}),a!==null&&await a.catch(()=>{})}};if(n.running){let f=t.firstDelayMs??5e3;c(f),u(f)}return d}async function zF(t,e,r,n,s,o,i,a){a.in_flight=!0,a.last_started_at=new Date().toISOString(),a.last_error=null;let l=[],c=0,u=0,d=[],f=null;try{for(cE({dal:t}),MT({dal:t}),d=await n(t);;){let p=await e({dal:t,worker_id:o,lease_ms:6e5});if(p===null)break;l.push(p)}let m=await r(t);c=m.recorded,u=m.failed,f=await FT(t,s,i,a)}catch(m){a.last_error=m instanceof Error?m.message:String(m);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:a.last_error})})}catch{}}finally{a.in_flight=!1,a.cycles+=1,a.last_jobs_processed=l.length,a.last_session_sizes_recorded=c,a.last_session_size_failures=u,a.last_intake_scanned=d.reduce((m,p)=>m+p.scanned,0),a.last_intake_new_jobs=d.reduce((m,p)=>m+p.new_jobs,0),a.last_intake_failures=d.filter(m=>m.error!==void 0).length,a.last_session_hung_detected=f?.hung_detected??0,a.jobs_processed+=l.length,a.last_finished_at=new Date().toISOString()}return{jobs_processed:l.length,outcomes:l,session_sizes_recorded:c,session_size_failures:u,intake:d,session_monitor:f}}async function FT(t,e,r,n){let s=lu(t,r),o=Date.now();if(n.last_session_monitor_checked_at!==null){let i=Date.parse(n.last_session_monitor_checked_at);if(Number.isFinite(i)&&o-i<s)return null}n.last_session_monitor_checked_at=new Date(o).toISOString(),n.last_session_monitor_error=null;try{return await e({dal:t,nowMs:o})}catch(i){n.last_session_monitor_error=i instanceof Error?i.message:String(i);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:n.last_session_monitor_error})})}catch{}return null}}var Vd=T(()=>{"use strict";oa();Ks();kd();di();jT();DT();cu()});function UT(t){let e=t.listMembersInState("in_chat");for(let r of e)t.setMemberState(r.id,"attention_needed","daemon_restarted_mid_chat");return e.length}var WT=T(()=>{"use strict"});import{mkdirSync as ZF,readFileSync as QF,readdirSync as eU,statSync as tU,writeFileSync as rU}from"node:fs";import{dirname as nU,join as qT,sep as BT}from"node:path";function Ja(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case HT:return sU(t,s.input);case JT:return oU(t,s.input);case XT:return iU(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:Zd,GetObjectCommand:zd,PutObjectCommand:Yd}}}function sU(t,e){let r=GT(t,e.Key);return ZF(nU(r),{recursive:!0}),rU(r,e.Body),{}}function oU(t,e){let r=GT(t,e.Key),n;try{n=QF(r)}catch(o){throw o.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):o}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function iU(t,e){let r=e.Prefix??"";KT(r);let s=aU(t).sort((u,d)=>u.key<d.key?-1:u.key>d.key?1:0).filter(u=>u.key.startsWith(r)),o=e.ContinuationToken;o!==void 0&&o!==""&&(s=s.filter(u=>u.key>o));let i=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;i!==void 0&&s.length>i&&(a=s.slice(0,i),l=!0);let c={Contents:a.map(u=>({Key:u.key,LastModified:u.lastModified})),IsTruncated:l};return l&&(c.NextContinuationToken=a[a.length-1].key),c}function GT(t,e){return KT(e),qT(t,e)}function KT(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function aU(t){let e=[],r=(n,s)=>{let o;try{o=eU(n,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of o){let a=s===""?i.name:`${s}/${i.name}`,l=qT(n,i.name);if(i.isDirectory())r(l,a);else if(i.isFile()){let c=BT==="/"?a:a.split(BT).join("/");e.push({key:c,lastModified:tU(l).mtime})}}};return r(t,""),e}var HT,JT,XT,Yd,zd,Zd,Qd=T(()=>{"use strict";HT="localfs-put",JT="localfs-get",XT="localfs-list",Yd=class{input;_localfsTag=HT;constructor(e){this.input=e}},zd=class{input;_localfsTag=JT;constructor(e){this.input=e}},Zd=class{input;_localfsTag=XT;constructor(e){this.input=e}}});function VT(){return{put:0,get:0,list:0}}function ef(t,e=lU){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function tf(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var lU,Xa,rf=T(()=>{"use strict";lU={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};Xa=class{counts=VT();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=VT(),e}estimateCostUsd(e){return ef(this.counts,e)}}});function YT(t){let e=t.now??Date.now,r=t.timers??cU,n=null,s=null;async function o(){let l=e(),c=tf(l),u=t.meter.drain();(u.put>0||u.get>0||u.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:c,put:u.put,get:u.get,list:u.list,updated_at:new Date(l).toISOString()});let d=t.store.loadUsage(t.userId,t.deviceId,c),f=d?{put:d.put_count,get:d.get_count,list:d.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(c,f)}catch(_){t.log?.(`[usage] publish rollup failed: ${_ instanceof Error?_.message:String(_)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(c)}catch(_){t.log?.(`[usage] read user total failed: ${_ instanceof Error?_.message:String(_)}`),m=f}let p=ef(m);if(n!==c&&p>=t.ceilingUsd){n=c,t.log?.(`[usage] quota exceeded period=${c} cost=$${p.toFixed(4)} >= ceiling $${t.ceilingUsd}`);try{t.onQuotaExceeded({period:c,costUsd:p,ceilingUsd:t.ceilingUsd})}catch(_){t.log?.(`[usage] onQuotaExceeded threw: ${_ instanceof Error?_.message:String(_)}`)}}}function i(){return s=(s??Promise.resolve()).then(()=>o()).catch(()=>{}),s}let a=r.setInterval(()=>{i()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return i()},isOverQuota(){return n!==null&&n===tf(e())}}}var cU,zT=T(()=>{"use strict";rf();cU={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var nf=T(()=>{"use strict";xa();La();La()});function uU(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.message_id!="string"||e.message_id==="")return null;if(typeof e.reply_to=="string"&&e.reply_to!==""){let s=e.response;if(typeof s!="object"||s===null)return null;let o=s;return typeof o.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:o}}let r=e.request;if(typeof r!="object"||r===null)return null;let n=r;return typeof n.method!="string"||n.method===""||typeof n.path!="string"||n.path===""?null:{message_id:e.message_id,request:n}}function dU(t){return t.reply_to!==void 0&&t.response!==void 0}function fU(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function ZT(t){let e=t.reason;if(e!==void 0)return e;try{return new DOMException("Aborted","AbortError")}catch{let r=new Error("Aborted");return r.name="AbortError",r}}var Ga,zs,QT=T(()=>{"use strict";nf();Ga=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},zs=class{client;log;now;random;pending=new Map;requestHandler=null;stopped=!1;constructor(e){this.client=e.client,this.log=e.log??(()=>{}),this.now=e.now??Date.now,this.random=e.random??Math.random}onRequest(e){if(this.requestHandler!==null)throw new Error("MailboxFetchClient: onRequest handler already registered");this.requestHandler=e}async fetch(e,r){if(this.stopped)throw new Ga("MailboxFetchClient.fetch after stop()");if(typeof e.path!="string"||e.path==="")throw new Error("MailboxFetchClient.fetch: request.path is required");let n=e.method;if(typeof n!="string"||n==="")throw new Error("MailboxFetchClient.fetch: request.method is required");let s=Zt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let o=r?.conversationId??s,i={message_id:s,request:e};return new Promise((a,l)=>{let c=r?.abortSignal,u;if(c!==void 0){if(c.aborted){l(ZT(c));return}u=()=>{this.pending.has(s)&&(this.pending.delete(s),l(ZT(c)))},c.addEventListener("abort",u,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...u!==void 0?{abortListener:u}:{},...c!==void 0?{abortSignal:c}:{}}),this.client.putMessage({conversation_id:o,payload:i}).catch(d=>{let f=this.pending.get(s);f!==void 0&&(this.pending.delete(s),f.abortListener!==void 0&&f.abortSignal!==void 0&&f.abortSignal.removeEventListener("abort",f.abortListener),f.reject(d))})})}async stop(){if(this.stopped)return;this.stopped=!0;let e=Array.from(this.pending.values());this.pending.clear();let r=new Ga;for(let n of e){n.abortListener!==void 0&&n.abortSignal!==void 0&&n.abortSignal.removeEventListener("abort",n.abortListener);try{n.reject(r)}catch{}}}async handleIncoming(e,r){let n=uU(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(dU(n)){let l=this.pending.get(n.reply_to);if(l===void 0){this.log(`MailboxFetchClient: dropping response for unknown reply_to=${n.reply_to}`);return}this.pending.delete(n.reply_to),l.abortListener!==void 0&&l.abortSignal!==void 0&&l.abortSignal.removeEventListener("abort",l.abortListener),l.resolve(n.response);return}if(this.requestHandler===null){this.log(`MailboxFetchClient: no handler registered; dropping request message_id=${n.message_id}`);return}let s=r?.conversation_id??fU(e)??n.message_id,o;try{o=await this.requestHandler(n.request)}catch(l){let c=l instanceof Error?l.message:String(l),u=typeof l.code=="string"?l.code:"INTERNAL_ERROR";o={status:500,headers:{"content-type":"application/json"},body:{error:u,message:c}}}let a={message_id:Zt(this.now(),this.random),reply_to:n.message_id,response:o};try{await this.client.putMessage({conversation_id:s,payload:a})}catch(l){this.log(`MailboxFetchClient: response PUT failed for reply_to=${n.message_id}: ${l instanceof Error?l.message:String(l)}`)}}}});function sf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return!(e.kind!=="terminal"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.data!="string"||typeof e.ts!="number")}var eb=T(()=>{"use strict"});function of(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="provider"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.ts!="number")return!1;if(e.direction==="agent_to_user"){if(!Array.isArray(e.events))return!1;for(let r of e.events)if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.event_type!="string")return!1}else if(typeof e.user_input!="string")return!1;return!0}var tb=T(()=>{"use strict"});function lf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="daemon_event"||typeof e.event!="string"||e.event===""||typeof e.ts!="number")return!1;if(e.event==="workflows"){if(!Array.isArray(e.workflows))return!1;for(let r of e.workflows){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let n=r;if(typeof n.teamfile_path!="string"||n.teamfile_path===""||n.name!==null&&typeof n.name!="string"||typeof n.registered_at!="string"||n.registered_at===""||n.last_seeded_at!==null&&typeof n.last_seeded_at!="string")return!1}}else if(e.event==="chat_log"){if(typeof e.entry!="object"||e.entry===null||Array.isArray(e.entry))return!1;let r=e.entry;if(typeof r.id!="number"||typeof r.root_teamfile!="string"||r.root_teamfile===""||r.sender_teamfile!==null&&(typeof r.sender_teamfile!="string"||r.sender_teamfile==="")||r.sender_alias!==null&&(typeof r.sender_alias!="string"||r.sender_alias==="")||typeof r.receiver_teamfile!="string"||r.receiver_teamfile===""||typeof r.receiver_alias!="string"||r.receiver_alias===""||typeof r.message!="string"||r.response!==null&&typeof r.response!="string"||typeof r.status!="string"||r.status===""||typeof r.created_at!="string"||r.created_at==="")return!1}return!0}var af,rb=T(()=>{"use strict";af="daemon:events"});function sb(t){return{kind:"prompt",prompt_id:t.prompt_id??Zt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function cf(t){if(t===null||typeof t!="object")return!1;let e=t;return e.kind==="prompt"&&typeof e.prompt_id=="string"&&e.prompt_id.length>0&&typeof e.root_teamfile=="string"&&e.root_teamfile.length>0&&typeof e.text=="string"}var nb,uf=T(()=>{"use strict";nf();nb="prompt:root"});function Zs(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(ib(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function mU(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(ib(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function ob(t,e=60){if(typeof t!="string"||t==="")return!0;let r=mU(t);return r===null?!0:Date.now()/1e3>=r-e}function ib(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=globalThis.Buffer;return n!==void 0?n.from(r,"base64").toString("utf8"):atob(r)}var df=T(()=>{"use strict"});async function Ka(t){let e=t.fetchImpl??fetch,r=`https://cognito-idp.${t.region}.amazonaws.com/`,n=await e(r,{method:"POST",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":pU},body:JSON.stringify({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:t.clientId,AuthParameters:{REFRESH_TOKEN:t.refreshToken}})}),s=await n.text();if(!n.ok){let l=s;try{let c=JSON.parse(s);l=c.message??c.__type??s}catch{}throw new Error(`cognito_refresh_failed: ${n.status} ${l}`)}let i=JSON.parse(s).AuthenticationResult,a=i?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof i?.AccessToken=="string"&&i.AccessToken!==""?{accessToken:i.AccessToken}:{},...typeof i?.ExpiresIn=="number"&&Number.isFinite(i.ExpiresIn)?{expiresAt:Date.now()+i.ExpiresIn*1e3}:{}}}var pU,ff=T(()=>{"use strict";pU="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as ab,mkdirSync as lb,readFileSync as cb,writeFileSync as ub}from"node:fs";import{homedir as db}from"node:os";import{dirname as fb,join as mb}from"node:path";function Qs(){return process.env.LMCTL_DEVICE_AUTH_PATH??mb(db(),".lmctl","device-auth.json")}function pb(){return process.env.LMCTL_TOKEN_PATH??mb(db(),".lmctl","cli-tokens.json")}function mf(t=Qs()){try{let e=JSON.parse(cb(t,"utf8"));return typeof e.userId!="string"||e.userId===""||typeof e.refreshToken!="string"||e.refreshToken===""?null:{userId:e.userId,refreshToken:e.refreshToken}}catch{return null}}function _b(t,e=Qs()){lb(fb(e),{recursive:!0,mode:448}),ub(e,JSON.stringify(t,null,2));try{ab(e,384)}catch{}}function pf(t,e=pb()){let r={};try{r=JSON.parse(cb(e,"utf8"))}catch{}let n={...r.cognito??{}};n.idToken=t.idToken,t.accessToken!==void 0&&(n.accessToken=t.accessToken),t.refreshToken!==void 0&&(n.refreshToken=t.refreshToken),t.expiresAt!==void 0&&(n.expiresAt=t.expiresAt);let s={...r,cognito:n};lb(fb(e),{recursive:!0,mode:448}),ub(e,JSON.stringify(s,null,2));try{ab(e,384)}catch{}}async function hb(t){let e=t.deviceAuthPath??Qs(),r=mf(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await Ka({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return pf({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??pb()),{idToken:n.idToken,userId:r.userId}}var _f=T(()=>{"use strict";ff()});import{existsSync as _U,realpathSync as hU}from"node:fs";import{dirname as gU}from"node:path";function hf(t){yU(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function yU(t){let e=t.payload.root_teamfile;try{e=hU(t.payload.root_teamfile)}catch(s){let o=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${s instanceof Error?s.message:String(s)}`;return await Wn(t.store,{rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:o,log:t.log}),t.log?.(`[mailbox] ${o}`),{status:"error",response:null,error_detail:o}}if(t.store.getRootTeam(e)===null){let s=`prompt root is not registered: ${e}`;return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:s,log:t.log}),t.log?.(`[mailbox] ${s}`),{status:"error",response:null,error_detail:s}}let r=wU(e);if("error"in r)return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:r.error,log:t.log}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=nr(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:bU(t.env??process.env)});if(!n.acquired){let s=TU(r.alias,n.current);return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:null,status:"error",error_detail:s,log:t.log}),t.log?.(`[mailbox] prompt rejected: ${s}`),{status:"error",response:null,error_detail:s}}try{let o=await(t.chat??Ht)({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,prompt:t.payload.text,env:t.env??process.env,alias:r.alias,permissionMode:"yolo",...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}),i=o.status==="stalled",a=!i&&o.text.trim()==="",l=i?`provider stalled${o.stalledAfterMs!==void 0?` after ${o.stalledAfterMs}ms`:""}`:a?"provider returned empty response":null,c=i||a?"error":"ok";return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:c==="error"?null:o.text,status:c,error_detail:l,log:t.log}),{status:c,response:c==="error"?null:o.text,error_detail:l}}catch(s){let o=s instanceof Error?s.message:String(s);return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:null,status:"error",error_detail:o,log:t.log}),t.log?.(`[mailbox] prompt provider error: ${o}`),{status:"error",response:null,error_detail:o}}finally{try{t.store.releaseAgentInflight(n.lease)}catch(s){t.log?.(`[mailbox] failed to release prompt in-flight slot: ${s instanceof Error?s.message:String(s)}`)}}}function wU(t){if(!_U(t))return{error:`prompt root missing/unreadable: ${t}`};let e=De(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=et(e);return r===void 0?{error:`prompt root has no Lead: ${t}`}:r.session===void 0||r.session.trim()===""?{error:`prompt root Lead is unseeded: ${t}`}:{alias:r.alias,provider:r.provider,sessionid:r.session,sessiondir:r.sessiondir??gU(t)}}async function Wn(t,e){let r=wb(e.message),n=e.response===null?null:wb(e.response);try{t.insertTeamChatLog({root_teamfile:e.rootTeamfile,sender_teamfile:e.rootTeamfile,sender_alias:"operator",receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,message:r.text,response:n?.text??null,origin:"unknown",status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()})}catch(s){e.log?.(`[mailbox] warning: failed to record prompt chat log: ${s instanceof Error?s.message:String(s)}`)}}function wb(t){return t.length<=gb?{text:t,truncated:!1}:{text:t.slice(0,gb),truncated:!0}}function EU(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function TU(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:EU(t,e)}function bU(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return yb;let r=Number(e);return!Number.isFinite(r)||r<=0?yb:r}var gb,yb,Eb=T(()=>{"use strict";At();vt();es();gb=256*1024,yb=30*60*1e3});import{chmodSync as Ib,existsSync as SU,mkdirSync as Nb,readFileSync as Za,writeFileSync as Ab}from"node:fs";import{dirname as gf,resolve as Va,join as xb}from"node:path";import{fileURLToPath as vU}from"node:url";import{homedir as Rb}from"node:os";import{CognitoIdentityClient as kU,GetIdCommand as IU}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as Tb}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as NU,ListObjectsV2Command as AU,PutObjectCommand as xU,S3Client as bb}from"@aws-sdk/client-s3";function to(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:jU(t.selfUrl),n={},s;for(let x of r)if(SU(x)){n=OU(x),s=x;break}let o=(...x)=>{for(let k of x)if(typeof k=="string"&&k!=="")return k},i=o(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??RU,a=o(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??LU,l=o(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??$U,c=o(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",u=o(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Qa,d=[];i===void 0&&d.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&d.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&d.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:d,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(d.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,_=za(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=za(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),h=za(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),E=za(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),w=o(e.LMCTL_MAILBOX_KEY),v=o(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:i,cognitoUserPoolId:a,cognitoClientId:u,region:c,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},..._!==void 0?{readIntervalMs:_}:{},...g!==void 0?{heartbeatIdleMs:g}:{},...h!==void 0?{backoffReadIntervalMs:h}:{},...E!==void 0?{chatLogPollIntervalMs:E}:{},...w!==void 0?{mailboxKey:w}:{},...v!==void 0?{tokenPath:v}:{}},f}function OU(t){try{let e=Za(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[o,i]of Object.entries(n))i!==null&&typeof i=="object"&&typeof i.value=="string"&&(s[o]=i.value);return s}catch{return{}}}function jU(t){let e=gf(vU(t??import.meta.url));return[Va(e,"..","..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","infra","terraform","terraform.tfstate")]}function za(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function CU(t){let e=MU(t.intervalMs)??Lb,r=Math.max(1,Math.trunc(t.limit??500)),n=t.now??Date.now,s=t.cursorKey!==void 0&&t.store.loadTeamChatLogCursor!==void 0&&t.store.saveTeamChatLogCursor!==void 0?{key:t.cursorKey,load:t.store.loadTeamChatLogCursor.bind(t.store),save:t.store.saveTeamChatLogCursor.bind(t.store)}:null,o,i=!1,a=!1,l=()=>{try{if(s!==null){let d=s.load(s.key);if(d!==null)return o=d.last_pushed_id,!0}return o=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:o,updated_at:new Date(n()).toISOString()}),!0}catch(d){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${d instanceof Error?d.message:String(d)}`),!1}};l();let c=async()=>{if(!(a||i)){i=!0;try{if(o===void 0&&!l())return;let d=t.store.listTeamChatLogSinceId(o,r);for(let f of d){let m={kind:"daemon_event",event:"chat_log",ts:n(),entry:{id:f.id,root_teamfile:f.root_teamfile,sender_teamfile:f.sender_teamfile,sender_alias:f.sender_alias,receiver_teamfile:f.receiver_teamfile,receiver_alias:f.receiver_alias,message:f.message,response:f.response,status:f.status,created_at:f.created_at}};await t.publishDaemonEvent(m),s!==null&&s.save({cursor_key:s.key,last_pushed_id:f.id,updated_at:new Date(n()).toISOString()}),o=Math.max(o,f.id)}}catch(d){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${d instanceof Error?d.message:String(d)}`)}finally{i=!1}}},u=setInterval(()=>{c()},e);return typeof u.unref=="function"&&u.unref(),{pollNow:c,stop(){a=!0,clearInterval(u)}}}function MU(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function $b(t){let e=t.tokenPath??xb(Rb(),".lmctl","cli-tokens.json"),r=vb(t.tokenPath);if(ob(r.cognito?.idToken)&&mf()!==null)try{await hb({region:t.region,clientId:t.cognitoClientId??Qa,cliTokensPath:e}),r=vb(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(A){let J=A instanceof Error?A.message:String(A);t.log?.(`[mx-mailbox] device-auth refresh failed: ${J}`)}if(r.cognito===void 0)throw new Error("agent_mailbox_not_logged_in: ~/.lmctl/cli-tokens.json has no cognito tokens; run `webcli login` or `lmctl device login` first");let n=r.cognito.idToken;if(typeof n!="string"||n==="")throw new Error("agent_mailbox_no_id_token: cli-tokens.json's cognito.idToken is empty; run `webcli login` or `lmctl device login` first");let s=`cognito-idp.${t.region}.amazonaws.com/${t.cognitoUserPoolId}`,o=r.cognito.identityId,i=!1;o===void 0||o===""?o=await kb({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(i=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${o}`));let a=Tb({identityId:o,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bb({region:t.region,credentials:a}),c={ListObjectsV2Command:AU,GetObjectCommand:NU,PutObjectCommand:xU},u=Zs(n),d=u??o,f=t.deviceId,m=Mn({identityId:o,userId:u,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,_;if(p!==void 0){let A=p.loadMailboxCursor(d,m);if(A!==null)_=A.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${_??"(sentinel)"} for user_id=${d}`);else{let J=!1,B=0;for(;!J&&B<2;){B+=1;try{let I=Na(m,"web"),N=0,C;do{let X=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:I,MaxKeys:1e3,...C!==void 0?{ContinuationToken:C}:{}}));for(let q of X.Contents??[]){let P=Aa(q.Key??"",m,"web");P!==void 0&&P>N&&(N=P)}C=X.IsTruncated===!0?X.NextContinuationToken:void 0}while(C!==void 0);_=N,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${N} for user_id=${d}`),J=!0}catch(I){let N=I instanceof Error?I.message:String(I);if(i&&B===1&&FU(I)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${N}); clearing + refreshing`),PU(e),i=!1,o=await kb({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=Tb({identityId:o,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bb({region:t.region,credentials:a}),m=Mn({identityId:o,userId:u,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${N}`);break}}p.saveMailboxCursor({user_id:d,mailbox_key:m,last_processed_version_id:null,last_processed_seq:_??null,last_processed_at:new Date().toISOString()})}}let g=null,h=t.terminalSessionManager,E=t.persistentSessionManager,w=t.promptTriggerStore,v=new Xa,x=new Hr({bucket:t.mailboxBucket,identityId:o,...u!==null?{userId:u}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:c,selfRole:"agent",onS3Op:A=>v.record(A),onMessage:async A=>{if(h!==void 0&&sf(A.payload)){h.onInbound(A.payload);return}if(E!==void 0&&of(A.payload)){await E.onInbound(A.payload);return}if(!lf(A.payload)){if(w!==void 0&&cf(A.payload)){hf({store:w,payload:A.payload,log:t.log});return}g!==null&&await g.handleIncoming(A.payload,A)}},...p!==void 0?{onCursorAdvance:A=>{p.saveMailboxCursor({user_id:d,mailbox_key:m,last_processed_version_id:null,last_processed_seq:A,last_processed_at:new Date().toISOString()})}}:{},..._!==void 0?{cursor:_}:{},...t.pollIntervalMs!==void 0?{pollIntervalMs:t.pollIntervalMs}:{},...t.readIntervalMs!==void 0?{readIntervalMs:t.readIntervalMs}:{},...t.heartbeatIdleMs!==void 0?{heartbeatIdleMs:t.heartbeatIdleMs}:{},...t.backoffReadIntervalMs!==void 0?{backoffReadIntervalMs:t.backoffReadIntervalMs}:{}});g=new zs({client:x,...t.log!==void 0?{log:t.log}:{}}),h!==void 0&&h.setPublish(async A=>x.putMessage({conversation_id:`terminal:${A.session_id}`,payload:A})),E!==void 0&&E.setPublish(async A=>x.putMessage({conversation_id:`provider:${A.session_id}`,payload:A}));let k=A=>x.putMessage({conversation_id:af,payload:A});x.start();let j=t.chatLogTailStore===void 0?void 0:CU({store:t.chatLogTailStore,publishDaemonEvent:k,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??Lb,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let K=t.deviceId??o,U=`${d}/usage/`,$;return $=t.usageStore===void 0?void 0:YT({meter:v,store:t.usageStore,userId:d,deviceId:K,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:A,costUsd:J,ceilingUsd:B})=>{t.log?.(`[usage] month ${A} cost $${J.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),x.stop().catch(()=>{}),$?.stop()},publishOwnRollup:async(A,J)=>{await l.send(new c.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${U}${K}-${A}.json`,Body:JSON.stringify({...J,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async A=>{let J={put:0,get:0,list:0},B;do{let I=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:U,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let N of I.Contents??[]){let C=N.Key??"";if(C.endsWith(`-${A}.json`))try{let X=await l.send(new c.GetObjectCommand({Bucket:t.mailboxBucket,Key:C}));if(X.Body===void 0)continue;let q=JSON.parse(await X.Body.transformToString("utf-8"));J.put+=q.put??0,J.get+=q.get??0,J.list+=q.list??0}catch{}}B=I.IsTruncated===!0?I.NextContinuationToken:void 0}while(B!==void 0);return J},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:o,mailbox:x,fetchClient:g,publishDaemonEvent:k,async stop(){j?.stop(),$!==void 0&&(await $.flushNow().catch(()=>{}),$.stop()),await g.stop().catch(()=>{}),await x.stop().catch(()=>{})}}}async function Ob(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:Ja(t.rootDir),r=Mn({identityId:eo,userId:eo,deviceId:Sb}),n=null,s=t.terminalSessionManager,o=t.persistentSessionManager,i=t.promptTriggerStore,a=new Hr({bucket:"local",identityId:eo,userId:eo,deviceId:Sb,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async c=>{if(s!==void 0&&sf(c.payload)){s.onInbound(c.payload);return}if(o!==void 0&&of(c.payload)){await o.onInbound(c.payload);return}if(!lf(c.payload)){if(i!==void 0&&cf(c.payload)){hf({store:i,payload:c.payload,log:t.log});return}n!==null&&await n.handleIncoming(c.payload,c)}},pollIntervalMs:t.pollIntervalMs??Ya,readIntervalMs:t.readIntervalMs??Ya,heartbeatIdleMs:t.heartbeatIdleMs??Ya,backoffReadIntervalMs:t.backoffReadIntervalMs??Ya});n=new zs({client:a,...t.log!==void 0?{log:t.log}:{}}),s!==void 0&&s.setPublish(async c=>a.putMessage({conversation_id:`terminal:${c.session_id}`,payload:c})),o!==void 0&&o.setPublish(async c=>a.putMessage({conversation_id:`provider:${c.session_id}`,payload:c}));let l=c=>a.putMessage({conversation_id:af,payload:c});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:eo,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function vb(t){let e=t??xb(Rb(),".lmctl","cli-tokens.json");try{let r=Za(e,"utf8");return JSON.parse(r)}catch{return{}}}function DU(t,e){if(e===void 0||e==="")return;let r={};try{let s=Za(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};Nb(gf(t),{recursive:!0,mode:448}),Ab(t,JSON.stringify(n,null,2));try{Ib(t,384)}catch{}}function PU(t){let e={};try{let n=Za(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,Nb(gf(t),{recursive:!0,mode:448}),Ab(t,JSON.stringify(r,null,2));try{Ib(t,384)}catch{}}async function kb(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new kU({region:t.region}).send(new IU({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{DU(t.tokenPath,r.IdentityId),t.log?.(`[mx-mailbox] persisted identityId=${r.IdentityId} to ${t.tokenPath}`)}catch(n){let s=n instanceof Error?n.message:String(n);t.log?.(`[mx-mailbox] WARNING: identityId persist failed (${s}); will redo GetId on next restart`)}return r.IdentityId}function FU(t){if(t===null||typeof t!="object")return!1;let e=t,r=[typeof e.name=="string"?e.name:void 0,typeof e.Code=="string"?e.Code:void 0,typeof e.__type=="string"?e.__type:void 0];for(let s of r)if(s!==void 0&&(s==="NotAuthorizedException"||s==="ResourceNotFoundException"||s==="InvalidIdentityPoolConfigurationException"||s==="ExpiredTokenException"))return!0;let n=typeof e.message=="string"?e.message:"";return!!(n.includes("NotAuthorizedException")||n.includes("Invalid identity pool configuration")||n.includes("Identity")&&n.includes("not found"))}var Lb,Ya,Qa,RU,LU,$U,eo,Sb,yf=T(()=>{"use strict";$a();Qd();rf();zT();QT();eb();tb();rb();uf();xa();df();_f();Eb();Lb=3e3,Ya=1e3,Qa="79u5jhkk46qofog661c9i0bdcs",RU="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",LU="us-east-1_4iUdFggDn",$U="lmctl-next-preview-mailbox-254332045686";eo="local",Sb="local"});import{spawn as bf}from"node:child_process";import{createInterface as jb}from"node:readline";var wf,Ef,Tf,Cb,Mb=T(()=>{"use strict";Bo();ve();wf=class{child;ctx;rl;nextRpcId=1;pending=new Map;threadId;nextLocalTurnId=1;closed=!1;setResumeThreadId(e){this.threadId=e}async start(e,r){this.ctx=r;let n=bf(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=jb({input:n.stdout}),this.rl.on("line",s=>{r.generation===r.currentGeneration()&&this.handleLine(s)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let o=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:o}})}),await this.rpc("initialize",{clientInfo:{name:"lmctl-dt3",title:"lmctl DT-3",version:"0.1.0"},capabilities:{experimentalApi:!1}}),this.notify("initialized",{}),this.threadId!==void 0&&this.threadId!=="")try{await this.rpc("thread/resume",{threadId:this.threadId,approvalPolicy:"never",sandbox:"danger-full-access"}),r.emit({event_type:"thread_started",payload:{thread_id:this.threadId,resumed:!0}})}catch{let o=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,i=typeof o?.id=="string"?o.id:void 0;this.threadId=i,r.emit({event_type:"thread_started",payload:{thread_id:i,resumed:!1}})}else{let o=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,i=typeof o?.id=="string"?o.id:void 0;this.threadId=i,r.emit({event_type:"thread_started",payload:{thread_id:i,resumed:!1}})}return n}async sendTurn(e){if(this.closed)throw new Error("codex_session_closed");if(this.threadId===void 0||this.threadId==="")throw new Error("codex_no_thread_id");let r=`local-${this.nextLocalTurnId++}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});try{let s=(await this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})).result?.turn,o=typeof s?.id=="string"?s.id:void 0;if(o!==void 0){let i=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),i!==void 0&&this.ctx?.turnMap.set(o,i)}}catch(n){throw this.ctx?.turnMap.delete(r),n}}async stop(){if(this.closed=!0,this.rl!==void 0&&(this.rl.close(),this.rl=void 0),this.child?.stdin!==null&&this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}for(let e of this.pending.values())e.reject(new Error("codex_session_stopping"));this.pending.clear()}async rpc(e,r){if(this.child?.stdin===null||this.child===void 0)throw new Error("codex_child_unavailable");return new Promise((n,s)=>{let o=this.nextRpcId++;this.pending.set(o,{resolve:n,reject:s});let i=JSON.stringify({jsonrpc:"2.0",id:o,method:e,params:r});try{this.child.stdin.write(i+`
|
|
2128
|
+
LIMIT ?`,r.id,3);if(n.length<3||!n.every(l=>t.query("SELECT 1 FROM step WHERE run_id = ? AND outcome = ? LIMIT 1",l.id,K1).length>0))continue;let o=n[0].team_id,i=t.listTeamMembers(o),a=i.find(l=>l.alias.toLowerCase().includes("coder"))??i[0];a!==void 0&&(t.hasUnackedDriftSignal(a.id,r.id,CT)||t.insertDriftSignal({team_member_id:a.id,project_id:r.id,signal_kind:CT,severity:"high",description:`3+ consecutive reviewer rejections (request_changes) for project ${r.name}`,detected_at:Date.now(),payload:JSON.stringify({run_ids:n.map(l=>l.id),consecutive_threshold:3})}))}}function MT(t){for(let e of Y1)try{e(t)}catch{}}var K1,CT,Y1,DT=T(()=>{"use strict";K1="request_changes",CT="reviewer_rejection_rate_high";Y1=[V1]});function Ys(){let t=process.env.LMCTL_DAEMON_INTERVAL_MS;if(t===void 0||t.trim().length===0)return 5e3;let e=Number(t);return Number.isFinite(e)&&e>0?e:5e3}function PT(t){let e=t.intervalMs??Ys(),r=t.runOnceFn??qr,n={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,cycles:0,jobs_processed:0,last_jobs_processed:0,last_started_at:null,last_finished_at:null,last_error:null,last_session_sizes_recorded:0,last_session_size_failures:0,last_intake_scanned:0,last_intake_new_jobs:0,last_intake_failures:0,last_session_hung_detected:0,last_session_monitor_checked_at:null,last_session_monitor_error:null},s=null,o=null,i=null,a=null,l=null;t.startRollupUpdaterFn!==!1&&(l=(t.startRollupUpdaterFn??OT)(t.dal));let c=f=>{n.running&&(s=setTimeout(()=>{d.runCycle().finally(()=>c(e))},f))},u=f=>{n.running&&(o=setTimeout(()=>{a===null&&(a=FT(t.dal,t.monitorSessionActivityFn??au,e,n).finally(()=>{a=null})),a.finally(()=>u(lu(t.dal,e)))},f))},d={state:n,runCycle:async()=>(i!==null||(i=z1(t.dal,r,t.collectSessionSizesFn??Th,t.scanIntakeFn??Rn,t.monitorSessionActivityFn??au,t.worker_id??"daemon",e,n).finally(()=>{i=null})),i),stop:async()=>{n.running=!1,s!==null&&clearTimeout(s),o!==null&&clearTimeout(o),l?.stop(),i!==null&&await i.catch(()=>{}),a!==null&&await a.catch(()=>{})}};if(n.running){let f=t.firstDelayMs??5e3;c(f),u(f)}return d}async function z1(t,e,r,n,s,o,i,a){a.in_flight=!0,a.last_started_at=new Date().toISOString(),a.last_error=null;let l=[],c=0,u=0,d=[],f=null;try{for(cE({dal:t}),MT({dal:t}),d=await n(t);;){let p=await e({dal:t,worker_id:o,lease_ms:6e5});if(p===null)break;l.push(p)}let m=await r(t);c=m.recorded,u=m.failed,f=await FT(t,s,i,a)}catch(m){a.last_error=m instanceof Error?m.message:String(m);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:a.last_error})})}catch{}}finally{a.in_flight=!1,a.cycles+=1,a.last_jobs_processed=l.length,a.last_session_sizes_recorded=c,a.last_session_size_failures=u,a.last_intake_scanned=d.reduce((m,p)=>m+p.scanned,0),a.last_intake_new_jobs=d.reduce((m,p)=>m+p.new_jobs,0),a.last_intake_failures=d.filter(m=>m.error!==void 0).length,a.last_session_hung_detected=f?.hung_detected??0,a.jobs_processed+=l.length,a.last_finished_at=new Date().toISOString()}return{jobs_processed:l.length,outcomes:l,session_sizes_recorded:c,session_size_failures:u,intake:d,session_monitor:f}}async function FT(t,e,r,n){let s=lu(t,r),o=Date.now();if(n.last_session_monitor_checked_at!==null){let i=Date.parse(n.last_session_monitor_checked_at);if(Number.isFinite(i)&&o-i<s)return null}n.last_session_monitor_checked_at=new Date(o).toISOString(),n.last_session_monitor_error=null;try{return await e({dal:t,nowMs:o})}catch(i){n.last_session_monitor_error=i instanceof Error?i.message:String(i);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:n.last_session_monitor_error})})}catch{}return null}}var Vd=T(()=>{"use strict";oa();Ks();kd();di();jT();DT();cu()});function UT(t){let e=t.listMembersInState("in_chat");for(let r of e)t.setMemberState(r.id,"attention_needed","daemon_restarted_mid_chat");return e.length}var WT=T(()=>{"use strict"});import{mkdirSync as Z1,readFileSync as Q1,readdirSync as eU,statSync as tU,writeFileSync as rU}from"node:fs";import{dirname as nU,join as qT,sep as BT}from"node:path";function Ja(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case HT:return sU(t,s.input);case JT:return oU(t,s.input);case XT:return iU(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:Zd,GetObjectCommand:zd,PutObjectCommand:Yd}}}function sU(t,e){let r=GT(t,e.Key);return Z1(nU(r),{recursive:!0}),rU(r,e.Body),{}}function oU(t,e){let r=GT(t,e.Key),n;try{n=Q1(r)}catch(o){throw o.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):o}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function iU(t,e){let r=e.Prefix??"";KT(r);let s=aU(t).sort((u,d)=>u.key<d.key?-1:u.key>d.key?1:0).filter(u=>u.key.startsWith(r)),o=e.ContinuationToken;o!==void 0&&o!==""&&(s=s.filter(u=>u.key>o));let i=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;i!==void 0&&s.length>i&&(a=s.slice(0,i),l=!0);let c={Contents:a.map(u=>({Key:u.key,LastModified:u.lastModified})),IsTruncated:l};return l&&(c.NextContinuationToken=a[a.length-1].key),c}function GT(t,e){return KT(e),qT(t,e)}function KT(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function aU(t){let e=[],r=(n,s)=>{let o;try{o=eU(n,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of o){let a=s===""?i.name:`${s}/${i.name}`,l=qT(n,i.name);if(i.isDirectory())r(l,a);else if(i.isFile()){let c=BT==="/"?a:a.split(BT).join("/");e.push({key:c,lastModified:tU(l).mtime})}}};return r(t,""),e}var HT,JT,XT,Yd,zd,Zd,Qd=T(()=>{"use strict";HT="localfs-put",JT="localfs-get",XT="localfs-list",Yd=class{input;_localfsTag=HT;constructor(e){this.input=e}},zd=class{input;_localfsTag=JT;constructor(e){this.input=e}},Zd=class{input;_localfsTag=XT;constructor(e){this.input=e}}});function VT(){return{put:0,get:0,list:0}}function ef(t,e=lU){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function tf(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var lU,Xa,rf=T(()=>{"use strict";lU={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};Xa=class{counts=VT();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=VT(),e}estimateCostUsd(e){return ef(this.counts,e)}}});function YT(t){let e=t.now??Date.now,r=t.timers??cU,n=null,s=null;async function o(){let l=e(),c=tf(l),u=t.meter.drain();(u.put>0||u.get>0||u.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:c,put:u.put,get:u.get,list:u.list,updated_at:new Date(l).toISOString()});let d=t.store.loadUsage(t.userId,t.deviceId,c),f=d?{put:d.put_count,get:d.get_count,list:d.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(c,f)}catch(_){t.log?.(`[usage] publish rollup failed: ${_ instanceof Error?_.message:String(_)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(c)}catch(_){t.log?.(`[usage] read user total failed: ${_ instanceof Error?_.message:String(_)}`),m=f}let p=ef(m);if(n!==c&&p>=t.ceilingUsd){n=c,t.log?.(`[usage] quota exceeded period=${c} cost=$${p.toFixed(4)} >= ceiling $${t.ceilingUsd}`);try{t.onQuotaExceeded({period:c,costUsd:p,ceilingUsd:t.ceilingUsd})}catch(_){t.log?.(`[usage] onQuotaExceeded threw: ${_ instanceof Error?_.message:String(_)}`)}}}function i(){return s=(s??Promise.resolve()).then(()=>o()).catch(()=>{}),s}let a=r.setInterval(()=>{i()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return i()},isOverQuota(){return n!==null&&n===tf(e())}}}var cU,zT=T(()=>{"use strict";rf();cU={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var nf=T(()=>{"use strict";xa();La();La()});function uU(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e=t;if(typeof e.message_id!="string"||e.message_id==="")return null;if(typeof e.reply_to=="string"&&e.reply_to!==""){let s=e.response;if(typeof s!="object"||s===null)return null;let o=s;return typeof o.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:o}}let r=e.request;if(typeof r!="object"||r===null)return null;let n=r;return typeof n.method!="string"||n.method===""||typeof n.path!="string"||n.path===""?null:{message_id:e.message_id,request:n}}function dU(t){return t.reply_to!==void 0&&t.response!==void 0}function fU(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function ZT(t){let e=t.reason;if(e!==void 0)return e;try{return new DOMException("Aborted","AbortError")}catch{let r=new Error("Aborted");return r.name="AbortError",r}}var Ga,zs,QT=T(()=>{"use strict";nf();Ga=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},zs=class{client;log;now;random;pending=new Map;requestHandler=null;stopped=!1;constructor(e){this.client=e.client,this.log=e.log??(()=>{}),this.now=e.now??Date.now,this.random=e.random??Math.random}onRequest(e){if(this.requestHandler!==null)throw new Error("MailboxFetchClient: onRequest handler already registered");this.requestHandler=e}async fetch(e,r){if(this.stopped)throw new Ga("MailboxFetchClient.fetch after stop()");if(typeof e.path!="string"||e.path==="")throw new Error("MailboxFetchClient.fetch: request.path is required");let n=e.method;if(typeof n!="string"||n==="")throw new Error("MailboxFetchClient.fetch: request.method is required");let s=Zt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let o=r?.conversationId??s,i={message_id:s,request:e};return new Promise((a,l)=>{let c=r?.abortSignal,u;if(c!==void 0){if(c.aborted){l(ZT(c));return}u=()=>{this.pending.has(s)&&(this.pending.delete(s),l(ZT(c)))},c.addEventListener("abort",u,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...u!==void 0?{abortListener:u}:{},...c!==void 0?{abortSignal:c}:{}}),this.client.putMessage({conversation_id:o,payload:i}).catch(d=>{let f=this.pending.get(s);f!==void 0&&(this.pending.delete(s),f.abortListener!==void 0&&f.abortSignal!==void 0&&f.abortSignal.removeEventListener("abort",f.abortListener),f.reject(d))})})}async stop(){if(this.stopped)return;this.stopped=!0;let e=Array.from(this.pending.values());this.pending.clear();let r=new Ga;for(let n of e){n.abortListener!==void 0&&n.abortSignal!==void 0&&n.abortSignal.removeEventListener("abort",n.abortListener);try{n.reject(r)}catch{}}}async handleIncoming(e,r){let n=uU(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(dU(n)){let l=this.pending.get(n.reply_to);if(l===void 0){this.log(`MailboxFetchClient: dropping response for unknown reply_to=${n.reply_to}`);return}this.pending.delete(n.reply_to),l.abortListener!==void 0&&l.abortSignal!==void 0&&l.abortSignal.removeEventListener("abort",l.abortListener),l.resolve(n.response);return}if(this.requestHandler===null){this.log(`MailboxFetchClient: no handler registered; dropping request message_id=${n.message_id}`);return}let s=r?.conversation_id??fU(e)??n.message_id,o;try{o=await this.requestHandler(n.request)}catch(l){let c=l instanceof Error?l.message:String(l),u=typeof l.code=="string"?l.code:"INTERNAL_ERROR";o={status:500,headers:{"content-type":"application/json"},body:{error:u,message:c}}}let a={message_id:Zt(this.now(),this.random),reply_to:n.message_id,response:o};try{await this.client.putMessage({conversation_id:s,payload:a})}catch(l){this.log(`MailboxFetchClient: response PUT failed for reply_to=${n.message_id}: ${l instanceof Error?l.message:String(l)}`)}}}});function sf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;return!(e.kind!=="terminal"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.data!="string"||typeof e.ts!="number")}var eb=T(()=>{"use strict"});function of(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="provider"||typeof e.session_id!="string"||e.session_id===""||e.direction!=="agent_to_user"&&e.direction!=="user_to_agent"||typeof e.ts!="number")return!1;if(e.direction==="agent_to_user"){if(!Array.isArray(e.events))return!1;for(let r of e.events)if(typeof r!="object"||r===null||Array.isArray(r)||typeof r.event_type!="string")return!1}else if(typeof e.user_input!="string")return!1;return!0}var tb=T(()=>{"use strict"});function lf(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=t;if(e.kind!=="daemon_event"||typeof e.event!="string"||e.event===""||typeof e.ts!="number")return!1;if(e.event==="workflows"){if(!Array.isArray(e.workflows))return!1;for(let r of e.workflows){if(typeof r!="object"||r===null||Array.isArray(r))return!1;let n=r;if(typeof n.teamfile_path!="string"||n.teamfile_path===""||n.name!==null&&typeof n.name!="string"||typeof n.registered_at!="string"||n.registered_at===""||n.last_seeded_at!==null&&typeof n.last_seeded_at!="string")return!1}}else if(e.event==="chat_log"){if(typeof e.entry!="object"||e.entry===null||Array.isArray(e.entry))return!1;let r=e.entry;if(typeof r.id!="number"||typeof r.root_teamfile!="string"||r.root_teamfile===""||r.sender_teamfile!==null&&(typeof r.sender_teamfile!="string"||r.sender_teamfile==="")||r.sender_alias!==null&&(typeof r.sender_alias!="string"||r.sender_alias==="")||typeof r.receiver_teamfile!="string"||r.receiver_teamfile===""||typeof r.receiver_alias!="string"||r.receiver_alias===""||typeof r.message!="string"||r.response!==null&&typeof r.response!="string"||typeof r.status!="string"||r.status===""||typeof r.created_at!="string"||r.created_at==="")return!1}return!0}var af,rb=T(()=>{"use strict";af="daemon:events"});function sb(t){return{kind:"prompt",prompt_id:t.prompt_id??Zt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function cf(t){if(t===null||typeof t!="object")return!1;let e=t;return e.kind==="prompt"&&typeof e.prompt_id=="string"&&e.prompt_id.length>0&&typeof e.root_teamfile=="string"&&e.root_teamfile.length>0&&typeof e.text=="string"}var nb,uf=T(()=>{"use strict";nf();nb="prompt:root"});function Zs(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(ib(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function mU(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(ib(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function ob(t,e=60){if(typeof t!="string"||t==="")return!0;let r=mU(t);return r===null?!0:Date.now()/1e3>=r-e}function ib(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"="),n=globalThis.Buffer;return n!==void 0?n.from(r,"base64").toString("utf8"):atob(r)}var df=T(()=>{"use strict"});async function Ka(t){let e=t.fetchImpl??fetch,r=`https://cognito-idp.${t.region}.amazonaws.com/`,n=await e(r,{method:"POST",headers:{"content-type":"application/x-amz-json-1.1","x-amz-target":pU},body:JSON.stringify({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:t.clientId,AuthParameters:{REFRESH_TOKEN:t.refreshToken}})}),s=await n.text();if(!n.ok){let l=s;try{let c=JSON.parse(s);l=c.message??c.__type??s}catch{}throw new Error(`cognito_refresh_failed: ${n.status} ${l}`)}let i=JSON.parse(s).AuthenticationResult,a=i?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof i?.AccessToken=="string"&&i.AccessToken!==""?{accessToken:i.AccessToken}:{},...typeof i?.ExpiresIn=="number"&&Number.isFinite(i.ExpiresIn)?{expiresAt:Date.now()+i.ExpiresIn*1e3}:{}}}var pU,ff=T(()=>{"use strict";pU="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as ab,mkdirSync as lb,readFileSync as cb,writeFileSync as ub}from"node:fs";import{homedir as db}from"node:os";import{dirname as fb,join as mb}from"node:path";function Qs(){return process.env.LMCTL_DEVICE_AUTH_PATH??mb(db(),".lmctl","device-auth.json")}function pb(){return process.env.LMCTL_TOKEN_PATH??mb(db(),".lmctl","cli-tokens.json")}function mf(t=Qs()){try{let e=JSON.parse(cb(t,"utf8"));return typeof e.userId!="string"||e.userId===""||typeof e.refreshToken!="string"||e.refreshToken===""?null:{userId:e.userId,refreshToken:e.refreshToken}}catch{return null}}function _b(t,e=Qs()){lb(fb(e),{recursive:!0,mode:448}),ub(e,JSON.stringify(t,null,2));try{ab(e,384)}catch{}}function pf(t,e=pb()){let r={};try{r=JSON.parse(cb(e,"utf8"))}catch{}let n={...r.cognito??{}};n.idToken=t.idToken,t.accessToken!==void 0&&(n.accessToken=t.accessToken),t.refreshToken!==void 0&&(n.refreshToken=t.refreshToken),t.expiresAt!==void 0&&(n.expiresAt=t.expiresAt);let s={...r,cognito:n};lb(fb(e),{recursive:!0,mode:448}),ub(e,JSON.stringify(s,null,2));try{ab(e,384)}catch{}}async function hb(t){let e=t.deviceAuthPath??Qs(),r=mf(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await Ka({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return pf({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??pb()),{idToken:n.idToken,userId:r.userId}}var _f=T(()=>{"use strict";ff()});import{existsSync as _U,realpathSync as hU}from"node:fs";import{dirname as gU}from"node:path";function hf(t){yU(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function yU(t){let e=t.payload.root_teamfile;try{e=hU(t.payload.root_teamfile)}catch(s){let o=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${s instanceof Error?s.message:String(s)}`;return await Wn(t.store,{rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:o,log:t.log}),t.log?.(`[mailbox] ${o}`),{status:"error",response:null,error_detail:o}}if(t.store.getRootTeam(e)===null){let s=`prompt root is not registered: ${e}`;return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:s,log:t.log}),t.log?.(`[mailbox] ${s}`),{status:"error",response:null,error_detail:s}}let r=wU(e);if("error"in r)return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,response:null,status:"error",error_detail:r.error,log:t.log}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=nr(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:bU(t.env??process.env)});if(!n.acquired){let s=TU(r.alias,n.current);return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:null,status:"error",error_detail:s,log:t.log}),t.log?.(`[mailbox] prompt rejected: ${s}`),{status:"error",response:null,error_detail:s}}try{let o=await(t.chat??Ht)({provider:r.provider,sessionId:r.sessionid,cwd:r.sessiondir,prompt:t.payload.text,env:t.env??process.env,alias:r.alias,permissionMode:"yolo",...t.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}),i=o.status==="stalled",a=!i&&o.text.trim()==="",l=i?`provider stalled${o.stalledAfterMs!==void 0?` after ${o.stalledAfterMs}ms`:""}`:a?"provider returned empty response":null,c=i||a?"error":"ok";return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:c==="error"?null:o.text,status:c,error_detail:l,log:t.log}),{status:c,response:c==="error"?null:o.text,error_detail:l}}catch(s){let o=s instanceof Error?s.message:String(s);return await Wn(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:null,status:"error",error_detail:o,log:t.log}),t.log?.(`[mailbox] prompt provider error: ${o}`),{status:"error",response:null,error_detail:o}}finally{try{t.store.releaseAgentInflight(n.lease)}catch(s){t.log?.(`[mailbox] failed to release prompt in-flight slot: ${s instanceof Error?s.message:String(s)}`)}}}function wU(t){if(!_U(t))return{error:`prompt root missing/unreadable: ${t}`};let e=De(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=et(e);return r===void 0?{error:`prompt root has no Lead: ${t}`}:r.session===void 0||r.session.trim()===""?{error:`prompt root Lead is unseeded: ${t}`}:{alias:r.alias,provider:r.provider,sessionid:r.session,sessiondir:r.sessiondir??gU(t)}}async function Wn(t,e){let r=wb(e.message),n=e.response===null?null:wb(e.response);try{t.insertTeamChatLog({root_teamfile:e.rootTeamfile,sender_teamfile:e.rootTeamfile,sender_alias:"operator",receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,message:r.text,response:n?.text??null,origin:"unknown",status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()})}catch(s){e.log?.(`[mailbox] warning: failed to record prompt chat log: ${s instanceof Error?s.message:String(s)}`)}}function wb(t){return t.length<=gb?{text:t,truncated:!1}:{text:t.slice(0,gb),truncated:!0}}function EU(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function TU(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:EU(t,e)}function bU(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return yb;let r=Number(e);return!Number.isFinite(r)||r<=0?yb:r}var gb,yb,Eb=T(()=>{"use strict";At();vt();es();gb=256*1024,yb=30*60*1e3});import{chmodSync as Ib,existsSync as SU,mkdirSync as Nb,readFileSync as Za,writeFileSync as Ab}from"node:fs";import{dirname as gf,resolve as Va,join as xb}from"node:path";import{fileURLToPath as vU}from"node:url";import{homedir as Rb}from"node:os";import{CognitoIdentityClient as kU,GetIdCommand as IU}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as Tb}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as NU,ListObjectsV2Command as AU,PutObjectCommand as xU,S3Client as bb}from"@aws-sdk/client-s3";function to(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:jU(t.selfUrl),n={},s;for(let x of r)if(SU(x)){n=OU(x),s=x;break}let o=(...x)=>{for(let k of x)if(typeof k=="string"&&k!=="")return k},i=o(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??RU,a=o(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??LU,l=o(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??$U,c=o(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",u=o(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Qa,d=[];i===void 0&&d.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&d.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&d.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:d,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(d.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,_=za(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=za(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),h=za(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),E=za(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),w=o(e.LMCTL_MAILBOX_KEY),v=o(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:i,cognitoUserPoolId:a,cognitoClientId:u,region:c,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},..._!==void 0?{readIntervalMs:_}:{},...g!==void 0?{heartbeatIdleMs:g}:{},...h!==void 0?{backoffReadIntervalMs:h}:{},...E!==void 0?{chatLogPollIntervalMs:E}:{},...w!==void 0?{mailboxKey:w}:{},...v!==void 0?{tokenPath:v}:{}},f}function OU(t){try{let e=Za(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[o,i]of Object.entries(n))i!==null&&typeof i=="object"&&typeof i.value=="string"&&(s[o]=i.value);return s}catch{return{}}}function jU(t){let e=gf(vU(t??import.meta.url));return[Va(e,"..","..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","..","infra","terraform","terraform.tfstate"),Va(e,"..","..","infra","terraform","terraform.tfstate")]}function za(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function CU(t){let e=MU(t.intervalMs)??Lb,r=Math.max(1,Math.trunc(t.limit??500)),n=t.now??Date.now,s=t.cursorKey!==void 0&&t.store.loadTeamChatLogCursor!==void 0&&t.store.saveTeamChatLogCursor!==void 0?{key:t.cursorKey,load:t.store.loadTeamChatLogCursor.bind(t.store),save:t.store.saveTeamChatLogCursor.bind(t.store)}:null,o,i=!1,a=!1,l=()=>{try{if(s!==null){let d=s.load(s.key);if(d!==null)return o=d.last_pushed_id,!0}return o=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:o,updated_at:new Date(n()).toISOString()}),!0}catch(d){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${d instanceof Error?d.message:String(d)}`),!1}};l();let c=async()=>{if(!(a||i)){i=!0;try{if(o===void 0&&!l())return;let d=t.store.listTeamChatLogSinceId(o,r);for(let f of d){let m={kind:"daemon_event",event:"chat_log",ts:n(),entry:{id:f.id,root_teamfile:f.root_teamfile,sender_teamfile:f.sender_teamfile,sender_alias:f.sender_alias,receiver_teamfile:f.receiver_teamfile,receiver_alias:f.receiver_alias,message:f.message,response:f.response,status:f.status,created_at:f.created_at}};await t.publishDaemonEvent(m),s!==null&&s.save({cursor_key:s.key,last_pushed_id:f.id,updated_at:new Date(n()).toISOString()}),o=Math.max(o,f.id)}}catch(d){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${d instanceof Error?d.message:String(d)}`)}finally{i=!1}}},u=setInterval(()=>{c()},e);return typeof u.unref=="function"&&u.unref(),{pollNow:c,stop(){a=!0,clearInterval(u)}}}function MU(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function $b(t){let e=t.tokenPath??xb(Rb(),".lmctl","cli-tokens.json"),r=vb(t.tokenPath);if(ob(r.cognito?.idToken)&&mf()!==null)try{await hb({region:t.region,clientId:t.cognitoClientId??Qa,cliTokensPath:e}),r=vb(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(A){let J=A instanceof Error?A.message:String(A);t.log?.(`[mx-mailbox] device-auth refresh failed: ${J}`)}if(r.cognito===void 0)throw new Error("agent_mailbox_not_logged_in: ~/.lmctl/cli-tokens.json has no cognito tokens; run `webcli login` or `lmctl device login` first");let n=r.cognito.idToken;if(typeof n!="string"||n==="")throw new Error("agent_mailbox_no_id_token: cli-tokens.json's cognito.idToken is empty; run `webcli login` or `lmctl device login` first");let s=`cognito-idp.${t.region}.amazonaws.com/${t.cognitoUserPoolId}`,o=r.cognito.identityId,i=!1;o===void 0||o===""?o=await kb({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(i=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${o}`));let a=Tb({identityId:o,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bb({region:t.region,credentials:a}),c={ListObjectsV2Command:AU,GetObjectCommand:NU,PutObjectCommand:xU},u=Zs(n),d=u??o,f=t.deviceId,m=Mn({identityId:o,userId:u,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,_;if(p!==void 0){let A=p.loadMailboxCursor(d,m);if(A!==null)_=A.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${_??"(sentinel)"} for user_id=${d}`);else{let J=!1,B=0;for(;!J&&B<2;){B+=1;try{let I=Na(m,"web"),N=0,C;do{let X=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:I,MaxKeys:1e3,...C!==void 0?{ContinuationToken:C}:{}}));for(let q of X.Contents??[]){let P=Aa(q.Key??"",m,"web");P!==void 0&&P>N&&(N=P)}C=X.IsTruncated===!0?X.NextContinuationToken:void 0}while(C!==void 0);_=N,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${N} for user_id=${d}`),J=!0}catch(I){let N=I instanceof Error?I.message:String(I);if(i&&B===1&&FU(I)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${N}); clearing + refreshing`),PU(e),i=!1,o=await kb({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=Tb({identityId:o,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bb({region:t.region,credentials:a}),m=Mn({identityId:o,userId:u,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${N}`);break}}p.saveMailboxCursor({user_id:d,mailbox_key:m,last_processed_version_id:null,last_processed_seq:_??null,last_processed_at:new Date().toISOString()})}}let g=null,h=t.terminalSessionManager,E=t.persistentSessionManager,w=t.promptTriggerStore,v=new Xa,x=new Hr({bucket:t.mailboxBucket,identityId:o,...u!==null?{userId:u}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:c,selfRole:"agent",onS3Op:A=>v.record(A),onMessage:async A=>{if(h!==void 0&&sf(A.payload)){h.onInbound(A.payload);return}if(E!==void 0&&of(A.payload)){await E.onInbound(A.payload);return}if(!lf(A.payload)){if(w!==void 0&&cf(A.payload)){hf({store:w,payload:A.payload,log:t.log});return}g!==null&&await g.handleIncoming(A.payload,A)}},...p!==void 0?{onCursorAdvance:A=>{p.saveMailboxCursor({user_id:d,mailbox_key:m,last_processed_version_id:null,last_processed_seq:A,last_processed_at:new Date().toISOString()})}}:{},..._!==void 0?{cursor:_}:{},...t.pollIntervalMs!==void 0?{pollIntervalMs:t.pollIntervalMs}:{},...t.readIntervalMs!==void 0?{readIntervalMs:t.readIntervalMs}:{},...t.heartbeatIdleMs!==void 0?{heartbeatIdleMs:t.heartbeatIdleMs}:{},...t.backoffReadIntervalMs!==void 0?{backoffReadIntervalMs:t.backoffReadIntervalMs}:{}});g=new zs({client:x,...t.log!==void 0?{log:t.log}:{}}),h!==void 0&&h.setPublish(async A=>x.putMessage({conversation_id:`terminal:${A.session_id}`,payload:A})),E!==void 0&&E.setPublish(async A=>x.putMessage({conversation_id:`provider:${A.session_id}`,payload:A}));let k=A=>x.putMessage({conversation_id:af,payload:A});x.start();let j=t.chatLogTailStore===void 0?void 0:CU({store:t.chatLogTailStore,publishDaemonEvent:k,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??Lb,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let K=t.deviceId??o,U=`${d}/usage/`,$;return $=t.usageStore===void 0?void 0:YT({meter:v,store:t.usageStore,userId:d,deviceId:K,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:A,costUsd:J,ceilingUsd:B})=>{t.log?.(`[usage] month ${A} cost $${J.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),x.stop().catch(()=>{}),$?.stop()},publishOwnRollup:async(A,J)=>{await l.send(new c.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${U}${K}-${A}.json`,Body:JSON.stringify({...J,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async A=>{let J={put:0,get:0,list:0},B;do{let I=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:U,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let N of I.Contents??[]){let C=N.Key??"";if(C.endsWith(`-${A}.json`))try{let X=await l.send(new c.GetObjectCommand({Bucket:t.mailboxBucket,Key:C}));if(X.Body===void 0)continue;let q=JSON.parse(await X.Body.transformToString("utf-8"));J.put+=q.put??0,J.get+=q.get??0,J.list+=q.list??0}catch{}}B=I.IsTruncated===!0?I.NextContinuationToken:void 0}while(B!==void 0);return J},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:o,mailbox:x,fetchClient:g,publishDaemonEvent:k,async stop(){j?.stop(),$!==void 0&&(await $.flushNow().catch(()=>{}),$.stop()),await g.stop().catch(()=>{}),await x.stop().catch(()=>{})}}}async function Ob(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:Ja(t.rootDir),r=Mn({identityId:eo,userId:eo,deviceId:Sb}),n=null,s=t.terminalSessionManager,o=t.persistentSessionManager,i=t.promptTriggerStore,a=new Hr({bucket:"local",identityId:eo,userId:eo,deviceId:Sb,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async c=>{if(s!==void 0&&sf(c.payload)){s.onInbound(c.payload);return}if(o!==void 0&&of(c.payload)){await o.onInbound(c.payload);return}if(!lf(c.payload)){if(i!==void 0&&cf(c.payload)){hf({store:i,payload:c.payload,log:t.log});return}n!==null&&await n.handleIncoming(c.payload,c)}},pollIntervalMs:t.pollIntervalMs??Ya,readIntervalMs:t.readIntervalMs??Ya,heartbeatIdleMs:t.heartbeatIdleMs??Ya,backoffReadIntervalMs:t.backoffReadIntervalMs??Ya});n=new zs({client:a,...t.log!==void 0?{log:t.log}:{}}),s!==void 0&&s.setPublish(async c=>a.putMessage({conversation_id:`terminal:${c.session_id}`,payload:c})),o!==void 0&&o.setPublish(async c=>a.putMessage({conversation_id:`provider:${c.session_id}`,payload:c}));let l=c=>a.putMessage({conversation_id:af,payload:c});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:eo,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function vb(t){let e=t??xb(Rb(),".lmctl","cli-tokens.json");try{let r=Za(e,"utf8");return JSON.parse(r)}catch{return{}}}function DU(t,e){if(e===void 0||e==="")return;let r={};try{let s=Za(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};Nb(gf(t),{recursive:!0,mode:448}),Ab(t,JSON.stringify(n,null,2));try{Ib(t,384)}catch{}}function PU(t){let e={};try{let n=Za(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,Nb(gf(t),{recursive:!0,mode:448}),Ab(t,JSON.stringify(r,null,2));try{Ib(t,384)}catch{}}async function kb(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new kU({region:t.region}).send(new IU({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{DU(t.tokenPath,r.IdentityId),t.log?.(`[mx-mailbox] persisted identityId=${r.IdentityId} to ${t.tokenPath}`)}catch(n){let s=n instanceof Error?n.message:String(n);t.log?.(`[mx-mailbox] WARNING: identityId persist failed (${s}); will redo GetId on next restart`)}return r.IdentityId}function FU(t){if(t===null||typeof t!="object")return!1;let e=t,r=[typeof e.name=="string"?e.name:void 0,typeof e.Code=="string"?e.Code:void 0,typeof e.__type=="string"?e.__type:void 0];for(let s of r)if(s!==void 0&&(s==="NotAuthorizedException"||s==="ResourceNotFoundException"||s==="InvalidIdentityPoolConfigurationException"||s==="ExpiredTokenException"))return!0;let n=typeof e.message=="string"?e.message:"";return!!(n.includes("NotAuthorizedException")||n.includes("Invalid identity pool configuration")||n.includes("Identity")&&n.includes("not found"))}var Lb,Ya,Qa,RU,LU,$U,eo,Sb,yf=T(()=>{"use strict";$a();Qd();rf();zT();QT();eb();tb();rb();uf();xa();df();_f();Eb();Lb=3e3,Ya=1e3,Qa="79u5jhkk46qofog661c9i0bdcs",RU="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",LU="us-east-1_4iUdFggDn",$U="lmctl-next-preview-mailbox-254332045686";eo="local",Sb="local"});import{spawn as bf}from"node:child_process";import{createInterface as jb}from"node:readline";var wf,Ef,Tf,Cb,Mb=T(()=>{"use strict";Bo();ve();wf=class{child;ctx;rl;nextRpcId=1;pending=new Map;threadId;nextLocalTurnId=1;closed=!1;setResumeThreadId(e){this.threadId=e}async start(e,r){this.ctx=r;let n=bf(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=jb({input:n.stdout}),this.rl.on("line",s=>{r.generation===r.currentGeneration()&&this.handleLine(s)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let o=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:o}})}),await this.rpc("initialize",{clientInfo:{name:"lmctl-dt3",title:"lmctl DT-3",version:"0.1.0"},capabilities:{experimentalApi:!1}}),this.notify("initialized",{}),this.threadId!==void 0&&this.threadId!=="")try{await this.rpc("thread/resume",{threadId:this.threadId,approvalPolicy:"never",sandbox:"danger-full-access"}),r.emit({event_type:"thread_started",payload:{thread_id:this.threadId,resumed:!0}})}catch{let o=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,i=typeof o?.id=="string"?o.id:void 0;this.threadId=i,r.emit({event_type:"thread_started",payload:{thread_id:i,resumed:!1}})}else{let o=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,i=typeof o?.id=="string"?o.id:void 0;this.threadId=i,r.emit({event_type:"thread_started",payload:{thread_id:i,resumed:!1}})}return n}async sendTurn(e){if(this.closed)throw new Error("codex_session_closed");if(this.threadId===void 0||this.threadId==="")throw new Error("codex_no_thread_id");let r=`local-${this.nextLocalTurnId++}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});try{let s=(await this.rpc("turn/start",{threadId:this.threadId,input:[{type:"text",text:e}]})).result?.turn,o=typeof s?.id=="string"?s.id:void 0;if(o!==void 0){let i=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),i!==void 0&&this.ctx?.turnMap.set(o,i)}}catch(n){throw this.ctx?.turnMap.delete(r),n}}async stop(){if(this.closed=!0,this.rl!==void 0&&(this.rl.close(),this.rl=void 0),this.child?.stdin!==null&&this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}for(let e of this.pending.values())e.reject(new Error("codex_session_stopping"));this.pending.clear()}async rpc(e,r){if(this.child?.stdin===null||this.child===void 0)throw new Error("codex_child_unavailable");return new Promise((n,s)=>{let o=this.nextRpcId++;this.pending.set(o,{resolve:n,reject:s});let i=JSON.stringify({jsonrpc:"2.0",id:o,method:e,params:r});try{this.child.stdin.write(i+`
|
|
2123
2129
|
`)}catch(a){this.pending.delete(o),s(a instanceof Error?a:new Error(String(a)))}})}notify(e,r){if(this.child?.stdin===null||this.child===void 0)return;let n=JSON.stringify({jsonrpc:"2.0",method:e,params:r});try{this.child.stdin.write(n+`
|
|
2124
2130
|
`)}catch{}}handleLine(e){if(e.trim()==="")return;let r;try{r=JSON.parse(e)}catch{return}if(typeof r.id=="number"&&this.pending.has(r.id)){let i=this.pending.get(r.id);if(this.pending.delete(r.id),r.error!==void 0){let a=r.error,l=typeof a?.message=="string"&&a.message!==""?a.message:JSON.stringify(r.error);i.reject(new Error(`codex_rpc_error: ${l}`))}else i.resolve(r);return}let n=typeof r.method=="string"?r.method:void 0;if(n===void 0)return;let s=r.params??{},o=this.normalizeNotification(n,s);o!==void 0&&this.ctx?.emit(o)}normalizeNotification(e,r){if(e==="thread/started"){let n=r.thread;return typeof n?.id=="string"&&(this.threadId=n.id),{event_type:"thread_started",payload:{thread_id:this.threadId,raw:r}}}if(e==="turn/started")return{event_type:"turn_started",payload:{turn_id:r.turn?.id,thread_id:this.threadId}};if(e==="item/agentMessage/delta")return{event_type:"assistant_message_delta",payload:{text:typeof r.delta=="string"?r.delta:""}};if(e==="item/started"||e==="item/completed"){let n=r.item;return n?.type!==void 0&&n.type!=="agentMessage"&&n.type!=="userMessage"?{event_type:"tool_call",payload:{name:n.name??n.type,status:e==="item/started"?"started":"completed",item:n}}:{event_type:"notification",payload:{method:e,params:r}}}if(e==="turn/completed"){let n=r.turn;return typeof n?.id=="string"&&this.ctx?.turnMap.delete(n.id),{event_type:"turn_complete",payload:r}}if(e==="error"){let n=r.error;return{event_type:"error",payload:{message:typeof n?.message=="string"?n.message:JSON.stringify(r),raw:r}}}return{event_type:"notification",payload:{method:e,params:r}}}},Ef=class{child;ctx;buffer="";sessionIdSeen;closed=!1;async start(e,r){this.ctx=r;let n=bf(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});return this.child=n,n.stdout.on("data",s=>{if(r.generation!==r.currentGeneration())return;let o=s instanceof Buffer?s.toString("utf8"):String(s);this.buffer+=o;let i=this.buffer.split(`
|
|
2125
2131
|
`);this.buffer=i.pop()??"";for(let a of i)this.handleLine(a)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let o=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:o}})}),n}async sendTurn(e){if(this.closed)throw new Error("claude_session_closed");if(this.child===void 0||this.child.stdin===null)throw new Error("claude_child_unavailable");let r=`claude-${Date.now()}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});let n=JSON.stringify({type:"user",message:{role:"user",content:e}});try{this.child.stdin.write(n+`
|
|
@@ -2161,7 +2167,7 @@ services. Help exits before any port binding or daemon startup.
|
|
|
2161
2167
|
Scan configured project GitHub issues into lmctl, or update per-project
|
|
2162
2168
|
intake settings such as enabled state, labels, and issue state filters.
|
|
2163
2169
|
scan writes JSON output; --project limits the scan to one project.
|
|
2164
|
-
`});function tS(t){let e=Qb(t.registry,t.fromTeamfile);if(e===void 0)return Bn(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!eS(e,t.fromAlias))return Bn(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Qb(t.registry,t.toTeamfile);return r===void 0?Bn(`target team is not registered in policy graph: ${t.toTeamfile}`):eS(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Bn(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Bn(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Bn(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Qb(t,e){return t.teams.find(r=>r.teamfile===e)}function eS(t,e){return t.aliases.some(r=>r===e)}function Bn(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var rS=T(()=>{"use strict"});import{randomUUID as dW}from"node:crypto";import{hostname as nS,networkInterfaces as fW}from"node:os";function sS(t){let e=(t.now??new Date).toISOString();return{lock_id:dW(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??nS(),holder_ips:t.ips??gW(),started_at:e,last_heartbeat:e}}function oS(t=process.env){return iS(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,mW)}function _W(t=process.env){return iS(t.LMCTL_TERMINAL_LOCK_STALE_MS,pW)}function Nf(t,e={}){let r=e.now??new Date,n=e.localHost??nS(),s=e.staleMs??_W();if(t.holder_host===n)return(e.isProcessAlive??hW)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let o=Date.parse(t.last_heartbeat);return Number.isFinite(o)?r.getTime()-o<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Af(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function iS(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 hW(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 gW(){let t=new Set;for(let e of Object.values(fW()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var mW,pW,xf=T(()=>{"use strict";mW=15e3,pW=12e4});function lS(t,e){if(!aS(t,e.sender))return;let r=`${e.sender.teamfile}:${e.sender.alias}`,n=yW(t,e.sender,r);for(let s of n){if(s.teamfile===e.currentTarget.teamfile&&s.alias===e.currentTarget.alias||!aS(t,s))continue;let o=TW(r,s);if(wW(t,s)){vW(t,o);continue}let i=`activity:${EW(t,s)}`;bW(t,o)?.occurrence_marker!==i&&(e.emit({kind:"warning",message:`your lead ${s.teamfile}:${s.alias} is idle \u2014 nudge it to use \`
|
|
2170
|
+
`});function tS(t){let e=Qb(t.registry,t.fromTeamfile);if(e===void 0)return Bn(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!eS(e,t.fromAlias))return Bn(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=Qb(t.registry,t.toTeamfile);return r===void 0?Bn(`target team is not registered in policy graph: ${t.toTeamfile}`):eS(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Bn(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Bn(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Bn(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function Qb(t,e){return t.teams.find(r=>r.teamfile===e)}function eS(t,e){return t.aliases.some(r=>r===e)}function Bn(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var rS=T(()=>{"use strict"});import{randomUUID as dW}from"node:crypto";import{hostname as nS,networkInterfaces as fW}from"node:os";function sS(t){let e=(t.now??new Date).toISOString();return{lock_id:dW(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??nS(),holder_ips:t.ips??gW(),started_at:e,last_heartbeat:e}}function oS(t=process.env){return iS(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,mW)}function _W(t=process.env){return iS(t.LMCTL_TERMINAL_LOCK_STALE_MS,pW)}function Nf(t,e={}){let r=e.now??new Date,n=e.localHost??nS(),s=e.staleMs??_W();if(t.holder_host===n)return(e.isProcessAlive??hW)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let o=Date.parse(t.last_heartbeat);return Number.isFinite(o)?r.getTime()-o<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Af(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function iS(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 hW(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 gW(){let t=new Set;for(let e of Object.values(fW()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var mW,pW,xf=T(()=>{"use strict";mW=15e3,pW=12e4});function lS(t,e){if(!aS(t,e.sender))return;let r=`${e.sender.teamfile}:${e.sender.alias}`,n=yW(t,e.sender,r);for(let s of n){if(s.teamfile===e.currentTarget.teamfile&&s.alias===e.currentTarget.alias||!aS(t,s))continue;let o=TW(r,s);if(wW(t,s)){vW(t,o);continue}let i=`activity:${EW(t,s)}`;bW(t,o)?.occurrence_marker!==i&&(e.emit({kind:"warning",message:`your lead ${s.teamfile}:${s.alias} is idle \u2014 nudge it to use \`notify_me\`
|
|
2165
2171
|
`}),SW(t,o,{occurrence_marker:i,warned_at:M()}))}}function yW(t,e,r){return t.db.prepare(`
|
|
2166
2172
|
SELECT DISTINCT teamfile, alias
|
|
2167
2173
|
FROM (
|
|
@@ -2251,7 +2257,7 @@ Send a prompt to a team member or raw provider session, or answer a paused run.`
|
|
|
2251
2257
|
`),i({code:127,signal:null,spawnError:c}))}),l.on("close",(c,u)=>{a||(a=!0,i({code:c,signal:u}))})})}async function sB(t,e,r){if(e!==null)try{await R(t,n=>n.finishTrackedInvocation(e,ES(r)))}catch{}}function ES(t){let e=t.spawnError===void 0&&t.signal===null&&t.code===0,r=oB(t);return{status:e?"done":"error",exit_code:t.code,signal:t.signal,result_summary:r,error:e?null:r}}function oB(t){return t.spawnError!==void 0?`spawn failed: ${t.spawnError.message}`:t.signal!==null?`terminated by signal ${t.signal}`:`exit ${t.code??1}`}function iB(t,e,r,n){if(!n||e===null)return;let s=ES(r);t.stdout.write(`${JSON.stringify({id:e,status:s.status,exit_code:s.exit_code,signal:s.signal})}
|
|
2252
2258
|
`)}function aB(t){return t.spawnError!==void 0?127:t.signal!==null?1:typeof t.code=="number"?t.code:1}function lB(t){return t.map(e=>JSON.stringify(e)).join(" ")}var VW,YW,bS=T(()=>{"use strict";gs();tt();ge();VW=`usage: lmctl exec [--root <teamfile>] [--cwd DIR] [--json] -- <command> [args...]
|
|
2253
2259
|
|
|
2254
|
-
Run a command as a tracked invocation. (Launch N background invocations by backgrounding this command, then lmctl
|
|
2260
|
+
Run a command as a tracked invocation. (Launch N background invocations by backgrounding this command, then lmctl notify_me interactively returns the FIRST completion; no ids).
|
|
2255
2261
|
Arguments after -- are passed directly to the child process; no shell is used.
|
|
2256
2262
|
Use "lmctl exec -- sh -lc '<command>'" when shell expansion is desired.
|
|
2257
2263
|
`,YW=3e4});function ro(t){for(let e=t.length-1;e>=0;e-=1){let r=t[e],n=cB.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),o=n[2]===void 0?0:Number.parseInt(n[2],10),i=n[3].toLowerCase(),a=n[4]?.trim()??null,l=`${n[1]}${n[2]!==void 0?`:${n[2]}`:""}${i}`;return{state:"LIMITED",resets_at:a===null?null:uB(r.timestamp,s,o,i,a),reset_time:l,timezone:a,detected_at:r.timestamp.toISOString()}}return null}function uB(t,e,r,n,s){if(!Number.isFinite(t.getTime())||e<1||e>12||r<0||r>59)return null;let o=dB(e,n);try{let i=fB(t,s),a=SS(i.year,i.month,i.day,o,r,s);if(a.getTime()<=t.getTime()){let l=hB(i,1);a=SS(l.year,l.month,l.day,o,r,s)}return a.toISOString()}catch{return null}}function dB(t,e){return e==="am"?t===12?0:t:t===12?12:t+12}function fB(t,e){let r=vS(e,!1).formatToParts(t);return{year:Qt(r,"year"),month:Qt(r,"month"),day:Qt(r,"day")}}function SS(t,e,r,n,s,o){let i=Date.UTC(t,e-1,r,n,s,0,0);for(let a=0;a<3;a+=1){let l=mB(new Date(i),o);i=Date.UTC(t,e-1,r,n,s,0,0)-l}return new Date(i)}function mB(t,e){let r=vS(e,!0).formatToParts(t);return Date.UTC(Qt(r,"year"),Qt(r,"month")-1,Qt(r,"day"),Qt(r,"hour"),Qt(r,"minute"),Qt(r,"second"),0)-t.getTime()}function vS(t,e){let r=e?_B:pB,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 Qt(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 hB(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 cB,pB,_B,Mf=T(()=>{"use strict";cB=/you['\u2019]ve hit your session limit\s*(?:\u00b7|-|:)?\s*resets\s+([0-9]{1,2})(?::([0-9]{2}))?\s*(am|pm)\s*(?:\(([^)]+)\))?/i;pB=new Map,_B=new Map});var NS={};se(NS,{runRecover:()=>yB});import{dirname as kS,resolve as IS}from"node:path";async function yB(t,e,r={}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${Df}
|
|
@@ -2262,7 +2268,7 @@ ${Df}`);if(n.positionals.length===0)return y(e,`recover requires a <teamfile>
|
|
|
2262
2268
|
${Df}`);if(n.positionals.length>2)return y(e,`unexpected argument: ${n.positionals[2]}`);let s=n.positionals[0],o=jr(s),i=o?.teamfile??s,a=n.positionals[1],l=o?.alias??a;if(o!==null&&a!==void 0)return y(e,"recover alias was provided twice; use either <teamfile>:<alias> or <teamfile> <alias>");if(D(n,"--all")&&l!==void 0)return y(e,"recover --all is mutually exclusive with <alias>");let c;try{c=await wB(e,i,l)}catch(p){if(p instanceof be)return y(e,p.message);throw p}let u=r.now??new Date,d=D(n,"--dry-run"),f=[];for(let p of c)f.push(await EB(e,p,{now:u,dryRun:d}));let m={checked:f.length,recovered:f.filter(p=>p.action==="recovered").length,wouldRecover:f.filter(p=>p.action==="would_recover").length,skipped:f.filter(p=>p.action!=="recovered"&&p.action!=="would_recover").length,errors:f.filter(p=>p.action==="load_error"||p.action==="send_error").length};if(D(n,"--json"))W(e,{dryRun:d,now:u.toISOString(),summary:m,members:f});else{for(let p of f)e.stdout.write(TB(p));e.stdout.write(`Recover checked ${m.checked}: ${d?`${m.wouldRecover} would recover`:`${m.recovered} recovered`}, ${m.skipped} skipped, ${m.errors} error(s).
|
|
2263
2269
|
`)}return m.errors>0?1:0}async function wB(t,e,r){return await R(t,n=>{let s=ye(e,n);if(r!==void 0){let o=qe(s,n);if(o.parseErrors.length>0)throw new be(`lmctl: ${e}: ${o.parseErrors.join("; ")}`);let i=Lo(o,r);return i?.teamfile!==void 0?Pf(IS(kS(s),i.teamfile),n,new Set):[Fe(e,r,n)]}return Pf(s,n,new Set)})}function Pf(t,e,r){let n=ye(t,e);if(r.has(n))return[];r.add(n);let s=qe(n,e);if(s.parseErrors.length>0)throw new be(`lmctl: ${n}: ${s.parseErrors.join("; ")}`);let o=[];for(let i of s.members){if(i.teamfile!==void 0){o.push(...Pf(IS(kS(n),i.teamfile),e,r));continue}i.session!==void 0&&o.push(Fe(n,i.alias,e))}return o}async function EB(t,e,r){let n;try{let a=await Xt(e.sessionid,e.provider);if(a===null)return jt(e,"session_not_found",null,"session detail not found");n=ro(a.messages)}catch(a){return jt(e,"load_error",null,a instanceof Error?a.message:String(a))}if(n===null)return jt(e,"not_limited",null,"no current session-limit marker");if(n.resets_at===null)return jt(e,"unknown_reset",n,"reset time could not be parsed");let s=Date.parse(n.resets_at);if(!Number.isFinite(s))return jt(e,"unknown_reset",n,"reset time could not be parsed");if(s>r.now.getTime())return jt(e,"not_due",n,`resets_at ${n.resets_at} is in the future`);let o=await R(t,a=>a.getAgentInflight(e.teamfile,e.alias));if(o!==null)return jt(e,"busy",n,`in-flight since ${o.started_at}`);if(r.dryRun)return jt(e,"would_recover",n,null);let i=await il({teamfile:e.teamfile,alias:e.alias,prompt:gB,permissionMode:"yolo",io:t,env:process.env});return i.status==="ok"||i.status==="stalled"?jt(e,"recovered",n,null):jt(e,i.status==="busy"?"busy":"send_error",n,i.message)}function jt(t,e,r,n){return{alias:t.alias,teamfile:t.teamfile,provider:t.provider,sessionid:t.sessionid,action:e,sessionLimit:r,reason:n}}function TB(t){let e=t.sessionLimit?.resets_at??"unknown",r=t.reason===null?"":` (${t.reason})`;return`${t.alias}: ${t.action} resets_at=${e}${r}
|
|
2264
2270
|
`}var gB,Df,AS=T(()=>{"use strict";Mf();Fr();vt();tt();xt();Cf();ge();gB="Your session limit reset time has passed. Continue your work from the last actionable point.",Df=["usage: lmctl recover <teamfile> [--all|<alias>] [--dry-run] [--json]","","Wake team members whose latest provider output is a session-limit message","and whose resets_at time has passed. Defaults to the full teamfile report","subtree. A busy/in-flight member is skipped."].join(`
|
|
2265
|
-
`)});var no,TZ,Ff=T(()=>{"use strict";no=[{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 batch or long-running shell work, launch it through `lmctl exec -- <command> &` and wait for completion with `lmctl
|
|
2271
|
+
`)});var no,TZ,Ff=T(()=>{"use strict";no=[{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 batch or long-running shell work, launch it through `lmctl exec -- <command> &` and wait for completion with `lmctl notify_me`.",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}],TZ=no.length});import{spawn as bB}from"node:child_process";async function RS(t,e,r){let n=vB.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 o of n.inputSchema.required??[])if(s[o]===void 0)return{status:"error",code:400,message:`missing required parameter: ${o}`};return kB(n.name,s)}function kB(t,e){return t==="lmctl_chat"?IB(e):{status:"error",code:404,message:`unknown local tool: ${t}`}}function IB(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=["chat",r,n,e];return ue()&&je(JSON.stringify({event:"mcp_chat_spawn",team:r,alias:n})),NB(s,process.cwd())}function NB(t,e){return new Promise(r=>{let n=!1,s,o=u=>{n||(n=!0,s!==void 0&&clearTimeout(s),r(u))},i=bB("lmctl",t,{cwd:e,env:process.env,stdio:["ignore","pipe","pipe"]}),a=AB(process.env);s=setTimeout(()=>{try{i.kill("SIGTERM")}catch{}o({status:"error",code:124,message:`lmctl chat timed out after ${a}ms`})},a),s.unref?.();let l="",c="";i.stdout?.on("data",u=>{l+=u.toString("utf8")}),i.stderr?.on("data",u=>{c+=u.toString("utf8")}),i.on("error",u=>{o({status:"error",code:1,message:`failed to spawn lmctl chat: ${u.message}`})}),i.on("exit",u=>{if(u===0){ue()&&je(JSON.stringify({event:"mcp_chat_payload",bytes:Buffer.byteLength(l,"utf8"),lines:l.split(`
|
|
2266
2272
|
`).length})),o({status:"ok",data:{text:l.trim()||"(empty response)"}});return}o({status:"error",code:u??1,message:c.trim()||`lmctl chat exited with code ${u}`})})})}function AB(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return xS;let r=Number(e);return!Number.isFinite(r)||r<=0?xS:r}function Uf(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:SB),o=t.getConfig("api.token")??(e.LMCTL_API_TOKEN!==void 0&&e.LMCTL_API_TOKEN.length>0?e.LMCTL_API_TOKEN:null);return{baseUrl:n,token:o}}var SB,xS,vB,Wf=T(()=>{"use strict";Ff();ve();SB="http://127.0.0.1:8787",xS=30*60*1e3,vB=new Map(no.map(t=>[t.name,t]))});async function $B(t,e){let r=t.id===void 0,n=t.id??null;if(t.method==="exit")return r||e.io.write(Bf({jsonrpc:"2.0",id:n,result:null})),{kind:"exit"};if(t.method==="initialize")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{protocolVersion:xB,capabilities:{tools:{listChanged:!1}},serverInfo:{name:RB,version:LB}}}};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:no.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:{},o=typeof s.name=="string"?s.name:"",i=s.arguments,a=await RS(o,i,e.dispatch),l=o==="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 Bf(t){return`${JSON.stringify(t)}
|
|
2267
2273
|
`}async function LS(t,e){let r=!1,n="",s=!1,o=async i=>{let a=i.trim();if(a.length===0)return;let l;try{l=JSON.parse(a)}catch(u){t.io.write(Bf({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 $B(l,t);c.kind==="response"?t.io.write(Bf(c.message)):c.kind==="exit"&&(s=!0)};return new Promise(i=>{let a=Promise.resolve(),l=!1,c=d=>{l||(l=!0,i(d))},u=()=>{let d=n.indexOf(`
|
|
2268
2274
|
`);for(;d!==-1;){let f=n.slice(0,d);n=n.slice(d+1),a=a.then(()=>o(f)).then(()=>{s&&c(0)}),d=n.indexOf(`
|
|
@@ -2475,8 +2481,8 @@ List native provider sessions in scope, or list recent managed runs with --runs.
|
|
|
2475
2481
|
`),0}async function R2(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(Yf),0;let r,n;if(t.length===1){let d=jr(t[0]);if(d===null)return e.stderr.write(Yf),2;r=d.teamfile,n=d.alias}else if(t.length===2)[r,n]=t;else return e.stderr.write(Yf),2;let s;try{s=await R(e,d=>ye(r,d))}catch(d){return Ce(e,`${r}: ${d instanceof Error?d.message:String(d)}`)}let o;try{o=_l(s,"utf8")}catch(d){return Ce(e,`${r}: ${d instanceof Error?d.message:String(d)}`)}let i=o.split(`
|
|
2476
2482
|
`),a=j2(i,n);if(a===void 0)return Ce(e,`${n}: no active _MEMBER_ entry found`);let l=i[a];if(uo(l,"teamfile")!==void 0)return Ce(e,`${n}: refresh only applies to provider-backed members, not teamfile= members`);let c=(e.env??process.env)[xr],u=uo(l,"sessionid");return c!==void 0&&c.length>0&&u===c?Ce(e,`${n}: cannot refresh its own running session \u2014 a meta-Lead or the operator must run this refresh.`):(i[a]=Nv(l,"sessionid"),a>0&&/^\s*#CreationTime:/u.test(i[a-1])&&i.splice(a-1,1),pl(s,i.join(`
|
|
2477
2483
|
`),"utf8"),Sv([s],e))}function vv(t){return p2("sha256").update(t).digest("hex")}function kv(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:vv(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function Iv(t,e){let r=kv(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(r),r}function L2(t,e,r){let n=r.filter(a=>a.alias.toLowerCase()!=="lead").map(a=>{let l=a.teamfile!==void 0?`teamfile=${a.teamfile}`:`provider=${a.provider}`;return`- ${a.alias}: ${l}`}),s=n.length>0?n.join(`
|
|
2478
|
-
`):"- (no non-Lead members)",o=r.find(a=>a.alias.toLowerCase()==="lead")?.provider??"",i=$2(o,t);return["lmctl seed initial connection only. Create or pin this provider session, then stop.","Do not inspect files, run commands, infer a task, delegate, edit, or begin work.","",`Teamfile path: ${t}`,"You are alias Lead for this AI-managed .lmctl team.","","Delegating work:",`- Blocking command shape: lmctl chat "${t}" <alias> "your task here"`,"- MCP lmctl_chat is synchronous/blocking; use it only as a quick-ping or backup path.",'- Plain shell "&" alone is blind backgrounding. Use lmctl-tracked commands, then run lmctl
|
|
2479
|
-
`)}function $2(t,e){let r=`lmctl chat "${e}" <alias> "your task here"`;switch(t.toLowerCase()){case"claude":return`- Claude tip: run the blocking command (${r}) as background Bash (run_in_background: true); the runtime re-invokes you with the reply when it completes.`;case"copilot":return`- Copilot tip: run the blocking command (${r}) via bash async mode (mode:"async"); the runtime notifies you with output when it completes.`;case"agy":return`- Antigravity tip: run the blocking command (${r}) via run_command with WaitMsBeforeAsync: 0 (Background Tasks); agy wakes you with the output when it completes.`;case"qwen":return`- Qwen tip: run the blocking command (${r}) via the monitor tool; it notifies you on completion.`;case"codex":return"- Codex note: no native completion push; for long work, background tracked lmctl chat or lmctl exec, then run lmctl
|
|
2484
|
+
`):"- (no non-Lead members)",o=r.find(a=>a.alias.toLowerCase()==="lead")?.provider??"",i=$2(o,t);return["lmctl seed initial connection only. Create or pin this provider session, then stop.","Do not inspect files, run commands, infer a task, delegate, edit, or begin work.","",`Teamfile path: ${t}`,"You are alias Lead for this AI-managed .lmctl team.","","Delegating work:",`- Blocking command shape: lmctl chat "${t}" <alias> "your task here"`,"- MCP lmctl_chat is synchronous/blocking; use it only as a quick-ping or backup path.",'- Plain shell "&" alone is blind backgrounding. Use lmctl-tracked commands, then run lmctl notify_me.',"- Call lmctl notify_me in the FOREGROUND; it holds your process and returns when a member finishes.","- notify_me means: I'm done with this round; my delegations are all running in the background; I'm taking a break \u2014 notify me when something lands.",`- For non-blocking member work: run the blocking lmctl chat command in the background, then run lmctl notify_me. Example: lmctl chat "${t}" <alias> "your task here" & lmctl notify_me`,"- For arbitrary shell work: lmctl exec -- <command> & lmctl notify_me",i,"","Delegation is an ACTION, not a plan: to hand a member a task, run the command or call the tool.","If you use lmctl_chat and it appears only after tool search, call it in the SAME turn and do not stop after discovering it or say you're about to call it.","","Team members:",s,"","Example MCP calls:",...r.filter(a=>a.alias.toLowerCase()!=="lead").map(a=>`lmctl_chat(team="${t}", alias="${a.alias}", prompt="your task here")`),"","If a member feels sluggish or starts drifting (degraded or off-track output):",` 1. Check ONE member's session health: lmctl health "${t}" <alias> (size/state \u2014 informational).`," 2. Make sure important state is captured in durable-memory/ \u2014 update it if not.",` 3. Replace its session: lmctl refresh "${t}" <alias> (re-seeds the member: drops chat history, re-reads durable-memory/). You cannot refresh your own Lead session \u2014 a meta-Lead or the operator does that.`,` Optional: lmctl tail "${t}" <alias> to inspect its recent messages while troubleshooting.`,"(These health/recovery commands are shell commands. For delegation, prefer tracked CLI commands plus lmctl notify_me; lmctl_chat is the synchronous backup.)","","Full teamfile document at seed time:","```lmctl",e.trimEnd(),"```","","Remember this teamfile path. Do not ask the operator for it when asked to ping or delegate to members.","Reply exactly: ACK: teamfile context recorded."].join(`
|
|
2485
|
+
`)}function $2(t,e){let r=`lmctl chat "${e}" <alias> "your task here"`;switch(t.toLowerCase()){case"claude":return`- Claude tip: run the blocking command (${r}) as background Bash (run_in_background: true); the runtime re-invokes you with the reply when it completes.`;case"copilot":return`- Copilot tip: run the blocking command (${r}) via bash async mode (mode:"async"); the runtime notifies you with output when it completes.`;case"agy":return`- Antigravity tip: run the blocking command (${r}) via run_command with WaitMsBeforeAsync: 0 (Background Tasks); agy wakes you with the output when it completes.`;case"qwen":return`- Qwen tip: run the blocking command (${r}) via the monitor tool; it notifies you on completion.`;case"codex":return"- Codex note: no native completion push; for long work, background tracked lmctl chat or lmctl exec, then run lmctl notify_me.";case"gemini":return"- Gemini note: no native completion push; for long work, background tracked lmctl chat or lmctl exec, then run lmctl notify_me.";case"opencode":return"- OpenCode note: use the provider-native background/task surface when available; otherwise run one blocking lmctl chat turn and wait.";default:return"- If your provider has native background-shell completion, use it around the blocking command; otherwise background the tracked command and run lmctl notify_me."}}function O2(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=uo(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function j2(t,e){let r=e.toLowerCase();for(let n=0;n<t.length;n+=1){let s=t[n];if(/^\s*_MEMBER_\s+\S/u.test(s)&&uo(s,"alias")?.toLowerCase()===r)return n}}function C2(t,e){for(let r of t.split(`
|
|
2480
2486
|
`))if(/^\s*#?\s*_MEMBER_\s+\S/u.test(r)&&uo(r,"alias")===e)return!0;return!1}function M2(t){return/^[A-Za-z][A-Za-z0-9_-]*$/u.test(t)}function uo(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function D2(t,e,r){let n=`${e}=${em(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(o,i)=>`${i}${n}`):`${t.trimEnd()} ${n}`}function Nv(t,e){let r=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return t.replace(r,"").replace(/\s+/gu," ").trimEnd()}function em(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function P2(t,e){let r=t.split(`
|
|
2481
2487
|
`),n=-1;for(let a=r.length-1;a>=0;a-=1)if(/^\s*_MEMBER_(?:\s|$)/u.test(r[a])){n=a;break}if(n>=0)return r.splice(n+1,0,e),r.join(`
|
|
2482
2488
|
`);let s=r.length;for(;s>0&&r[s-1]==="";)s-=1;let o=r.slice(0,s).join(`
|
|
@@ -2777,11 +2783,11 @@ Daemon & client:
|
|
|
2777
2783
|
Teams & sessions:
|
|
2778
2784
|
team Manage DB-backed teams, members, and provider session seeding.
|
|
2779
2785
|
chat Send a prompt or operator answer to a member, raw session, or paused run.
|
|
2780
|
-
|
|
2786
|
+
notify_me Foreground wait: hold this process and return when a member finishes.
|
|
2781
2787
|
terminal Open a member's native provider TUI or show session-size estimates.
|
|
2782
2788
|
tail Print or watch provider session messages or a run timeline.
|
|
2783
2789
|
health Show provider session, team rollup, or run state/token info (informational; no actions).
|
|
2784
|
-
exec Run a command as a tracked invocation for lmctl
|
|
2790
|
+
exec Run a command as a tracked invocation for lmctl notify_me.
|
|
2785
2791
|
recover Wake members after provider session-limit reset times pass.
|
|
2786
2792
|
ls List provider sessions or recent runs.
|
|
2787
2793
|
lint Validate an lmctl teamfile.
|
|
@@ -2809,15 +2815,15 @@ Global flags:
|
|
|
2809
2815
|
write full stack + cause chain and context to that file.
|
|
2810
2816
|
|
|
2811
2817
|
Run 'lmctl help <command>' for command-specific help.
|
|
2812
|
-
`,qk=new Set(["api","chat","
|
|
2818
|
+
`,qk=new Set(["api","chat","notify_me","code","serve","intake","mcp","monitor","device","team","terminal","tail","health","exec","recover","ls","lint","seed","hire","refresh","clone","plan","workflow","run","project","workspace","diagnose","diagnose-prompt","status","db"]);function Nm(t,e){return t.stderr.write(`error: ${e}
|
|
2813
2819
|
${Kr}Run 'lmctl help' for usage.
|
|
2814
2820
|
`),2}function Jk(t,e){return e==="send"?(t.stderr.write(`error: unknown command: send (use lmctl chat)
|
|
2815
2821
|
${Kr}Run 'lmctl help' for usage.
|
|
2816
|
-
`),1):e==="recv"?(t.stderr.write(`error: unknown command: recv (use lmctl
|
|
2822
|
+
`),1):e==="recv"?(t.stderr.write(`error: unknown command: recv (use lmctl notify_me)
|
|
2817
2823
|
${Kr}Run 'lmctl help' for usage.
|
|
2818
|
-
`),1):e==="loop"?(t.stderr.write(`error: unknown command: loop (use backgrounded lmctl chat/
|
|
2824
|
+
`),1):e==="loop"?(t.stderr.write(`error: unknown command: loop (use backgrounded lmctl chat/exec with lmctl notify_me)
|
|
2819
2825
|
${Kr}Run 'lmctl help' for usage.
|
|
2820
|
-
`),1):e==="check"||e==="push"||e==="wait"?(t.stderr.write(`error: unknown command: ${e} (use lmctl
|
|
2826
|
+
`),1):e==="check"||e==="push"||e==="wait"?(t.stderr.write(`error: unknown command: ${e} (use lmctl notify_me)
|
|
2821
2827
|
${Kr}Run 'lmctl help' for usage.
|
|
2822
2828
|
`),1):(t.stderr.write(`error: unknown command: ${e}
|
|
2823
2829
|
${Kr}Run 'lmctl help' for usage.
|
|
@@ -2825,7 +2831,7 @@ ${Kr}Run 'lmctl help' for usage.
|
|
|
2825
2831
|
`),0;if(n==="--help"||n==="-h"||n===void 0)return e.stdout.write(Im),0;if(n==="help"){let[a,...l]=r.slice(1);return a===void 0||a==="--help"||a==="-h"?(e.stdout.write(Im),0):qk.has(a)?Hk(a,[...l,"--help"],e):Jk(e,a)}$m(le(),e.stderr),jm(e.stderr);let[s,...o]=r;if(s===void 0)return e.stdout.write(Im),0;let i=Date.now();Am(s,o,{phase:"start",started_at:new Date(i).toISOString()});try{let a=await Hk(s,o,e);return Am(s,o,{phase:"finish",outcome:a===0?"ok":"error",exit_code:a,duration_ms:Date.now()-i}),qk.has(s)&&!jl(r,e)&&await Vm(e,r),a}catch(a){let l=a instanceof Error?a:new Error(String(a));return Am(s,o,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-i,error_class:l.name,error_message:l.message,error_stack:l.stack??null,causes:aX(l)}),iX(a,s,o,e)}}function Am(t,e,r){Oe({event:t,record_kind:"cli_action",command:t,argv:e,cwd:process.cwd(),db_path:le(),workspace:process.env.LMCTL_WORKSPACE??null,lmctl_version:Tt(),node_version:process.version,...r})}function iX(t,e,r,n){let s=t instanceof Error?t:new Error(String(t));return n.stderr.write(`error: ${s.message}
|
|
2826
2832
|
`),Gm()?(n.stderr.write(`(debug details written to ~/.lmctl/debug-*.log)
|
|
2827
2833
|
`),1):(n.stderr.write(`(re-run with --debug for the full stack trace and context in ~/.lmctl/debug-*.log)
|
|
2828
|
-
`),1)}function aX(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 Hk(t,e,r){switch(t){case"__deliver-lane":{let{runDeliveryWorker:n}=await Promise.resolve().then(()=>(eu(),Qc));return n(e,r)}case"api":{let{runApi:n}=await Promise.resolve().then(()=>(hu(),rg));return n(e,r)}case"code":{let{runCode:n}=await Promise.resolve().then(()=>(Mu(),Xg));return n(e,r)}case"serve":{let{runServe:n}=await Promise.resolve().then(()=>(Yb(),Vb));return n(e,r)}case"intake":{let{runIntake:n}=await Promise.resolve().then(()=>(Zb(),zb));return n(e,r)}case"chat":{let{runChat:n}=await Promise.resolve().then(()=>(wS(),yS));return n(e,r)}case"
|
|
2834
|
+
`),1)}function aX(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 Hk(t,e,r){switch(t){case"__deliver-lane":{let{runDeliveryWorker:n}=await Promise.resolve().then(()=>(eu(),Qc));return n(e,r)}case"api":{let{runApi:n}=await Promise.resolve().then(()=>(hu(),rg));return n(e,r)}case"code":{let{runCode:n}=await Promise.resolve().then(()=>(Mu(),Xg));return n(e,r)}case"serve":{let{runServe:n}=await Promise.resolve().then(()=>(Yb(),Vb));return n(e,r)}case"intake":{let{runIntake:n}=await Promise.resolve().then(()=>(Zb(),zb));return n(e,r)}case"chat":{let{runChat:n}=await Promise.resolve().then(()=>(wS(),yS));return n(e,r)}case"notify_me":{let{runNotifyMe:n}=await Promise.resolve().then(()=>(eu(),Qc));return n(e,r)}case"exec":{let{runExec:n}=await Promise.resolve().then(()=>(bS(),TS));return n(e,r)}case"recover":{let{runRecover:n}=await Promise.resolve().then(()=>(AS(),NS));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(CS(),jS));return n(e,r)}case"monitor":{let{runMonitor:n}=await Promise.resolve().then(()=>(qS(),BS));return n(e,r)}case"device":{let{runDevice:n}=await Promise.resolve().then(()=>(JS(),HS));return n(e,r)}case"team":{let{runTeam:n}=await Promise.resolve().then(()=>(KS(),GS));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(rv(),tv));return n(e,r)}case"health":{let{runInfo:n}=await Promise.resolve().then(()=>(uv(),cv));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(mv(),fv));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>(mo(),fo));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>(mo(),fo));return n(e,r)}case"hire":{let{runHire:n}=await Promise.resolve().then(()=>(mo(),fo));return n(e,r)}case"refresh":{let{runRefresh:n}=await Promise.resolve().then(()=>(mo(),fo));return n(e,r)}case"clone":{let{runClone:n}=await Promise.resolve().then(()=>(jv(),Ov));return n(e,r)}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(Pv(),Dv));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(Bv(),Wv));return n(e,r)}case"workflow":{let{runWorkflow:n}=await Promise.resolve().then(()=>(pm(),mm));return n(e,r)}case"run":{let{runWorkflow:n}=await Promise.resolve().then(()=>(pm(),mm));return n(["run",...e],r)}case"workspace":{let{runWorkspace:n}=await Promise.resolve().then(()=>(fk(),dk));return n(e,r)}case"project":{let{runProject:n}=await Promise.resolve().then(()=>(hk(),_k));return n(e,r)}case"diagnose":{let{runDiagnose:n}=await Promise.resolve().then(()=>(Rk(),xk));return n(e,r)}case"diagnose-prompt":{let{runDiagnosePrompt:n}=await Promise.resolve().then(()=>(Dk(),Mk));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Bk(),Wk));return n(e,r)}case"db":return lX(e,r);default:return Jk(r,t)}}function lX(t,e){let[r,...n]=t;return r==="--help"||r==="-h"||r==="help"?(e.stdout.write(`usage: lmctl db downgrade --to <version> --confirm
|
|
2829
2835
|
|
|
2830
2836
|
Database utilities. The downgrade command is currently a documented stub;
|
|
2831
2837
|
restore from backup for rollback and use normal migrations for forward changes.
|