@lmctl-ai/lmctl 0.1.178 → 0.1.179
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +215 -133
- package/dist/cli/schema.sql +112 -0
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -2,7 +2,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
2
2
|
`)}function Za(){return Mt(Ir(),$k)}function em(){return Mt(Ir(),Ck)}function jk(){try{return Ys(Za())}catch{return!1}}function tm(t=process.stderr){jk()&&t.write(`note: legacy ~/.lmctl/profiles/ detected \u2014 run 'lmctl workspace migrate' to move it to ~/.lmctl/workspaces/
|
|
3
3
|
`)}var Rk,zf,Lk,Ok,Zf,$k,Ck,Nr,We=E(()=>{"use strict";Rk=".lmctl",zf="state.db",Lk="workspaces",Ok="active-workspace",Zf="default",$k="profiles",Ck="active-profile";Nr={default:Zf}});function Uk(t){for(let e of Fk)if(t.startsWith(e))return!0;if(t.startsWith("172.")){let e=Number(t.split(".")[1]);if(Number.isFinite(e)&&e>=16&&e<=31)return!0}return!!t.startsWith("169.254.")}function Wk(t){let e=t.toLowerCase();return!!(e==="::1"||e==="::"||e.startsWith("fe80:")||e.startsWith("fe80::"))}function Hk(t){let e=t.split(".");if(e.length!==4)return!1;for(let r of e){if(r.length===0||r.length>3)return!1;let n=Number(r);if(!Number.isFinite(n)||n<0||n>255)return!1}return!0}function Bn(t){let e=t;for(let{re:r,replacement:n}of Pk)e=e.replace(r,n);return e=e.replace(Bk,r=>!Hk(r)||Uk(r)?r:rm),e=e.replace(qk,r=>Wk(r)?r:rm),e}function qn(t){return t.split(`
|
|
4
4
|
`).map(e=>Bn(e)).join(`
|
|
5
|
-
`)}function sm(t,e){let r=t.toUpperCase();return r.includes("TOKEN")||r.includes("SECRET")||r.includes("KEY")||r.includes("PASSWORD")||r.includes("PASSWD")||r.includes("CREDENTIAL")||r.includes("AUTH")?{key:t,value:it}:{key:t,value:Bn(e)}}function tr(t){if(typeof t=="string")return Bn(t);if(Array.isArray(t))return t.map(e=>tr(e));if(t!==null&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t)){let s=r.toUpperCase();s.includes("TOKEN")||s.includes("SECRET")||s.includes("KEY")||s.includes("PASSWORD")||s.includes("PASSWD")||s.includes("CREDENTIAL")?e[r]=typeof n=="string"?it:tr(n):e[r]=tr(n)}return e}return t}function im(t,e){for(let{name:r,re:n}of
|
|
5
|
+
`)}function sm(t,e){let r=t.toUpperCase();return r.includes("TOKEN")||r.includes("SECRET")||r.includes("KEY")||r.includes("PASSWORD")||r.includes("PASSWD")||r.includes("CREDENTIAL")||r.includes("AUTH")?{key:t,value:it}:{key:t,value:Bn(e)}}function tr(t){if(typeof t=="string")return Bn(t);if(Array.isArray(t))return t.map(e=>tr(e));if(t!==null&&typeof t=="object"){let e={};for(let[r,n]of Object.entries(t)){let s=r.toUpperCase();s.includes("TOKEN")||s.includes("SECRET")||s.includes("KEY")||s.includes("PASSWORD")||s.includes("PASSWD")||s.includes("CREDENTIAL")?e[r]=typeof n=="string"?it:tr(n):e[r]=tr(n)}return e}return t}function im(t,e){for(let{name:r,re:n}of Xk){let s=e.match(n);if(s!==null&&!s[0].includes(it))throw new xr(t,r)}}var it,Dk,rm,nm,Pk,Fk,Bk,qk,Xk,xr,ti=E(()=>{"use strict";it="[REDACTED]",Dk="[REDACTED_EMAIL]",rm="[REDACTED_IP]",nm="[USER]",Pk=[{re:/(authorization\s*[:=]\s*)(bearer\s+[^\s,;"']+)/gi,replacement:`$1Bearer ${it}`},{re:/(authorization\s*[:=]\s*)(basic\s+[^\s,;"']+)/gi,replacement:`$1Basic ${it}`},{re:/\b(Bearer\s+)[A-Za-z0-9_\-./+=]{8,}/g,replacement:`$1${it}`},{re:/\bsk-ant-[A-Za-z0-9_\-]{8,}/g,replacement:it},{re:/\bsk-[A-Za-z0-9_\-]{16,}/g,replacement:it},{re:/\bgh[pousr]_[A-Za-z0-9]{30,}/g,replacement:it},{re:/\bAKIA[0-9A-Z]{16}\b/g,replacement:it},{re:/\b(api[_-]?key|token|secret|password|passwd)(\s*[:=]\s*"?)([A-Za-z0-9_\-./+=]{8,})("?)/gi,replacement:`$1$2${it}$4`},{re:/(\/home\/)[^/\s"'`]+/g,replacement:`$1${nm}`},{re:/(\/Users\/)[^/\s"'`]+/g,replacement:`$1${nm}`},{re:/\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b/g,replacement:Dk}],Fk=["127.","10.","192.168.","0.0.0.0"];Bk=/\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b/g,qk=/\b(?:[0-9a-fA-F]{1,4}:){2,7}(?::[0-9a-fA-F]{1,4})+\b|\b(?:[0-9a-fA-F]{1,4}:){3,7}[0-9a-fA-F]{1,4}\b|::1\b|::\b(?=[\s,;"')]|$)/g;Xk=[{name:"sk-ant",re:/\bsk-ant-[A-Za-z0-9_\-]{8,}/},{name:"sk-openai",re:/\bsk-[A-Za-z0-9_\-]{16,}/},{name:"github-pat",re:/\bgh[pousr]_[A-Za-z0-9]{30,}/},{name:"aws-akid",re:/\bAKIA[0-9A-Z]{16}\b/},{name:"bearer",re:/\bBearer\s+[A-Za-z0-9_\-./+=]{8,}/},{name:"email",re:/\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b/},{name:"home-path",re:/\/home\/(?!\[USER\])[^/\s"'`]+/},{name:"users-path",re:/\/Users\/(?!\[USER\])[^/\s"'`]+/}],xr=class extends Error{bundlePath;patternName;constructor(e,r){super(`sanitization failed: ${r} pattern matched in ${e}`),this.bundlePath=e,this.patternName=r,this.name="SanitizationError"}}});import{spawnSync as Qa}from"node:child_process";import{readFileSync as Jk}from"node:fs";import{readFile as tl,stat as om}from"node:fs/promises";import{homedir as Gk}from"node:os";import{join as Kk}from"node:path";import{fileURLToPath as Vk}from"node:url";function Et(){try{let t=new URL("../../package.json",import.meta.url),e=JSON.parse(Jk(Vk(t),"utf8"));if(typeof e.version=="string")return e.version}catch{}return"0.0.0"}async function am(t){let e=new Set(t.include??ri),r={};return e.has("serve")&&(r.serve=await zk(t)),e.has("db")&&(r.db=Zk(t)),e.has("runs")&&(r.runs=Qk(t)),e.has("jobs")&&(r.jobs=eI(t)),e.has("attentions")&&(r.attentions=tI(t)),e.has("env")&&(r.env=await rI(t)),e.has("intents")&&(r.intents=await sI(t)),r}async function zk(t){let e=t.pidFile??process.env.LMCTL_PID_FILE,r=t.serveLog??process.env.LMCTL_SERVE_LOG,n=t.logTailLines??1e3,s=null,i="none";if(e!==void 0)try{let d=(await tl(e,"utf8")).trim(),u=Number.parseInt(d,10);Number.isInteger(u)&&u>0&&(s=u,i="pidfile")}catch{}let o=null;if(s!==null)try{process.kill(s,0),o=!0}catch{o=!1}let a="",l=null,c=0;if(r===void 0)l="no serve log configured (set LMCTL_SERVE_LOG or --serve-log)";else try{let u=(await tl(r,"utf8")).split(`
|
|
6
6
|
`),f=u.slice(Math.max(0,u.length-n));c=f.length,a=qn(f.join(`
|
|
7
7
|
`))}catch(d){l=`serve log unreadable: ${d instanceof Error?d.message:String(d)}`}return{pid:s,pid_source:i,pid_alive:o,log_tail_lines:c,log_tail:a,log_note:l}}function Zk(t){let{dal:e}=t,r="unknown";try{r=e.query("PRAGMA integrity_check;").map(o=>o.integrity_check??JSON.stringify(o)).join(`
|
|
8
8
|
`)}catch(i){r=`integrity_check failed: ${i instanceof Error?i.message:String(i)}`}let n=0;try{n=e.query("PRAGMA user_version;")[0]?.user_version??0}catch{n=0}let s={};try{let i=e.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name");for(let{name:o}of i)try{let a=e.query(`SELECT COUNT(*) AS c FROM "${o.replace(/"/g,'""')}"`);s[o]=a[0]?.c??0}catch{s[o]=-1}}catch{}return{integrity_check:r,schema_version:n,table_counts:s}}function Qk(t){let{dal:e}=t,r=(t.now??new Date).toISOString(),n=(t.staleThresholdMin??60)*6e4,s=new Date(Date.parse(r)-n).toISOString(),i=e.query(`SELECT ${el} FROM run ORDER BY id DESC LIMIT 50`),o=e.query(`SELECT ${el} FROM run WHERE paused_at IS NOT NULL AND terminal_state IS NULL ORDER BY paused_at DESC LIMIT 50`),a=e.query(`SELECT ${el} FROM run
|
|
@@ -14,7 +14,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
14
14
|
`).filter(o=>o.length>0),i=s.slice(Math.max(0,s.length-r));return{source_path:e,tail_lines:i.length,tail:qn(i.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 ri,Yk,el,Hn=E(()=>{"use strict";ti();ri=["serve","db","runs","jobs","attentions","env","intents"];Yk=["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"];el=["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 dm,appendFileSync as iI,mkdirSync as oI,existsSync as p2,readdirSync as _2,unlinkSync as h2}from"node:fs";import{join as si,dirname as aI}from"node:path";import{homedir as lI}from"node:os";function rl(){return si(lI(),".lmctl")}function um(){Yr=!0,process.env.LMCTL_DEBUG="1"}function fm(){return{cliDebug:Yr,lmctlDebugEnv:process.env.LMCTL_DEBUG}}function mm(t){Yr=t.cliDebug,t.lmctlDebugEnv===void 0?delete process.env.LMCTL_DEBUG:process.env.LMCTL_DEBUG=t.lmctlDebugEnv}function ce(){if(Yr||process.env.LMCTL_DEBUG==="1")return!0;let t=Date.now();return t-cm>=cI&&(lm=fI(),cm=t),lm}function pm(){return Yr||process.env.LMCTL_DEBUG==="1"}function dI(){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 Ae(t,e){if(e?.verbose){if(!Yr)return}else if(!e?.always&&!ce())return;try{uI();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};iI(ni,JSON.stringify(r)+`
|
|
16
16
|
`)}catch{}}function uI(){if(!ni){let e=dI().slice(0,13).replace("T","-");ni=si(rl(),`debug-${e}.log`)}oI(aI(ni),{recursive:!0})}function Oe(...t){Ae({event:"legacy",msg:t.join(" ")})}function Tt(...t){Ae({event:"legacy",msg:t.join(" ")},{verbose:!0})}function C(t){Ae(t,{always:!0})}function fI(){return mI()||pI()}function mI(){try{let t=dm(si(rl(),"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 pI(){try{let t=dm(si(rl(),"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,lm,cm,cI,ni,de=E(()=>{"use strict";Yr=!1,lm=!1,cm=0,cI=5e3;ni=null});import{existsSync as $I}from"node:fs";import{createRequire as CI}from"node:module";function MI(){return sl===null&&(sl=CI(import.meta.url)("node:sqlite").DatabaseSync),sl}function il(t){return t.length===1&&jI(t[0])?[t[0]]:t}function jI(t){if(!ll(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ll(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var sl,ol,wm,al,Em=E(()=>{"use strict";sl=null;ol=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!$I(e))throw new Error("unable to open database file");this.name=e,this.handle=new(MI())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new al(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)}}},wm=ol,al=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...il(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...il(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...il(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&ll(e)?Object.values(e):ll(e)?{...e}:e}}});import{existsSync as DI,mkdirSync as PI,readFileSync as bm}from"node:fs";import{homedir as FI}from"node:os";import{dirname as Sm,join as UI,resolve as vm}from"node:path";import{fileURLToPath as WI,pathToFileURL as BI}from"node:url";function cl(t){t.dbPath!==":memory:"&&PI(Sm(t.dbPath),{recursive:!0});let e=new wm(t.dbPath);e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=Nm(e);return r===0&&(e.exec(bm(Im,"utf8")),e.pragma(`user_version = ${HI}`)),
|
|
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 pI(){try{let t=dm(si(rl(),"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,lm,cm,cI,ni,de=E(()=>{"use strict";Yr=!1,lm=!1,cm=0,cI=5e3;ni=null});import{existsSync as $I}from"node:fs";import{createRequire as CI}from"node:module";function MI(){return sl===null&&(sl=CI(import.meta.url)("node:sqlite").DatabaseSync),sl}function il(t){return t.length===1&&jI(t[0])?[t[0]]:t}function jI(t){if(!ll(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ll(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var sl,ol,wm,al,Em=E(()=>{"use strict";sl=null;ol=class{name;handle;transactionDepth=0;savepointId=0;constructor(e,r={}){if(r.fileMustExist===!0&&e!==":memory:"&&!$I(e))throw new Error("unable to open database file");this.name=e,this.handle=new(MI())(e,{readOnly:r.readonly===!0}),this.exec("PRAGMA busy_timeout = 5000")}prepare(e){return new al(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)}}},wm=ol,al=class{handle;rawMode=!1;constructor(e){this.handle=e,this.handle.setAllowBareNamedParameters(!0)}get(...e){let r=this.handle.get(...il(e));return this.normalizeRow(r)}all(...e){return this.handle.all(...il(e)).map(r=>this.normalizeRow(r))}run(...e){let r=this.handle.run(...il(e));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}raw(){return this.rawMode=!0,this}normalizeRow(e){return e==null?e:this.rawMode&&ll(e)?Object.values(e):ll(e)?{...e}:e}}});import{existsSync as DI,mkdirSync as PI,readFileSync as bm}from"node:fs";import{homedir as FI}from"node:os";import{dirname as Sm,join as UI,resolve as vm}from"node:path";import{fileURLToPath as WI,pathToFileURL as BI}from"node:url";function cl(t){t.dbPath!==":memory:"&&PI(Sm(t.dbPath),{recursive:!0});let e=new wm(t.dbPath);e.pragma("journal_mode = WAL"),e.pragma("synchronous = NORMAL"),e.pragma("foreign_keys = ON");let r=Nm(e);return r===0&&(e.exec(bm(Im,"utf8")),e.pragma(`user_version = ${HI}`)),XI(e,r),e}function XI(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,
|
|
@@ -428,7 +428,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
428
428
|
updated_at TEXT NOT NULL,
|
|
429
429
|
PRIMARY KEY(user_id, device_id, period)
|
|
430
430
|
);
|
|
431
|
-
`),t.pragma("user_version = 36"),r=36),r<37&&r!==0&&(
|
|
431
|
+
`),t.pragma("user_version = 36"),r=36),r<37&&r!==0&&(Xn(t,"team_connection")&&t.exec(`
|
|
432
432
|
CREATE TABLE IF NOT EXISTS team_connection_v37 (
|
|
433
433
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
434
434
|
source_teamfile TEXT NOT NULL,
|
|
@@ -553,7 +553,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
553
553
|
ON agent_mailbox(sender_teamfile, sender_alias, created_at);
|
|
554
554
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_created
|
|
555
555
|
ON agent_mailbox(created_at);
|
|
556
|
-
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(
|
|
556
|
+
`),t.pragma("user_version = 45"),r=45),r<46&&r!==0&&(Xn(t,"team_chat_log")?Tm(t):t.exec(`
|
|
557
557
|
CREATE TABLE IF NOT EXISTS team_chat_log (
|
|
558
558
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
559
559
|
root_teamfile TEXT NOT NULL,
|
|
@@ -572,7 +572,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
572
572
|
`),t.exec(`
|
|
573
573
|
CREATE INDEX IF NOT EXISTS idx_team_chat_log_root_time
|
|
574
574
|
ON team_chat_log(root_teamfile, created_at);
|
|
575
|
-
`),t.pragma("user_version = 46"),r=46),r>=46&&
|
|
575
|
+
`),t.pragma("user_version = 46"),r=46),r>=46&&Xn(t,"team_chat_log")&&!re(t,"team_chat_log").has("origin")&&Tm(t),r<47&&r!==0){Ar(t,"agent_mailbox"),Ar(t,"tracked_invocation");let n=re(t,"agent_mailbox");n.has("delivered_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivered_at TEXT;"),n.has("receipt")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN receipt TEXT;");let s=re(t,"tracked_invocation");s.has("notified_by")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_by TEXT;"),s.has("notified_at")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN notified_at TEXT;"),t.pragma("user_version = 47"),r=47}if(r<48&&r!==0){Ar(t,"agent_mailbox");let n=re(t,"agent_mailbox");n.has("delivering_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivering_at TEXT;"),n.has("delivery_holder_pid")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_pid INTEGER;"),n.has("delivery_holder_host")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN delivery_holder_host TEXT;"),n.has("waited_at")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_at TEXT;"),n.has("waited_by")||t.exec("ALTER TABLE agent_mailbox ADD COLUMN waited_by TEXT;"),t.exec(`
|
|
576
576
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_sender_delivery_wait
|
|
577
577
|
ON agent_mailbox(sender_teamfile, sender_alias, delivered_at, waited_at, id);
|
|
578
578
|
CREATE INDEX IF NOT EXISTS idx_agent_mailbox_lane_delivery
|
|
@@ -599,7 +599,89 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
599
599
|
BEGIN
|
|
600
600
|
SELECT RAISE(ABORT, 'agent_mailbox response requires request_mailbox_id');
|
|
601
601
|
END;
|
|
602
|
-
`),t.pragma("user_version = 51"),r=51}r<52&&r!==0&&(Ar(t,"tracked_invocation"),re(t,"tracked_invocation").has("request_payload")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN request_payload TEXT;"),t.pragma("user_version = 52"),r=52),
|
|
602
|
+
`),t.pragma("user_version = 51"),r=51}r<52&&r!==0&&(Ar(t,"tracked_invocation"),re(t,"tracked_invocation").has("request_payload")||t.exec("ALTER TABLE tracked_invocation ADD COLUMN request_payload TEXT;"),t.pragma("user_version = 52"),r=52),r<53&&r!==0&&(t.exec(`
|
|
603
|
+
CREATE TABLE IF NOT EXISTS message_event (
|
|
604
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
605
|
+
event_id TEXT NOT NULL UNIQUE,
|
|
606
|
+
ts TEXT NOT NULL,
|
|
607
|
+
stream_id TEXT NOT NULL,
|
|
608
|
+
event_type TEXT NOT NULL,
|
|
609
|
+
payload TEXT NOT NULL CHECK(json_valid(payload)),
|
|
610
|
+
sender_teamfile TEXT GENERATED ALWAYS AS (json_extract(payload, '$.sender.teamfile')) STORED,
|
|
611
|
+
sender_alias TEXT GENERATED ALWAYS AS (json_extract(payload, '$.sender.alias')) STORED,
|
|
612
|
+
receiver_teamfile TEXT GENERATED ALWAYS AS (json_extract(payload, '$.receiver.teamfile')) STORED,
|
|
613
|
+
receiver_alias TEXT GENERATED ALWAYS AS (json_extract(payload, '$.receiver.alias')) STORED
|
|
614
|
+
);
|
|
615
|
+
CREATE INDEX IF NOT EXISTS idx_message_event_stream ON message_event(stream_id, seq);
|
|
616
|
+
CREATE INDEX IF NOT EXISTS idx_message_event_type ON message_event(event_type, seq);
|
|
617
|
+
CREATE INDEX IF NOT EXISTS idx_message_event_sender ON message_event(sender_teamfile, sender_alias, seq);
|
|
618
|
+
CREATE INDEX IF NOT EXISTS idx_message_event_receiver ON message_event(receiver_teamfile, receiver_alias, seq);
|
|
619
|
+
CREATE TABLE IF NOT EXISTS agent_state (
|
|
620
|
+
receiver_teamfile TEXT NOT NULL,
|
|
621
|
+
receiver_alias TEXT NOT NULL,
|
|
622
|
+
lease_id TEXT UNIQUE,
|
|
623
|
+
sender_teamfile TEXT,
|
|
624
|
+
sender_alias TEXT,
|
|
625
|
+
holder_pid INTEGER,
|
|
626
|
+
holder_host TEXT,
|
|
627
|
+
started_at TEXT,
|
|
628
|
+
last_heartbeat_at TEXT,
|
|
629
|
+
terminal_lock_id TEXT UNIQUE,
|
|
630
|
+
terminal_invocation_id TEXT UNIQUE,
|
|
631
|
+
terminal_invocation_pid INTEGER,
|
|
632
|
+
terminal_invocation_host TEXT,
|
|
633
|
+
terminal_invocation_heartbeat_at TEXT,
|
|
634
|
+
last_seq INTEGER NOT NULL,
|
|
635
|
+
PRIMARY KEY(receiver_teamfile, receiver_alias)
|
|
636
|
+
);
|
|
637
|
+
CREATE TABLE IF NOT EXISTS message_pending (
|
|
638
|
+
message_id TEXT PRIMARY KEY,
|
|
639
|
+
message_type TEXT NOT NULL CHECK(message_type IN ('request','response')),
|
|
640
|
+
in_reply_to TEXT UNIQUE,
|
|
641
|
+
sender_teamfile TEXT,
|
|
642
|
+
sender_alias TEXT,
|
|
643
|
+
receiver_teamfile TEXT NOT NULL,
|
|
644
|
+
receiver_alias TEXT NOT NULL,
|
|
645
|
+
lifecycle_state TEXT NOT NULL,
|
|
646
|
+
delivery_lease_id TEXT,
|
|
647
|
+
delivery_holder_pid INTEGER,
|
|
648
|
+
created_seq INTEGER NOT NULL,
|
|
649
|
+
last_seq INTEGER NOT NULL
|
|
650
|
+
);
|
|
651
|
+
CREATE INDEX IF NOT EXISTS idx_message_pending_lane
|
|
652
|
+
ON message_pending(sender_teamfile, sender_alias, receiver_teamfile,
|
|
653
|
+
receiver_alias, message_type, created_seq)
|
|
654
|
+
WHERE lifecycle_state = 'queued';
|
|
655
|
+
CREATE TABLE IF NOT EXISTS invocation_state (
|
|
656
|
+
invocation_id TEXT PRIMARY KEY,
|
|
657
|
+
kind TEXT NOT NULL,
|
|
658
|
+
origin TEXT NOT NULL,
|
|
659
|
+
launch_source TEXT NOT NULL,
|
|
660
|
+
from_identity TEXT NOT NULL,
|
|
661
|
+
target_teamfile TEXT,
|
|
662
|
+
target_alias TEXT,
|
|
663
|
+
root_teamfile TEXT,
|
|
664
|
+
cwd TEXT,
|
|
665
|
+
command TEXT,
|
|
666
|
+
request_message_id TEXT,
|
|
667
|
+
request_payload TEXT,
|
|
668
|
+
holder_pid INTEGER,
|
|
669
|
+
holder_host TEXT,
|
|
670
|
+
status TEXT NOT NULL,
|
|
671
|
+
started_at TEXT NOT NULL,
|
|
672
|
+
last_heartbeat_at TEXT,
|
|
673
|
+
ended_at TEXT,
|
|
674
|
+
result_summary TEXT,
|
|
675
|
+
error TEXT,
|
|
676
|
+
notified_by TEXT,
|
|
677
|
+
notified_at TEXT,
|
|
678
|
+
last_seq INTEGER NOT NULL
|
|
679
|
+
);
|
|
680
|
+
CREATE INDEX IF NOT EXISTS idx_invocation_state_target_status
|
|
681
|
+
ON invocation_state(target_teamfile, target_alias, status, launch_source);
|
|
682
|
+
CREATE INDEX IF NOT EXISTS idx_invocation_state_from_time
|
|
683
|
+
ON invocation_state(from_identity, started_at DESC);
|
|
684
|
+
`),t.pragma("user_version = 53"),r=53),DI(qI)}function re(t,e){let r=t.prepare(`PRAGMA table_info(${e})`).all();return new Set(r.map(n=>n.name))}function Xn(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Ar(t,e){if(!Xn(t,e)&&(t.exec(bm(Im,"utf8")),!Xn(t,e)))throw new Error(`schema.sql did not create expected table: ${e}`)}function Tm(t){let e=re(t,"team_chat_log");t.pragma("foreign_keys = OFF");try{t.exec(`
|
|
603
685
|
DROP TABLE IF EXISTS team_chat_log_v46;
|
|
604
686
|
CREATE TABLE team_chat_log_v46 (
|
|
605
687
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -628,7 +710,7 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
628
710
|
FROM team_chat_log;
|
|
629
711
|
DROP TABLE team_chat_log;
|
|
630
712
|
ALTER TABLE team_chat_log_v46 RENAME TO team_chat_log;
|
|
631
|
-
`)}finally{t.pragma("foreign_keys = ON")}}function Nm(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function
|
|
713
|
+
`)}finally{t.pragma("foreign_keys = ON")}}function Nm(t){let e=t.pragma("user_version",{simple:!0});return typeof e=="number"?e:0}function JI(){return process.env.LMCTL_DB??UI(FI(),".lmctl","state.db")}var km,Im,qI,HI,xm=E(()=>{"use strict";Em();km=Sm(WI(import.meta.url)),Im=vm(km,"schema.sql"),qI=vm(km,"migrations"),HI=53;if(process.argv[1]&&import.meta.url===BI(process.argv[1]).href){let t=cl({dbPath:process.argv[2]??JI()});try{process.stdout.write(`migrated user_version=${Nm(t)}
|
|
632
714
|
`)}finally{t.close()}}});function Am(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(`
|
|
633
715
|
INSERT INTO agent_inflight (receiver_teamfile, receiver_alias, sender_teamfile, sender_alias, started_at, active_count, holder_pid)
|
|
634
716
|
VALUES (@receiver_teamfile, @receiver_alias, @sender_teamfile, @sender_alias, @started_at, 1, @holder_pid)
|
|
@@ -953,9 +1035,9 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
953
1035
|
AND delivered_at IS NULL
|
|
954
1036
|
AND delivering_at IS NULL
|
|
955
1037
|
ORDER BY receiver_teamfile ASC, receiver_alias ASC, id ASC
|
|
956
|
-
`),deleteMailboxMessage:t.prepare("DELETE FROM agent_mailbox WHERE id = ?")}}function
|
|
1038
|
+
`),deleteMailboxMessage:t.prepare("DELETE FROM agent_mailbox WHERE id = ?")}}function Jn(t){if(Buffer.byteLength(t,"utf8")<=65536)return t;let r=Buffer.byteLength(Cm,"utf8"),n=Math.max(0,65536-r),s=Buffer.from(t,"utf8"),i=n;for(;i>0&&(s[i]&192)===128;)i-=1;return`${s.subarray(0,i).toString("utf8")}${Cm}`}var Cm,dl=E(()=>{"use strict";Cm=`
|
|
957
1039
|
...[truncated]`});function Vn(t,e){return JSON.stringify([t,e])}function jm(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 Gn,Kn,Dm=E(()=>{"use strict";Gn="terminal_lock",Kn="member"});import{readFileSync as Pm}from"node:fs";function ot(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"}}function ul(t){if(!Number.isInteger(t)||(t??0)<=0)return null;let e=GI();if(e===null)return null;try{let r=Pm(`/proc/${t}/stat`,"utf-8"),n=r.lastIndexOf(")");if(n<0)return null;let i=r.slice(n+2).trim().split(/\s+/)[19];return i===void 0||!/^\d+$/.test(i)?null:`${e}:${i}`}catch{return null}}function GI(){try{let t=Pm("/proc/sys/kernel/random/boot_id","utf-8").trim();return/^[0-9a-f-]{36}$/i.test(t)?t:null}catch{return null}}function KI(t){return typeof t=="string"&&/^[0-9a-f-]{36}:\d+$/i.test(t)}function Fm(t,e){if(!ot(t))return"gone";if(!KI(e))return"unverified";let r=ul(t);return r===null?"unverified":r===e?"same":"different"}var Yn=E(()=>{"use strict"});function zr(t){return typeof t=="string"&&VI.has(t)}function Bm(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: ${ii[0]}`,` STANCE: ${ii[1]}`,` STANCE: ${ii[2]}`,` STANCE: ${Um}: <one short sentence: why no declared outcome fits>`,"Never invent a different outcome; never leave the STANCE line out."].join(`
|
|
958
|
-
`)}var Um,ii,VI,zn,Wm,fl,oi,Zn=E(()=>{"use strict";Um="other",ii=["not_enough_information","dont_know","other_work"],VI=new Set([Um,...ii]),zn="@abort",Wm="invalid_decision",fl="escalation_aborted",oi="workflow_escalation"});import{randomUUID as qm}from"node:crypto";import{hostname as Qn}from"node:os";function Be(t){return t.provider_resolved??t.provider}function O(){return new Date().toISOString()}function ke(t){return new ml(cl({dbPath:t.path}))}function Hm(t,e,r){let n=
|
|
1040
|
+
`)}var Um,ii,VI,zn,Wm,fl,oi,Zn=E(()=>{"use strict";Um="other",ii=["not_enough_information","dont_know","other_work"],VI=new Set([Um,...ii]),zn="@abort",Wm="invalid_decision",fl="escalation_aborted",oi="workflow_escalation"});import{randomUUID as qm}from"node:crypto";import{hostname as Qn}from"node:os";function Be(t){return t.provider_resolved??t.provider}function O(){return new Date().toISOString()}function ke(t){return new ml(cl({dbPath:t.path}))}function Hm(t,e,r){let n=Xm(e);if(n.length===0)return;let s=new Set,i=[],o=l=>{if(l===t)return n;let c=r(l);if(c===null)throw new Error(`unknown workflow reference: ${l}`);return Xm(c.definition)},a=l=>{let c=i.indexOf(l);if(c>=0)throw new Error(`cycle detected: ${[...i.slice(c),l].join(" -> ")}`);if(!s.has(l)){i.push(l);try{for(let d of o(l))a(d)}finally{i.pop()}s.add(l)}};a(t)}function Xm(t){let e=YI(t),r=e===null?null:zI(e,"states");if(r===null)return[];let n=[];for(let s of Object.values(r))ai(s)&&s.type==="Subflow"&&typeof s.workflow_name=="string"&&s.workflow_name.length>0&&n.push(s.workflow_name);return n}function YI(t){try{let e=JSON.parse(t);return ai(e)?e:null}catch{return null}}function zI(t,e){let r=t[e];return ai(r)?r:null}function ai(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ZI(t){try{let e=JSON.parse(t);return!ai(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 QI(t,e){return t===null?!0:t.holder_host===Qn()?!ot(t.holder_pid):t.last_heartbeat<e}function eN(t,e){if(t.delivering_at===null)return{reclaim:!1,reason:"not-delivering",holderPidAlive:null};let r=t.delivering_at<e;if(t.delivery_holder_host===Qn()&&tN(t.delivery_holder_pid)){let n=ot(t.delivery_holder_pid);return n?r?{reclaim:!0,reason:"stale-live-local-pid",holderPidAlive:n}:{reclaim:!1,reason:"pid-still-alive",holderPidAlive:n}:{reclaim:!0,reason:"dead-local-pid",holderPidAlive:n}}return r?{reclaim:!0,reason:"stale-other-holder",holderPidAlive:null}:{reclaim:!1,reason:"not-yet-stale",holderPidAlive:null}}function rr(t,e,r={}){let n=new Date().toISOString(),s=e.delivering_at===null?NaN:Date.parse(e.delivering_at),i=Date.parse(n);C({event:t,event_at:n,message_id:e.id,message_type:e.message_type,lane_key:JSON.stringify([e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias]),sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,message_created_at:e.created_at,delivering_at:e.delivering_at,delivered_at:e.delivered_at,delivery_holder_pid:e.delivery_holder_pid,delivery_holder_host:e.delivery_holder_host,lease_age_ms:Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-s):null,...r})}function tN(t){return Number.isInteger(t)&&(t??0)>0}function rN(t){return{...Mm(t),getRuntimeState:t.prepare("SELECT * FROM runtime_state WHERE scope = ? AND key = ? AND kind = ?"),upsertRuntimeState:t.prepare(`
|
|
959
1041
|
INSERT INTO runtime_state (scope, key, kind, data, updated_at)
|
|
960
1042
|
VALUES (?, ?, ?, ?, ?)
|
|
961
1043
|
ON CONFLICT(scope, key, kind) DO UPDATE SET
|
|
@@ -1355,72 +1437,72 @@ var Nk=Object.defineProperty;var E=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{f
|
|
|
1355
1437
|
error_detail = ?,
|
|
1356
1438
|
truncated = ?
|
|
1357
1439
|
WHERE id = ?
|
|
1358
|
-
`),...Om(t),...Am(t)}}function n0(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var ml,Qe=E(()=>{"use strict";xm();Rm();$m();dl();Dm();Yn();de();Zn();ml=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=r0(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=i?"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)=>n0("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==oi)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==zn&&!a.includes(n))return{resumed:!1,reason:Wm};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=n.reclaim_observed,i=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}),o=i!==void 0?{acquired:!0,current:i}:{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"),o}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 i of s)this.stmts.deleteMailboxMessage.run(i.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){Hm(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,O()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,O());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Hm(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,O());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,O())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,O());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,O()),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,O(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(O(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,O());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,O());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,O(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,O());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",O());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,O());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=O(),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,O(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,O(),e)??null}closeIssue(e,r,n){let s=O(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,O(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,O(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=O();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,O(),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,O(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=qm(),s=O();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=O(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,O())}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??O(),e.dedupe_key??null,e.concurrency_key??null,O());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=O(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=O(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=O(),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:O();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,O()),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,O()),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??O(),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,O());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=O(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,O(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(O(),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??O(),n=e.holder_host??Qn(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Pt(e.command),r,e.holder_pid??null,n,s,Pt(e.meta),e.launch_source??e.kind,e.request_payload??null);return this.getTrackedInvocation(Number(i.lastInsertRowid))}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){let n=r.ended_at??O();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??O();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=O()){return this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1?null:this.getTrackedInvocation(e)}updateTrackedInvocationRequestPayload(e,r){return this.stmts.updateTrackedInvocationRequestPayload.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=O()){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 i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}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,Xn(e.payload),e.created_at??O(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null,e.message_type??"request",e.reply_mode??"pull",e.request_mailbox_id??null);return this.getMailboxMessage(Number(r.lastInsertRowid))}listEnqueuedRequestMailFromSender(e,r,n,s){return this.stmts.listEnqueuedRequestMailFromSender.all(e,r,n,s)}listEnqueuedResponseMailFromSender(e,r,n,s){return this.stmts.listEnqueuedResponseMailFromSender.all(e,r,n,s)}listRelayMailboxLanes(e){return this.stmts.listRelayMailboxLanes.all(Math.max(1,Math.trunc(e)))}markMailDelivered(e,r,n){let s=[...new Set(e.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))];if(s.length===0)return 0;let i=Xn(r),o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of s){let c=this.getMailboxMessage(l),d=this.stmts.markMailboxMessageDelivered.run(n,i,l);a+=d.changes,d.changes===1&&c!==null&&o.push(c)}this.db.exec("COMMIT");for(let l of o)rr("mailbox_delivery_delivered",l,{transition:l.delivering_at===null?"pending->delivered":"delivering->delivered",delivered_at:n});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDelivered(e,r,n){let s=Xn(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,l.id,l.delivering_at,l.delivery_holder_pid,l.delivery_holder_host).changes!==1){o.push(l);continue}a+=1,i.push(l)}this.db.exec("COMMIT");for(let l of i)rr("mailbox_delivery_delivered",l,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas"});for(let l of o)rr("mailbox_delivery_finalize_skipped",l,{delivered_at:n,finalizer:"lease-cas",reason:"observed delivery lease changed before finalization"});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDeliveredAndEnqueueResponses(e,r,n){let s=Xn(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0,l=0;for(let c of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,c.id,c.delivering_at,c.delivery_holder_pid,c.delivery_holder_host).changes!==1){o.push(c);continue}if(a+=1,i.push(c),c.sender_teamfile===null||c.sender_alias===null)continue;let u=this.stmts.insertMailboxResponseIfAbsent.run(c.sender_teamfile,c.sender_alias,c.receiver_teamfile,c.receiver_alias,c.root_teamfile,s,n,null,null,null,null,c.reply_mode,c.id);l+=u.changes}this.db.exec("COMMIT");for(let c of i)rr("mailbox_delivery_delivered",c,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas-with-response"});for(let c of o)rr("mailbox_delivery_finalize_skipped",c,{delivered_at:n,finalizer:"lease-cas-with-response",reason:"observed delivery lease changed before finalization"});return{marked:a,responses:l}}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}claimMailForDelivery(e,r,n=process.pid,s=Qn()){let i=[...new Set(e.map(o=>Math.trunc(o)).filter(o=>Number.isInteger(o)&&o>0))];if(i.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let o=[];for(let l of i)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,l).changes===1){let d=this.getMailboxMessage(l);d!==null&&o.push(d)}this.db.exec("COMMIT");let a=o.map(l=>l.id);for(let l of o)rr("mailbox_delivery_claimed",l,{transition:"pending->delivering",batch_ids:a,delivering_at:r,delivery_holder_pid:n,delivery_holder_host:s});return o}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearMailDelivery(e){let r=[...new Set(e.map(s=>Math.trunc(s)).filter(s=>Number.isInteger(s)&&s>0))];if(r.length===0)return 0;let n=[];this.db.exec("BEGIN IMMEDIATE");try{let s=0;for(let i of r){let o=this.getMailboxMessage(i),a=this.stmts.clearMailboxMessageDelivery.run(i);s+=a.changes,a.changes===1&&o!==null&&n.push(o)}this.db.exec("COMMIT");for(let i of n)rr("mailbox_delivery_cleared",i,{transition:"delivering->pending",reason:"explicit non-CAS clear"});return s}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}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=[],s=[];this.db.exec("BEGIN IMMEDIATE");try{for(let i of r){let o=e0(i,e);if(!o.reclaim){s.push({row:i,decision:o,reclaimed:!1});continue}let a=this.reclaimMailboxDeliveryIfUnchanged(i),l=a!==null;s.push({row:i,decision:o,reclaimed:l}),l&&n.push(a)}this.db.exec("COMMIT");for(let i of s)rr(i.decision.reclaim?i.reclaimed?"mailbox_delivery_reclaimed":"mailbox_delivery_reclaim_raced":"mailbox_delivery_reclaim_deferred",i.row,{transition:i.reclaimed?"delivering->pending":"delivering->delivering",stale_before:e,reclaim_reason:i.decision.reason,holder_pid_alive:i.decision.holderPidAlive});return n}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}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(Gn,Vn(e,r),Kn);return n===void 0?null:jm(n.data)}setTerminalLock(e){this.stmts.upsertRuntimeState.run(Gn,Vn(e.teamfile,e.alias),Kn,JSON.stringify(e),e.last_heartbeat)}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Gn,Vn(e,r),Kn,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Gn,Vn(e,r),Kn);return this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:ZI(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=O()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!QI(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:qm(),holder_pid:process.pid,holder_host:Qn(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,O(),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,O())}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,O());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,O(),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??O(),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,O());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,O()).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,O()),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,O());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(O(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=O();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??O());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,O())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,O())}}});import{realpathSync as s0}from"node:fs";import{resolve as i0}from"node:path";function pl(t){let e=i0(t);try{return s0(e)}catch{return e}}var Xm=E(()=>{"use strict"});import{platform as Gm}from"node:os";function bt(t){let e=new es;for(let r of t)e.registerAdapter(r);return e}var es,_l=E(()=>{"use strict";Xm();es=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)r.push(...o);let i=r;if(e?.workspace){let o=pl(e.workspace);i=i.filter(a=>pl(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,r){let n=await this.resolveSessions(e,r);return n.length===1?n[0]:null}async resolveSessions(e,r){let n=r?this.providers.filter(i=>i.name===r):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Gm()==="darwin"||Gm()==="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 Km}from"node:fs";import{createInterface as Vm}from"node:readline";import{stat as o0}from"node:fs/promises";import{homedir as a0}from"node:os";async function*qe(t){let e=Km(t,{encoding:"utf-8"}),r=Vm({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 Me(t,e){let r=[],n=Km(t,{encoding:"utf-8"}),s=Vm({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(o){try{r.push(JSON.parse(o))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Ne(t){let e=await o0(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function fe(t){return t.replace(/\\n/g,`
|
|
1359
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function J(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var be,nr=E(()=>{"use strict";be=a0()});import{readdir as li,stat as Ym,unlink as l0}from"node:fs/promises";import{join as Zr,basename as zm}from"node:path";function c0(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function d0(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return fe(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return t.type==="progress"&&t.data!==void 0?JSON.stringify(t.data,null,2):JSON.stringify(t,null,2)}async function Zm(t){let e=0,r=0,n=0,s=0,i=0,o=0,a;for await(let l of qe(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 u of c)u.type==="text"&&e++;let d=l.message.usage;if(d){let u=d.input_tokens||0,f=d.cache_creation_input_tokens||0,m=d.cache_read_input_tokens||0,p=d.output_tokens||0;r+=u+f+m,n+=m,s+=f,i+=p;let h=u+f+m;h&&(o=h),a={inputTokens:u,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a}}var ci,Qm=E(()=>{"use strict";nr();ci=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Zr(be,".claude"),this.projectsDir=Zr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await li(this.projectsDir)}catch{return e}for(let n of r){let s=Zr(this.projectsDir,n);if(!(await Ym(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await li(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=zm(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Zr(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await Me(e,50),s=await Ne(e),i="",o,a,l,c,d,u;for(let m of n)if(!c0(m.type)&&(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!u&&m.timestamp&&(u=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let p=m.message.content;if(typeof p=="string"){if(p.includes("<command-name>")||p.includes("<local-command-"))continue;c||(c=J(p.trim(),80)),d=J(p.trim(),80)}}if(!i)return null;let f=await Zm(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:d,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Ne(r),s=[],i="",o,a,l,c,d,u,f,m=e;for await(let h of qe(r))if(h.type!=="file-history-snapshot"&&!h.isSidechain){if(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!c&&h.gitBranch&&(c=h.gitBranch),!f&&h.timestamp&&(f=new Date(h.timestamp)),h.sessionId&&(m=h.sessionId),h.type==="system"||h.type==="progress"||h.type==="queue-operation"){s.push({role:"system",timestamp:new Date(h.timestamp||0),content:d0(h)});continue}if(h.type==="user"&&h.message){if(h.isMeta)continue;let g=new Date(h.timestamp||0),_=h.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;d||(d=J(_.trim(),80)),u=J(_.trim(),80),s.push({role:"user",timestamp:g,content:fe(_.trim())})}else if(Array.isArray(_)){for(let y of _)if(y.type==="tool_result"){let T=typeof y.content=="string"?fe(y.content):JSON.stringify(y.content);s.push({role:"tool_result",timestamp:g,content:T,toolCallId:y.tool_use_id})}}}if(h.type==="assistant"&&h.message){h.message.model&&(l=h.message.model);let g=new Date(h.timestamp||0),_=h.message.content;if(Array.isArray(_))for(let y of _)y.type==="text"&&y.text?s.push({role:"assistant",timestamp:g,content:fe(y.text),model:h.message.model}):y.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:y.name||"unknown tool",toolName:y.name,toolInput:JSON.stringify(y.input,null,2),toolCallId:y.id,model:h.message.model}):y.type==="thinking"&&y.thinking&&s.push({role:"thinking",timestamp:g,content:y.thinking})}}if(!i)return null;let p=await Zm(r);return{provider:"claude",sessionId:m,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,firstUserMessage:d,lastUserMessage:u,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 l0(r),!0):!1}async resolveSessionFile(e){let r;try{r=await li(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Zr(this.projectsDir,o);if(!(await Ym(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await li(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=zm(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Zr(a,d),fileSessionId:u})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await Me(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});function di(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function f0(t,e,r){if(!r)return"";let n=t.tools[e]??hl[e],s=n?.profiles?.[r]?.flags??hl[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 ep(t,e){return!!t.tools[e]}function tp(t,e,r,n,s){let i=t.tools[e]??hl[e],o;if(i?.agent){let l=di(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=u0[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(d=>d.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let d=c.map(di).join(" ");o=`printf '%s\\n' ${di(n)} | ${d}`}else o=c.map(di).join(" ")}let a=f0(t,e,s);return a&&(o+=" "+a),o}var hl,u0,rp=E(()=>{"use strict";hl={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:""}}}},u0={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 np(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 sp=E(()=>{"use strict"});var m0,ge,ui,St=E(()=>{"use strict";m0="ACK: waiting for explicit lmctl task.",ge=`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: ${m0}`,ui=`send this exact lmctl seed instruction: "${ge}"`});function sr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function _0(t,e){return e===void 0||e.length===0?t:{...t??process.env,[ts]:e}}function je(t,e,r,n="chat"){return{..._0(sr(t,e),r),[p0]:n}}var ts,p0,at=E(()=>{"use strict";ts="LMCTL_SELF_SESSIONID",p0="LMCTL_LAUNCH_SOURCE"});import{spawn as ip}from"node:child_process";import{mkdirSync as h0}from"node:fs";var gl,xe,Ft=E(()=>{"use strict";rp();sp();St();at();gl=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},xe=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===ge?r:n)}seed(e,r){return h0(e,{recursive:!0}),new Promise(n=>{let s;try{s=ip(this.binary,this.seedArgsFor(r),{cwd:e,env:sr(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let i="";s.stderr?.on("data",a=>{i+=a.toString()});let o=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1360
|
-
`:this.seedStdin;o&&s.stdin?.write(o),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:i.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:ui,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&ep(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,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),d(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},d=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let u={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),n.onProgress?.(p)}},f=this.transportFn(r,u).then(p=>(d(),{...p,status:"ok"})).catch(p=>{throw d(),o==="external"?new gl("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=tp(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=np(r.env),c=ip(s,{shell:!0,cwd:r.cwd,env:je(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,f=setTimeout(()=>{u=!0,c.kill()},l),m="",p="";if(c.stdout?.on("data",h=>{let g=h.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",h=>{p+=h.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",h=>{if(d)return;d=!0,clearTimeout(f);let g=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${h}`))}),c.on("error",h=>{d||(d=!0,clearTimeout(f),a(h))})})}}});function mi(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new Wt(t,r,e)}var et,ye,Ut,fi,Wt,Qr=E(()=>{"use strict";et=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},ye=class extends et{},Ut=class extends et{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},fi=class extends et{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},Wt=class extends et{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as wl from"node:child_process";function
|
|
1440
|
+
`),...Om(t),...Am(t)}}function nN(t,e){return e===void 0?{resumed:!1,reason:t}:{resumed:!1,reason:t,valid:e}}var ml,Qe=E(()=>{"use strict";xm();Rm();$m();dl();Dm();Yn();de();Zn();ml=class{db;stmts;claimTxn;claimWithConcurrencyTxn;claimByIdWithConcurrencyTxn;resumeRunTxn;resumeInteractiveTxn;resumeEscalationTxn;tryAcquireAgentInflightTxn;recvMailboxMessagesTxn;constructor(e){e.pragma("foreign_keys = ON"),this.db=e,this.stmts=rN(e),this.claimTxn=e.transaction((r,n,s)=>{let i=this.stmts.selectClaimableJob.get(s,s,s);return i===void 0||this.stmts.claimJob.run(r,n,s,i.id,s,s,s).changes!==1?null:this.getJob(i.id)}),this.claimWithConcurrencyTxn=e.transaction((r,n,s,i)=>{let o=this.stmts.selectClaimableJobs.all(s,s,s);for(let a of o){let l=this.getJob(a.id);if(l===null)continue;let c=i(l);if(c.concurrency_key!==null&&(l.concurrency_key_resolved!==c.concurrency_key&&this.stmts.setJobConcurrencyKey.run(c.concurrency_key,l.id),(this.stmts.countRunningByConcurrencyKey.get(c.concurrency_key,s,l.id)?.count??0)>=Math.max(1,c.concurrent_limit)))continue;if(this.stmts.claimJob.run(r,n,s,l.id,s,s,s).changes===1)return this.getJob(l.id)}return null}),this.claimByIdWithConcurrencyTxn=e.transaction((r,n,s,i,o)=>{let a=this.getJob(r);if(a===null)return{claimed:!1,reason:"not_found",job_id:r};if(a.locked_until!==null&&a.locked_until>=i)return{claimed:!1,reason:"locked",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let c=a.status==="queued"&&a.available_at<=i,d=a.status==="running"&&a.locked_until!==null&&a.locked_until<i;if(!c&&!d)return{claimed:!1,reason:"not_claimable",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};let u=o(a);if(u.concurrency_key!==null&&(a.concurrency_key_resolved!==u.concurrency_key&&this.stmts.setJobConcurrencyKey.run(u.concurrency_key,a.id),(this.stmts.countRunningByConcurrencyKey.get(u.concurrency_key,i,a.id)?.count??0)>=Math.max(1,u.concurrent_limit)))return{claimed:!1,reason:"concurrency_limit",job_id:r,status:a.status,locked_by:a.locked_by,locked_until:a.locked_until};if(this.stmts.claimJob.run(n,s,i,a.id,i,i,i).changes!==1){let p=this.getJob(a.id);return{claimed:!1,reason:p?.locked_until!==null&&p?.locked_until!==void 0&&p.locked_until>=i?"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)=>nN("state_not_found")),this.resumeInteractiveTxn=e.transaction((r,n,s,i)=>{let o=this.getInteractiveSessionByStepId(r);if(o===null)return{resumed:!1,reason:"not_found"};if(o.status!=="waiting_operator")return{resumed:!1,reason:"not_waiting_operator"};let a=this.getRun(o.run_id);if(a===null)return{resumed:!1,reason:"run_not_found"};let l=s?"done":"waiting_agent";return this.stmts.updateInteractiveSession.run(l,n,Date.now(),o.id),this.stmts.resumeRunState.run(o.state_name,a.id),this.stmts.requeuePausedJob.run(i,a.job_id),{resumed:!0,session:this.getInteractiveSessionByStepId(r),run:this.getRun(a.id),job:this.getJob(a.job_id)}}),this.resumeEscalationTxn=e.transaction((r,n,s)=>{let i=this.stmts.getAttention.get(r);if(i===void 0)return{resumed:!1,reason:"not_found"};if(i.kind!==oi)return{resumed:!1,reason:"wrong_kind"};if(i.acknowledged_at!==null)return{resumed:!1,reason:"already_acked"};if(i.run_id===null)return{resumed:!1,reason:"run_not_found"};let o=null,a=[];if(i.payload!==null)try{let d=JSON.parse(i.payload);d.step!==void 0&&typeof d.step.id=="string"&&d.step.id.length>0&&(o=d.step.id),Array.isArray(d.declared_outcomes)&&(a=d.declared_outcomes.filter(u=>typeof u=="string"))}catch{}if(o===null)return{resumed:!1,reason:"no_step"};let l=this.getRun(i.run_id);if(l===null)return{resumed:!1,reason:"run_not_found"};if(n!==zn&&!a.includes(n))return{resumed:!1,reason:Wm};let c={};if(l.pending_escalation_decision!==null)try{let d=JSON.parse(l.pending_escalation_decision);d!==null&&typeof d=="object"&&!Array.isArray(d)&&(c=d)}catch{c={}}return c[o]=n,this.stmts.setRunPendingEscalationDecision.run(JSON.stringify(c),l.id),this.stmts.resumeRunState.run(o,l.id),this.stmts.requeuePausedJob.run(s,l.job_id),this.stmts.ackAttention.run(s,r),{resumed:!0,run:this.getRun(l.id),job:this.getJob(l.job_id)}}),this.tryAcquireAgentInflightTxn=(r,n={})=>{this.db.exec("BEGIN IMMEDIATE");try{let s=n.reclaim_observed,i=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}),o=i!==void 0?{acquired:!0,current:i}:{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"),o}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 i of s)this.stmts.deleteMailboxMessage.run(i.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){Hm(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.stmts.insertWorkflow.run(e.name,e.version??1,e.definition_schema_version??1,e.definition,O()),n=this.getWorkflow(Number(r.lastInsertRowid)),s=this.stmts.insertWorkflowVersion.run(n.id,n.version,e.definition,e.author??null,O());this.stmts.updateWorkflowActiveVersion.run(s.lastInsertRowid,n.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,n.id);let i=this.getWorkflow(n.id);return this.syncWorkflowTriggers(n.id,e.definition),i}upsertWorkflow(e){Hm(e.name,e.definition,o=>this.getWorkflowByName(o));let r=this.getWorkflowByName(e.name);if(r===null)return this.insertWorkflow({name:e.name,definition_schema_version:e.definition_schema_version,definition:e.definition,author:e.author,source_uri:e.source_uri,source_sha256:e.source_sha256});let s=(this.stmts.getLatestWorkflowVersion.get(r.id)?.version??r.version)+1,i=this.stmts.insertWorkflowVersion.run(r.id,s,e.definition,e.author??null,O());return this.stmts.updateWorkflowActiveVersionDefinitionAndVersion.run(Number(i.lastInsertRowid),e.definition,e.definition_schema_version??r.definition_schema_version,s,r.id),(e.source_uri!=null||e.source_sha256!=null)&&this.stmts.setWorkflowSource.run(e.source_uri??null,e.source_sha256??null,r.id),this.syncWorkflowTriggers(r.id,e.definition),this.getWorkflow(r.id)}insertCompositionUnit(e){this.stmts.insertCompositionUnit.run(e.name,e.version,e.lang,e.source,e.source_sha,e.compiled_workflow_version_id,O())}getWorkflow(e){return this.stmts.getWorkflow.get(e)??null}getWorkflowByName(e,r){return(r===void 0?this.stmts.findWorkflowLatest.get(e):this.stmts.findWorkflowVersion.get(e,r))??null}findWorkflowByName(e,r){return this.getWorkflowByName(e,r)}insertWorkflowVersion(e,r,n){let i=(this.stmts.getLatestWorkflowVersion.get(e)?.version??0)+1,o=this.stmts.insertWorkflowVersion.run(e,i,r,n??null,O());return this.stmts.getWorkflowVersion.get(o.lastInsertRowid)}activateWorkflowVersion(e,r){let n=this.getWorkflowVersionById(r);if(n===null||n.workflow_id!==e)return null;let s=1;try{let i=JSON.parse(n.definition);typeof i.definition_schema_version=="number"&&(s=i.definition_schema_version)}catch{}return this.stmts.updateWorkflowActiveVersionAndDefinition.run(r,n.definition,s,e),this.syncWorkflowTriggers(e,n.definition),this.getWorkflow(e)}getWorkflowVersionById(e){return this.stmts.getWorkflowVersion.get(e)??null}listWorkflowVersions(e){return this.stmts.listWorkflowVersions.all(e)}upsertTriggerInstance(e){return this.stmts.upsertTriggerInstance.run(e.workflow_id,e.trigger_id,e.trigger_type,e.parameters,e.enabled===!1?0:1,O()),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,O(),e),this.stmts.getTriggerInstance.get(e)??null}setTriggerFailure(e,r){return this.stmts.setTriggerFailure.run(O(),r,e),this.stmts.getTriggerInstance.get(e)??null}syncWorkflowTriggers(e,r){let n;try{n=JSON.parse(r)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let s=n.triggers;if(Array.isArray(s))for(let i of s){if(i===null||typeof i!="object"||Array.isArray(i))continue;let o=i;typeof o.id!="string"||o.id.length===0||typeof o.type!="string"||o.type.length===0||this.upsertTriggerInstance({workflow_id:e,trigger_id:o.id,trigger_type:o.type,parameters:JSON.stringify(o.parameters??{})})}}insertTeam(e){let r=this.stmts.insertTeam.run(e.name,O());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,O());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,O(),e),this.stmts.getTeamMember.get(e)??null}listMembersInState(e){return this.stmts.listMembersInState.all(e)}setMemberPromptSnapshot(e,r){return this.stmts.setMemberPromptSnapshot.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberProviderResolved(e,r){return this.stmts.setMemberProviderResolved.run(r,e),this.stmts.getTeamMember.get(e)??null}setMemberRolePrompt(e,r){return this.stmts.setMemberRolePrompt.run(r,e),this.stmts.getTeamMember.get(e)??null}updateTeamMemberMeta(e,r){let n=this.stmts.getTeamMember.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"role_prompt"),i=Object.prototype.hasOwnProperty.call(r,"model"),o=Object.prototype.hasOwnProperty.call(r,"provider");return this.stmts.updateTeamMemberMeta.run(s?r.role_prompt??null:n.role_prompt,i?r.model??null:n.model,o?r.provider??n.provider:n.provider,e),this.stmts.getTeamMember.get(e)??null}insertTeamMemberCompanion(e){let r=this.stmts.insertTeamMemberCompanion.run(e.interpreter_id,e.companion_id,O());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",O());return this.stmts.getProject.get(r.lastInsertRowid)}listProjects(){return this.stmts.listProjects.all()}getProject(e){return this.stmts.getProject.get(e)??null}findProjectByName(e){return this.stmts.findProjectByName.get(e)??null}setProjectIntakeConfig(e,r){return this.stmts.setProjectIntakeConfig.run(r,e),this.stmts.getProject.get(e)??null}updateProjectSettings(e,r){let n=this.stmts.getProject.get(e);if(n===void 0)return null;let s=Object.prototype.hasOwnProperty.call(r,"local_path"),i=Object.prototype.hasOwnProperty.call(r,"durable_memory_mode"),o=Object.prototype.hasOwnProperty.call(r,"default_branch"),a=Object.prototype.hasOwnProperty.call(r,"intake_config");return this.stmts.updateProjectSettings.run(s?r.local_path:n.local_path,i?r.durable_memory_mode:n.durable_memory_mode,o?r.default_branch??null:n.default_branch,a?r.intake_config??null:n.intake_config,e),this.stmts.getProject.get(e)??null}listProjectsWithIntakeEnabled(){return this.stmts.listProjectsWithIntakeConfig.all().filter(e=>{if(e.intake_config===null)return!1;try{let r=JSON.parse(e.intake_config);return typeof r=="object"&&r!==null&&!Array.isArray(r)&&r.scan_github_issues===!0}catch{return!1}})}getProjectByJob(e){return this.stmts.getProjectByJob.get(e)??null}insertProjectWorkflow(e){let r=e.condition??null,n=this.stmts.findProjectWorkflowUnique.get(e.project_id,e.workflow_id,r);if(n!==void 0)return n;let s=this.stmts.insertProjectWorkflow.run(e.project_id,e.workflow_id,r,e.parameters_override??null,e.enabled===!1?0:1,e.priority??100,O());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=O(),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,O(),e)??null}claimIssue(e,r){return this.stmts.claimIssue.get(r,O(),e)??null}closeIssue(e,r,n){let s=O(),i=this.stmts.closeIssue.get(r,n??null,s,s,e);if(i===void 0)throw new Error(`issue not found: ${e}`);return i}reopenIssue(e,r){let n=this.stmts.reopenIssue.get(r,O(),e);if(n===void 0)throw this.getIssue(e)===null?new Error(`issue not found: ${e}`):new Error(`issue ${e} is not closed`);return n}updateIssue(e,r){let n=this.getIssue(e);if(n===null)throw new Error(`issue not found: ${e}`);let s=Object.prototype.hasOwnProperty.call(r,"labels"),i=Object.prototype.hasOwnProperty.call(r,"ai_test_path"),o=this.stmts.updateIssue.get(r.title??n.title,r.body??n.body,r.severity??n.severity,s?r.labels??null:n.labels,i?r.ai_test_path??null:n.ai_test_path,O(),e);if(o===void 0)throw new Error(`issue not found: ${e}`);return o}listWorkflows(){return this.stmts.listWorkflows.all()}getOrCreateWebuiSession(e,r){let n=this.stmts.getWebuiSession.get(e);if(n!==void 0)return n;let s=O();return this.stmts.insertWebuiSession.run(e,r,"N1",null,null,null,null,"authenticated",s,s),this.stmts.getWebuiSession.get(e)}getWebuiSession(e){return this.stmts.getWebuiSession.get(e)??null}updateWebuiSessionTransition(e,r,n,s,i){if(this.stmts.updateWebuiSessionTransition.run(r,n,s,i,O(),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,O(),e).changes===0)throw new Error(`webui_session not found: ${e}`);return this.stmts.getWebuiSession.get(e)}createChatbotSession(e,r){let n=qm(),s=O();return this.stmts.insertChatbotSession.run(n,e,r??null,s,s,"active"),this.stmts.getChatbotSession.get(n)}getChatbotSession(e){return this.stmts.getChatbotSession.get(e)??null}listChatbotSessions(e){return this.stmts.listChatbotSessionsForUser.all(e)}appendChatbotMessage(e,r,n,s){let i=O(),o=this.stmts.insertChatbotMessage.run(e,r,n,s??null,i);return this.stmts.touchChatbotSession.run(i,e),this.stmts.getChatbotMessage.get(o.lastInsertRowid)}listChatbotMessages(e){return this.stmts.listChatbotMessages.all(e)}getConfig(e){return this.stmts.getConfig.get(e)?.value??null}setConfig(e,r){this.stmts.upsertConfig.run(e,r,O())}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??O(),e.dedupe_key??null,e.concurrency_key??null,O());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=O(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimTxn(e.worker_id,n,r)}claimNextJobWithConcurrency(e){let r=O(),n=new Date(Date.now()+e.lease_ms).toISOString();return this.claimWithConcurrencyTxn(e.worker_id,n,r,e.evaluator)}claimJobByIdWithConcurrency(e){let r=O(),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:O();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,O()),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,O()),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??O(),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,O());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=O(),n=this.stmts.insertWebProject.run(e.workspace_id,e.name,e.repo_path,e.config_json??null,e.linked_v4_project_id??null,r,r),s=Number(n.lastInsertRowid),i=this.getWebProject(s);if(i===null)throw new Error(`web_project ${s} missing after insert`);return i}updateWebProject(e){let r=this.getWebProject(e.id);return r===null||r.deleted_at!==null?null:(this.stmts.updateWebProject.run(e.name??r.name,e.config_json===void 0?r.config_json:e.config_json,O(),e.id),this.getWebProject(e.id))}softDeleteWebProject(e){return this.stmts.softDeleteWebProject.run(O(),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??O(),n=e.holder_host??Qn(),s=e.last_heartbeat_at??r,i=this.stmts.insertTrackedInvocation.run(e.kind,e.origin,e.scope_teamfile??null,e.from_identity,e.target_teamfile??null,e.target_alias??null,e.root_teamfile??null,e.cwd??null,Pt(e.command),r,e.holder_pid??null,n,s,Pt(e.meta),e.launch_source??e.kind,e.request_payload??null);return this.getTrackedInvocation(Number(i.lastInsertRowid))}getTrackedInvocation(e){return this.stmts.getTrackedInvocation.get(e)??null}listAllRunningTrackedInvocations(){return this.stmts.listAllRunningTrackedInvocations.all()}finishTrackedInvocation(e,r){let n=r.ended_at??O();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??O();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=O()){return this.stmts.heartbeatTrackedInvocation.run(r,e).changes!==1?null:this.getTrackedInvocation(e)}updateTrackedInvocationRequestPayload(e,r){return this.stmts.updateTrackedInvocationRequestPayload.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=O()){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 i=r.length===0?"":` WHERE ${r.join(" AND ")}`;return this.db.prepare(`SELECT * FROM tracked_invocation${i} ORDER BY started_at DESC, id DESC LIMIT ?`).all(...n)}maxTrackedInvocationId(e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.scope_teamfile!==void 0&&(r.push("scope_teamfile = ?"),n.push(e.scope_teamfile));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`,i=this.db.prepare(`SELECT COALESCE(MAX(id), 0) AS max_id FROM tracked_invocation${s}`).get(...n);return Number(i?.max_id??0)}listRunningTrackedInvocations(e={}){return this.listTrackedInvocations({...e,status:"running"})}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,Jn(e.payload),e.created_at??O(),e.remote_transport??null,e.remote_message_id??null,e.remote_thread_id??null,e.meta??null,e.message_type??"request",e.reply_mode??"pull",e.request_mailbox_id??null);return this.getMailboxMessage(Number(r.lastInsertRowid))}listEnqueuedRequestMailFromSender(e,r,n,s){return this.stmts.listEnqueuedRequestMailFromSender.all(e,r,n,s)}listEnqueuedResponseMailFromSender(e,r,n,s){return this.stmts.listEnqueuedResponseMailFromSender.all(e,r,n,s)}listRelayMailboxLanes(e){return this.stmts.listRelayMailboxLanes.all(Math.max(1,Math.trunc(e)))}markMailDelivered(e,r,n){let s=[...new Set(e.map(a=>Math.trunc(a)).filter(a=>Number.isInteger(a)&&a>0))];if(s.length===0)return 0;let i=Jn(r),o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of s){let c=this.getMailboxMessage(l),d=this.stmts.markMailboxMessageDelivered.run(n,i,l);a+=d.changes,d.changes===1&&c!==null&&o.push(c)}this.db.exec("COMMIT");for(let l of o)rr("mailbox_delivery_delivered",l,{transition:l.delivering_at===null?"pending->delivered":"delivering->delivered",delivered_at:n});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDelivered(e,r,n){let s=Jn(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0;for(let l of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,l.id,l.delivering_at,l.delivery_holder_pid,l.delivery_holder_host).changes!==1){o.push(l);continue}a+=1,i.push(l)}this.db.exec("COMMIT");for(let l of i)rr("mailbox_delivery_delivered",l,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas"});for(let l of o)rr("mailbox_delivery_finalize_skipped",l,{delivered_at:n,finalizer:"lease-cas",reason:"observed delivery lease changed before finalization"});return a}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}markRelayRequestDeliveredAndEnqueueResponses(e,r,n){let s=Jn(r),i=[],o=[];this.db.exec("BEGIN IMMEDIATE");try{let a=0,l=0;for(let c of e){if(this.stmts.markMailboxMessageDeliveredIfUnchanged.run(n,s,c.id,c.delivering_at,c.delivery_holder_pid,c.delivery_holder_host).changes!==1){o.push(c);continue}if(a+=1,i.push(c),c.sender_teamfile===null||c.sender_alias===null)continue;let u=this.stmts.insertMailboxResponseIfAbsent.run(c.sender_teamfile,c.sender_alias,c.receiver_teamfile,c.receiver_alias,c.root_teamfile,s,n,null,null,null,null,c.reply_mode,c.id);l+=u.changes}this.db.exec("COMMIT");for(let c of i)rr("mailbox_delivery_delivered",c,{transition:"delivering->delivered",delivered_at:n,finalizer:"lease-cas-with-response"});for(let c of o)rr("mailbox_delivery_finalize_skipped",c,{delivered_at:n,finalizer:"lease-cas-with-response",reason:"observed delivery lease changed before finalization"});return{marked:a,responses:l}}catch(a){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),a}}claimMailForDelivery(e,r,n=process.pid,s=Qn()){let i=[...new Set(e.map(o=>Math.trunc(o)).filter(o=>Number.isInteger(o)&&o>0))];if(i.length===0)return[];this.db.exec("BEGIN IMMEDIATE");try{let o=[];for(let l of i)if(this.stmts.claimMailboxMessageDelivery.run(r,n,s,l).changes===1){let d=this.getMailboxMessage(l);d!==null&&o.push(d)}this.db.exec("COMMIT");let a=o.map(l=>l.id);for(let l of o)rr("mailbox_delivery_claimed",l,{transition:"pending->delivering",batch_ids:a,delivering_at:r,delivery_holder_pid:n,delivery_holder_host:s});return o}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearMailDelivery(e){let r=[...new Set(e.map(s=>Math.trunc(s)).filter(s=>Number.isInteger(s)&&s>0))];if(r.length===0)return 0;let n=[];this.db.exec("BEGIN IMMEDIATE");try{let s=0;for(let i of r){let o=this.getMailboxMessage(i),a=this.stmts.clearMailboxMessageDelivery.run(i);s+=a.changes,a.changes===1&&o!==null&&n.push(o)}this.db.exec("COMMIT");for(let i of n)rr("mailbox_delivery_cleared",i,{transition:"delivering->pending",reason:"explicit non-CAS clear"});return s}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}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=[],s=[];this.db.exec("BEGIN IMMEDIATE");try{for(let i of r){let o=eN(i,e);if(!o.reclaim){s.push({row:i,decision:o,reclaimed:!1});continue}let a=this.reclaimMailboxDeliveryIfUnchanged(i),l=a!==null;s.push({row:i,decision:o,reclaimed:l}),l&&n.push(a)}this.db.exec("COMMIT");for(let i of s)rr(i.decision.reclaim?i.reclaimed?"mailbox_delivery_reclaimed":"mailbox_delivery_reclaim_raced":"mailbox_delivery_reclaim_deferred",i.row,{transition:i.reclaimed?"delivering->pending":"delivering->delivering",stale_before:e,reclaim_reason:i.decision.reason,holder_pid_alive:i.decision.holderPidAlive});return n}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}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(Gn,Vn(e,r),Kn);return n===void 0?null:jm(n.data)}setTerminalLock(e){this.stmts.upsertRuntimeState.run(Gn,Vn(e.teamfile,e.alias),Kn,JSON.stringify(e),e.last_heartbeat)}heartbeatTerminalLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getTerminalLock(e,r);if(i===null||i.lock_id!==n)return this.db.exec("COMMIT"),!1;let o={...i,last_heartbeat:s};return this.stmts.upsertRuntimeState.run(Gn,Vn(e,r),Kn,JSON.stringify(o),s),this.db.exec("COMMIT"),!0}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}clearTerminalLock(e,r,n){this.db.exec("BEGIN IMMEDIATE");try{let s=this.getTerminalLock(e,r);if(s===null||s.lock_id!==n)return this.db.exec("COMMIT"),!1;let i=this.stmts.deleteRuntimeState.run(Gn,Vn(e,r),Kn);return this.db.exec("COMMIT"),i.changes===1}catch(s){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),s}}getRuntimeProcessLock(e,r,n){let s=this.stmts.getRuntimeState.get(e,r,n);return s===void 0?null:ZI(s.data)}tryAcquireRuntimeProcessLock(e,r,n,s,i=O()){this.db.exec("BEGIN IMMEDIATE");try{let o=this.getRuntimeProcessLock(e,r,n);if(o!==null&&!QI(o,s))return this.db.exec("COMMIT"),{acquired:!1,current:o};let a={lock_id:qm(),holder_pid:process.pid,holder_host:Qn(),started_at:i,last_heartbeat:i};return this.stmts.upsertRuntimeState.run(e,r,n,JSON.stringify(a),i),this.db.exec("COMMIT"),{acquired:!0,lock:a,previous:o}}catch(o){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),o}}clearRuntimeProcessLock(e,r,n,s){this.db.exec("BEGIN IMMEDIATE");try{let i=this.getRuntimeProcessLock(e,r,n);if(i===null||i.lock_id!==s)return this.db.exec("COMMIT"),!1;let o=this.stmts.deleteRuntimeState.run(e,r,n);return this.db.exec("COMMIT"),o.changes===1}catch(i){throw this.db.inTransaction&&this.db.exec("ROLLBACK"),i}}getRun(e){return this.stmts.getRun.get(e)??null}setRunCurrentState(e,r){return this.stmts.setRunCurrentState.run(r,e),this.stmts.getRun.get(e)??null}setRunPausedState(e,r,n){return this.stmts.setRunPausedState.run(r,n,e),this.stmts.getRun.get(e)??null}setRunPendingEscalationDecision(e,r){return this.stmts.setRunPendingEscalationDecision.run(r,e),this.stmts.getRun.get(e)??null}setRunTerminalState(e,r){return this.stmts.setRunTerminalState.run(r,O(),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,O())}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,O());return this.stmts.getStep.get(r.lastInsertRowid)}finishStep(e,r,n){return this.stmts.finishStep.run(r??null,n??null,O(),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??O(),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,O());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,O()).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,O()),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,O());return this.stmts.getAttention.get(r.lastInsertRowid)}acknowledgeAttention(e){return this.stmts.ackAttention.run(O(),e),this.stmts.getAttention.get(e)??null}upsertDurableMemory(e){let r=O();return this.stmts.upsertDurableMemory.run(e.project_id,e.type,e.name,e.description??null,e.body,r,r),this.stmts.getDurableMemoryByName.get(e.project_id,e.name)}getDurableMemoryByName(e,r){return this.stmts.getDurableMemoryByName.get(e,r)??null}deleteDurableMemory(e,r){return this.stmts.deleteDurableMemory.run(e,r).changes>0}listDurableMemory(e,r){return r!==void 0?this.stmts.listDurableMemoryByType.all(e,r):this.stmts.listDurableMemory.all(e)}indexDurableMemory(e,r){return r!==void 0&&r.length>0?this.stmts.listDurableMemory.all(e).filter(s=>r.includes(s.type)).map(({name:s,description:i,type:o,updated_at:a})=>({name:s,description:i,type:o,updated_at:a})):this.stmts.listDurableMemory.all(e).map(({name:n,description:s,type:i,updated_at:o})=>({name:n,description:s,type:i,updated_at:o}))}recordSessionSize(e){let r=this.stmts.insertSessionSize.run(e.team_name,e.alias,e.sessionid,e.input_tokens??null,e.cache_tokens??null,e.output_tokens??null,e.total_tokens??null,e.observed_at??O());return this.stmts.getSessionSize.get(r.lastInsertRowid)}latestSessionSizes(){return this.stmts.latestSessionSizes.all()}sessionSizeHistory(e,r,n=20){return this.stmts.sessionSizeHistory.all(e,r,n)}insertSessionEvent(e){let r=this.stmts.insertSessionEvent.run(e.run_id,e.step_id??null,e.kind,e.timestamp_ms,e.payload,e.payload_truncated??0,e.overflow_artifact_id??null);return this.stmts.getSessionEvent.get(r.lastInsertRowid)}listSessionEvents(e,r){return r!==void 0?this.stmts.listSessionEventsSince.all(e,r):this.stmts.listSessionEvents.all(e)}listSessionEventsSince(e,r=1e3){return this.stmts.listAllEventsSince.all(e,r)}latestAgentCall(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call' ORDER BY id DESC LIMIT 1").get(e);if(r===void 0)return null;try{let n=JSON.parse(r.payload);return typeof n.alias!="string"||typeof n.provider!="string"?null:{alias:n.alias,provider:n.provider,...typeof n.model=="string"?{model:n.model}:{}}}catch{return null}}agentCallTokenTotals(e){let r=this.db.prepare("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'agent_call'").all(e),n=0,s=0,i=0;for(let o of r)try{let a=JSON.parse(o.payload);typeof a.tokens_in=="number"&&(n+=a.tokens_in),typeof a.tokens_out=="number"&&(s+=a.tokens_out),i+=1}catch{}return{totalInputTokens:n,totalOutputTokens:s,agentCallCount:i}}addRollupValue(e){this.stmts.upsertRollupStat.run(e.run_id,e.step_id??null,e.metric_kind,e.value,e.bucket_start_ms,e.bucket_end_ms,e.updated_at)}listRollupStats(e){return this.stmts.listRollupStats.all(e)}getRollupCursor(){return this.stmts.getRollupCursor.get("last_event_id")?.value??0}setRollupCursor(e){this.stmts.setRollupCursor.run("last_event_id",e)}insertDriftSignal(e){let r=this.stmts.insertDriftSignal.run(e.team_member_id,e.project_id??null,e.signal_kind,e.severity,e.description,e.detected_at,e.expires_at??null,e.payload??null);return this.stmts.getDriftSignal.get(r.lastInsertRowid)}listDriftSignals(e={}){return e.team_member_id!==void 0&&e.unacked?this.stmts.listUnackedDriftByMember.all(e.team_member_id):e.team_member_id!==void 0?this.stmts.listDriftByMember.all(e.team_member_id):e.project_id!==void 0?this.stmts.listDriftByProject.all(e.project_id):this.stmts.listAllDrift.all()}hasUnackedDriftSignal(e,r,n){return this.stmts.findUnackedDrift.get(e,r??null,n)!==void 0}acknowledgeDriftSignal(e){return this.stmts.ackDriftSignal.run(Date.now(),e),this.stmts.getDriftSignal.get(e)??null}insertInteractiveSession(e){let r=Date.now();return this.stmts.insertInteractiveSession.run(e.run_id,e.step_id,e.state_name,e.status,r,r),this.stmts.getInteractiveSessionByStepId.get(e.step_id)}getInteractiveSessionByStepId(e){return this.stmts.getInteractiveSessionByStepId.get(e)??null}getInteractiveSessionByRunAndState(e,r){return this.stmts.getInteractiveSessionByRunAndState.get(e,r)??null}setInteractiveAgentOutput(e,r,n){this.stmts.setInteractiveAgentOutput.run(r,n,Date.now(),e)}resumeInteractive(e,r,n){return this.resumeInteractiveTxn(e,r,n,O())}resumeEscalation(e,r){return this.resumeEscalationTxn(e,r,O())}}});import{realpathSync as sN}from"node:fs";import{resolve as iN}from"node:path";function pl(t){let e=iN(t);try{return sN(e)}catch{return e}}var Jm=E(()=>{"use strict"});import{platform as Gm}from"node:os";function bt(t){let e=new es;for(let r of t)e.registerAdapter(r);return e}var es,_l=E(()=>{"use strict";Jm();es=class{providers=[];adapters=new Map;register(e){this.providers.push(e)}async listAll(e){let r=[],n=e?.provider?this.providers.filter(o=>o.name===e.provider):this.providers,s=await Promise.all(n.map(o=>o.discoverSessions()));for(let o of s)r.push(...o);let i=r;if(e?.workspace){let o=pl(e.workspace);i=i.filter(a=>pl(a.cwd)===o)}if(e?.from){let o=e.from.getTime();i=i.filter(a=>a.modifiedAt.getTime()>=o)}if(e?.to){let o=e.to.getTime();i=i.filter(a=>a.modifiedAt.getTime()<=o)}return i.sort((o,a)=>a.modifiedAt.getTime()-o.modifiedAt.getTime()),e?.limit&&(i=i.slice(0,e.limit)),i}async getSession(e,r){let n=r?this.providers.filter(s=>s.name===r):this.providers;for(let s of n){let i=await s.loadSession(e);if(i)return i}return null}async resolveSession(e,r){let n=await this.resolveSessions(e,r);return n.length===1?n[0]:null}async resolveSessions(e,r){let n=r?this.providers.filter(i=>i.name===r):this.providers,s=[];for(let i of n){let o=await i.resolveSessionPath(e);o&&s.push({provider:i,filePath:o})}return s}getWatchTargets(){let e=Gm()==="darwin"||Gm()==="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 Km}from"node:fs";import{createInterface as Vm}from"node:readline";import{stat as oN}from"node:fs/promises";import{homedir as aN}from"node:os";async function*qe(t){let e=Km(t,{encoding:"utf-8"}),r=Vm({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 Me(t,e){let r=[],n=Km(t,{encoding:"utf-8"}),s=Vm({input:n,crlfDelay:1/0});try{for await(let i of s){let o=i.trim();if(o){try{r.push(JSON.parse(o))}catch{}if(r.length>=e)break}}}finally{s.close(),n.destroy()}return r}async function Ne(t){let e=await oN(t);return{createdAt:e.birthtime,modifiedAt:e.mtime}}function fe(t){return t.replace(/\\n/g,`
|
|
1441
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function X(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}var be,nr=E(()=>{"use strict";be=aN()});import{readdir as li,stat as Ym,unlink as lN}from"node:fs/promises";import{join as Zr,basename as zm}from"node:path";function cN(t){return t==="file-history-snapshot"||t==="progress"||t==="system"||t==="queue-operation"}function dN(t){if(t.type==="system"){let e=t.message?.content;if(typeof e=="string"&&e.trim())return fe(e.trim());if(e!==void 0)return JSON.stringify(e,null,2)}return t.type==="progress"&&t.data!==void 0?JSON.stringify(t.data,null,2):JSON.stringify(t,null,2)}async function Zm(t){let e=0,r=0,n=0,s=0,i=0,o=0,a;for await(let l of qe(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 u of c)u.type==="text"&&e++;let d=l.message.usage;if(d){let u=d.input_tokens||0,f=d.cache_creation_input_tokens||0,m=d.cache_read_input_tokens||0,p=d.output_tokens||0;r+=u+f+m,n+=m,s+=f,i+=p;let h=u+f+m;h&&(o=h),a={inputTokens:u,cacheWriteInputTokens:f,cachedInputTokens:m,outputTokens:p}}}}return{messageCount:e,totalInputTokens:r,totalCacheReadInputTokens:n,totalCacheWriteInputTokens:s,totalOutputTokens:i,lastInputTokens:o,lastTokenUsage:a}}var ci,Qm=E(()=>{"use strict";nr();ci=class{name="claude";claudeDir;projectsDir;constructor(e={}){this.claudeDir=e.claudeDir||Zr(be,".claude"),this.projectsDir=Zr(this.claudeDir,"projects")}getWatchPaths(){return[{directory:this.projectsDir,filePattern:/\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await li(this.projectsDir)}catch{return e}for(let n of r){let s=Zr(this.projectsDir,n);if(!(await Ym(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await li(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=zm(a,".jsonl");if(!/^[0-9a-f]{8}-/.test(l))continue;let c=Zr(s,a);try{let d=await this.extractSummary(c,l);d&&e.push(d)}catch{}}}return e}async extractSummary(e,r){let n=await Me(e,50),s=await Ne(e),i="",o,a,l,c,d,u;for(let m of n)if(!cN(m.type)&&(!i&&m.cwd&&(i=m.cwd),!o&&m.slug&&(o=m.slug),!a&&m.version&&(a=m.version),!u&&m.timestamp&&(u=new Date(m.timestamp)),m.type==="assistant"&&m.message?.model&&(l=m.message.model),m.type==="user"&&!m.isMeta&&m.message)){let p=m.message.content;if(typeof p=="string"){if(p.includes("<command-name>")||p.includes("<local-command-"))continue;c||(c=X(p.trim(),80)),d=X(p.trim(),80)}}if(!i)return null;let f=await Zm(e);return{provider:"claude",sessionId:r,slug:o,cwd:i,createdAt:u||s.createdAt,modifiedAt:s.modifiedAt,model:l,cliVersion:a,startCommand:"claude",firstUserMessage:c,lastUserMessage:d,messageCount:f.messageCount,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCacheReadInputTokens||void 0,totalCacheWriteInputTokens:f.totalCacheWriteInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Ne(r),s=[],i="",o,a,l,c,d,u,f,m=e;for await(let h of qe(r))if(h.type!=="file-history-snapshot"&&!h.isSidechain){if(!i&&h.cwd&&(i=h.cwd),!o&&h.slug&&(o=h.slug),!a&&h.version&&(a=h.version),!c&&h.gitBranch&&(c=h.gitBranch),!f&&h.timestamp&&(f=new Date(h.timestamp)),h.sessionId&&(m=h.sessionId),h.type==="system"||h.type==="progress"||h.type==="queue-operation"){s.push({role:"system",timestamp:new Date(h.timestamp||0),content:dN(h)});continue}if(h.type==="user"&&h.message){if(h.isMeta)continue;let g=new Date(h.timestamp||0),_=h.message.content;if(typeof _=="string"){if(_.includes("<command-name>")||_.includes("<local-command-"))continue;d||(d=X(_.trim(),80)),u=X(_.trim(),80),s.push({role:"user",timestamp:g,content:fe(_.trim())})}else if(Array.isArray(_)){for(let y of _)if(y.type==="tool_result"){let T=typeof y.content=="string"?fe(y.content):JSON.stringify(y.content);s.push({role:"tool_result",timestamp:g,content:T,toolCallId:y.tool_use_id})}}}if(h.type==="assistant"&&h.message){h.message.model&&(l=h.message.model);let g=new Date(h.timestamp||0),_=h.message.content;if(Array.isArray(_))for(let y of _)y.type==="text"&&y.text?s.push({role:"assistant",timestamp:g,content:fe(y.text),model:h.message.model}):y.type==="tool_use"?s.push({role:"tool_use",timestamp:g,content:y.name||"unknown tool",toolName:y.name,toolInput:JSON.stringify(y.input,null,2),toolCallId:y.id,model:h.message.model}):y.type==="thinking"&&y.thinking&&s.push({role:"thinking",timestamp:g,content:y.thinking})}}if(!i)return null;let p=await Zm(r);return{provider:"claude",sessionId:m,slug:o,cwd:i,createdAt:f||n.createdAt,modifiedAt:n.modifiedAt,model:l,cliVersion:a,startCommand:"claude",gitBranch:c,firstUserMessage:d,lastUserMessage:u,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 lN(r),!0):!1}async resolveSessionFile(e){let r;try{r=await li(this.projectsDir)}catch{return null}let n=[];for(let o of r){let a=Zr(this.projectsDir,o);if(!(await Ym(a).catch(()=>null))?.isDirectory())continue;let c;try{c=await li(a)}catch{continue}for(let d of c){if(!d.endsWith(".jsonl"))continue;let u=zm(d,".jsonl");/^[0-9a-f]{8}-/.test(u)&&n.push({filePath:Zr(a,d),fileSessionId:u})}}let s=n.find(o=>o.fileSessionId===e);if(s)return s.filePath;let i=n.filter(o=>o.fileSessionId.startsWith(e));if(i.length===1)return i[0].filePath;for(let o of n){let a=await Me(o.filePath,20);for(let l of a)if(l.slug&&l.slug===e)return o.filePath}return null}}});function di(t){return"'"+t.replace(/'/g,"'\\''")+"'"}function fN(t,e,r){if(!r)return"";let n=t.tools[e]??hl[e],s=n?.profiles?.[r]?.flags??hl[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 ep(t,e){return!!t.tools[e]}function tp(t,e,r,n,s){let i=t.tools[e]??hl[e],o;if(i?.agent){let l=di(n);o=i.agent.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,l)}else{let l=uN[e];if(!l)throw new Error(`No agent command configured for tool "${e}"`);let c=l.argv.map(d=>d.replace(/\{\{session_id\}\}/g,r).replace(/\{\{prompt\}\}/g,n));if(l.mode==="stdin"){let d=c.map(di).join(" ");o=`printf '%s\\n' ${di(n)} | ${d}`}else o=c.map(di).join(" ")}let a=fN(t,e,s);return a&&(o+=" "+a),o}var hl,uN,rp=E(()=>{"use strict";hl={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:""}}}},uN={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 np(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 sp=E(()=>{"use strict"});var mN,ge,ui,St=E(()=>{"use strict";mN="ACK: waiting for explicit lmctl task.",ge=`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: ${mN}`,ui=`send this exact lmctl seed instruction: "${ge}"`});function sr(t,e){let r={...t??process.env,PWD:e};return delete r.OLDPWD,r}function _N(t,e){return e===void 0||e.length===0?t:{...t??process.env,[ts]:e}}function je(t,e,r,n="chat"){return{..._N(sr(t,e),r),[pN]:n}}var ts,pN,at=E(()=>{"use strict";ts="LMCTL_SELF_SESSIONID",pN="LMCTL_LAUNCH_SOURCE"});import{spawn as ip}from"node:child_process";import{mkdirSync as hN}from"node:fs";var gl,xe,Ft=E(()=>{"use strict";rp();sp();St();at();gl=class t extends Error{cancelReason;constructor(e,r){super(e),this.name="TurnAbortError",this.cancelReason=r,Object.setPrototypeOf(this,t.prototype)}},xe=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===ge?r:n)}seed(e,r){return hN(e,{recursive:!0}),new Promise(n=>{let s;try{s=ip(this.binary,this.seedArgsFor(r),{cwd:e,env:sr(void 0,e),stdio:["pipe","pipe","pipe"],timeout:6e4})}catch(a){return n({success:!1,error:a instanceof Error?a.message:String(a)})}let i="";s.stderr?.on("data",a=>{i+=a.toString()});let o=r?.prompt!==void 0&&this.seedStdin!==void 0?`${r.prompt}
|
|
1442
|
+
`:this.seedStdin;o&&s.stdin?.write(o),s.stdin?.end(),s.on("exit",a=>{n(a===0||a===null?{success:!0}:{success:!1,error:i.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:ui,lsCommand:`lmctl ls --provider ${this.name} --sessiondir ${e}`}}static DEFAULT_IDLE_TIMEOUT_MS=8*60*60*1e3;sendTurn(e,r){if(r.userConfig&&ep(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,i,o,a="",l,c=()=>{e<=0||(clearTimeout(i),i=setTimeout(()=>{n.onIdleWarning?.(e),d(),s.abort(),l&&l({text:a,sessionId:n.sessionId,durationMs:e,status:"stalled",stalledAfterMs:e})},e))},d=()=>{clearTimeout(i)};n.signal&&(n.signal.aborted?(o="external",s.abort()):n.signal.addEventListener("abort",()=>{o="external",s.abort()},{once:!0})),c();let u={...n,binary:this.binary,signal:s.signal,onDelta:p=>{a+=p,c(),n.onDelta?.(p)},onProgress:p=>{p.kind!=="api_retry"&&c(),n.onProgress?.(p)}},f=this.transportFn(r,u).then(p=>(d(),{...p,status:"ok"})).catch(p=>{throw d(),o==="external"?new gl("Turn cancelled","external"):p}),m=new Promise(p=>{l=p});return Promise.race([f,m])}runOneShotAgent(e,r,n){let s=tp(r.userConfig,this.name,r.sessionId,e,r.profile),i=Date.now();return new Promise((o,a)=>{let l=np(r.env),c=ip(s,{shell:!0,cwd:r.cwd,env:je(r.env,r.cwd,r.sessionId),stdio:["pipe","pipe","pipe"]}),d=!1,u=!1,f=setTimeout(()=>{u=!0,c.kill()},l),m="",p="";if(c.stdout?.on("data",h=>{let g=h.toString();m+=g,r.onDelta?.(g)}),c.stderr?.on("data",h=>{p+=h.toString()}),r.signal){if(r.signal.aborted)return clearTimeout(f),c.kill(),a(new Error("Aborted"));r.signal.addEventListener("abort",()=>c.kill(),{once:!0})}c.on("exit",h=>{if(d)return;d=!0,clearTimeout(f);let g=Date.now()-i;u?a(new Error(`Agent command timed out after ${l}ms`)):h===0||h===null?o({text:m.trim(),sessionId:r.sessionId,durationMs:g}):a(new Error(p.trim().slice(0,200)||`Agent command exited with code ${h}`))}),c.on("error",h=>{d||(d=!0,clearTimeout(f),a(h))})})}}});function mi(t,e){let r;if(e&&typeof e=="object"){let n=e.code;typeof n=="number"&&(r=n)}return new Wt(t,r,e)}var et,ye,Ut,fi,Wt,Qr=E(()=>{"use strict";et=class extends Error{constructor(e,r){super(e,r),this.name=this.constructor.name}},ye=class extends et{},Ut=class extends et{exitCode;signal;stderr;constructor(e,r,n=null,s){super(e),this.exitCode=r,this.signal=n,this.stderr=s}},fi=class extends et{line;constructor(e,r,n){super(e,{cause:n}),this.line=r}},Wt=class extends et{rpcCode;rpcData;constructor(e,r,n){super(e),r!==void 0&&(this.rpcCode=r),n!==void 0&&(this.rpcData=n)}}});import*as wl from"node:child_process";function yN(t){if(typeof wl.spawnSync=="function")try{wl.spawnSync("taskkill",["/T","/F","/PID",String(t)],{windowsHide:!0})}catch{}}function op(t){return t.exitCode!==null||t.signalCode!==null}function yl(t,e){return op(t)?Promise.resolve(!0):new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),r(!0))},i=setTimeout(()=>{n||(n=!0,t.removeListener("exit",s),r(!1))},e);t.once("exit",s)})}async function tt(t,e={}){let r=Date.now(),n=e.stdinEnd!==!1,s=e.softDelayMs??5e3,i=e.killDelayMs??5e3,o=e.platform??process.platform,a=e.runTaskkill??yN;if(op(t))return{signal:"natural",elapsedMs:Date.now()-r};if(n&&t.stdin&&!t.stdin.destroyed)try{t.stdin.end()}catch{}if(await yl(t,s))return{signal:"stdin",elapsedMs:Date.now()-r};if(o==="win32"&&typeof t.pid=="number")a(t.pid);else try{t.kill("SIGTERM")}catch{}if(await yl(t,i))return{signal:"SIGTERM",elapsedMs:Date.now()-r};if(o!=="win32")try{t.kill("SIGKILL")}catch{}return await yl(t,gN)?{signal:"SIGKILL",elapsedMs:Date.now()-r}:{signal:"abandoned",elapsedMs:Date.now()-r}}var gN,pi=E(()=>{"use strict";gN=1e3});function ap(t){ce()&&Ae({event:"legacy",msg:`[debug] ${t}`},{always:!0})}function ir(t,e){let r=EN[t];if(r)return r[e]??r.yolo}function bN(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 lt(t,e,r="yolo"){if(TN.has(t)){ap(`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"):wN[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 C({event:"yolo_assert_failed",provider:t,reason:"unconfigured_provider",args:e.join(" "),message:s}),new ye(s)}if(!bN(e,n)){let s=n.join(" "),i=`${t} spawn missing YOLO flag '${s}' \u2014 YOLO is mandatory for every provider; see src/providers/yolo-contract.ts. Got argv: [${e.map(o=>JSON.stringify(o)).join(", ")}]`;throw C({event:"yolo_assert_failed",provider:t,reason:"flag_missing",required_flag:s,mode:r,args:e.join(" "),message:i}),new ye(i)}ap(`YOLO ${t} [mode=${r}]: argv flag '${n.join(" ")}'`)}var wN,EN,TN,en=E(()=>{"use strict";Qr();de();wN={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"],gemini:["-y"],copilot:["--yolo"],agy:["--dangerously-skip-permissions"],lmplayer:["--dangerously-skip-permissions"]},EN={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"]}};TN=new Set(["codex","opencode"])});function lp(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(`
|
|
1361
1443
|
|
|
1362
1444
|
--- additional response (turn ${r+1} of ${t.length}; likely an injected mid-call notification) ---
|
|
1363
1445
|
|
|
1364
|
-
`+t[r]);return e.join("")}function El(t={}){let e=[],r="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}t.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(r=i.session_id||r),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&t.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=cp(e);return{result:lp(s.resultTexts),sessionId:s.sessionId||r,durationMs:s.durationMs,numTurns:s.numTurns}}}}function cp(t){let e=[],r=0,n=0,s="";for(let i of t){e.push(i.result||"");let o=i.duration_ms;typeof o=="number"&&Number.isFinite(o)&&(r+=o);let a=i.num_turns;typeof a=="number"&&Number.isFinite(a)&&(n=a);let l=i.session_id;typeof l=="string"&&l&&(s=l)}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s}}var Tl=E(()=>{"use strict"});import{spawn as
|
|
1446
|
+
`+t[r]);return e.join("")}function El(t={}){let e=[],r="",n=!1;return{processLine(s){if(!s.trim())return;let i;try{i=JSON.parse(s)}catch{return}t.onEvent?.(i);let o=i.type;if(o==="system"&&i.subtype==="init"&&(r=i.session_id||r),o==="assistant"){let l=i.message?.content;if(Array.isArray(l))for(let c of l)c.type==="text"&&c.text&&t.onText?.(c.text)}o==="result"&&(n=!0,e.push(i))},sawResult(){return n},finalize(){if(!n)return null;let s=cp(e);return{result:lp(s.resultTexts),sessionId:s.sessionId||r,durationMs:s.durationMs,numTurns:s.numTurns}}}}function cp(t){let e=[],r=0,n=0,s="";for(let i of t){e.push(i.result||"");let o=i.duration_ms;typeof o=="number"&&Number.isFinite(o)&&(r+=o);let a=i.num_turns;typeof a=="number"&&Number.isFinite(a)&&(n=a);let l=i.session_id;typeof l=="string"&&l&&(s=l)}return{resultTexts:e,durationMs:r,numTurns:n,sessionId:s}}var Tl=E(()=>{"use strict"});import{spawn as SN}from"node:child_process";import{existsSync as vN}from"node:fs";function IN(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} exited with code ${t.exitCode} before returning a final result event.
|
|
1365
1447
|
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:
|
|
1366
1448
|
${e}
|
|
1367
1449
|
|
|
1368
|
-
${r}`:r}function dp(t,e){return new Promise((r,n)=>{let s=e.tool||"claude",i=e.binaryPath||
|
|
1369
|
-
`);f=_.pop()||"";for(let y of _)m(y)});let p="";c.stderr?.on("data",g=>{p+=g.toString()}),c.on("error",g=>{C({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:g.message}),n(new ye(`Failed to spawn ${i}: ${g.message}`,{cause:g}))}),c.on("exit",g=>{if(d)return;f.trim()&&m(f);let _=u.finalize();_?(Tt(`stream-json: result ${_.result.slice(0,80)}${_.result.length>80?"...":""} (${_.durationMs}ms)`),r({..._,exitCode:g})):(C({event:"transport_error",provider:s,error_class:"Error",reason:"provider_no_result",exit_code:g,stderr_tail:p.slice(0,500)}),n(new Error(
|
|
1370
|
-
`),Tt(`stream-json: prompt sent (${t.length} chars)`)})}var
|
|
1450
|
+
${r}`:r}function dp(t,e){return new Promise((r,n)=>{let s=e.tool||"claude",i=e.binaryPath||kN[s]||"claude",o=["-p","","--output-format","stream-json","--input-format","stream-json"];s==="claude"&&o.push("--verbose"),e.sessionId&&o.push("--resume",e.sessionId),e.model&&o.push("--model",e.model);let a=e.permissionMode??"yolo",l=ir(s,a)??NN[s]??["--dangerously-skip-permissions"];o.push(...l);try{lt(s,o,a)}catch(g){return n(g)}if(e.cwd&&!vN(e.cwd))return C({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),n(new ye(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let c=SN(i,o,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:je(e.env,e.cwd,e.sessionId)}),d=!1;if(e.signal){if(e.signal.aborted)return d=!0,C({event:"transport_abort",provider:s,phase:"pre_spawn"}),tt(c).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{d=!0,C({event:"transport_abort",provider:s}),tt(c).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let u=El({onEvent:e.onEvent,onText:e.onText}),f="";function m(g){let _=u.sawResult();u.processLine(g),!_&&u.sawResult()&&c.stdin?.end()}c.stdout?.on("data",g=>{f+=g.toString();let _=f.split(`
|
|
1451
|
+
`);f=_.pop()||"";for(let y of _)m(y)});let p="";c.stderr?.on("data",g=>{p+=g.toString()}),c.on("error",g=>{C({event:"transport_error",provider:s,error_class:"TransportConnectionError",error_message:g.message}),n(new ye(`Failed to spawn ${i}: ${g.message}`,{cause:g}))}),c.on("exit",g=>{if(d)return;f.trim()&&m(f);let _=u.finalize();_?(Tt(`stream-json: result ${_.result.slice(0,80)}${_.result.length>80?"...":""} (${_.durationMs}ms)`),r({..._,exitCode:g})):(C({event:"transport_error",provider:s,error_class:"Error",reason:"provider_no_result",exit_code:g,stderr_tail:p.slice(0,500)}),n(new Error(IN({tool:s,exitCode:g,stderr:p}))))});let h=JSON.stringify({type:"user",message:{role:"user",content:t}});c.stdin?.write(h+`
|
|
1452
|
+
`),Tt(`stream-json: prompt sent (${t.length} chars)`)})}var kN,NN,up=E(()=>{"use strict";Qr();pi();en();de();at();Tl();Tl();kN={claude:"claude",qwen:"qwen"};NN={claude:["--dangerously-skip-permissions"],qwen:["--approval-mode","yolo"]}});function _i(t={}){return[]}var bl=E(()=>{"use strict"});function Sl(t){return t==="plan"?"read-only":"danger-full-access"}function fp(t="0.0.0"){return{clientInfo:{name:"lmctl",title:"lmctl",version:t},capabilities:{experimentalApi:!1}}}function vl(){return{agentItems:new Map,resultText:""}}function hi(t,e,r,n){let s=t.method;if(!s)return!1;let i=t.params;if(s==="turn/started")return e.agentItems.clear(),e.resultText="",!1;if(s==="item/started"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=typeof o.phase=="string"?o.phase:void 0,l=a==="commentary"||a==="final_answer"?a:void 0;return e.agentItems.set(o.id,{phase:l,buffer:""}),!0}return!1}if(s==="item/agentMessage/delta"){let o=i?.delta||"",a=typeof i?.itemId=="string"?i.itemId:void 0;if(!o)return!0;let l=a?e.agentItems.get(a):void 0;return l?(l.phase==="commentary"||(l.buffer+=o),r?.(o),l.phase&&i&&(i._lmctlItemPhase=l.phase)):(e.resultText+=o,r?.(o)),!0}if(s==="item/completed"){let o=i?.item;if(o?.type==="agentMessage"&&typeof o.id=="string"){let a=e.agentItems.get(o.id);if(a){if(a.phase!=="commentary"){let l=typeof o.text=="string"?o.text:a.buffer;if(n&&typeof o.text=="string"&&o.text!==a.buffer){let c=typeof i?.threadId=="string"?i.threadId:void 0,d=typeof i?.turnId=="string"?i.turnId:void 0;n({itemId:o.id,threadId:c,turnId:d,expectedFromItemText:o.text,gotFromBuffer:a.buffer})}e.resultText+=l}e.agentItems.delete(o.id)}return!0}return!1}return!1}function kl(t){for(let[,e]of t.agentItems.entries())e.phase!=="commentary"&&e.buffer&&(t.resultText+=e.buffer);t.agentItems.clear()}function mp(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 Il(){return{pendingCodexError:null}}function Nl(t,e){let r=mp(t);return r.willRetry||(e.pendingCodexError=r.turnError),r}function xl(t,e){if(e.pendingCodexError){let i=e.pendingCodexError;return e.pendingCodexError=null,{shouldReject:!0,turnError:i}}let n=t.params?.turn;if((typeof n?.status=="string"?n.status:void 0)==="failed"){let i=n?.error,o=typeof i?.message=="string"?i.message:void 0,a=o&&o.length>0?o:"(no message)";return{shouldReject:!0,turnError:new Error(`Turn errored: ${a}`)}}return{shouldReject:!1}}var Al=E(()=>{"use strict"});import{spawn as xN}from"node:child_process";import{createInterface as AN}from"node:readline";import{existsSync as RN,readFileSync as LN}from"node:fs";import{fileURLToPath as ON}from"node:url";function CN(){return fp($N)}function or(t,e){Tt(`[codex:${t}] ${JSON.stringify(e)}`)}function MN(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: codex app-server exited with code ${t.exitCode} before completing the turn.
|
|
1371
1453
|
One possible cause: Codex stopped before delivering a terminal turn/completed event.`;return e?`Original provider error:
|
|
1372
1454
|
${e}
|
|
1373
1455
|
|
|
1374
|
-
${r}`:r}function pp(t,e){return new Promise((r,n)=>{let s=e.binaryPath||"codex",i=["app-server","--listen","stdio://"];e.model&&i.push("-c",`model=${JSON.stringify(e.model)}`);let o=e.isLead??e.alias?.toLowerCase()==="lead",a=o?_i():[];i.push(...a),ce()&&Oe(JSON.stringify({event:"codex_mcp_inject",alias:e.alias??null,isLead:o,injected:a.length>0}));let l=e.permissionMode??"yolo",c=Sl(l);try{lt("codex",i,l)}catch(U){return n(U)}if(e.cwd&&!
|
|
1456
|
+
${r}`:r}function pp(t,e){return new Promise((r,n)=>{let s=e.binaryPath||"codex",i=["app-server","--listen","stdio://"];e.model&&i.push("-c",`model=${JSON.stringify(e.model)}`);let o=e.isLead??e.alias?.toLowerCase()==="lead",a=o?_i():[];i.push(...a),ce()&&Oe(JSON.stringify({event:"codex_mcp_inject",alias:e.alias??null,isLead:o,injected:a.length>0}));let l=e.permissionMode??"yolo",c=Sl(l);try{lt("codex",i,l)}catch(U){return n(U)}if(e.cwd&&!RN(e.cwd))return C({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`}),n(new ye(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let d=xN(s,i,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:je(e.env,e.cwd,e.threadId)}),u=!1;if(e.signal){if(e.signal.aborted)return u=!0,C({event:"transport_abort",provider:"codex",phase:"pre_spawn"}),tt(d).catch(()=>{}),n(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,C({event:"transport_abort",provider:"codex"}),tt(d).catch(()=>{}),n(new Error("Aborted"))},{once:!0})}let f=AN({input:d.stdout}),m=new Map,p=1,h=e.threadId||"",g="",_=!1,y=!1,T=Date.now(),b=vl(),I=Il();function x(U,j={}){return new Promise((A,ee)=>{let B=p++;m.set(B,{resolve:A,reject:ee});let k=JSON.stringify({jsonrpc:"2.0",id:B,method:U,params:j});d.stdin?.write(k+`
|
|
1375
1457
|
`)})}function H(U,j={}){let A=JSON.stringify({jsonrpc:"2.0",method:U,params:j});d.stdin?.write(A+`
|
|
1376
|
-
`)}f.on("line",U=>{let j;try{j=JSON.parse(U)}catch{return}if(typeof j.id=="number"&&m.has(j.id)){let B=m.get(j.id);if(m.delete(j.id),j.error){let k=j.error,N=typeof k?.message=="string"&&k.message.length>0?k.message:JSON.stringify(j.error);B.reject(mi(`codex app-server error: ${N}`,k))}else B.resolve(j);e.onEvent?.(j);return}let A=j.method;if(!A){e.onEvent?.(j);return}if(A==="thread/started"){let k=j.params?.thread;k?.id&&(h=k.id)}let ee=ce()?B=>{or("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=j.params,k=B?.turn;k?.id&&(g=k.id),hi(j,b,e.onDelta,ee),ce()&&or("turn/started",{params:B??null})}if(ce()&&(A==="item/started"||A==="item/completed")){let B=j.params;B?.item?.type==="agentMessage"&&or(A,{params:B??null})}if(A==="item/started"||A==="item/agentMessage/delta"||A==="item/completed"){if(A==="item/agentMessage/delta"){let B=j.params;ce()&&or("agentMessage/delta",{params:B??null})}hi(j,b,e.onDelta,ee)}if(A==="turn/completed"){let B=j.params;if(ce())for(let[N,L]of b.agentItems.entries())L.buffer&&or("turn/completed/unflushed-item",{itemId:N,phase:L.phase,bufferLen:L.buffer.length});kl(b),ce()&&or("turn/completed",{params:B??null});let k=xl(j,I);k.shouldReject?(ce()&&or("turn/completed/terminal-reject",{message:k.turnError.message}),y=!0,_=!0,d.stdin?.end(),n(k.turnError)):(_=!0,d.stdin?.end())}if(A==="error"){let B=Nl(j,I);if(ce()){let k=j.params,N=k?.error,L=typeof N?.message=="string"?N.message:"(no message)";or(B.willRetry?"error/retry":"error/terminal-deferred",{message:L,willRetry:B.willRetry,params:k??null})}}e.onEvent?.(j)});let pe="";d.stderr?.on("data",U=>{pe+=U.toString()}),d.on("error",U=>{C({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:U.message}),n(new ye(`Failed to spawn codex app-server: ${U.message}`,{cause:U}))}),d.on("exit",U=>{if(!u&&!y){if(_){r({result:b.resultText,threadId:h,turnId:g,durationMs:Date.now()-T,exitCode:U});return}if(I.pendingCodexError){n(I.pendingCodexError);return}C({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:U,stderr_tail:pe.slice(0,500)}),n(new Error(
|
|
1377
|
-
`),C({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:U instanceof Error?U.message:String(U)});let A=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;A?.id&&(h=A.id)}else{let j=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;j?.id&&(h=j.id)}await x("turn/start",{threadId:h,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(U){tt(d).catch(()=>{}),n(U instanceof Error?U:new Error(String(U)))}})()})}var $
|
|
1378
|
-
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function gi(t,e={}){let r=rs(t,".opencode"),n=rs(r,"opencode.json");if(!yp(n)){
|
|
1458
|
+
`)}f.on("line",U=>{let j;try{j=JSON.parse(U)}catch{return}if(typeof j.id=="number"&&m.has(j.id)){let B=m.get(j.id);if(m.delete(j.id),j.error){let k=j.error,N=typeof k?.message=="string"&&k.message.length>0?k.message:JSON.stringify(j.error);B.reject(mi(`codex app-server error: ${N}`,k))}else B.resolve(j);e.onEvent?.(j);return}let A=j.method;if(!A){e.onEvent?.(j);return}if(A==="thread/started"){let k=j.params?.thread;k?.id&&(h=k.id)}let ee=ce()?B=>{or("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=j.params,k=B?.turn;k?.id&&(g=k.id),hi(j,b,e.onDelta,ee),ce()&&or("turn/started",{params:B??null})}if(ce()&&(A==="item/started"||A==="item/completed")){let B=j.params;B?.item?.type==="agentMessage"&&or(A,{params:B??null})}if(A==="item/started"||A==="item/agentMessage/delta"||A==="item/completed"){if(A==="item/agentMessage/delta"){let B=j.params;ce()&&or("agentMessage/delta",{params:B??null})}hi(j,b,e.onDelta,ee)}if(A==="turn/completed"){let B=j.params;if(ce())for(let[N,L]of b.agentItems.entries())L.buffer&&or("turn/completed/unflushed-item",{itemId:N,phase:L.phase,bufferLen:L.buffer.length});kl(b),ce()&&or("turn/completed",{params:B??null});let k=xl(j,I);k.shouldReject?(ce()&&or("turn/completed/terminal-reject",{message:k.turnError.message}),y=!0,_=!0,d.stdin?.end(),n(k.turnError)):(_=!0,d.stdin?.end())}if(A==="error"){let B=Nl(j,I);if(ce()){let k=j.params,N=k?.error,L=typeof N?.message=="string"?N.message:"(no message)";or(B.willRetry?"error/retry":"error/terminal-deferred",{message:L,willRetry:B.willRetry,params:k??null})}}e.onEvent?.(j)});let pe="";d.stderr?.on("data",U=>{pe+=U.toString()}),d.on("error",U=>{C({event:"transport_error",provider:"codex",error_class:"TransportConnectionError",error_message:U.message}),n(new ye(`Failed to spawn codex app-server: ${U.message}`,{cause:U}))}),d.on("exit",U=>{if(!u&&!y){if(_){r({result:b.resultText,threadId:h,turnId:g,durationMs:Date.now()-T,exitCode:U});return}if(I.pendingCodexError){n(I.pendingCodexError);return}C({event:"transport_error",provider:"codex",error_class:"Error",reason:"provider_no_result",exit_code:U,stderr_tail:pe.slice(0,500)}),n(new Error(MN({exitCode:U,stderr:pe})))}}),(async()=>{try{if(await x("initialize",CN()),H("initialized",{}),e.threadId)try{let U=x("thread/resume",{threadId:e.threadId,sandbox:c,approvalPolicy:"never",...e.model?{model:e.model}:{}}),j=new Promise((A,ee)=>setTimeout(()=>ee(new Error("resume timeout")),5e3));await Promise.race([U,j]),h=e.threadId}catch(U){process.stderr.write(`[codex] thread/resume failed, creating new thread
|
|
1459
|
+
`),C({event:"codex_thread_resume_fallback",provider:"codex",thread_id:e.threadId,error_message:U instanceof Error?U.message:String(U)});let A=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;A?.id&&(h=A.id)}else{let j=(await x("thread/start",{cwd:e.cwd,approvalPolicy:"never",sandbox:c,...e.model?{model:e.model}:{}})).result?.thread;j?.id&&(h=j.id)}await x("turn/start",{threadId:h,input:[{type:"text",text:t}],...e.model?{model:e.model}:{}})}catch(U){tt(d).catch(()=>{}),n(U instanceof Error?U:new Error(String(U)))}})()})}var $N,_p=E(()=>{"use strict";de();de();Qr();pi();en();bl();de();at();Al();Al();$N=(()=>{try{let t=new URL("../../../package.json",import.meta.url),e=JSON.parse(LN(ON(t),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}})()});import{existsSync as yp,mkdirSync as jN,readFileSync as wp,writeFileSync as hp}from"node:fs";import{join as rs,resolve as DN}from"node:path";function Ep(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 Rl(t,e,r={existsSync:yp,readFileSync:wp}){let n=[];for(let s of t){if(s.provider.trim().toLowerCase()!=="opencode")continue;let i=DN(e,s.sessiondir??e);for(let o of PN(i)){let a=FN(o,r);a!==void 0&&Object.prototype.hasOwnProperty.call(a,"permission")&&(Ep(a.permission)||n.push(`[${s.alias}] ${o} sets a non-allow \`permission\`, which opencode merges over lmctl's YOLO (.opencode/opencode.json permission:"allow") \u2014 the member may hang on permission prompts. Set \`permission: "allow"\` in that file (or remove the key).`))}}return n}function PN(t){return[rs(t,".opencode","opencode.jsonc"),rs(t,"opencode.jsonc"),rs(t,"opencode.json")]}function FN(t,e){try{if(!e.existsSync(t))return;let r=e.readFileSync(t,"utf-8"),n=JSON.parse(UN(r));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function UN(t){let e="",r=!1,n="",s=!1;for(let i=0;i<t.length;i+=1){let o=t[i],a=t[i+1];if(r){e+=o,s?s=!1:o==="\\"?s=!0:o===n&&(r=!1,n="");continue}if(o==='"'||o==="'"){r=!0,n=o,e+=o;continue}if(o==="/"&&a==="/"){for(;i<t.length&&t[i]!==`
|
|
1460
|
+
`;)i+=1;i<t.length&&(e+=t[i]);continue}if(o==="/"&&a==="*"){for(i+=2;i<t.length&&!(t[i]==="*"&&t[i+1]==="/");)i+=1;i+=1;continue}e+=o}return e.replace(/,\s*([}\]])/g,"$1")}function gi(t,e={}){let r=rs(t,".opencode"),n=rs(r,"opencode.json");if(!yp(n)){jN(r,{recursive:!0});let o=JSON.stringify({permission:"allow"},null,2);return hp(n,o+`
|
|
1379
1461
|
`,"utf-8"),!0}let s;try{s=JSON.parse(wp(n,"utf-8"))}catch{return console.log(gp.yellow(` .opencode/opencode.json at ${n} is malformed \u2014 skipping opencode config install.`)),!1}if(typeof s!="object"||s===null)return console.log(gp.yellow(` .opencode/opencode.json at ${n} is not an object \u2014 skipping opencode config install.`)),!1;let i=!1;return s.permission===void 0&&(s.permission="allow",i=!0),Ep(s.permission)||C({event:"opencode_yolo_override",provider:"opencode",config_path:n,user_permission:s.permission,message:`opencode.json has a user-set 'permission' value other than 'allow' \u2014 lmctl's YOLO contract is NOT in effect; turns may hang waiting on permission prompts. Set permission: "allow" or remove the key to restore YOLO.`}),i&&hp(n,JSON.stringify(s,null,2)+`
|
|
1380
|
-
`,"utf-8"),i}var gp,yi=E(()=>{"use strict";de();gp={yellow:t=>t}});function Sp(t){let e=[...t.matchAll(
|
|
1462
|
+
`,"utf-8"),i}var gp,yi=E(()=>{"use strict";de();gp={yellow:t=>t}});function Sp(t){let e=[...t.matchAll(WN)];if(e.length>0){let r=e[e.length-1],n=(r.index??0)+r[0].length;return Tp(t.slice(n).trimStart())}return Tp(JN(t.replace(BN,"")))}function JN(t){let e=qN.exec(t);if(e===null)return t;let r=t.slice(e[0].length),n=[...r.matchAll(HN)];if(n.length<2)return t;let s=n[0],i=(s.index??0)+s[0].length;return r.slice(i).trimStart()}function Tp(t){let e=[...t.matchAll(XN)];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 tn(t,e=""){let r=t.result;return typeof r?.sessionId=="string"&&r.sessionId.length>0?r.sessionId:e}function vp(t){let e=t.result;return typeof e?.stopReason=="string"?e.stopReason:""}function Ll(t={}){let e="",r="",n="",s=!1,i=!1,o=()=>({result:t.tool==="gemini"?Sp(r):r,sessionId:e,stopReason:n});return{setSessionId(a){e=a},beginTurn(){r="",n="",s=!1,i=!0},completeTurn(a){return n=vp(a),s=!0,i=!1,o()},processMessage(a){if(a.method!=="session/update")return!1;let c=a.params?.update;if(c?.sessionUpdate!=="agent_message_chunk")return!1;let d=c.content,u=typeof d?.text=="string"?d.text:"";return u&&i&&(r+=u,t.onDelta?.(u)),!0},finalize(){return s?o():null}}}var bp,WN,BN,qN,HN,XN,Ol=E(()=>{"use strict";bp="(?:png|jpe?g|webp|heic|pdf)",WN=new RegExp(`\\bSTANCE:\\s*\\S+_\\d{6,}\\.${bp}\\s*`,"gi"),BN=new RegExp(`^ACK:\\s*waiting for explicit lmctl task\\.\\d{6,}\\.${bp}\\s*`,"i"),qN=/^ACK:\s*waiting for explicit lmctl task[._]?\s*/i,HN=/^STANCE:\s+\S+\s*$/gim,XN=/\[Thought:\s*true\]\s*/gi});import{spawn as kp}from"node:child_process";import{existsSync as GN}from"node:fs";import{createInterface as KN}from"node:readline";function VN(t){let e=t.stderr.trim().slice(0,500),r=`lmctl: ${t.tool} ACP process exited with code ${t.exitCode} before completing the prompt.
|
|
1381
1463
|
One possible cause: the provider process failed before a complete ACP response was delivered.`;return e?`Original provider error:
|
|
1382
1464
|
${e}
|
|
1383
1465
|
|
|
1384
|
-
${r}`:r}function Ip(t,e){let r=
|
|
1466
|
+
${r}`:r}function Ip(t,e){let r=KN({input:t.stdout}),n=new Map,s=(o,a={})=>new Promise((l,c)=>{let d=YN++;n.set(d,{resolve:l,reject:c});let u=JSON.stringify({jsonrpc:"2.0",id:d,method:o,params:a});Ae({event:"acp_send",direction:"SEND",provider:e.provider,method:o,id:d,params:a}),t.stdin?.write(`${u}
|
|
1385
1467
|
`)}),i=(o,a={})=>{t.stdin?.write(`${JSON.stringify({jsonrpc:"2.0",method:o,params:a})}
|
|
1386
1468
|
`)};return r.on("line",o=>{let a;try{a=JSON.parse(o)}catch{return}if(Ae({event:"acp_recv",direction:"RECV",provider:e.provider,id:typeof a.id=="number"?a.id:void 0,method:typeof a.method=="string"?a.method:void 0,preview:JSON.stringify(a).slice(0,300)}),e.onEvent?.(a),typeof a.id=="number"&&n.has(a.id)){let c=n.get(a.id);if(n.delete(a.id),a.error){let d=a.error,u=typeof d?.message=="string"&&d.message.length>0?d.message:JSON.stringify(a.error);c.reject(mi(`ACP RPC error: ${u}`,d))}else c.resolve(a);return}let l=a.method;if(l){if(typeof a.id=="number"){C({event:"acp_unhandled_request",provider:e.provider,method:l,id:a.id,params:a.params});let c=JSON.stringify({jsonrpc:"2.0",id:a.id,error:{code:-32601,message:`Method not found: ${l} (lmctl does not implement server-side ACP methods)`}});Ae({event:"acp_send",direction:"SEND",provider:e.provider,replyTo:a.id,error:"method not found"}),t.stdin?.write(`${c}
|
|
1387
1469
|
`);return}e.onNotification?.(a)}}),{sendRpc:s,sendNotification:i,close(o=new ye("ACP RPC channel closed")){r.close();for(let a of n.values())a.reject(o);n.clear()}}}function Cl(t){let e;try{e=kp(t.binaryPath??$l.opencode.binary,$l.opencode.args,{cwd:t.cwd,stdio:["pipe","pipe","pipe"],env:je(t.env,t.cwd,void 0,"unknown")})}catch(s){return Promise.resolve({status:"unavailable",reason:"spawn",error:s instanceof Error?s.message:String(s)})}let r=Ip(e,{provider:"opencode"}),n=t.timeoutMs??5e3;return new Promise(s=>{let i=!1,o=(d,u=!0)=>{if(!i){if(i=!0,clearTimeout(c),e.removeListener("error",a),e.removeListener("exit",l),r.close(),!u){s(d);return}tt(e,{softDelayMs:100,killDelayMs:100}).finally(()=>s(d))}},a=d=>{o({status:"unavailable",reason:"spawn",error:d.message},!1)},l=(d,u)=>{o({status:"unavailable",reason:"handshake",error:`opencode ACP exited before verification (code=${String(d)}, signal=${String(u)})`},!1)};e.once("error",a),e.once("exit",l);let c=setTimeout(()=>{o({status:"unavailable",reason:"timeout"})},n);(async()=>{try{await r.sendRpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),r.sendNotification("notifications/initialized");let d=await r.sendRpc("session/new",{cwd:t.cwd,mcpServers:[]}),u=tn(d);try{await r.sendRpc("session/set_config_option",{sessionId:u,configId:"model",value:t.model})}catch(f){o({status:"rejected",option:"model",value:t.model,error:f instanceof Error?f.message:String(f)});return}if(t.effort!==void 0)try{await r.sendRpc("session/set_config_option",{sessionId:u,configId:"effort",value:t.effort})}catch(f){o({status:"rejected",option:"effort",value:t.effort,error:f instanceof Error?f.message:String(f)});return}o({status:"verified"})}catch(d){o({status:"unavailable",reason:"handshake",error:d instanceof Error?d.message:String(d)})}})()})}function Np(t,e){let r=$l[e.tool];return r?new Promise((n,s)=>{let i=e.binaryPath||r.binary;if(e.tool==="opencode")try{gi(e.cwd)}catch(y){C({event:"opencode_config_install_failed",cwd:e.cwd,error_message:y instanceof Error?y.message:String(y)})}let o=e.permissionMode??"yolo",a=[...r.args];if(o==="plan")if(e.tool==="gemini"){let y=ir("gemini","plan"),T=ir("gemini","yolo");a=a.filter(b=>!(T??[]).includes(b)),y&&a.push(...y)}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.
|
|
1388
1470
|
`),C({event:"acp_plan_mode_unsupported",provider:e.tool,requested_mode:"plan",effective_mode:"yolo"}));e.model&&e.tool==="gemini"&&a.push("--model",e.model);let l=e.tool==="copilot"?"yolo":o;try{lt(e.tool,a,l)}catch(y){return s(y)}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.
|
|
1389
|
-
`),C({event:"acp_model_unsupported",provider:e.tool,model:e.model})),e.cwd&&!
|
|
1471
|
+
`),C({event:"acp_model_unsupported",provider:e.tool,model:e.model})),e.cwd&&!GN(e.cwd))return C({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:`sessiondir missing: ${e.cwd}`,elapsed_ms:0}),s(new ye(`sessiondir missing: ${e.cwd}`,{cause:Object.assign(new Error("cwd missing"),{code:"ENOENT_CWD"})}));let c=kp(i,a,{cwd:e.cwd,stdio:["pipe","pipe","pipe"],env:je(e.env,e.cwd,e.sessionId)}),d=Date.now(),u=!1;if(e.signal){if(e.signal.aborted)return u=!0,C({event:"transport_abort",provider:e.tool,phase:"pre_spawn"}),tt(c).catch(()=>{}),s(new Error("Aborted"));e.signal.addEventListener("abort",()=>{u=!0,C({event:"transport_abort",provider:e.tool,elapsed_ms:Date.now()-d}),tt(c).catch(()=>{}),s(new Error("Aborted"))},{once:!0})}let f=e.sessionId||"",m=Ll({tool:e.tool,onDelta:e.onDelta});m.setSessionId(f);let p=Ip(c,{provider:e.tool,onEvent:e.onEvent,onNotification:y=>m.processMessage(y)}),{sendRpc:h,sendNotification:g}=p,_="";c.stderr?.on("data",y=>{_+=y.toString()}),c.on("error",y=>{p.close(y),C({event:"transport_error",provider:e.tool,error_class:"TransportConnectionError",error_message:y.message,elapsed_ms:Date.now()-d}),s(new ye(`Failed to spawn ${r.binary} ${r.args.join(" ")}: ${y.message}`,{cause:y}))}),c.on("exit",y=>{if(p.close(new ye(`ACP process exited with code ${String(y)}`)),u)return;let T=m.finalize();T!==null?n({result:T.result,sessionId:T.sessionId,durationMs:Date.now()-d,stopReason:T.stopReason,exitCode:y}):(C({event:"transport_error",provider:e.tool,error_class:"Error",reason:"provider_no_result",exit_code:y,stderr_tail:_.slice(0,500),elapsed_ms:Date.now()-d}),s(new Error(VN({tool:e.tool,exitCode:y,stderr:_}))))}),(async()=>{try{if(await h("initialize",{protocolVersion:1,clientInfo:{name:"lmctl",version:"0.1.0"},clientCapabilities:{}}),g("notifications/initialized"),e.sessionId)try{let b=await h("session/load",{sessionId:e.sessionId,cwd:e.cwd,mcpServers:[]});f=tn(b,e.sessionId),m.setSessionId(f)}catch(b){if(e.requireResume)throw new Error(`Cannot resume session ${e.sessionId} via ACP: ${b instanceof Error?b.message:String(b)}`);process.stderr.write(`[acp] session/load failed for ${e.sessionId}, creating new session
|
|
1390
1472
|
`),C({event:"acp_session_resume_fallback",provider:e.tool,session_id:e.sessionId,error_message:b instanceof Error?b.message:String(b)});let I=await h("session/new",{cwd:e.cwd,mcpServers:[]});f=tn(I),m.setSessionId(f)}else{let b=await h("session/new",{cwd:e.cwd,mcpServers:[]});f=tn(b),m.setSessionId(f)}if(e.model&&e.tool==="opencode")try{await h("session/set_config_option",{sessionId:f,configId:"model",value:e.model}),Tt(`acp: set_config_option(model=${e.model}) ok`)}catch(b){let I=b instanceof Error?b.message:String(b);process.stderr.write(`[acp] set_config_option(model=${e.model}) failed: ${I}
|
|
1391
1473
|
`),C({event:"acp_config_option_failed",provider:e.tool,config_id:"model",value:e.model,error_message:I})}if(e.effort&&e.tool==="opencode")try{await h("session/set_config_option",{sessionId:f,configId:"effort",value:e.effort}),Tt(`acp: set_config_option(effort=${e.effort}) ok`)}catch(b){let I=b instanceof Error?b.message:String(b);process.stderr.write(`[acp] set_config_option(effort=${e.effort}) failed: ${I}
|
|
1392
|
-
`),C({event:"acp_config_option_failed",provider:e.tool,config_id:"effort",value:e.effort,error_message:I})}m.beginTurn(),Tt(`acp: prompt sent (${t.length} chars)`);let y=await h("session/prompt",{sessionId:f,prompt:[{type:"text",text:t}]}),T=m.completeTurn(y);Tt(`acp: result received (${T.result.length} chars, stopReason=${T.stopReason})`),c.stdin?.end()}catch(y){tt(c).catch(()=>{}),s(y instanceof Error?y:new Error(String(y)))}})()}):Promise.reject(new Error(`No ACP config for tool "${e.tool}"`))}var $l,
|
|
1474
|
+
`),C({event:"acp_config_option_failed",provider:e.tool,config_id:"effort",value:e.effort,error_message:I})}m.beginTurn(),Tt(`acp: prompt sent (${t.length} chars)`);let y=await h("session/prompt",{sessionId:f,prompt:[{type:"text",text:t}]}),T=m.completeTurn(y);Tt(`acp: result received (${T.result.length} chars, stopReason=${T.stopReason})`),c.stdin?.end()}catch(y){tt(c).catch(()=>{}),s(y instanceof Error?y:new Error(String(y)))}})()}):Promise.reject(new Error(`No ACP config for tool "${e.tool}"`))}var $l,YN,Ml=E(()=>{"use strict";de();Qr();pi();en();yi();de();at();Ol();Ol();$l={gemini:{binary:"gemini",args:["--acp","-y","--skip-trust"]},copilot:{binary:"copilot",args:["--acp","--yolo"]},opencode:{binary:"opencode",args:["acp"]}},YN=1});function _e(t,e=120){let r=t.replace(/\s+/g," ").trim();return r.length>e?r.slice(0,e-1)+"\u2026":r}function xp(t,e){return r=>{if(r.kind==="tool_use"&&typeof r.id=="string"){if(t.size>=zN){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 ZN(){let t=new Map;return(e,r)=>{QN(e,xp(t,r))}}function QN(t,e){let r=t.type;if(r==="system"){let n=t.subtype;if(n==="api_retry"){let s=typeof t.attempt=="number"?t.attempt:void 0,i=typeof t.max_retries=="number"?t.max_retries:void 0,o=typeof t.error_status=="number"?t.error_status:void 0,a=typeof t.error=="string"?t.error:void 0,l=typeof t.retry_delay_ms=="number"?t.retry_delay_ms:void 0,c=[];s!==void 0&&c.push(i!==void 0?`attempt ${s}/${i}`:`attempt ${s}`),o!==void 0&&c.push(`HTTP ${o}`),l!==void 0&&c.push(`retry in ${Math.round(l/1e3)}s`),a&&c.push(_e(a,60));let d=c.length>0?c.join(", "):n;e({kind:"api_retry",summary:d});return}if(n==="api_error"){let s=typeof t.error_status=="number"?t.error_status:void 0,i=typeof t.error=="string"?t.error:void 0,o=["api_error"];s!==void 0&&o.push(`HTTP ${s}`),i&&o.push(_e(i,80)),e({kind:"other",summary:o.join(": "),raw:t});return}e({kind:"system",summary:n||"system",raw:t});return}if(r==="assistant"||r==="user"){let s=t.message?.content;if(!Array.isArray(s))return;for(let i of s){let o=i.type;if(o==="text"){let a=i.text||"";a&&e({kind:"text",summary:_e(a),raw:i})}else if(o==="tool_use"){let a=i.name||"tool",l=typeof i.id=="string"?i.id:void 0,c=i.input,d="";c&&(typeof c.command=="string"?d=c.command:typeof c.file_path=="string"?d=c.file_path:typeof c.path=="string"?d=c.path:typeof c.pattern=="string"?d=c.pattern:typeof c.url=="string"?d=c.url:d=_e(JSON.stringify(c))),e({kind:"tool_use",tool:a,summary:_e(d),id:l,raw:i})}else if(o==="thinking"){let a=i.thinking||"";e({kind:"thinking",summary:_e(a),raw:i})}else if(o==="tool_result"){let l=i.is_error===!0?"error":"ok",c=typeof i.tool_use_id=="string"?i.tool_use_id:void 0,d,u=i.content;if(typeof u=="string")d=`${u.split(`
|
|
1393
1475
|
`).length} lines, ${u.length} chars`;else if(Array.isArray(u)){let f=u.map(m=>typeof m=="object"&&m&&"text"in m?m.text:"").filter(Boolean).join("");f&&(d=`${f.split(`
|
|
1394
|
-
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:d,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function wi(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?
|
|
1476
|
+
`).length} lines, ${f.length} chars`)}e({kind:"tool_result",status:l,summary:d,id:c,raw:i})}else o&&e({kind:"other",summary:o,raw:i})}return}if(r==="result"){e({kind:"system",summary:"result",raw:t});return}}async function wi(t,e){let r=e.binary==="qwen"?"qwen":"claude",n=e.onProgress?ZN():void 0,s=await dp(t,{sessionId:e.sessionId,cwd:e.cwd,env:e.env,tool:r,binaryPath:e.progPath,model:e.model,permissionMode:e.permissionMode,onText:e.onDelta,onEvent:n?i=>n(i,e.onProgress):void 0,signal:e.signal});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,numTurns:s.numTurns}}function e0(){let t=new Map;return(e,r)=>{t0(e,xp(t,r))}}function t0(t,e){if(t.method!=="session/update")return;let s=t.params?.update;if(!s)return;let i=s.sessionUpdate;if(i){if(i==="agent_message_chunk"){let a=s.content?.text||"";a&&e({kind:"text",summary:_e(a)});return}if(i==="agent_thought_chunk"){let a=s.content?.text||"";e({kind:"thinking",summary:_e(a)});return}if(i==="tool_call"){let o=s.title||s.kind||"tool",a=typeof s.toolCallId=="string"?s.toolCallId:void 0,l="",c=s.rawInput;c&&(typeof c.command=="string"?l=c.command:typeof c.file_path=="string"?l=c.file_path:typeof c.path=="string"?l=c.path:l=_e(JSON.stringify(c))),e({kind:"tool_use",tool:o,summary:_e(l),id:a});return}if(i==="tool_call_update"){let o=s.status||"",a=typeof s.toolCallId=="string"?s.toolCallId:void 0;if(o==="completed"||o==="failed")e({kind:"tool_result",summary:o,status:o==="failed"?"error":"ok",id:a});else if(o==="in_progress"){let l=s.content,c=typeof l=="string"?l:typeof l?.text=="string"?l.text:"",d=c?`running\u2026 ${_e(c,80)}`:"running\u2026";e({kind:"other",summary:d,id:a})}return}e({kind:"other",summary:i})}}async function rn(t,e){let r=e.acpTool||e.binary;e.model&&r==="copilot"&&Ae({event:"model_ignored",provider:r,model:e.model,reason:"copilot --acp does not implement per-session model selection"});let n=e.onProgress?e0():void 0,s=await Np(t,{tool:r,sessionId:e.sessionId,cwd:e.cwd,env:e.env,binaryPath:e.progPath,model:e.model,effort:e.effort,alias:e.alias,permissionMode:e.permissionMode,onDelta:e.onDelta,onEvent:n?i=>n(i,e.onProgress):void 0,signal:e.signal});return{text:s.result,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason}}function r0(t,e){let r=t.method;if(!r)return;let n=t.params;if(r==="turn/started"){e({kind:"system",summary:"turn started"});return}if(r==="turn/completed"){e({kind:"system",summary:"turn completed"});return}if(r==="error"){let s=n?.error,i=typeof s?.message=="string"?s.message:void 0,o=i&&i.length>0?i:"(no message)",a=n?.willRetry===!0;e(a?{kind:"api_retry",summary:`codex retry: ${_e(o,120)}`}:{kind:"other",summary:`codex error: ${_e(o,120)}`});return}if(r==="item/started"||r==="item/completed"){let s=n?.item;if(!s)return;let i=s.type,o=r==="item/started";switch(i){case"commandExecution":{let a=typeof s.id=="string"?s.id:void 0,l=s.command,c=Array.isArray(l)?l.join(" "):typeof l=="string"?l:"";if(o)e({kind:"tool_use",tool:"Bash",summary:_e(c||"(command)"),id:a});else{let d=s.exitCode,u=s.status||"",f=typeof s.durationMs=="number"?s.durationMs:void 0,m=typeof d=="number"?`exit ${d}`:u||"done",p=[];typeof d=="number"?p.push(`exit ${d}`):u&&p.push(u),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(o){let l=s.changes,c=Array.isArray(l)?l.map(d=>d.path||"").filter(Boolean).join(", "):"";e({kind:"tool_use",tool:"FileChange",summary:_e(c||"(edit)"),id:a})}else{let l=s.status||"done";e({kind:"tool_result",summary:l,status:l,id:a})}return}case"mcpToolCall":{let a=typeof s.id=="string"?s.id:void 0,l=s.server||"mcp",c=s.tool||"tool";if(o)e({kind:"tool_use",tool:`${l}/${c}`,summary:"",id:a});else{let d=s.status||"done";e({kind:"tool_result",summary:d,status:d,id:a})}return}case"webSearch":{let a=typeof s.id=="string"?s.id:void 0;e(o?{kind:"tool_use",tool:"WebSearch",summary:_e(s.query||""),id:a}:{kind:"tool_result",summary:"done",status:"done",id:a});return}case"reasoning":{o&&e({kind:"thinking",summary:""});return}case"agentMessage":case"userMessage":return;default:{i&&e({kind:o?"tool_use":"tool_result",tool:i,summary:""});return}}}if(r==="item/agentMessage/delta"){let s=n?.delta||"";if(s){let i=typeof n?._lmctlItemPhase=="string"?n._lmctlItemPhase:void 0;e(i==="commentary"?{kind:"thinking",summary:_e(s)}:{kind:"text",summary:_e(s)})}return}if(r==="item/reasoning/summaryTextDelta"||r==="item/reasoning/textDelta"){let s=n?.delta||"";s&&e({kind:"thinking",summary:_e(s)});return}if(r==="item/commandExecution/outputDelta"){let s=(typeof n?.delta=="string"?n.delta:"")||"";if(s){let i=s.split(`
|
|
1395
1477
|
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${_e(o,60)}`:_e(s,80);e({kind:"other",summary:`running\u2026 ${a}`})}else e({kind:"other",summary:"running\u2026"});return}if(r==="item/commandExecution/terminalInteraction"||r==="item/commandExecution/outputChunk"||r==="item/commandExecution/output"){let s=(typeof n?.stdin=="string"?n.stdin:"")||(typeof n?.delta=="string"?n.delta:"")||(typeof n?.output=="string"?n.output:"")||(typeof n?.text=="string"?n.text:"")||(typeof n?.content=="string"?n.content:"")||(typeof n?.chunk=="string"?n.chunk:"")||"";if(s){let i=s.split(`
|
|
1396
|
-
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${_e(o,60)}`:_e(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 Ap(t,e){let r=await pp(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=>
|
|
1397
|
-
`);try{return JSON.stringify(t)}catch{return String(t)}}async function Op(t){let e=0,r=0,n=0,s=0,i=0,o,a;for await(let l of qe(t)){if(l.type==="response_item"&&l.payload){let c=l.payload;if(c.type==="message"&&c.role==="user"&&c.content)for(let d of c.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&e++;else if(c.type==="message"&&c.role==="assistant"&&c.content)for(let d of c.content)d.type==="output_text"&&typeof d.text=="string"&&d.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,i=c.reasoning_output_tokens??i;let d=
|
|
1398
|
-
`);y.trim()&&ss(s,m,{role:"thinking",timestamp:g,content:fe(y)});continue}}if(h.type==="event_msg"&&h.payload&&h.payload.type==="agent_reasoning"){let _=h.payload.message||h.payload.text;_&&ss(s,m,{role:"thinking",timestamp:g,content:fe(_)})}}if(!i)return null;let p=await Op(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,firstUserMessage:c,lastUserMessage:d,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
|
|
1478
|
+
`).filter(l=>l.length>0),o=i[i.length-1]||"",a=i.length>1?`${i.length} lines: ${_e(o,60)}`:_e(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 Ap(t,e){let r=await pp(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=>r0(n,e.onProgress):void 0,signal:e.signal});return{text:r.result,sessionId:r.threadId,durationMs:r.durationMs}}var zN,Rr=E(()=>{"use strict";up();_p();Ml();de();zN=256});function Dl(t){return new jl(t)}var jl,Pl=E(()=>{"use strict";Qm();Ft();Rr();St();jl=class extends xe{constructor(e){super({provider:new ci(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"claude",seedArgs:["-p",ge,"--dangerously-skip-permissions"],resumeTemplate:"claude --resume {{session_id}}",startTemplate:"claude",transport:wi})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as n0,stat as Rp,unlink as s0}from"node:fs/promises";import{join as ns,basename as i0}from"node:path";function o0(t,e,r){return`${t}|${e.toISOString()}|${r}`}function ss(t,e,r){let n=o0(r.role,r.timestamp,r.content);e.has(n)||(e.add(n),t.push(r))}function Lp(t,e){return e==="exec"||t==="codex_exec"?"codex exec":"codex"}function a0(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 Ei(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 Ei(r)}).filter(r=>r.length>0).join(`
|
|
1479
|
+
`);try{return JSON.stringify(t)}catch{return String(t)}}async function Op(t){let e=0,r=0,n=0,s=0,i=0,o,a;for await(let l of qe(t)){if(l.type==="response_item"&&l.payload){let c=l.payload;if(c.type==="message"&&c.role==="user"&&c.content)for(let d of c.content)d.type==="input_text"&&typeof d.text=="string"&&d.text&&e++;else if(c.type==="message"&&c.role==="assistant"&&c.content)for(let d of c.content)d.type==="output_text"&&typeof d.text=="string"&&d.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,i=c.reasoning_output_tokens??i;let d=a0(l.payload.info.last_token_usage);d&&(o=d),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:i,lastTokenUsage:o,modelContextWindow:a}}var Ti,$p=E(()=>{"use strict";nr();Ti=class{name="codex";codexDirs;constructor(e={}){let r=[ns(be,".codex"),ns(be,".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:ns(e,"sessions"),filePattern:/\.jsonl$/}))}async getSessionsDirs(){let e=[];for(let r of this.codexDirs){let n=ns(r,"sessions");try{await Rp(n),e.push(n)}catch{}}return e}async discoverSessions(){let e=[],r=await this.getSessionsDirs();for(let n of r){let s=await this.findSessionFiles(n);for(let i of s)try{let o=await this.extractSummary(i);o&&e.push(o)}catch{}}return e}async findSessionFiles(e){let r=[],n;try{n=await n0(e)}catch{return r}for(let s of n){let i=ns(e,s),o=await Rp(i).catch(()=>null);if(o)if(o.isDirectory()){let a=await this.findSessionFiles(i);r.push(...a)}else s.endsWith(".jsonl")&&r.push(i)}return r}extractSessionIdFromFilename(e){let r=i0(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 Me(e,30),n=await Ne(e),s=this.extractSessionIdFromFilename(e),i="",o,a,l,c,d,u,f;for(let p of r){if(p.type==="session_meta"&&p.payload&&(p.payload.id&&(s=p.payload.id),p.payload.cwd&&(i=p.payload.cwd),p.payload.cli_version&&(o=p.payload.cli_version),p.payload.timestamp&&(l=new Date(p.payload.timestamp)),p.payload.originator&&(u=p.payload.originator),p.payload.source&&(f=p.payload.source)),p.type==="turn_context"&&p.payload&&(p.payload.model&&(a=p.payload.model),!i&&p.payload.cwd&&(i=p.payload.cwd)),p.type==="event_msg"&&p.payload?.type==="user_message"){let h=p.payload.message||p.payload.text;h&&(c||(c=X(h.trim(),80)),d=X(h.trim(),80))}if(p.type==="response_item"&&p.payload?.type==="message"&&p.payload.role==="user"&&p.payload.content){let h=p.payload.content.find(g=>g.type==="input_text"&&typeof g.text=="string"&&g.text);typeof h?.text=="string"&&(c||(c=X(h.text.trim(),80)),d=X(h.text.trim(),80))}}if(!i)return null;let m=await Op(e);return{provider:"codex",sessionId:s,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:Lp(u,f),firstUserMessage:c,lastUserMessage:d,messageCount:m.messageCount,filePath:e,totalInputTokens:m.totalInputTokens||void 0,totalCachedInputTokens:m.totalCachedInputTokens||void 0,totalOutputTokens:m.totalOutputTokens||void 0,totalReasoningOutputTokens:m.totalReasoningOutputTokens||void 0,lastInputTokens:m.lastTokenUsage?.inputTokens||void 0,lastTokenUsage:m.lastTokenUsage,modelContextWindow:m.modelContextWindow}}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n=await Ne(r),s=[],i="",o,a,l,c,d,u=e,f,m=new Set;for await(let h of qe(r)){let g=h.timestamp?new Date(h.timestamp):new Date;if(h.type==="session_meta"&&h.payload){h.payload.id&&(u=h.payload.id),h.payload.cwd&&(i=h.payload.cwd),h.payload.cli_version&&(o=h.payload.cli_version),h.payload.timestamp&&(l=new Date(h.payload.timestamp)),f=Lp(h.payload.originator,h.payload.source);continue}if(h.type==="turn_context"&&h.payload){h.payload.model&&(a=h.payload.model),!i&&h.payload.cwd&&(i=h.payload.cwd);continue}if(h.type==="response_item"&&h.payload){let _=h.payload;if(_.type==="message"){if(_.role==="user"&&_.content){for(let y of _.content)if(y.type==="input_text"&&typeof y.text=="string"&&y.text){let T=y.text.trim();c||(c=X(T,80)),d=X(T,80),ss(s,m,{role:"user",timestamp:g,content:fe(T)})}continue}if(_.role==="assistant"&&_.content){for(let y of _.content)y.type==="output_text"&&typeof y.text=="string"&&y.text&&ss(s,m,{role:"assistant",timestamp:g,content:fe(y.text),model:a});continue}if(_.role!=="user"&&_.role!=="assistant"&&_.content){for(let y of _.content)(y.type==="input_text"||y.type==="output_text")&&typeof y.text=="string"&&y.text&&ss(s,m,{role:"system",timestamp:g,content:fe(y.text.trim())});continue}}if(_.type==="function_call"){s.push({role:"tool_use",timestamp:g,content:_.name||"unknown tool",toolName:_.name,toolInput:_.arguments!==void 0?fe(Ei(_.arguments)):void 0,toolCallId:_.call_id});continue}if(_.type==="function_call_output"){s.push({role:"tool_result",timestamp:g,content:fe(Ei(_.output)),toolCallId:_.call_id});continue}if(_.type==="reasoning"&&_.summary){let y=_.summary.map(T=>Ei(T.text)).join(`
|
|
1480
|
+
`);y.trim()&&ss(s,m,{role:"thinking",timestamp:g,content:fe(y)});continue}}if(h.type==="event_msg"&&h.payload&&h.payload.type==="agent_reasoning"){let _=h.payload.message||h.payload.text;_&&ss(s,m,{role:"thinking",timestamp:g,content:fe(_)})}}if(!i)return null;let p=await Op(r);return{provider:"codex",sessionId:u,cwd:i,createdAt:l||n.createdAt,modifiedAt:n.modifiedAt,model:a,cliVersion:o,startCommand:f,firstUserMessage:c,lastUserMessage:d,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 s0(r),!0):!1}async resolveSessionFile(e){let r=await this.getSessionsDirs(),n=[];for(let i of r){let o=await this.findSessionFiles(i);n.push(...o)}for(let i of n)if(this.extractSessionIdFromFilename(i)===e)return i;let s=[];for(let i of n)this.extractSessionIdFromFilename(i).startsWith(e)&&s.push(i);if(s.length===1)return s[0];for(let i of n){let o=await Me(i,1);if(o.length>0&&o[0].type==="session_meta"){let a=o[0].payload?.id;if(a===e||a&&a.startsWith(e))return i}}return null}}});function Ul(t){return new Fl(t)}var Fl,Wl=E(()=>{"use strict";$p();Ft();Rr();St();Fl=class extends xe{constructor(e){super({provider:new Ti(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:`${ge}
|
|
1399
1481
|
`,resumeTemplate:"codex resume {{session_id}}",startTemplate:"codex",transport:Ap})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r.slice(0,-1),"--model",e.model,r[r.length-1]]:r}}});function is(t){if(!t.trim())return"unknown";let e=t.split(/\r?\n/).filter(n=>n.trim().length>0);if(e.length>1)try{let n=JSON.parse(e[0]);if(n!==null&&typeof n=="object"&&!Array.isArray(n)&&"kind"in n)return"jsonl"}catch{}let r;try{r=JSON.parse(t)}catch{return"unknown"}if(r!==null&&typeof r=="object"&&!Array.isArray(r)){let n=r;if(Array.isArray(n.messages))return"json";if("kind"in n)return"jsonl"}return"unknown"}function bi(t){let e=is(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(`
|
|
1400
|
-
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let d=c;if(typeof d.id=="string"){let u=o.get(d.id);u?
|
|
1482
|
+
`).map(a=>a).filter(a=>a.trim().length>0);if(r.length===0)throw new Error("gemini session file is empty");let n=r[0],s;try{s=JSON.parse(n)}catch(a){throw new Error(`gemini JSONL session: metadata line failed to parse: ${a instanceof Error?a.message:String(a)}`)}if(s===null||typeof s!="object")throw new Error("gemini JSONL session: metadata line is not an object");let i=[],o=new Map;for(let a=1;a<r.length;a++){let l;try{l=JSON.parse(r[a])}catch{continue}if(l===null||typeof l!="object")continue;let c=l;if("$set"in c&&c.$set&&typeof c.$set=="object"){Object.assign(s,c.$set);continue}if(typeof c.id=="string"||typeof c.type=="string"){let d=c;if(typeof d.id=="string"){let u=o.get(d.id);u?l0(u,d):(i.push(d),o.set(d.id,d))}else i.push(d)}}return{sessionId:typeof s.sessionId=="string"?s.sessionId:void 0,projectHash:typeof s.projectHash=="string"?s.projectHash:void 0,startTime:typeof s.startTime=="string"?s.startTime:void 0,lastUpdated:typeof s.lastUpdated=="string"?s.lastUpdated:void 0,kind:typeof s.kind=="string"?s.kind:void 0,messages:i}}function l0(t,e){for(let[r,n]of Object.entries(e))if(n!==void 0){if(r==="tokens"&&Cp(t.tokens)&&Cp(n)){t.tokens={...t.tokens,...n};continue}t[r]=n}}function Cp(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Mp(t,e){if(e==="json")return JSON.stringify(t,null,2);let{messages:r,...n}=t,s=[JSON.stringify(n)];for(let i of r)s.push(JSON.stringify(i));return s.join(`
|
|
1401
1483
|
`)+`
|
|
1402
|
-
`}var Bl=E(()=>{"use strict"});import{createHash as
|
|
1403
|
-
`).trim();x&&i.push({role:"thinking",timestamp:Lr(I.timestamp,_),content:fe(x)})}i.push({role:"assistant",timestamp:_,content:T,model:g.model});continue}let b=y?`[${y}] `:"";i.push({role:"system",timestamp:_,content:`${b}${T}`.trim()})}let m=Lr(n.startTime,s.createdAt),p=Lr(n.lastUpdated,s.modifiedAt),h=Fp(o);return{provider:"gemini",sessionId:a,cwd:c,createdAt:m,modifiedAt:p,model:f,startCommand:"gemini",firstUserMessage:d,lastUserMessage:u,messageCount:i.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await Ne(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let m of s)if(Pp(m.type)){u++;let p=Dp(m.content).trim();p&&(l||(l=
|
|
1404
|
-
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:ui,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,r){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=
|
|
1405
|
-
`)){let n=r.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function Or(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function
|
|
1484
|
+
`}var Bl=E(()=>{"use strict"});import{createHash as c0}from"node:crypto";import{readdir as os,readFile as jp,stat as Si,unlink as d0}from"node:fs/promises";import{join as Xe,basename as u0,dirname as f0}from"node:path";import{cwd as m0}from"node:process";function Dp(t){return t?typeof t=="string"?t:Array.isArray(t)?t.map(e=>e.text||"").join(""):"":""}function Pp(t){return t==="user"}function ql(t){return t==="gemini"||t==="assistant"}function Lr(t,e=new Date(0)){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function p0(t){return`${t.sessionId}\0${t.cwd}`}function _0(t,e){let r=t.filePaths??[t.filePath],n=e.filePaths??[e.filePath],s=[...new Set([...r,...n])],i=e.modifiedAt.getTime()>=t.modifiedAt.getTime()?e:t;return{...i,createdAt:t.createdAt.getTime()<=e.createdAt.getTime()?t.createdAt:e.createdAt,modifiedAt:i.modifiedAt,filePath:i.filePath,filePaths:s}}function vi(t){let e=Number(t??0);return Number.isFinite(e)?Math.max(0,Math.round(e)):0}function Fp(t){let e=0,r=0,n=0,s=0,i=0,o;for(let a of t){if(!ql(a.type)||!a.tokens)continue;let l=vi(a.tokens.input),c=vi(a.tokens.cached),d=Math.max(l-c,0),u=vi(a.tokens.output),f=vi(a.tokens.thoughts);e+=l,r+=c,n+=u,s+=f,i=l,o={inputTokens:d,cachedInputTokens:c,cacheWriteInputTokens:0,outputTokens:u,reasoningOutputTokens:f,totalTokens:l+u+f}}return{totalInputTokens:e,totalCachedInputTokens:r,totalOutputTokens:n,totalReasoningOutputTokens:s,lastInputTokens:i,lastTokenUsage:o}}function h0(t){return c0("sha256").update(t).digest("hex")}function as(t,e){let r=e;for(;r&&!t.has(r);){t.add(r);let n=f0(r);if(n===r)break;r=n}}var ki,Up=E(()=>{"use strict";nr();Bl();de();ki=class{name="gemini";workspaceHashMap;geminiProjectsFile;geminiTmpDir;claudeProjectsDir;codexSessionDirs;extraWorkspacePaths;constructor(e={}){let r=e.geminiDir||Xe(be,".gemini");this.geminiProjectsFile=Xe(r,"projects.json"),this.geminiTmpDir=Xe(r,"tmp");let n=e.claudeDir||Xe(be,".claude");this.claudeProjectsDir=Xe(n,"projects");let s=[Xe(be,".codex"),Xe(be,".code")],i=e.codexDirs&&e.codexDirs.length>0?e.codexDirs:[e.codexDir||s[0],e.codeDir||s[1]];this.codexSessionDirs=[...new Set(i)].map(o=>Xe(o,"sessions")),this.extraWorkspacePaths=e.extraWorkspacePaths||[]}getWatchPaths(){return[{directory:this.geminiTmpDir,filePattern:/\.jsonl?$/}]}async discoverSessions(){let e=await this.findSessionFiles(),r=new Map;for(let n of e)try{let s=await this.extractSummary(n);if(!s)continue;let i=p0(s),o=r.get(i);r.set(i,o?_0(o,s):s)}catch{}return[...r.values()]}async loadSession(e){let r=await this.resolveSessionFile(e);if(!r)return null;let n;try{n=await this.readSessionFile(r)}catch{return null}if(!n)return null;let s=await Ne(r),i=[],o=n.messages||[],a=n.sessionId||this.extractSessionIdFromFilename(r),l=n.projectHash||"",c=await this.resolveWorkspace(l),d,u,f;for(let g of o){let _=Lr(g.timestamp),y=g.type,T=fe(Dp(g.content));if(Pp(y)){let I=T.trim();I&&(d||(d=X(I,80)),u=X(I,80)),i.push({role:"user",timestamp:_,content:I||T});continue}if(ql(y)){g.model&&(f=g.model);for(let I of g.thoughts||[]){let x=[I.subject,I.description].filter(Boolean).join(`
|
|
1485
|
+
`).trim();x&&i.push({role:"thinking",timestamp:Lr(I.timestamp,_),content:fe(x)})}i.push({role:"assistant",timestamp:_,content:T,model:g.model});continue}let b=y?`[${y}] `:"";i.push({role:"system",timestamp:_,content:`${b}${T}`.trim()})}let m=Lr(n.startTime,s.createdAt),p=Lr(n.lastUpdated,s.modifiedAt),h=Fp(o);return{provider:"gemini",sessionId:a,cwd:c,createdAt:m,modifiedAt:p,model:f,startCommand:"gemini",firstUserMessage:d,lastUserMessage:u,messageCount:i.filter(g=>g.role==="user"||g.role==="assistant").length,filePath:r,totalInputTokens:h.totalInputTokens||void 0,totalCachedInputTokens:h.totalCachedInputTokens||void 0,totalOutputTokens:h.totalOutputTokens||void 0,totalReasoningOutputTokens:h.totalReasoningOutputTokens||void 0,lastInputTokens:h.lastInputTokens||void 0,lastTokenUsage:h.lastTokenUsage,messages:i}}async extractSummary(e){let r=await this.readSessionFile(e);if(!r)return null;let n=await Ne(e),s=r.messages||[],i=r.sessionId||this.extractSessionIdFromFilename(e),o=r.projectHash||"",a=await this.resolveWorkspace(o),l,c,d,u=0;for(let m of s)if(Pp(m.type)){u++;let p=Dp(m.content).trim();p&&(l||(l=X(fe(p),80)),c=X(fe(p),80))}else ql(m.type)&&(u++,m.model&&(d=m.model));let f=Fp(s);return{provider:"gemini",sessionId:i,cwd:a,createdAt:Lr(r.startTime,n.createdAt),modifiedAt:Lr(r.lastUpdated,n.modifiedAt),model:d,startCommand:"gemini",firstUserMessage:l,lastUserMessage:c,messageCount:u,filePath:e,totalInputTokens:f.totalInputTokens||void 0,totalCachedInputTokens:f.totalCachedInputTokens||void 0,totalOutputTokens:f.totalOutputTokens||void 0,totalReasoningOutputTokens:f.totalReasoningOutputTokens||void 0,lastInputTokens:f.lastInputTokens||void 0,lastTokenUsage:f.lastTokenUsage}}async readSessionFile(e){let r=await jp(e,"utf-8");if(is(r)==="unknown")return C({event:"gemini_session_format_unknown",provider:"gemini",file:e,preview:r.slice(0,120),message:`gemini session file at ${e} matches neither old (.json with messages[]) nor new (.jsonl with kind metadata) format. Skipping; lmctl ls / audit / stats will not see this session.`}),null;try{return bi(r)}catch{return null}}extractSessionIdFromFilename(e){let r=u0(e).replace(/\.jsonl?$/,""),n=r.match(/session-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-(.+)$/);return n?n[1]:r}async findSessionFiles(){let e=[],r;try{r=await os(this.geminiTmpDir)}catch{return e}for(let n of r){let s=Xe(this.geminiTmpDir,n,"chats");if(!(await Si(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await os(s)}catch{continue}for(let a of o)a.startsWith("session-")&&(!a.endsWith(".json")&&!a.endsWith(".jsonl")||e.push(Xe(s,a)))}return e}async resolveSessionPath(e){return this.resolveSessionFile(e)}async deleteSession(e){let r=await this.resolveSessionFile(e);return r?(await d0(r),!0):!1}async resolveSessionFile(e){let r=await this.findSessionFiles(),n=[];for(let s of r){let i=await this.readSessionFile(s).catch(()=>null),o=this.extractSessionIdFromFilename(s),a=i?.sessionId||o,l=a===e||a.startsWith(e),c=o===e||o.startsWith(e)||o.length>=8&&e.startsWith(o);if(!l&&!c)continue;let d=await Ne(s).catch(()=>({createdAt:new Date(0),modifiedAt:new Date(0)}));n.push({filePath:s,modifiedAt:Lr(i?.lastUpdated,d.modifiedAt)})}return n.sort((s,i)=>{let o=i.modifiedAt.getTime()-s.modifiedAt.getTime();return o!==0?o:i.filePath.localeCompare(s.filePath)}),n[0]?.filePath??null}async resolveWorkspace(e){return e?(await this.getWorkspaceHashMap()).get(e)||`[hash:${e.slice(0,16)}]`:"(unknown workspace)"}async getWorkspaceHashMap(){if(this.workspaceHashMap)return this.workspaceHashMap;let e=new Set;as(e,m0());for(let n of this.extraWorkspacePaths)as(e,n);for(let n of await this.collectGeminiProjectPaths())as(e,n);for(let n of await this.collectCodexCwds())as(e,n);for(let n of await this.collectClaudeCwds())as(e,n);let r=new Map;for(let n of e)r.set(h0(n),n);return this.workspaceHashMap=r,r}async collectGeminiProjectPaths(){let e;try{e=await jp(this.geminiProjectsFile,"utf-8")}catch{return[]}try{let n=JSON.parse(e).projects;return!n||typeof n!="object"||Array.isArray(n)?[]:Object.keys(n)}catch{return[]}}async collectCodexCwds(){let e=new Set;for(let r of this.codexSessionDirs){let n=await this.findJsonlFiles(r);for(let s of n){let o=(await Me(s,1).catch(()=>[]))[0]?.payload?.cwd;o&&e.add(o)}}return[...e]}async collectClaudeCwds(){let e=new Set,r;try{r=await os(this.claudeProjectsDir)}catch{return[]}for(let n of r){let s=Xe(this.claudeProjectsDir,n);if(!(await Si(s).catch(()=>null))?.isDirectory())continue;let o;try{o=await os(s)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=Xe(s,a),d=(await Me(l,1).catch(()=>[]))[0]?.cwd;d&&e.add(d)}}return[...e]}async findJsonlFiles(e){let r=[];if(!(await Si(e).catch(()=>null))?.isDirectory())return r;let s;try{s=await os(e)}catch{return r}for(let i of s){let o=Xe(e,i),a=await Si(o).catch(()=>null);if(a)if(a.isDirectory()){let l=await this.findJsonlFiles(o);r.push(...l)}else i.endsWith(".jsonl")&&r.push(o)}return r}}});import{readFileSync as g0,writeFileSync as y0,mkdirSync as w0}from"node:fs";import{join as E0,dirname as T0}from"node:path";import{randomUUID as b0}from"node:crypto";function Xl(t){return new Hl(t)}var Hl,Jl=E(()=>{"use strict";Up();Ft();Rr();St();Bl();Hl=class extends xe{constructor(e){super({provider:new ki(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!0,forkSupport:"automatic",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"skill-file",leaderSetupHint:"Place skill files in the project's .gemini/ directory"},binary:"gemini",seedArgs:["-p",ge,"-y","--skip-trust"],resumeTemplate:"gemini --resume {{session_id}} --skip-trust",startTemplate:"gemini --skip-trust",transport:(r,n)=>rn(r,{...n,acpTool:"gemini"})})}forkHint(e){return["Gemini fork: copies the session file with a new ID.","The forked session has the same conversation history","but diverges from that point forward."].join(`
|
|
1486
|
+
`)}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}manualSeedHint(e){return{launchCommand:`cd ${e} && gemini --skip-trust`,postLaunchNote:ui,lsCommand:`lmctl ls --provider gemini --sessiondir ${e}`}}async fork(e,r){let n=await this.resolvePath(e);if(!n)return{success:!1,error:`Session file not found for ${e}`};try{let s=g0(n,"utf-8"),i=is(s),o=bi(s),a=b0();o.sessionId=a,o.kind="main";let l=T0(n),c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=i==="jsonl"?".jsonl":".json",u=`session-${c}-${a.slice(0,8)}${d}`,f=E0(l,u);return w0(l,{recursive:!0}),y0(f,Mp(o,i),"utf-8"),{success:!0,sessionId:a,filePath:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}});import{readdir as Wp,readFile as S0,rm as v0,stat as nn}from"node:fs/promises";import{basename as k0,join as ct}from"node:path";function I0(t){let e={};for(let r of t.split(`
|
|
1487
|
+
`)){let n=r.match(/^(\w+):\s*(.*)$/);n&&(e[n[1]]=n[2].trim())}return{id:e.id,cwd:e.cwd,summary_count:e.summary_count?parseInt(e.summary_count,10):void 0,created_at:e.created_at,updated_at:e.updated_at,summary:e.summary}}function Or(t){if(!t)return;let e=new Date(t);return Number.isNaN(e.getTime())?void 0:e}async function N0(t){let e=0;for await(let r of qe(t))(r.type==="user.message"||r.type==="assistant.message"&&(r.data?.content||"").trim())&&e++;return e}var Ii,Bp=E(()=>{"use strict";nr();Ii=class{name="copilot";sessionStateDir;constructor(e={}){let r=e.copilotDir||ct(be,".copilot");this.sessionStateDir=ct(r,"session-state")}getWatchPaths(){return[{directory:this.sessionStateDir,filePattern:/events\.jsonl$/}]}async discoverSessions(){let e=[],r;try{r=await Wp(this.sessionStateDir)}catch{return e}for(let n of r){let s=ct(this.sessionStateDir,n);if((await nn(s).catch(()=>null))?.isDirectory())try{let o=await this.extractSummary(s,n);o&&e.push(o)}catch{}}return e}async loadSession(e){let r=await this.resolveSessionDir(e);if(!r)return null;let n=await this.readWorkspaceYaml(r),s=ct(r,"events.jsonl"),i=await nn(s).catch(()=>null),o=i?s:ct(r,"workspace.yaml"),a=await Ne(i?s:r),l=[],c=n?.cwd||"(unknown workspace)",d,u,f,m,p,h,g=n?.id||k0(r)||e;if(i)for await(let _ of qe(s)){let y=Or(_.timestamp)||a.modifiedAt;if(_.type==="session.start"&&_.data){_.data.sessionId&&(g=_.data.sessionId),_.data.copilotVersion&&(u=_.data.copilotVersion),_.data.startTime&&(h=Or(_.data.startTime)),_.data.selectedModel&&(d=_.data.selectedModel),_.data.context&&(_.data.context.cwd&&(c=_.data.context.cwd),_.data.context.branch&&(f=_.data.context.branch));continue}if(_.type==="session.model_change"&&_.data?.newModel){d=_.data.newModel;continue}if(_.type==="user.message"&&_.data){let T=_.data.content||"",b=T.trim();b&&(m||(m=X(b,80)),p=X(b,80)),l.push({role:"user",timestamp:y,content:fe(b||T)});continue}if(_.type==="assistant.message"&&_.data){let T=(_.data.content||"").trim();if(T&&l.push({role:"assistant",timestamp:y,content:fe(T),model:d}),_.data.toolRequests)for(let b of _.data.toolRequests)l.push({role:"tool_use",timestamp:y,content:b.name||"unknown tool",toolName:b.name,toolInput:b.arguments?JSON.stringify(b.arguments,null,2):void 0,toolCallId:b.toolCallId});continue}if(_.type==="tool.execution_complete"&&_.data){let T=_.data.result?.content||"",b=_.data.result?.detailedContent||"";l.push({role:"tool_result",timestamp:y,content:fe(T),toolDetailedContent:b?fe(b):void 0,toolCallId:_.data.toolCallId});continue}if(_.type==="assistant.reasoning"&&_.data?.content){l.push({role:"thinking",timestamp:y,content:fe(_.data.content)});continue}if(_.type==="session.error"||_.type==="session.warning"||_.type==="session.info"||_.type==="system.message"){let T=_.data?.message||"";T.trim()&&l.push({role:"system",timestamp:y,content:fe(T)});continue}}if(!m){let _=(n?.summary||"").trim();_&&(m=X(_,80))}return{provider:"copilot",sessionId:g,cwd:c,createdAt:h??Or(n?.created_at)??a.createdAt,modifiedAt:Or(n?.updated_at)??a.modifiedAt,model:d,cliVersion:u,startCommand:"copilot",gitBranch:f,firstUserMessage:m,lastUserMessage:p,messageCount:l.filter(_=>_.role==="user"||_.role==="assistant").length,filePath:o,messages:l}}async extractSummary(e,r){let n=await this.readWorkspaceYaml(e),s=ct(e,"events.jsonl"),i=await nn(s).catch(()=>null),o=i?s:ct(e,"workspace.yaml"),a=await Ne(i?s:e),l=i?await Me(s,20):[],c=n?.id||r,d=n?.cwd||"(unknown workspace)",u,f,m,p,h;for(let _ of l)if(_.type==="session.start"&&_.data&&(_.data.sessionId&&(c=_.data.sessionId),_.data.copilotVersion&&(f=_.data.copilotVersion),_.data.startTime&&(m=Or(_.data.startTime)),_.data.selectedModel&&(u=_.data.selectedModel),_.data.context?.cwd&&(d=_.data.context.cwd)),_.type==="session.model_change"&&_.data?.newModel&&(u||(u=_.data.newModel)),_.type==="user.message"&&_.data){let y=(_.data.content||"").trim();y&&(p||(p=X(y,80)),h=X(y,80))}if(!p){let _=(n?.summary||"").trim();_&&(p=X(_,80))}let g=i?await N0(s):0;return{provider:"copilot",sessionId:c,cwd:d,createdAt:m??Or(n?.created_at)??a.createdAt,modifiedAt:Or(n?.updated_at)??a.modifiedAt,model:u,cliVersion:f,startCommand:"copilot",firstUserMessage:p,lastUserMessage:h,messageCount:g,filePath:o}}async readWorkspaceYaml(e){let r=ct(e,"workspace.yaml");try{let n=await S0(r,"utf-8");return I0(n)}catch{return null}}async resolveSessionPath(e){return this.resolveSessionDir(e)}async deleteSession(e){let r=await this.resolveSessionDir(e);return r?(await v0(r,{recursive:!0}),!0):!1}async resolveSessionDir(e){let r;try{r=await Wp(this.sessionStateDir)}catch{return null}if(r.includes(e)){let s=ct(this.sessionStateDir,e);if((await nn(s).catch(()=>null))?.isDirectory())return s}let n=[];for(let s of r)if(s.startsWith(e)){let i=ct(this.sessionStateDir,s);(await nn(i).catch(()=>null))?.isDirectory()&&n.push(i)}if(n.length===1)return n[0];for(let s of r){let i=ct(this.sessionStateDir,s);if(!(await nn(i).catch(()=>null))?.isDirectory())continue;let a=await this.readWorkspaceYaml(i);if(a&&(a.id===e||a.id?.startsWith(e)))return i}return null}}});function Kl(t){return new Gl(t)}var Gl,Vl=E(()=>{"use strict";Bp();Ft();Rr();de();St();Gl=class extends xe{constructor(e){super({provider:new Ii(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"copilot",seedArgs:["-p",ge,"--yolo"],resumeTemplate:"copilot --resume={{session_id}}",startTemplate:"copilot",transport:(r,n)=>rn(r,{...n,acpTool:"copilot"})})}async seed(e,r){let n=await super.seed(e,r);if(r?.model===void 0||r.model.trim().length===0)return n;let s="copilot seed does not implement per-session model selection";return Ae({event:"model_ignored",provider:"copilot",model:r.model,reason:s}),{...n,warnings:[...n.warnings??[],`copilot seed ignored model=${r.model}: ${s}`]}}}});import{existsSync as qp,readdirSync as x0,statSync as Hp}from"node:fs";import{join as ar}from"node:path";import{createRequire as A0}from"node:module";function Xp(){return Yl===null&&(Yl=A0(import.meta.url)("node:sqlite").DatabaseSync),Yl}function R0(){let t=process.env.XDG_DATA_HOME||ar(be,".local","share"),e=process.env.XDG_CONFIG_HOME||ar(be,".config");return[ar(t,"opencode","opencode.db"),ar(e,"opencode","opencode.db")]}function L0(){if(process.env.OPENCODE_DB)return[process.env.OPENCODE_DB];let t=process.env.XDG_DATA_HOME||ar(be,".local","share"),e=ar(t,"lmplayer"),r=ar(e,"opencode-local.db"),n=[r];try{let s=x0(e).filter(i=>/^opencode.*\.db$/u.test(i)).map(i=>ar(e,i)).filter(i=>i!==r).sort((i,o)=>{try{return Hp(o).mtimeMs-Hp(i).mtimeMs}catch{return 0}});n.push(...s)}catch{}return n}function O0(t){return t==="lmplayer"?L0():R0()}var Yl,sn,zl=E(()=>{"use strict";nr();Yl=null;sn=class{name;startCommand;dbPaths;constructor(e){this.name=e?.providerName??"opencode",this.startCommand=e?.startCommand??this.name,e?.dbPath?this.dbPaths=[e.dbPath]:this.dbPaths=O0(this.name)}existingDbPaths(){return this.dbPaths.filter(e=>qp(e))}openDb(e){return qp(e)?new(Xp())(e,{open:!0,readOnly:!0}):null}async discoverSessions(){let e=[];for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=new Map,i=n.prepare("SELECT id, worktree, name FROM project").all();for(let a of i)s.set(a.id,a);let o=n.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1406
1488
|
s.time_created, s.time_updated
|
|
1407
1489
|
FROM session s
|
|
1408
1490
|
ORDER BY s.time_updated DESC`).all();for(let a of o){let l=s.get(a.project_id),c=a.directory||l?.worktree||"(unknown)",d=n.prepare(`SELECT m.id, m.data, m.time_created FROM message m
|
|
1409
|
-
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,m,p,h=[];for(let _ of d){let y;try{y=JSON.parse(_.data)}catch{continue}p||(p=y.model?.modelID||y.modelID),(y.role==="user"||y.role==="assistant")&&u++,y.role==="user"&&h.push(_.id)}let g=[...h.length>0?[h[0]]:[],...h.length>1?[h[h.length-1]]:[]];for(let _ of g){let y=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_),T=this.extractText(y);T&&(f||(f=
|
|
1410
|
-
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=0,c,d,u;for(let f of o){let m;try{m=JSON.parse(f.data)}catch{continue}c||(c=m.model?.modelID||m.modelID);let p=m.model?.modelID||m.modelID,h=new Date(m.time?.created||f.time_created),g=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(f.id);if(m.role==="user"){let _=this.extractText(g);_&&(d||(d=
|
|
1411
|
-
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(
|
|
1491
|
+
WHERE m.session_id = ? ORDER BY m.time_created ASC`).all(a.id),u=0,f,m,p,h=[];for(let _ of d){let y;try{y=JSON.parse(_.data)}catch{continue}p||(p=y.model?.modelID||y.modelID),(y.role==="user"||y.role==="assistant")&&u++,y.role==="user"&&h.push(_.id)}let g=[...h.length>0?[h[0]]:[],...h.length>1?[h[h.length-1]]:[]];for(let _ of g){let y=n.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(_),T=this.extractText(y);T&&(f||(f=X(T,80)),m=X(T,80))}e.push({provider:this.name,sessionId:a.id,slug:a.slug,cwd:c,createdAt:new Date(a.time_created),modifiedAt:new Date(a.time_updated),model:p,startCommand:this.startCommand,firstUserMessage:f,lastUserMessage:m,messageCount:u,filePath:r})}}catch{}finally{n.close()}}return e.sort((r,n)=>n.modifiedAt.getTime()-r.modifiedAt.getTime())}async loadSession(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{let s=this.findSessionRow(n,e);if(!s)continue;return this.buildSessionDetail(n,s,r)}catch{}finally{n.close()}}return null}buildSessionDetail(e,r,n){let s=e.prepare("SELECT id, worktree, name FROM project WHERE id = ?").get(r.project_id),i=r.directory||s?.worktree||"(unknown)",o=e.prepare(`SELECT id, session_id, time_created, time_updated, data
|
|
1492
|
+
FROM message WHERE session_id = ? ORDER BY time_created ASC`).all(r.id),a=[],l=0,c,d,u;for(let f of o){let m;try{m=JSON.parse(f.data)}catch{continue}c||(c=m.model?.modelID||m.modelID);let p=m.model?.modelID||m.modelID,h=new Date(m.time?.created||f.time_created),g=e.prepare("SELECT id, data FROM part WHERE message_id = ? ORDER BY time_created ASC").all(f.id);if(m.role==="user"){let _=this.extractText(g);_&&(d||(d=X(_,80)),u=X(_,80)),a.push({role:"user",timestamp:h,content:_||"(empty)"}),l++}else if(m.role==="assistant"){for(let _ of g){let y;try{y=JSON.parse(_.data)}catch{continue}y.type==="text"&&y.text?a.push({role:"assistant",timestamp:h,content:y.text,model:p}):y.type==="reasoning"&&y.text?a.push({role:"thinking",timestamp:h,content:y.text}):y.type==="tool"&&y.tool&&(a.push({role:"tool_use",timestamp:h,content:`${y.tool}`,toolName:y.tool,toolCallId:y.callID,toolInput:y.state?.input?JSON.stringify(y.state.input):void 0}),(y.state?.output||y.state?.error)&&a.push({role:"tool_result",timestamp:h,content:y.state.error||y.state.output||"",toolCallId:y.callID}))}l++}}return{provider:this.name,sessionId:r.id,slug:r.slug,cwd:i,createdAt:new Date(r.time_created),modifiedAt:new Date(r.time_updated),model:c,startCommand:this.startCommand,firstUserMessage:d,lastUserMessage:u,messageCount:l,filePath:n,messages:a}}extractText(e){let r=[];for(let n of e){let s;try{s=JSON.parse(n.data)}catch{continue}s.type==="text"&&s.text&&r.push(s.text)}return r.join(`
|
|
1493
|
+
`).trim()}async resolveSessionPath(e){for(let r of this.existingDbPaths()){let n=this.openDb(r);if(n)try{if(this.findSessionRow(n,e))return r}catch{}finally{n.close()}}return null}async deleteSession(e){for(let r of this.existingDbPaths()){let n=new(Xp())(r,{open:!0});try{let s=this.findSessionRow(n,e);if(!s)continue;return n.prepare("DELETE FROM session WHERE id = ?").run(s.id).changes>0}catch{}finally{n.close()}}return!1}findSessionRow(e,r){let n=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1412
1494
|
s.time_created, s.time_updated
|
|
1413
1495
|
FROM session s WHERE s.id = ?`).get(r);if(n)return n;let s=e.prepare(`SELECT s.id, s.project_id, s.slug, s.directory, s.title, s.version,
|
|
1414
1496
|
s.time_created, s.time_updated
|
|
1415
1497
|
FROM session s
|
|
1416
1498
|
WHERE s.id LIKE ?
|
|
1417
1499
|
ORDER BY s.time_updated DESC
|
|
1418
|
-
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function Ql(){return new Zl}var Zl,ec=E(()=>{"use strict";zl();Ft();Rr();St();Zl=class extends xe{constructor(){super({provider:new sn,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"custom-tool",leaderSetupHint:"OpenCode supports custom tools via .opencode/tools/ directory"},binary:"opencode",seedArgs:["run",ge],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>rn(e,{...r,acpTool:"opencode"})})}seedArgsFor(e){let r=["run"];return e?.model&&r.push("--model",e.model),e?.effort&&r.push("--variant",e.effort),r.push(e?.prompt??ge),r}}});import{spawn as $
|
|
1500
|
+
LIMIT 2`).all(`${r}%`);return s.length!==1?null:s[0]}}});function Ql(){return new Zl}var Zl,ec=E(()=>{"use strict";zl();Ft();Rr();St();Zl=class extends xe{constructor(){super({provider:new sn,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"custom-tool",leaderSetupHint:"OpenCode supports custom tools via .opencode/tools/ directory"},binary:"opencode",seedArgs:["run",ge],resumeTemplate:"opencode --session {{session_id}}",startTemplate:"opencode",transport:(e,r)=>rn(e,{...r,acpTool:"opencode"})})}seedArgsFor(e){let r=["run"];return e?.model&&r.push("--model",e.model),e?.effort&&r.push("--variant",e.effort),r.push(e?.prompt??ge),r}}});import{spawn as $0}from"node:child_process";import{mkdirSync as C0}from"node:fs";function rc(t){return new tc(t)}async function M0(t,e){let r=Date.now(),n=Jp({prompt:t,sessionId:e.sessionId,model:e.model,effort:e.effort,formatJson:!0,permissionMode:e.permissionMode??"yolo"});lt("lmplayer",n,e.permissionMode??"yolo");let s=await Gp(e.binary,n,{cwd:e.cwd,env:je(e.env,e.cwd,e.sessionId),signal:e.signal,onText:i=>{e.onProgress?.({kind:"text",summary:i.slice(0,120)}),e.onDelta?.(i)}});if(s.code!==0&&s.code!==null)throw new Error(s.stderr.trim().slice(0,200)||`lmplayer exited with code ${s.code}`);return{text:s.text.trim(),sessionId:s.sessionId??e.sessionId,durationMs:Date.now()-r}}function Jp(t){let e=["run"];return t.model&&e.push("--model",t.model),t.sessionId&&e.push("--session",t.sessionId),t.formatJson&&e.push("--format","json"),t.effort&&e.push("--effort",t.effort),e.push(...ir("lmplayer",t.permissionMode)??[]),e.push(t.prompt),e}function Gp(t,e,r){return new Promise((n,s)=>{let i;try{i=$0(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(g){s(g);return}let o="",a="",l="",c,d,u=[],f=!1,m=r.timeoutMs===void 0?void 0:setTimeout(()=>{f||(f=!0,i.kill(),p(),s(new Error(`lmplayer seed timed out after ${r.timeoutMs}ms`)))},r.timeoutMs),p=()=>{m!==void 0&&clearTimeout(m)},h=g=>{let _=g.trim();if(!_)return;let y;try{y=JSON.parse(_)}catch{u.push(g),r.onText?.(g);return}if(!xi(y))return;let T=Ni(y,!1);c===void 0&&T!==void 0&&(c=T),d=Ni(y,!0)??d;let b=Kp(y);b&&(u.push(b),r.onText?.(b))};i.stdout?.on("data",g=>{let _=g.toString("utf8");o+=_,l+=_;let y=l.indexOf(`
|
|
1419
1501
|
`);for(;y>=0;){let T=l.slice(0,y);l=l.slice(y+1),h(T),y=l.indexOf(`
|
|
1420
|
-
`)}}),i.stderr?.on("data",g=>{a+=g.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",g=>{f||(f=!0,p(),l.length>0&&h(l),n({code:g,stdout:o,stderr:a,sessionId:c??d,text:u.join("")}))}),i.on("error",g=>{f||(f=!0,p(),s(g))})})}function Kp(t){for(let e of["text","content","delta","output","message"]){let r=t[e];if(typeof r=="string")return r}for(let e of["data","event","payload","part"]){let r=t[e];if(xi(r)){let n=Kp(r);if(n)return n}}}function Ni(t,e){for(let n of["sessionID","sessionId","session_id"]){let s=t[n];if(typeof s=="string"&&s.length>0)return s}let r=t.session;if(typeof r=="string"&&r.length>0)return r;if(xi(r)){let n=Ni(r,e);if(n!==void 0)return n}if(e){let n=t.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=t[n];if(xi(s)){let i=Ni(s,e);if(i!==void 0)return i}}}function xi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var tc,nc=E(()=>{"use strict";zl();Ft();St();en();at();tc=class extends xe{constructor(e){super({provider:new sn({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none"},binary:"lmplayer",seedArgs:["run","--format","json","--dangerously-skip-permissions",ge],resumeTemplate:"lmplayer run --session {{session_id}} --dangerously-skip-permissions",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:
|
|
1502
|
+
`)}}),i.stderr?.on("data",g=>{a+=g.toString("utf8")}),r.signal&&(r.signal.aborted?i.kill():r.signal.addEventListener("abort",()=>i.kill(),{once:!0})),i.on("exit",g=>{f||(f=!0,p(),l.length>0&&h(l),n({code:g,stdout:o,stderr:a,sessionId:c??d,text:u.join("")}))}),i.on("error",g=>{f||(f=!0,p(),s(g))})})}function Kp(t){for(let e of["text","content","delta","output","message"]){let r=t[e];if(typeof r=="string")return r}for(let e of["data","event","payload","part"]){let r=t[e];if(xi(r)){let n=Kp(r);if(n)return n}}}function Ni(t,e){for(let n of["sessionID","sessionId","session_id"]){let s=t[n];if(typeof s=="string"&&s.length>0)return s}let r=t.session;if(typeof r=="string"&&r.length>0)return r;if(xi(r)){let n=Ni(r,e);if(n!==void 0)return n}if(e){let n=t.id;if(typeof n=="string"&&n.length>0)return n}for(let n of["data","event","payload","part"]){let s=t[n];if(xi(s)){let i=Ni(s,e);if(i!==void 0)return i}}}function xi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var tc,nc=E(()=>{"use strict";zl();Ft();St();en();at();tc=class extends xe{constructor(e){super({provider:new sn({providerName:"lmplayer",startCommand:"lmplayer",dbPath:e?.lmplayerDbPath}),capabilities:{canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!0},injection:{leaderMode:"none"},binary:"lmplayer",seedArgs:["run","--format","json","--dangerously-skip-permissions",ge],resumeTemplate:"lmplayer run --session {{session_id}} --dangerously-skip-permissions",startTemplate:"lmplayer run --dangerously-skip-permissions",transport:M0})}seedArgsFor(e){return Jp({prompt:e?.prompt??ge,model:e?.model,effort:e?.effort,formatJson:!0,permissionMode:"yolo"})}async seed(e,r){C0(e,{recursive:!0});let n=this.seedArgsFor(r);lt("lmplayer",n);try{let s=await Gp(this.binary,n,{cwd:e,env:sr(void 0,e),timeoutMs:6e4});return s.code!==0&&s.code!==null?{success:!1,error:s.stderr.trim().slice(0,200)||`exit code ${s.code}`}:s.sessionId?{success:!0,sessionId:s.sessionId}:{success:!1,error:"lmplayer seed failed; provider did not report a sessionID"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}manualSeedHint(e){return{launchCommand:`cd ${e} && lmplayer run --format json --dangerously-skip-permissions "${ge}"`,postLaunchNote:"Copy the sessionID reported by lmplayer into this member's sessionid= field.",lsCommand:`lmctl ls --provider lmplayer --sessiondir ${e}`}}}});import{readdir as Ai,readFile as j0,rm as D0}from"node:fs/promises";import{basename as Vp,join as lr}from"node:path";function Yp(t){return t.type==="user"||t.message?.role==="user"}function zp(t){return t.type==="assistant"||t.message?.role==="assistant"||t.message?.role==="model"}function Zp(t){let e=t.message;return e?typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.filter(r=>r.type==="text").map(r=>r.text||"").join(`
|
|
1421
1503
|
`):Array.isArray(e.parts)?e.parts.filter(r=>!r.thought&&r.type!=="thinking").map(r=>r.text||"").join(`
|
|
1422
|
-
`):"":""}function Qp(t){return t.model||t.message?.model}var Ri,e_=E(()=>{"use strict";nr();Ri=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||lr(be,".qwen")}async discoverSessions(){let e=lr(this.baseDir,"projects"),r;try{r=await Ai(e)}catch{return[]}let n=[];for(let s of r){let i=lr(e,s,"chats"),o;try{o=await Ai(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=lr(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=await Me(e,30);if(n.length===0)return null;let s=await Ne(e),i="(unknown)",o,a,l,c,d=0;for(let u of n){if(u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Yp(u)){let f=Zp(u).trim();f&&(l||(l=J(f,80)),c=J(f,80)),d++}if(zp(u)){let f=Qp(u);f&&(o=f),d++}}return{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Vp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await Ne(e),s="(unknown)",i,o,a,l,c,d,u=[];for await(let f of qe(e)){if(f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let m=f.message,p=f.timestamp?new Date(f.timestamp):n.modifiedAt;if(Yp(f)){let h=Zp(f);h.trim()&&(c||(c=J(h.trim(),80)),d=J(h.trim(),80)),u.push({role:"user",timestamp:p,content:h})}else if(zp(f)){let h=Qp(f);if(h&&(i=h),Array.isArray(m.content))for(let g of m.content)g.type==="text"&&g.text?u.push({role:"assistant",timestamp:p,content:g.text,model:h}):g.type==="thinking"&&g.thinking&&u.push({role:"thinking",timestamp:p,content:g.thinking});else if(typeof m.content=="string")u.push({role:"assistant",timestamp:p,content:m.content,model:h});else if(Array.isArray(m.parts))for(let g of m.parts)if(g.thought||g.type==="thinking"){let _=g.thinking||g.text;_&&u.push({role:"thinking",timestamp:p,content:_})}else g.text&&u.push({role:"assistant",timestamp:p,content:g.text,model:h})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.length,filePath:e,messages:u}}async resolveSessionPath(e){let r=lr(this.baseDir,"projects");try{let n=await Ai(r),s=[];for(let i of n){let o=lr(r,i,"chats",`${e}.jsonl`);try{return await jN(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=lr(r,i,"chats"),a;try{a=await Ai(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Vp(l,".jsonl").startsWith(e)&&s.push(lr(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await DN(r),!0}catch{return!1}}}});function ic(){return new sc}var sc,oc=E(()=>{"use strict";e_();Ft();Rr();St();sc=class extends xe{constructor(){super({provider:new Ri,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ge,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:wi})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as t_,readFile as PN,rm as r_,stat as n_}from"node:fs/promises";import{basename as ac,join as Bt}from"node:path";async function FN(t){let e=await Promise.all(t.map(r=>Ne(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function UN(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function s_(t){return t.type==="USER_INPUT"}function i_(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function WN(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function o_(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function a_(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function BN(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function qN(t){for await(let e of qe(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=HN(s);if(i)return i}let n=JN(e.content);if(n)return n}return null}function HN(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function JN(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function l_(t){if(t.endsWith(".db"))return ac(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Li,c_=E(()=>{"use strict";nr();Li=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Bt(be,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Bt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Bt(this.baseDir,"conversations"),r;try{r=await t_(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=ac(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Bt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e){return Bt(this.baseDir,"brain",e,".system_generated","logs","transcript.jsonl")}async existingTranscriptPath(e){let r=this.transcriptPath(e);try{return await n_(r),r}catch{return null}}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await FN([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n){let u=await Me(n,80);for(let f of u){let m=a_(f.content);if(m&&(a=m),s_(f)){let p=o_(f.content).trim();p&&(l||(l=J(p,80)),c=J(p,80)),d++}else i_(f)&&d++}}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=l_(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage;if(i)for await(let d of qe(i)){let u=UN(d.created_at,s.modifiedAt),f=a_(d.content);if(f&&(a=f),s_(d)){let m=o_(d.content),p=m.trim();p&&(l||(l=J(p,80)),c=J(p,80)),o.push({role:"user",timestamp:u,content:m});continue}if(Array.isArray(d.tool_calls))for(let m of d.tool_calls)o.push({role:"tool_use",timestamp:u,content:BN(m.args),toolName:m.name||"tool"});i_(d)&&d.content?o.push({role:"assistant",timestamp:u,content:d.content,model:a}):WN(d)&&d.content&&o.push({role:"tool_result",timestamp:u,content:d.content,toolName:d.type?.toLowerCase()}),d.thinking&&o.push({role:"thinking",timestamp:u,content:d.thinking})}return{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await n_(r),r}catch{}let n=Bt(this.baseDir,"conversations");try{let s=[];for(let i of await t_(n)){if(!i.endsWith(".db"))continue;ac(i,".db").startsWith(e)&&s.push(Bt(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=l_(r);return n?(await r_(this.conversationPath(n),{force:!0}),await r_(Bt(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await qN(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Bt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await PN(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}}});import{spawn as XN}from"node:child_process";function cc(t){return new lc(t)}async function GN(t,e){let r=Date.now(),n=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",VN(e.timeoutMs)];e.model&&n.push("--model",e.model),lt("agy",n,e.permissionMode??"yolo"),e.onProgress?.({kind:"system",summary:"agy -p one-shot started (no streaming events)"});let{stdout:s}=await KN(e.binary,n,{cwd:e.cwd,env:je(e.env,e.cwd,e.sessionId),signal:e.signal});return e.onProgress?.({kind:"system",summary:"agy -p one-shot completed"}),{text:s.trimEnd(),sessionId:e.sessionId,durationMs:Date.now()-r}}function KN(t,e,r){return new Promise((n,s)=>{let i;try{i=XN(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(c){s(c);return}let o="",a="";i.stdout?.on("data",c=>{o+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()});let l=()=>{i.kill("SIGTERM"),s(new Error("agy turn aborted"))};if(r.signal){if(r.signal.aborted){l();return}r.signal.addEventListener("abort",l,{once:!0})}i.on("error",c=>{r.signal?.removeEventListener("abort",l),s(c)}),i.on("exit",(c,d)=>{if(r.signal?.removeEventListener("abort",l),c===0){n({stdout:o,stderr:a});return}let u=d?`signal ${d}`:`exit code ${c}`,f=a.trim()||o.trim();s(new Error(`agy failed (${u})${f?`: ${f}`:""}`))})})}function VN(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var lc,dc=E(()=>{"use strict";c_();Ft();St();at();en();lc=class extends xe{constructor(e){super({provider:new Li(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",ge,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:GN})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}}});import{createHash as YN}from"node:crypto";import{existsSync as zN,mkdirSync as ZN,readFileSync as QN,renameSync as ex,writeFileSync as tx}from"node:fs";import{dirname as p_,join as d_,resolve as uc}from"node:path";function rx(t){return YN("sha256").update(t).digest("hex").slice(0,8)}function nx(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function sx(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function __(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Oi(t){return Math.max(1,Math.ceil(t.length/4))}function an(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return uc(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?d_(p_(uc(r)),".lmctl-claude-mock","sessions.json"):d_(uc(t),".lmctl-claude-mock","sessions.json")}function u_(){return{schemaVersion:1,sessions:{}}}function ls(t){if(!zN(t))return u_();try{let e=JSON.parse(QN(t,"utf8")),r=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0;return{schemaVersion:1,sessions:r,...n!==void 0?{script:n}:{}}}catch{return u_()}}function h_(t,e){ZN(p_(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;tx(r,`${JSON.stringify(e,null,2)}
|
|
1423
|
-
`,"utf8"),ex(r,t)}function ix(t){return{...t,timestamp:t.timestamp.toISOString()}}function ox(t){return{...t,timestamp:new Date(t.timestamp)}}function ax(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(ix)}}function g_(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(ox)}}function $i(t,e=process.cwd()){let r=on.get(t);if(r!==void 0)return r;let s=ls(an(e)).sessions[t];if(s===void 0)return;let i=g_(s);return on.set(i.sessionId,i),i}function f_(t){on.set(t.sessionId,t);let e=an(t.cwd),r=ls(e);r.sessions[t.sessionId]=ax({...t,filePath:e}),h_(e,r)}function lx(){let t=ls(an()),e=Object.values(t.sessions).map(g_);for(let r of e)on.set(r.sessionId,r);return e}function cx(t,e){let r=e.script;if(r===void 0)return;let n=r[t],s=r[__(t)],i=n??s;if(typeof i=="string")return i;if(i!==void 0&&typeof i.text=="string")return i.text}function m_(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function pc(){return new mc}var on,fc,mc,_c=E(()=>{"use strict";on=new Map;fc=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of lx())e.set(r.sessionId,r);for(let r of on.values())e.set(r.sessionId,r);return[...e.values()].map(m_)}async loadSession(e){let r=$i(e);return r===void 0?null:{...m_(r),messages:r.messages.slice()}}async resolveSessionPath(e){return $i(e)?.filePath??null}async deleteSession(e){let r=on.delete(e),n=an(),s=ls(n),i=s.sessions[e]!==void 0;return delete s.sessions[e],i&&h_(n,s),r||i}},mc=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new fc;discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return[]}async seed(e,r){let n=nx(sx(e,r)),s=`mock-${n}-${rx(`${e}:${n}`)}`,i=new Date,o=an(e),a=$i(s,e),l=r?.prompt??"ClaudeMock seed",c=Oi(l),d={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=Oi("ACK: ClaudeMock seeded"),f_(d),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=$i(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=ls(an(r.cwd)),a=cx(e,o)??`ClaudeMock ack: ${__(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:a,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Oi(e),s.totalOutputTokens+=Oi(a),f_(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),{text:a,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function vt(t){let e=[Dl({claudeDir:t?.claudeDir}),Ul({codexDir:t?.codexDir,codeDir:t?.codeDir}),Jl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),Kl({copilotDir:t?.copilotDir}),Ql(),rc({lmplayerDbPath:t?.lmplayerDbPath}),ic(),cc({agyDir:t?.agyDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(pc()),e}var hc=E(()=>{"use strict";Pl();Wl();Xl();Vl();ec();nc();oc();dc();_c();Pl();Wl();Xl();Vl();ec();nc();oc();dc();_c()});var Ec={};Ee(Ec,{ProviderRegistry:()=>es,TransportConnectionError:()=>ye,TransportError:()=>et,TransportJsonError:()=>fi,TransportProcessError:()=>Ut,TransportRpcError:()=>Wt,_resetDefaultRegistryForTests:()=>dx,chat:()=>kt,countTokens:()=>wc,createAdapterRegistry:()=>bt,createAllAdapters:()=>vt,listSessions:()=>yc,seed:()=>gc});function Mi(){return Ci===null&&(Ci=bt(vt())),Ci}function dx(){Ci=null}function w_(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function kt(t){let e=t.registry??Mi(),r=w_(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs}}async function gc(t){let e=t.registry??Mi(),r=w_(e,t.provider),n=await y_(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await y_(e,t.provider,t.cwd),a=ux(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function y_(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function ux(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function yc(t={}){return(t.registry??Mi()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function wc(t){let r=await(t.registry??Mi()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var Ci,It=E(()=>{"use strict";_l();hc();_l();hc();Qr();Ci=null});function fx(){return Tc===null&&(Tc=bt(vt())),Tc}async function ji(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,i;try{return await px(t)}catch(o){throw s=!0,i=o,o}finally{if(n)if(!s)ln.delete(r),e.setMemberState(r,"idle");else{let o=mx(i,r);e.setMemberState(r,o!==null?"attention_needed":"idle",o)}}}function mx(t,e){if(!(t instanceof Se))return ln.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=(ln.get(e)??0)+1;return r>=3?(ln.delete(e),"consecutive_timeouts"):(ln.set(e,r),null)}return ln.delete(e),null}async function px(t){let e=t.timeoutMs,r=typeof e=="number"&&e>0,n=fx(),s;try{let d=await n.resolveSession(t.sessionid);if(!d)return Promise.reject(new Se("other",null,`library: sessionid "${t.sessionid}" matched no registered provider`,bc(t.sessionid,t.sessiondir,"unresolved")));s=d.provider.name}catch(d){return Promise.reject(new Se("other",null,`library: session resolution failed: ${E_(d)}`,bc(t.sessionid,t.sessiondir,"unresolved")))}let i=bc(t.sessionid,t.sessiondir,s),o=new AbortController,a=r?setTimeout(()=>o.abort(),e):null,l=!1;o.signal.addEventListener("abort",()=>{l=!0},{once:!0});let c=Date.now();try{let d=await kt({provider:s,sessionId:t.sessionid,cwd:t.sessiondir,prompt:t.prompt,timeoutMs:0,signal:o.signal,registry:n,onProgress:t.onProgress,permissionMode:t.permissionMode});if(d.status==="stalled")throw new Se("timeout",null,`library: stalled after ${d.stalledAfterMs??0}ms`,i);return{text:d.text,ms:Date.now()-c,exit_status:0,argv:i}}catch(d){throw l?new Se("timeout",null,`library: wall-clock timeout after ${e??0}ms`,i):_x(d,i)}finally{a!==null&&clearTimeout(a)}}function bc(t,e,r){return["<library>","chat",t,e,"--provider",r]}function E_(t){return t instanceof Error?t.message:String(t)}function _x(t,e){if(t instanceof Se)return t;if(t instanceof ye){let r=t.cause;return r?.code==="ENOENT_CWD"?new Se("sessiondir_missing",null,t.message,e):r?.code==="ENOENT"?new Se("enoent",null,t.message,e):new Se("other",null,t.message,e)}return t instanceof Ut?new Se("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Wt?new Se("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof et?new Se("other",null,t.message,e):new Se("other",null,E_(t),e)}var Se,Tc,ln,Di=E(()=>{"use strict";It();Se=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"}},Tc=null;ln=new Map});function T_(){return Sc===null&&(Sc=bt(vt())),Sc}function gx(t,e){if(!hx.test(t))return t;let r=e.getConfig(`workspace.${t}`);if(r===null||r.length===0)throw new Ie("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 Pi(t){let e=gx(t.member.provider,t.dal),r=e===t.member.provider?t.member:{...t.member,provider:e},n=await yx({member:r});return t.dal.setMemberProviderResolved(t.member.id,e),{sessionid:n.sessionid,provider_resolved:e}}async function yx(t){let e=t.member.provider,r=t.member.sessiondir,n=vc("seed",r,e);try{let s=await gc({provider:e,cwd:r,registry:T_()});if(!s.success)throw Ex(s.error,n);if(!s.sessionId)throw new Ie("parse",0,"",n);return{sessionid:s.sessionId}}catch(s){throw s instanceof Ie?s:kc(s,n)}}async function b_(t){return wx(t)}async function wx(t){let e=T_(),r=vc("tokens",t.sessionid,"unresolved"),n;try{let i=await e.resolveSession(t.sessionid);if(!i)throw new Ie("parse",0,`library: sessionid "${t.sessionid}" matched no registered provider`,r);n=i.provider.name}catch(i){throw i instanceof Ie?i:kc(i,r)}let s=vc("tokens",t.sessionid,n);try{let i=await wc({sessionId:t.sessionid,provider:n,registry:e});return{input_tokens:i.input,cache_tokens:i.cachedInput+i.cacheWriteInput,output_tokens:i.output,total_tokens:i.total}}catch(i){throw i instanceof Ie?i:kc(i,s)}}function vc(t,e,r){return["<library>",t,e,"--provider",r]}function Ex(t,e){let r=t??"";if(/\bENOENT\b/i.test(r))return new Ie("enoent",null,r,e);if(/timed?\s*out/i.test(r))return new Ie("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 Ie("nonzero_exit",Number(n[1]),r,e)}return new Ie("other",null,r,e)}function kc(t,e){return t instanceof Ie?t:t instanceof ye?t.cause?.code==="ENOENT"?new Ie("enoent",null,t.message,e):new Ie("other",null,t.message,e):t instanceof Ut?new Ie("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Wt?new Ie("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof et?new Ie("other",null,t.message,e):new Ie("other",null,t instanceof Error?t.message:String(t),e)}var Ie,Sc,hx,Ic=E(()=>{"use strict";It();Ie=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"}},Sc=null;hx=/^provider[123]$/});function Fi(t){return Buffer.from(t,"utf8").toString("base64url")}function ds(t){return Buffer.from(t,"base64url").toString("utf8")}async function S_(t,e=r=>b_({sessionid:r})){if(process.env.LMCTL_SESSION_SIZE_DISABLED==="1")return{recorded:0,failed:0};let r=0,n=0;for(let s of Tx(t)){let i=s.member.sessionid;if(i!==null)try{let o=await e(i);t.recordSessionSize({team_name:s.team_name,alias:s.member.alias,sessionid:i,...o}),r+=1}catch(o){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:i,error:o instanceof Error?o.message:String(o)})})}catch{}}}return{recorded:r,failed:n}}async function v_(t,e,r){let n=k_(t,e,r);if(n===null||n.member.sessionid===null)throw new Error("session member not found");if(n.member.state!=="idle")throw new cs(r,n.member.state);t.setMemberState(n.member.id,"in_chat","compacting");try{return await ji({sessionid:n.member.sessionid,sessiondir:n.member.sessiondir,prompt:"/compact"}),t.setMemberState(n.member.id,"idle",null),{ok:!0,row:I_(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 Nc(t,e,r){let n=k_(t,e,r);if(n===null)throw new Error("session member not found");let s=await Pi({member:n.member,dal:t});return t.updateTeamMemberSession(n.member.id,s.sessionid),{ok:!0,sessionid:s.sessionid,row:I_(t,e,r)}}function Tx(t){return t.listTeams().flatMap(e=>t.listTeamMembers(e.id).filter(r=>r.sessionid!==null).map(r=>({team_name:e.name,member:r})))}function k_(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 I_(t,e,r){return t.sessionSizeHistory(e,r,1)[0]??null}var cs,Ui=E(()=>{"use strict";Di();Ic();cs=class extends Error{constructor(e,r){super(`member ${e} is currently ${r}; cannot compact while busy`),this.name="MemberBusyError"}}});async function xc(t){let e=t.dal,r=t.nowMs??Date.now(),n=t.thresholdMs??Sx(e),s=r-n,i=e.query(`
|
|
1504
|
+
`):"":""}function Qp(t){return t.model||t.message?.model}var Ri,e_=E(()=>{"use strict";nr();Ri=class{name="qwen";baseDir;constructor(e){this.baseDir=e?.qwenDir||lr(be,".qwen")}async discoverSessions(){let e=lr(this.baseDir,"projects"),r;try{r=await Ai(e)}catch{return[]}let n=[];for(let s of r){let i=lr(e,s,"chats"),o;try{o=await Ai(i)}catch{continue}for(let a of o){if(!a.endsWith(".jsonl"))continue;let l=a.replace(/\.jsonl$/,""),c=lr(i,a);try{let d=await this.extractSummary(c,l);d&&n.push(d)}catch{}}}return n}async extractSummary(e,r){let n=await Me(e,30);if(n.length===0)return null;let s=await Ne(e),i="(unknown)",o,a,l,c,d=0;for(let u of n){if(u.cwd&&(i=u.cwd,u.version&&(a=u.version)),u.type==="system"&&u.cwd&&(i=u.cwd,u.version&&(a=u.version),u.model&&(o=u.model)),Yp(u)){let f=Zp(u).trim();f&&(l||(l=X(f,80)),c=X(f,80)),d++}if(zp(u)){let f=Qp(u);f&&(o=f),d++}}return{provider:"qwen",sessionId:r,cwd:i,createdAt:s.createdAt,modifiedAt:s.modifiedAt,model:o,cliVersion:a,startCommand:"qwen",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:e}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=Vp(r,".jsonl");return this.loadFromFile(r,n)}async loadFromFile(e,r){let n=await Ne(e),s="(unknown)",i,o,a,l,c,d,u=[];for await(let f of qe(e)){if(f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.gitBranch&&(a=f.gitBranch)),f.type==="system"&&f.cwd&&(s=f.cwd,f.version&&(o=f.version),f.model&&(i=f.model),f.gitBranch&&(a=f.gitBranch)),!f.message)continue;let m=f.message,p=f.timestamp?new Date(f.timestamp):n.modifiedAt;if(Yp(f)){let h=Zp(f);h.trim()&&(c||(c=X(h.trim(),80)),d=X(h.trim(),80)),u.push({role:"user",timestamp:p,content:h})}else if(zp(f)){let h=Qp(f);if(h&&(i=h),Array.isArray(m.content))for(let g of m.content)g.type==="text"&&g.text?u.push({role:"assistant",timestamp:p,content:g.text,model:h}):g.type==="thinking"&&g.thinking&&u.push({role:"thinking",timestamp:p,content:g.thinking});else if(typeof m.content=="string")u.push({role:"assistant",timestamp:p,content:m.content,model:h});else if(Array.isArray(m.parts))for(let g of m.parts)if(g.thought||g.type==="thinking"){let _=g.thinking||g.text;_&&u.push({role:"thinking",timestamp:p,content:_})}else g.text&&u.push({role:"assistant",timestamp:p,content:g.text,model:h})}}return{provider:"qwen",sessionId:r,slug:l,cwd:s,createdAt:n.createdAt,modifiedAt:n.modifiedAt,model:i,cliVersion:o,gitBranch:a,startCommand:"qwen",firstUserMessage:c,lastUserMessage:d,messageCount:u.length,filePath:e,messages:u}}async resolveSessionPath(e){let r=lr(this.baseDir,"projects");try{let n=await Ai(r),s=[];for(let i of n){let o=lr(r,i,"chats",`${e}.jsonl`);try{return await j0(o,{flag:"r"}),o}catch{continue}}for(let i of n){let o=lr(r,i,"chats"),a;try{a=await Ai(o)}catch{continue}for(let l of a){if(!l.endsWith(".jsonl"))continue;Vp(l,".jsonl").startsWith(e)&&s.push(lr(o,l))}}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;try{return await D0(r),!0}catch{return!1}}}});function ic(){return new sc}var sc,oc=E(()=>{"use strict";e_();Ft();Rr();St();sc=class extends xe{constructor(){super({provider:new Ri,capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!0,canCancel:!0},injection:{leaderMode:"prompt-append"},binary:"qwen",seedArgs:["-p",ge,"--approval-mode","yolo"],resumeTemplate:"qwen --resume {{session_id}}",startTemplate:"qwen",transport:wi})}seedArgsFor(e){let r=super.seedArgsFor(e);return e?.model?[...r,"--model",e.model]:r}}});import{readdir as t_,readFile as P0,rm as r_,stat as n_}from"node:fs/promises";import{basename as ac,join as Bt}from"node:path";async function F0(t){let e=await Promise.all(t.map(r=>Ne(r)));return{createdAt:new Date(Math.min(...e.map(r=>r.createdAt.getTime()))),modifiedAt:new Date(Math.max(...e.map(r=>r.modifiedAt.getTime())))}}function U0(t,e){if(!t)return e;let r=new Date(t);return Number.isNaN(r.getTime())?e:r}function s_(t){return t.type==="USER_INPUT"}function i_(t){return t.source==="MODEL"&&t.type==="PLANNER_RESPONSE"}function W0(t){return t.source==="MODEL"&&t.type!=="PLANNER_RESPONSE"}function o_(t){if(!t)return"";let e=/<USER_REQUEST>\n?([\s\S]*?)\n?<\/USER_REQUEST>/.exec(t);return e?e[1]:t}function a_(t){if(!t)return;let e=/Model Selection` from [^\n]+? to ([^\n]+)/.exec(t);if(e)return e[1].replace(/\. No need\b[\s\S]*$/,"").replace(/\. If reporting\b[\s\S]*$/,"").replace(/\.\s*$/,"").trim()}function B0(t){if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}}async function q0(t){for await(let e of qe(t)){let r=e.tool_calls?.map(s=>s.args)??[];for(let s of r){let i=H0(s);if(i)return i}let n=X0(e.content);if(n)return n}return null}function H0(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t,r=e.Cwd??e.cwd??e.DirectoryPath;return typeof r!="string"?null:r.replace(/^"|"$/g,"")}function X0(t){return t?/"Cwd":"([^"]+)"/.exec(t)?.[1]??null:null}function l_(t){if(t.endsWith(".db"))return ac(t,".db");let e="/brain/",r=t.indexOf(e);return r===-1?null:t.slice(r+e.length).split("/")[0]||null}var Li,c_=E(()=>{"use strict";nr();Li=class{name="agy";baseDir;constructor(e={}){this.baseDir=e.agyDir||Bt(be,".gemini","antigravity-cli")}getWatchPaths(){return[{directory:Bt(this.baseDir,"conversations"),filePattern:/\.db$/}]}async discoverSessions(){let e=Bt(this.baseDir,"conversations"),r;try{r=await t_(e)}catch{return[]}let n=[];for(let s of r){if(!s.endsWith(".db"))continue;let i=ac(s,".db");try{let o=await this.extractSummary(i);o&&n.push(o)}catch{}}return n}conversationPath(e){return Bt(this.baseDir,"conversations",`${e}.db`)}transcriptPath(e){return Bt(this.baseDir,"brain",e,".system_generated","logs","transcript.jsonl")}async existingTranscriptPath(e){let r=this.transcriptPath(e);try{return await n_(r),r}catch{return null}}async extractSummary(e){let r=this.conversationPath(e),n=await this.existingTranscriptPath(e),s=n??r,i=await F0([r,n].filter(Boolean)),o=await this.resolveCwd(e,n),a,l,c,d=0;if(n){let u=await Me(n,80);for(let f of u){let m=a_(f.content);if(m&&(a=m),s_(f)){let p=o_(f.content).trim();p&&(l||(l=X(p,80)),c=X(p,80)),d++}else i_(f)&&d++}}return{provider:"agy",sessionId:e,cwd:o,createdAt:i.createdAt,modifiedAt:i.modifiedAt,model:a,startCommand:"agy",firstUserMessage:l,lastUserMessage:c,messageCount:d,filePath:s,filePaths:n?[r,n]:[r]}}async loadSession(e){let r=await this.resolveSessionPath(e);if(!r)return null;let n=l_(r);if(!n)return null;let s=await this.extractSummary(n);if(!s)return null;let i=await this.existingTranscriptPath(n),o=[],a=s.model,l=s.firstUserMessage,c=s.lastUserMessage;if(i)for await(let d of qe(i)){let u=U0(d.created_at,s.modifiedAt),f=a_(d.content);if(f&&(a=f),s_(d)){let m=o_(d.content),p=m.trim();p&&(l||(l=X(p,80)),c=X(p,80)),o.push({role:"user",timestamp:u,content:m});continue}if(Array.isArray(d.tool_calls))for(let m of d.tool_calls)o.push({role:"tool_use",timestamp:u,content:B0(m.args),toolName:m.name||"tool"});i_(d)&&d.content?o.push({role:"assistant",timestamp:u,content:d.content,model:a}):W0(d)&&d.content&&o.push({role:"tool_result",timestamp:u,content:d.content,toolName:d.type?.toLowerCase()}),d.thinking&&o.push({role:"thinking",timestamp:u,content:d.thinking})}return{...s,model:a,firstUserMessage:l,lastUserMessage:c,messageCount:o.length,messages:o}}async resolveSessionPath(e){let r=this.conversationPath(e);try{return await n_(r),r}catch{}let n=Bt(this.baseDir,"conversations");try{let s=[];for(let i of await t_(n)){if(!i.endsWith(".db"))continue;ac(i,".db").startsWith(e)&&s.push(Bt(n,i))}if(s.length===1)return s[0]}catch{}return null}async deleteSession(e){let r=await this.resolveSessionPath(e);if(!r)return!1;let n=l_(r);return n?(await r_(this.conversationPath(n),{force:!0}),await r_(Bt(this.baseDir,"brain",n),{recursive:!0,force:!0}),!0):!1}async resolveCwd(e,r){let n=await this.cwdFromLastConversationCache(e);if(n)return n;if(r){let s=await q0(r);if(s)return s}return"(unknown)"}async cwdFromLastConversationCache(e){let r=Bt(this.baseDir,"cache","last_conversations.json");try{let n=JSON.parse(await P0(r,"utf8"));for(let[s,i]of Object.entries(n))if(i===e)return s}catch{}return null}}});import{spawn as J0}from"node:child_process";function cc(t){return new lc(t)}async function G0(t,e){let r=Date.now(),n=["--conversation",e.sessionId,"-p",t,"--dangerously-skip-permissions","--print-timeout",V0(e.timeoutMs)];e.model&&n.push("--model",e.model),lt("agy",n,e.permissionMode??"yolo"),e.onProgress?.({kind:"system",summary:"agy -p one-shot started (no streaming events)"});let{stdout:s}=await K0(e.binary,n,{cwd:e.cwd,env:je(e.env,e.cwd,e.sessionId),signal:e.signal});return e.onProgress?.({kind:"system",summary:"agy -p one-shot completed"}),{text:s.trimEnd(),sessionId:e.sessionId,durationMs:Date.now()-r}}function K0(t,e,r){return new Promise((n,s)=>{let i;try{i=J0(t,e,{cwd:r.cwd,env:r.env,stdio:["ignore","pipe","pipe"]})}catch(c){s(c);return}let o="",a="";i.stdout?.on("data",c=>{o+=c.toString()}),i.stderr?.on("data",c=>{a+=c.toString()});let l=()=>{i.kill("SIGTERM"),s(new Error("agy turn aborted"))};if(r.signal){if(r.signal.aborted){l();return}r.signal.addEventListener("abort",l,{once:!0})}i.on("error",c=>{r.signal?.removeEventListener("abort",l),s(c)}),i.on("exit",(c,d)=>{if(r.signal?.removeEventListener("abort",l),c===0){n({stdout:o,stderr:a});return}let u=d?`signal ${d}`:`exit code ${c}`,f=a.trim()||o.trim();s(new Error(`agy failed (${u})${f?`: ${f}`:""}`))})})}function V0(t){return!t||t<=0?"8h":`${Math.max(1,Math.ceil(t/1e3))}s`}var lc,dc=E(()=>{"use strict";c_();Ft();St();at();en();lc=class extends xe{constructor(e){super({provider:new Li(e),capabilities:{canCreate:!0,canResumeInteractive:!0,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1},injection:{leaderMode:"prompt-append",leaderSetupHint:"Antigravity uses one-shot print turns; no streaming events are available."},binary:"agy",seedArgs:["-p",ge,"--dangerously-skip-permissions","--print-timeout","2m"],resumeTemplate:"agy --conversation {{session_id}} --dangerously-skip-permissions",startTemplate:"agy --dangerously-skip-permissions",transport:G0})}seedArgsFor(e){let r=[...super.seedArgsFor(e)];return e?.model&&r.push("--model",e.model),r}manualSeedHint(e){return{launchCommand:`cd ${e} && agy --dangerously-skip-permissions`,postLaunchNote:"Send the lmctl seed instruction, wait for the conversation to write, then exit.",lsCommand:`lmctl ls --provider agy --sessiondir ${e}`}}}});import{createHash as Y0}from"node:crypto";import{existsSync as z0,mkdirSync as Z0,readFileSync as Q0,renameSync as ex,writeFileSync as tx}from"node:fs";import{dirname as p_,join as d_,resolve as uc}from"node:path";function rx(t){return Y0("sha256").update(t).digest("hex").slice(0,8)}function nx(t){let e=t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"session"}function sx(t,e){let r=e?.prompt??"",n=/\bYou are alias\s+([A-Za-z][A-Za-z0-9_-]*)\b/.exec(r);return n!==null?n[1]:t.split(/[\\/]/).filter(Boolean).pop()??"session"}function __(t){return t.split(/\r?\n/,1)[0]?.trim()||"(empty prompt)"}function Oi(t){return Math.max(1,Math.ceil(t.length/4))}function an(t=process.cwd()){let e=process.env.LMCTL_CLAUDE_MOCK_STORE;if(e!==void 0&&e.trim().length>0)return uc(e);let r=process.env.LMCTL_DB;return r!==void 0&&r.trim().length>0?d_(p_(uc(r)),".lmctl-claude-mock","sessions.json"):d_(uc(t),".lmctl-claude-mock","sessions.json")}function u_(){return{schemaVersion:1,sessions:{}}}function ls(t){if(!z0(t))return u_();try{let e=JSON.parse(Q0(t,"utf8")),r=typeof e.sessions=="object"&&e.sessions!==null?e.sessions:{},n=typeof e.script=="object"&&e.script!==null?e.script:void 0;return{schemaVersion:1,sessions:r,...n!==void 0?{script:n}:{}}}catch{return u_()}}function h_(t,e){Z0(p_(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;tx(r,`${JSON.stringify(e,null,2)}
|
|
1505
|
+
`,"utf8"),ex(r,t)}function ix(t){return{...t,timestamp:t.timestamp.toISOString()}}function ox(t){return{...t,timestamp:new Date(t.timestamp)}}function ax(t){return{...t,createdAt:t.createdAt.toISOString(),modifiedAt:t.modifiedAt.toISOString(),messages:t.messages.map(ix)}}function g_(t){return{...t,createdAt:new Date(t.createdAt),modifiedAt:new Date(t.modifiedAt),messages:t.messages.map(ox)}}function $i(t,e=process.cwd()){let r=on.get(t);if(r!==void 0)return r;let s=ls(an(e)).sessions[t];if(s===void 0)return;let i=g_(s);return on.set(i.sessionId,i),i}function f_(t){on.set(t.sessionId,t);let e=an(t.cwd),r=ls(e);r.sessions[t.sessionId]=ax({...t,filePath:e}),h_(e,r)}function lx(){let t=ls(an()),e=Object.values(t.sessions).map(g_);for(let r of e)on.set(r.sessionId,r);return e}function cx(t,e){let r=e.script;if(r===void 0)return;let n=r[t],s=r[__(t)],i=n??s;if(typeof i=="string")return i;if(i!==void 0&&typeof i.text=="string")return i.text}function m_(t){return{provider:"ClaudeMock",sessionId:t.sessionId,cwd:t.cwd,createdAt:t.createdAt,modifiedAt:t.modifiedAt,messageCount:t.messages.length,filePath:t.filePath,cliVersion:"ClaudeMock/0",model:"claude-mock",totalInputTokens:t.totalInputTokens,totalOutputTokens:t.totalOutputTokens,lastTokenUsage:{totalTokens:t.totalInputTokens+t.totalOutputTokens}}}function pc(){return new mc}var on,fc,mc,_c=E(()=>{"use strict";on=new Map;fc=class{name="ClaudeMock";async discoverSessions(){let e=new Map;for(let r of lx())e.set(r.sessionId,r);for(let r of on.values())e.set(r.sessionId,r);return[...e.values()].map(m_)}async loadSession(e){let r=$i(e);return r===void 0?null:{...m_(r),messages:r.messages.slice()}}async resolveSessionPath(e){return $i(e)?.filePath??null}async deleteSession(e){let r=on.delete(e),n=an(),s=ls(n),i=s.sessions[e]!==void 0;return delete s.sessions[e],i&&h_(n,s),r||i}},mc=class{name="ClaudeMock";capabilities={canCreate:!0,canResumeInteractive:!1,canFork:!1,forkSupport:"manual",canStructuredTurn:!0,canStreamDeltas:!1,canCancel:!1};injection={leaderMode:"none"};provider=new fc;discover(){return this.provider.discoverSessions()}load(e){return this.provider.loadSession(e)}resolvePath(e){return this.provider.resolveSessionPath(e)}delete(e){return this.provider.deleteSession(e)}getWatchPaths(){return[]}async seed(e,r){let n=nx(sx(e,r)),s=`mock-${n}-${rx(`${e}:${n}`)}`,i=new Date,o=an(e),a=$i(s,e),l=r?.prompt??"ClaudeMock seed",c=Oi(l),d={sessionId:s,cwd:e,filePath:o,createdAt:a?.createdAt??i,modifiedAt:i,messages:a?.messages.slice()??[],totalInputTokens:a?.totalInputTokens??0,totalOutputTokens:a?.totalOutputTokens??0};return d.messages.push({role:"user",timestamp:i,content:l}),d.messages.push({role:"assistant",timestamp:i,content:"ACK: ClaudeMock seeded"}),d.totalInputTokens+=c,d.totalOutputTokens+=Oi("ACK: ClaudeMock seeded"),f_(d),{success:!0,sessionId:s}}resumeCommand(e){return`ClaudeMock --resume ${e}`}startCommand(){return"ClaudeMock"}manualSeedHint(e){return{launchCommand:`cd ${e} && ClaudeMock`,postLaunchNote:"ClaudeMock is a hermetic test provider; no manual seed is required.",lsCommand:`lmctl ls --provider ClaudeMock --sessiondir ${e}`}}forkHint(e){return"ClaudeMock does not support fork."}async fork(e,r){return{success:!1,error:"ClaudeMock does not support fork."}}async sendTurn(e,r){let n=Date.now(),s=$i(r.sessionId,r.cwd);if(s===void 0)throw new Error(`ClaudeMock session not found: ${r.sessionId}`);let i=new Date,o=ls(an(r.cwd)),a=cx(e,o)??`ClaudeMock ack: ${__(e)}`;return s.messages.push({role:"user",timestamp:i,content:e}),s.messages.push({role:"assistant",timestamp:i,content:a,model:r.model??"claude-mock"}),s.modifiedAt=i,s.totalInputTokens+=Oi(e),s.totalOutputTokens+=Oi(a),f_(s),r.onProgress?.({kind:"text",summary:"ClaudeMock deterministic reply"}),{text:a,sessionId:r.sessionId,durationMs:Math.max(1,Date.now()-n),stopReason:"mock_stop",numTurns:1,status:"ok"}}}});function vt(t){let e=[Dl({claudeDir:t?.claudeDir}),Ul({codexDir:t?.codexDir,codeDir:t?.codeDir}),Xl({geminiDir:t?.geminiDir,claudeDir:t?.claudeDir,codexDir:t?.codexDir,codeDir:t?.codeDir}),Kl({copilotDir:t?.copilotDir}),Ql(),rc({lmplayerDbPath:t?.lmplayerDbPath}),ic(),cc({agyDir:t?.agyDir})];return process.env.LMCTL_ENABLE_MOCK_PROVIDER==="1"&&e.push(pc()),e}var hc=E(()=>{"use strict";Pl();Wl();Jl();Vl();ec();nc();oc();dc();_c();Pl();Wl();Jl();Vl();ec();nc();oc();dc();_c()});var Ec={};Ee(Ec,{ProviderRegistry:()=>es,TransportConnectionError:()=>ye,TransportError:()=>et,TransportJsonError:()=>fi,TransportProcessError:()=>Ut,TransportRpcError:()=>Wt,_resetDefaultRegistryForTests:()=>dx,chat:()=>kt,countTokens:()=>wc,createAdapterRegistry:()=>bt,createAllAdapters:()=>vt,listSessions:()=>yc,seed:()=>gc});function Mi(){return Ci===null&&(Ci=bt(vt())),Ci}function dx(){Ci=null}function w_(t,e){let r=t.getAdapter(e);if(!r)throw new Error(`provider "${e}" is not registered in this registry`);return r}async function kt(t){let e=t.registry??Mi(),r=w_(e,t.provider),n={sessionId:t.sessionId,cwd:t.cwd,env:t.env,onDelta:t.onDelta,onProgress:t.onProgress,signal:t.signal,timeoutMs:t.timeoutMs,model:t.model,effort:t.effort,progPath:t.progPath,alias:t.alias,isLead:t.isLead,permissionMode:t.permissionMode},s=await r.sendTurn(t.prompt,n);return{text:s.text,sessionId:s.sessionId,durationMs:s.durationMs,stopReason:s.stopReason,numTurns:s.numTurns,status:s.status,stalledAfterMs:s.stalledAfterMs}}async function gc(t){let e=t.registry??Mi(),r=w_(e,t.provider),n=await y_(e,t.provider,t.cwd),s=await r.seed(t.cwd,{model:t.model,effort:t.effort,prompt:t.prompt}),i=s.warnings!==void 0&&s.warnings.length>0?{warnings:s.warnings}:{};if(!s.success)return{success:!1,error:s.error,...i};if(s.sessionId)return{success:!0,sessionId:s.sessionId,...i};let o=await y_(e,t.provider,t.cwd),a=ux(n,o);return a?{success:!0,sessionId:a,...i}:{success:!0,...i}}async function y_(t,e,r){let n=await t.listAll({provider:e,workspace:r}),s=new Map;for(let i of n)s.set(i.sessionId,i.modifiedAt);return s}function ux(t,e){let r=[];for(let n of e.keys())t.has(n)||r.push(n);return r.length===1?r[0]:void 0}async function yc(t={}){return(t.registry??Mi()).listAll({provider:t.provider,workspace:t.workspace,limit:t.limit,from:t.from,to:t.to})}async function wc(t){let r=await(t.registry??Mi()).getSession(t.sessionId,t.provider);if(!r)throw new Error(`session "${t.sessionId}" not found`);let n=r.totalInputTokens??0,s=r.totalCachedInputTokens??0,i=r.totalCacheWriteInputTokens??0,o=r.totalOutputTokens??0,a=r.totalReasoningOutputTokens??0;return{provider:r.provider,sessionId:r.sessionId,input:n,cachedInput:s,cacheWriteInput:i,output:o,reasoningOutput:a,total:n+s+i+o+a,lastTurn:r.lastTokenUsage}}var Ci,It=E(()=>{"use strict";_l();hc();_l();hc();Qr();Ci=null});function fx(){return Tc===null&&(Tc=bt(vt())),Tc}async function ji(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,i;try{return await px(t)}catch(o){throw s=!0,i=o,o}finally{if(n)if(!s)ln.delete(r),e.setMemberState(r,"idle");else{let o=mx(i,r);e.setMemberState(r,o!==null?"attention_needed":"idle",o)}}}function mx(t,e){if(!(t instanceof Se))return ln.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=(ln.get(e)??0)+1;return r>=3?(ln.delete(e),"consecutive_timeouts"):(ln.set(e,r),null)}return ln.delete(e),null}async function px(t){let e=t.timeoutMs,r=typeof e=="number"&&e>0,n=fx(),s;try{let d=await n.resolveSession(t.sessionid);if(!d)return Promise.reject(new Se("other",null,`library: sessionid "${t.sessionid}" matched no registered provider`,bc(t.sessionid,t.sessiondir,"unresolved")));s=d.provider.name}catch(d){return Promise.reject(new Se("other",null,`library: session resolution failed: ${E_(d)}`,bc(t.sessionid,t.sessiondir,"unresolved")))}let i=bc(t.sessionid,t.sessiondir,s),o=new AbortController,a=r?setTimeout(()=>o.abort(),e):null,l=!1;o.signal.addEventListener("abort",()=>{l=!0},{once:!0});let c=Date.now();try{let d=await kt({provider:s,sessionId:t.sessionid,cwd:t.sessiondir,prompt:t.prompt,timeoutMs:0,signal:o.signal,registry:n,onProgress:t.onProgress,permissionMode:t.permissionMode});if(d.status==="stalled")throw new Se("timeout",null,`library: stalled after ${d.stalledAfterMs??0}ms`,i);return{text:d.text,ms:Date.now()-c,exit_status:0,argv:i}}catch(d){throw l?new Se("timeout",null,`library: wall-clock timeout after ${e??0}ms`,i):_x(d,i)}finally{a!==null&&clearTimeout(a)}}function bc(t,e,r){return["<library>","chat",t,e,"--provider",r]}function E_(t){return t instanceof Error?t.message:String(t)}function _x(t,e){if(t instanceof Se)return t;if(t instanceof ye){let r=t.cause;return r?.code==="ENOENT_CWD"?new Se("sessiondir_missing",null,t.message,e):r?.code==="ENOENT"?new Se("enoent",null,t.message,e):new Se("other",null,t.message,e)}return t instanceof Ut?new Se("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Wt?new Se("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof et?new Se("other",null,t.message,e):new Se("other",null,E_(t),e)}var Se,Tc,ln,Di=E(()=>{"use strict";It();Se=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"}},Tc=null;ln=new Map});function T_(){return Sc===null&&(Sc=bt(vt())),Sc}function gx(t,e){if(!hx.test(t))return t;let r=e.getConfig(`workspace.${t}`);if(r===null||r.length===0)throw new Ie("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 Pi(t){let e=gx(t.member.provider,t.dal),r=e===t.member.provider?t.member:{...t.member,provider:e},n=await yx({member:r});return t.dal.setMemberProviderResolved(t.member.id,e),{sessionid:n.sessionid,provider_resolved:e}}async function yx(t){let e=t.member.provider,r=t.member.sessiondir,n=vc("seed",r,e);try{let s=await gc({provider:e,cwd:r,registry:T_()});if(!s.success)throw Ex(s.error,n);if(!s.sessionId)throw new Ie("parse",0,"",n);return{sessionid:s.sessionId}}catch(s){throw s instanceof Ie?s:kc(s,n)}}async function b_(t){return wx(t)}async function wx(t){let e=T_(),r=vc("tokens",t.sessionid,"unresolved"),n;try{let i=await e.resolveSession(t.sessionid);if(!i)throw new Ie("parse",0,`library: sessionid "${t.sessionid}" matched no registered provider`,r);n=i.provider.name}catch(i){throw i instanceof Ie?i:kc(i,r)}let s=vc("tokens",t.sessionid,n);try{let i=await wc({sessionId:t.sessionid,provider:n,registry:e});return{input_tokens:i.input,cache_tokens:i.cachedInput+i.cacheWriteInput,output_tokens:i.output,total_tokens:i.total}}catch(i){throw i instanceof Ie?i:kc(i,s)}}function vc(t,e,r){return["<library>",t,e,"--provider",r]}function Ex(t,e){let r=t??"";if(/\bENOENT\b/i.test(r))return new Ie("enoent",null,r,e);if(/timed?\s*out/i.test(r))return new Ie("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 Ie("nonzero_exit",Number(n[1]),r,e)}return new Ie("other",null,r,e)}function kc(t,e){return t instanceof Ie?t:t instanceof ye?t.cause?.code==="ENOENT"?new Ie("enoent",null,t.message,e):new Ie("other",null,t.message,e):t instanceof Ut?new Ie("nonzero_exit",t.exitCode??null,t.stderr??t.message,e):t instanceof Wt?new Ie("nonzero_exit",t.rpcCode??null,t.message,e):t instanceof et?new Ie("other",null,t.message,e):new Ie("other",null,t instanceof Error?t.message:String(t),e)}var Ie,Sc,hx,Ic=E(()=>{"use strict";It();Ie=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"}},Sc=null;hx=/^provider[123]$/});function Fi(t){return Buffer.from(t,"utf8").toString("base64url")}function ds(t){return Buffer.from(t,"base64url").toString("utf8")}async function S_(t,e=r=>b_({sessionid:r})){if(process.env.LMCTL_SESSION_SIZE_DISABLED==="1")return{recorded:0,failed:0};let r=0,n=0;for(let s of Tx(t)){let i=s.member.sessionid;if(i!==null)try{let o=await e(i);t.recordSessionSize({team_name:s.team_name,alias:s.member.alias,sessionid:i,...o}),r+=1}catch(o){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:i,error:o instanceof Error?o.message:String(o)})})}catch{}}}return{recorded:r,failed:n}}async function v_(t,e,r){let n=k_(t,e,r);if(n===null||n.member.sessionid===null)throw new Error("session member not found");if(n.member.state!=="idle")throw new cs(r,n.member.state);t.setMemberState(n.member.id,"in_chat","compacting");try{return await ji({sessionid:n.member.sessionid,sessiondir:n.member.sessiondir,prompt:"/compact"}),t.setMemberState(n.member.id,"idle",null),{ok:!0,row:I_(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 Nc(t,e,r){let n=k_(t,e,r);if(n===null)throw new Error("session member not found");let s=await Pi({member:n.member,dal:t});return t.updateTeamMemberSession(n.member.id,s.sessionid),{ok:!0,sessionid:s.sessionid,row:I_(t,e,r)}}function Tx(t){return t.listTeams().flatMap(e=>t.listTeamMembers(e.id).filter(r=>r.sessionid!==null).map(r=>({team_name:e.name,member:r})))}function k_(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 I_(t,e,r){return t.sessionSizeHistory(e,r,1)[0]??null}var cs,Ui=E(()=>{"use strict";Di();Ic();cs=class extends Error{constructor(e,r){super(`member ${e} is currently ${r}; cannot compact while busy`),this.name="MemberBusyError"}}});async function xc(t){let e=t.dal,r=t.nowMs??Date.now(),n=t.thresholdMs??Sx(e),s=r-n,i=e.query(`
|
|
1424
1506
|
SELECT
|
|
1425
1507
|
isess.id AS interactive_session_id,
|
|
1426
1508
|
isess.run_id,
|
|
@@ -1455,7 +1537,7 @@ ${r}`:r}function Ip(t,e){let r=K0({input:t.stdout}),n=new Map,s=(o,a={})=>new Pr
|
|
|
1455
1537
|
SELECT terminal_state, COUNT(*) AS count FROM run GROUP BY terminal_state
|
|
1456
1538
|
`),s=t.query(`
|
|
1457
1539
|
SELECT acknowledged_at, COUNT(*) AS count FROM attention GROUP BY acknowledged_at IS NOT NULL
|
|
1458
|
-
`);return{generated_at:new Date().toISOString(),jobs:r,runs:{active:n.filter(i=>i.terminal_state===null).reduce((i,o)=>i+o.count,0),terminal:n.filter(i=>i.terminal_state!==null).reduce((i,o)=>i+o.count,0),total:Oc(n)},attentions:{unacked:s.filter(i=>i.acknowledged_at===null).reduce((i,o)=>i+o.count,0),total:Oc(s)},projects:Lc(t,"project"),teams:Lc(t,"team"),workflows:Lc(t,"workflow")}}function
|
|
1540
|
+
`);return{generated_at:new Date().toISOString(),jobs:r,runs:{active:n.filter(i=>i.terminal_state===null).reduce((i,o)=>i+o.count,0),terminal:n.filter(i=>i.terminal_state!==null).reduce((i,o)=>i+o.count,0),total:Oc(n)},attentions:{unacked:s.filter(i=>i.acknowledged_at===null).reduce((i,o)=>i+o.count,0),total:Oc(s)},projects:Lc(t,"project"),teams:Lc(t,"team"),workflows:Lc(t,"workflow")}}function Xi(t){return t.listProjects()}function L_(t){return t.listTeams().map(e=>({...e,members:t.listTeamMembers(e.id)}))}function Ji(t){return t.query(`
|
|
1459
1541
|
SELECT w.*
|
|
1460
1542
|
FROM workflow w
|
|
1461
1543
|
JOIN (
|
|
@@ -1574,11 +1656,11 @@ ${r}`:r}function Ip(t,e){let r=K0({input:t.stdout}),n=new Map,s=(o,a={})=>new Pr
|
|
|
1574
1656
|
ON isess.run_id = a.run_id
|
|
1575
1657
|
AND isess.id = (
|
|
1576
1658
|
SELECT MAX(id) FROM interactive_session WHERE run_id = a.run_id
|
|
1577
|
-
)`});var sh={};Ee(sh,{parseApiArgs:()=>G_,readApiClientConfig:()=>fs,runApi:()=>Vx});import{readFileSync as Hx}from"node:fs";import{basename as
|
|
1659
|
+
)`});var sh={};Ee(sh,{parseApiArgs:()=>G_,readApiClientConfig:()=>fs,runApi:()=>Vx});import{readFileSync as Hx}from"node:fs";import{basename as Xx,extname as Jx}from"node:path";async function Vx(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(Kx),0;if(t[0]==="config")return zx(t.slice(1),e);let r=rh(t,"--direct");if(r.rest[0]==="escalations")return Zx(r.rest.slice(1),e,r.present);if(r.rest[0]==="workflows"&&r.rest[1]==="verify"&&to(r.rest.slice(2)))return e.stdout.write(`${rA}
|
|
1578
1660
|
`),0;if(r.rest[0]==="workflows"&&r.rest[1]==="verify")return r.present?(e.stderr.write(`error: --direct is not supported for workflows verify; use the HTTP api route
|
|
1579
1661
|
`),2):YA(r.rest.slice(2),e);if(r.rest[0]==="run"&&r.rest[1]==="where"&&to(r.rest.slice(2)))return e.stdout.write(`${eA}
|
|
1580
1662
|
`),0;if(r.rest[0]==="run"&&r.rest[1]==="timeline"&&to(r.rest.slice(2)))return e.stdout.write(`${tA}
|
|
1581
|
-
`),0;if(r.rest[0]==="run"&&r.rest[1]==="where")return r.present?
|
|
1663
|
+
`),0;if(r.rest[0]==="run"&&r.rest[1]==="where")return r.present?JA(r.rest.slice(2),e):GA(r.rest.slice(2),e);if(r.rest[0]==="run"&&r.rest[1]==="timeline")return r.present?KA(r.rest.slice(2),e):VA(r.rest.slice(2),e);if(r.present)return LA(r.rest,e);let n=G_(t);if(typeof n=="string")return e.stderr.write(`error: ${n}
|
|
1582
1664
|
`),2;let s=jr(e),i=s.baseUrl,o=ur(n.accept,s.token),a=n.body;if(n.upload!==void 0)try{a=dA(n.upload.filePath,n.upload.project)}catch(c){return e.stderr.write(`error: upload failed: ${c instanceof Error?c.message:String(c)}
|
|
1583
1665
|
`),2}else n.body!==void 0&&n.contentType!==void 0?o["Content-Type"]=n.contentType:n.body!==void 0&&(o["Content-Type"]="application/json");let l;try{l=await fetch(new URL(n.path,i),{method:n.method,headers:o,body:a})}catch(c){return e.stderr.write(`error: network failure: ${c instanceof Error?c.message:String(c)}
|
|
1584
1666
|
`),2}if(!l.ok)return e.stderr.write(`error: HTTP ${l.status}: ${await l.text()}
|
|
@@ -1633,44 +1715,44 @@ ${r}`:r}function Ip(t,e){let r=K0({input:t.stdout}),n=new Map,s=(o,a={})=>new Pr
|
|
|
1633
1715
|
`),1;if(!d.ok){let f=await d.text();return e.stderr.write(`error: HTTP ${d.status}: ${f}
|
|
1634
1716
|
`),d.status===400?2:1}let u=await d.json();return r?e.stdout.write(`${JSON.stringify(u,null,2)}
|
|
1635
1717
|
`):e.stdout.write(`ok: attention ${i} acknowledged; step ${u.step_id} resumed (session_status=${String(u.session_status)})
|
|
1636
|
-
`),0}function q_(t,e,r){return t!=="api.token"||r?e:e.length<=8?"***":`${e.slice(0,8)}\u2026(masked; use --show-secrets to reveal)`}function cA(t,e){if(e.length===0)return`${t} value must be non-empty`;if(t==="api.port"){let r=Number(e);if(!Number.isInteger(r)||r<=0||r>65535)return`invalid api.port: ${e}`}if(t==="api.url")try{new URL(e)}catch{return`invalid api.url: ${e}`}if(t===Wi||t===Bi){let r=Number(e);if(!Number.isInteger(r)||r<=0)return`invalid ${t}: ${e}`}return null}function dA(t,e){let r=Hx(t),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),s=new FormData;return s.append("image",new Blob([n],{type:uA(t)}),Jx(t)),e!==void 0&&s.append("project",e),s}function uA(t){switch(Xx(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".heic":return"image/heic";case".pdf":return"application/pdf";default:return"application/octet-stream"}}function fA(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t.id;return typeof e=="number"&&Number.isInteger(e)?e:null}return null}function mA(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api pr <id|list|get>";if(r==="list")return us(n,"--status","/api/submitted-prs","status",e);if(r==="get"){let[s]=n;return s===void 0?"usage: api pr get <id-or-url>":/^\d+$/.test(s)?{method:"GET",path:`/api/submitted-prs/${s}`,accept:"application/json",json:e}:{method:"GET",path:`/api/submitted-prs?pr_url=${encodeURIComponent(s)}`,accept:"application/json",json:e}}return/^\d+$/.test(r)?{method:"GET",path:`/api/submitted-prs/${r}`,accept:"application/json",json:e}:`usage: lmctl api pr <id|list|get>; got: ${r}`}function Y_(t){let e=[],r="json";for(let n of t)n==="--json"?r="json":n==="--text"?r="text":e.push(n);return{args:e,format:r}}function eo(t,e,r){return t.length>0?ne(t[0]):{method:"GET",path:e,accept:r?"application/json":"text/html",json:r}}function us(t,e,r,n,s,i=!1){let o;for(let l=0;l<t.length;l+=1){let c=t[l];if(c!==e)return ne(c);let d=t[++l];if(d===void 0||d.startsWith("--"))return`missing value for ${e}`;if(i&&(!/^\d+$/.test(d)||Number(d)<=0))return`invalid ${e}: ${d}`;o=d}let a=o===void 0?"":`?${n}=${encodeURIComponent(o)}`;return{method:"GET",path:`${r}${a}`,accept:s?"application/json":"text/html",json:s}}function H_(t,e,r,n,s){let i=!1;for(let o of t){if(o!==e)return ne(o);i=!0}return{method:"GET",path:`${r}${i?`?${n}=true`:""}`,accept:s?"application/json":"text/html",json:s}}function pA(t,e,r){if(t.length!==1)return`usage: lmctl api ${r} <id>`;let n=se(t[0],"id");return typeof n=="string"?n:{method:"GET",path:`${e}/${n}`,accept:"application/json",json:!0}}function _A(t,e){let[r,...n]=t;if(r!==void 0&&n.length===0&&r!=="enqueue"&&r!=="run")return pA([r],"/api/jobs","job");if(r==="enqueue"){let s,i,o="manual",a,l,c;for(let u=0;u<n.length;u+=1){let f=n[u],m=n[++u];if(m===void 0||m.startsWith("--"))return`missing value for ${f}`;if(f==="--project")s=m;else if(f==="--project-id"){let p=Number(m);if(!Number.isInteger(p))return`invalid --project-id: ${m}`;i=p}else if(f==="--source")o=m;else if(f==="--payload")a=m;else if(f==="--dedupe-key")l=m;else if(f==="--priority"){let p=Number(m);if(!Number.isInteger(p))return`invalid --priority: ${m}`;c=p}else return ne(f)}if(s===void 0&&i===void 0)return"usage: lmctl api job enqueue (--project NAME | --project-id ID) [--source S] [--payload JSON] [--dedupe-key K] [--priority N]";let d={source:o};return s!==void 0&&(d.project=s),i!==void 0&&(d.project_id=i),a!==void 0&&(d.payload=jc(a)),l!==void 0&&(d.dedupe_key=l),c!==void 0&&(d.priority=c),{method:"POST",path:"/api/jobs",accept:"application/json",json:e,body:JSON.stringify(d)}}if(r==="run"){if(n.length!==1)return"usage: lmctl api job run <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"POST",path:`/api/jobs/${s}/run`,accept:"application/json",json:e}}return"usage: lmctl api job <id|enqueue|run>"}function hA(t,e){let[r,...n]=t;if(r==="list"){let[s,...i]=n;if(s===void 0||s.startsWith("--"))return"usage: lmctl api issues list <project> [--status STATUS] [--severity SEVERITY] [--ai-test-path P]";let o=new URLSearchParams;for(let l=0;l<i.length;l+=1){let c=i[l],d=i[++l];if(d===void 0||d.startsWith("--"))return`missing value for ${c}`;if(c==="--status")o.set("status",d);else if(c==="--severity")o.set("severity",d);else if(c==="--ai-test-path")o.set("ai_test_path",d);else return ne(c)}let a=o.toString();return{method:"GET",path:`/api/projects/${encodeURIComponent(s)}/issues${a.length>0?`?${a}`:""}`,accept:e?"application/json":"text/html",json:e}}if(r==="show"){if(n.length!==1)return"usage: lmctl api issues show <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"GET",path:`/api/issues/${s}`,accept:"application/json",json:e}}return r==="create"?z_(n,e):r==="claim"?Z_(n,e):r==="claim-next"?Q_(n,e):r==="close"?eh(n,e):r==="reopen"?th(n,e):"usage: lmctl api issues <list|show|create|claim|claim-next|close|reopen>"}function z_(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api issues create <project> --title T --body B [--severity S] [--labels JSON] [--ai-test-path P]";let s=new Set(["--title","--body"]),i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0)return`missing value for ${a}`;if(!s.has(a)&&l.startsWith("--"))return`missing value for ${a}`;if(a==="--title")i.title=l;else if(a==="--body")i.body=l;else if(a==="--severity")i.severity=l;else if(a==="--labels")i.labels=jc(l);else if(a==="--ai-test-path")i.ai_test_path=l;else if(a==="--source-run-id"){let c=se(l,"--source-run-id");if(typeof c=="string")return c;i.source_run_id=c}else return ne(a)}return typeof i.title!="string"?"missing value for --title":typeof i.body!="string"?"missing value for --body":{method:"POST",path:`/api/projects/${encodeURIComponent(r)}/issues`,accept:"application/json",json:e,body:JSON.stringify(i)}}function Z_(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues claim <id> --assigned-run-id RUN";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--assigned-run-id"){let c=se(l,"--assigned-run-id");if(typeof c=="string")return c;i.assigned_run_id=c}else return ne(a)}return typeof i.assigned_run_id!="number"?"missing value for --assigned-run-id":{method:"POST",path:`/api/issues/${s}/claim`,accept:"application/json",json:e,body:JSON.stringify(i)}}function Q_(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api issues claim-next <project> --assigned-run-id RUN";let s={};for(let i=0;i<n.length;i+=1){let o=n[i],a=n[++i];if(a===void 0||a.startsWith("--"))return`missing value for ${o}`;if(o==="--assigned-run-id"){let l=se(a,"--assigned-run-id");if(typeof l=="string")return l;s.assigned_run_id=l}else return ne(o)}return typeof s.assigned_run_id!="number"?"missing value for --assigned-run-id":{method:"POST",path:`/api/projects/${encodeURIComponent(r)}/issues/claim-next`,accept:"application/json",json:e,body:JSON.stringify(s)}}function eh(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues close <id> [--commit-hash SHA] [--closed-run-id RUN]";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--commit-hash")i.commit_hash=l;else if(a==="--closed-run-id"){let c=se(l,"--closed-run-id");if(typeof c=="string")return c;i.closed_run_id=c}else return ne(a)}return{method:"POST",path:`/api/issues/${s}/close`,accept:"application/json",json:e,body:JSON.stringify(i)}}function th(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues reopen <id> [--source-run-id RUN]";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--source-run-id"){let c=se(l,"--source-run-id");if(typeof c=="string")return c;i.source_run_id=c}else return ne(a)}return{method:"POST",path:`/api/issues/${s}/reopen`,accept:"application/json",json:e,body:JSON.stringify(i)}}function gA(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api upload <file> [--project NAME] [--json]";let s;for(let i=0;i<n.length;i+=1){let o=n[i];if(o!=="--project")return ne(o);let a=n[++i];if(a===void 0||a.startsWith("--"))return"missing value for --project";s=a}return{method:"POST",path:"/api/uploads",accept:"application/json",json:e,upload:{filePath:r,project:s}}}function yA(t,e){let r,n,s,i;for(let a=0;a<t.length;a+=1){let l=t[a],c=t[++a];if(c===void 0||c.startsWith("--"))return`missing value for ${l}`;if(l==="--workflow")r=c;else if(l==="--workflow-id-override"){let d=Number(c);if(!Number.isInteger(d)||d<=0)return`invalid --workflow-id-override: ${c}`;n=d}else if(l==="--project")s=c;else if(l==="--inputs")try{let d=JSON.parse(c);if(d===null||typeof d!="object"||Array.isArray(d))return"--inputs must be a JSON object";i=d}catch{return"invalid --inputs JSON"}else return ne(l)}if(r===void 0&&n===void 0)return"missing value for --workflow";if(i===void 0)return"missing value for --inputs";let o={source:"api-submit-job",payload:i};return r!==void 0&&(o.workflow=r),n!==void 0&&(o.workflow_id_override=n),s!==void 0&&(o.project=s),{method:"POST",path:"/api/jobs",accept:"application/json",json:e,body:JSON.stringify(o),runAfterSubmit:!0}}function jc(t){try{return JSON.parse(t)}catch{return t}}function wA(t,e){let[r,n]=t;return r!=="show"||n===void 0||t.length!==2?"usage: lmctl api workflow show <name>":{method:"GET",path:`/api/workflows/${encodeURIComponent(n)}`,accept:"application/json",json:e}}function EA(t,e){for(let r of t)if(!(r==="--json"||r==="--text"))return ne(r);return{method:"GET",path:"/api/workflows/verify",accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}function TA(t,e){let[r,n,...s]=t;return r==="workflow"?bA([n,...s].filter(i=>i!==void 0),e):r!=="show"||n===void 0||t.length!==2?"usage: lmctl api project <show|workflow>":{method:"GET",path:`/api/projects/${encodeURIComponent(n)}`,accept:"application/json",json:e}}function bA(t,e){let[r,...n]=t;if(r==="list")return n.length!==1?"usage: lmctl api project workflow list <project>":{method:"GET",path:`/api/projects/${encodeURIComponent(n[0])}/workflows`,accept:e?"application/json":"text/html",json:e};if(r==="show"){if(n.length!==1)return"usage: lmctl api project workflow show <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"GET",path:`/api/projects/workflows/${s}`,accept:e?"application/json":"text/html",json:e}}if(r==="remove"||r==="enable"||r==="disable"){if(n.length!==1)return`usage: lmctl api project workflow ${r} <id>`;let s=se(n[0],"id");if(typeof s=="string")return s;let i=r==="remove"?"DELETE":"POST",o=r==="remove"?"":`/${r}`;return{method:i,path:`/api/projects/workflows/${s}${o}`,accept:"application/json",json:e}}if(r==="add"){let s=SA(n);return typeof s=="string"?s:{method:"POST",path:`/api/projects/${encodeURIComponent(s.project)}/workflows`,accept:"application/json",json:e,body:JSON.stringify(s.body)}}return"usage: lmctl api project workflow <add|list|show|remove|enable|disable>"}function SA(t){let[e,r,...n]=t;if(e===void 0||r===void 0)return"usage: lmctl api project workflow add <project> <workflow> [--condition JEXL] [--params JSON] [--priority N]";let s={workflow:r};for(let i=0;i<n.length;i+=1){let o=n[i],a=n[++i];if(a===void 0||a.startsWith("--"))return`missing value for ${o}`;if(o==="--condition")s.condition=a;else if(o==="--params")s.params=jc(a);else if(o==="--priority"){let l=Number(a);if(!Number.isInteger(l))return`invalid --priority: ${a}`;s.priority=l}else return ne(o)}return{project:e,body:s}}function vA(t,e){if(t[0]!=="get")return"usage: lmctl api artifact get --run R --kind K [--raw]";let r,n,s=!1;for(let o=1;o<t.length;o+=1){let a=t[o];if(a==="--raw"){s=!0;continue}let l=t[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--run"){let c=se(l,"run");if(typeof c=="string")return c;r=c}else if(a==="--kind")n=l;else return ne(a)}return r===void 0||n===void 0?"usage: lmctl api artifact get --run R --kind K [--raw]":{method:"GET",path:`/api/runs/${r}/artifacts/${encodeURIComponent(n)}${s?"?raw=true":""}`,accept:s?"text/plain":"application/json",json:!s&&e}}function kA(t,e){if(t[0]!=="ack"||t.length!==2)return"usage: lmctl api attention ack <id>";let r=se(t[1],"id");return typeof r=="string"?r:{method:"POST",path:`/api/attentions/${r}/ack`,accept:e?"application/json":"text/html",json:e}}function IA(t,e){return t.length!==1||t[0]!=="run-throughput"?"usage: lmctl api stats run-throughput":{method:"GET",path:"/api/stats/run-throughput",accept:e?"application/json":"text/html",json:e}}function NA(t,e){return t.length!==1||t[0]!=="state"&&t[0]!=="cycle"?"usage: lmctl api daemon <state|cycle>":{method:t[0]==="cycle"?"POST":"GET",path:t[0]==="cycle"?"/api/daemon/cycle":"/api/daemon/state",accept:e?"application/json":"text/html",json:e}}function xA(t,e){return t.length!==1||t[0]!=="state"&&t[0]!=="scan"?"usage: lmctl api intake <state|scan>":{method:t[0]==="scan"?"POST":"GET",path:t[0]==="scan"?"/api/intake/scan":"/api/intake/state",accept:e?"application/json":"text/html",json:e}}function AA(t,e){let r=t[0];if(r==="list")return t.length!==1?"usage: lmctl api session list":{method:"GET",path:"/api/sessions",accept:e?"application/json":"text/html",json:e};if(r==="history"||r==="compact"||r==="refresh"){if(t.length!==3)return`usage: lmctl api session ${r} <team_name> <alias>`;let n=Fi(t[1]),s=encodeURIComponent(t[2]);return{method:r==="history"?"GET":"POST",path:`/api/sessions/${n}/${s}/${r}`,accept:e?"application/json":"text/html",json:e}}return"usage: lmctl api session <list|history|compact|refresh>"}function RA(t,e){let[r,n,s,i]=t;if(r!==void 0&&/^\d+$/.test(r)&&n===void 0){let o=se(r,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}`,accept:"application/json",json:e!=="text"}}if(r==="resume"){if(n===void 0)return"usage: lmctl api run resume <run_id> --outcome <value>";let o=se(n,"run_id");if(typeof o=="string")return o;let a;for(let l=2;l<t.length;l+=1){let c=t[l];if(c!=="--outcome")return ne(c);let d=t[++l];if(d===void 0||d.startsWith("--"))return"missing value for --outcome";a=d}return a===void 0?"missing value for --outcome":{method:"POST",path:`/api/runs/${o}/resume?outcome=${encodeURIComponent(a)}`,accept:e==="text"?"text/html":"application/json",json:e!=="text"}}if(r==="get"){if(n===void 0||s!==void 0)return"usage: lmctl api run get <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}`,accept:"application/json",json:e!=="text"}}if(r==="step"||r==="transcript"||r==="messages"){if(n===void 0||s===void 0||i!==void 0)return`usage: lmctl api run ${r} <run_id> <step_id>`;let o=se(n,"run_id");if(typeof o=="string")return o;let a=se(s,"step_id");if(typeof a=="string")return a;let l=r==="step"?"":`/${r}`,c=r==="transcript"&&e==="text";return{method:"GET",path:`/api/runs/${o}/steps/${a}${l}`,accept:c?"text/plain":"application/json",json:!c}}if(r==="artifacts"){if(n===void 0)return"usage: lmctl api run artifacts <run_id> [--kind K]";let o=se(n,"run_id");if(typeof o=="string")return o;let a;for(let c=2;c<t.length;c+=1){let d=t[c];if(d!=="--kind")return ne(d);let u=t[++c];if(u===void 0)return"missing value for --kind";a=u}let l=a===void 0?"":`?kind=${encodeURIComponent(a)}`;return{method:"GET",path:`/api/runs/${o}/artifacts${l}`,accept:"application/json",json:e!=="text"}}if(r==="where"){if(n===void 0||s!==void 0)return"usage: lmctl api run where <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}/where`,accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}if(r==="timeline"){if(n===void 0||s!==void 0)return"usage: lmctl api run timeline <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}/timeline`,accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}return"usage: lmctl api run <id|get|step|transcript|messages|resume|artifacts|where|timeline>"}function se(t,e){return t===void 0||t.startsWith("--")?`missing value for ${e}`:!/^\d+$/.test(t)||Number(t)<=0?`invalid ${e}: ${t}`:Number(t)}function ne(t){return t.startsWith("--")?`unknown flag: ${t}`:`unknown argument: ${t}`}function rh(t,e){let r=[],n=!1;for(let s of t){if(s===e){n=!0;continue}r.push(s)}return{rest:r,present:n}}async function LA(t,e){let r=Y_(t);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
1718
|
+
`),0}function q_(t,e,r){return t!=="api.token"||r?e:e.length<=8?"***":`${e.slice(0,8)}\u2026(masked; use --show-secrets to reveal)`}function cA(t,e){if(e.length===0)return`${t} value must be non-empty`;if(t==="api.port"){let r=Number(e);if(!Number.isInteger(r)||r<=0||r>65535)return`invalid api.port: ${e}`}if(t==="api.url")try{new URL(e)}catch{return`invalid api.url: ${e}`}if(t===Wi||t===Bi){let r=Number(e);if(!Number.isInteger(r)||r<=0)return`invalid ${t}: ${e}`}return null}function dA(t,e){let r=Hx(t),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),s=new FormData;return s.append("image",new Blob([n],{type:uA(t)}),Xx(t)),e!==void 0&&s.append("project",e),s}function uA(t){switch(Jx(t).toLowerCase()){case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".webp":return"image/webp";case".heic":return"image/heic";case".pdf":return"application/pdf";default:return"application/octet-stream"}}function fA(t){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let e=t.id;return typeof e=="number"&&Number.isInteger(e)?e:null}return null}function mA(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api pr <id|list|get>";if(r==="list")return us(n,"--status","/api/submitted-prs","status",e);if(r==="get"){let[s]=n;return s===void 0?"usage: api pr get <id-or-url>":/^\d+$/.test(s)?{method:"GET",path:`/api/submitted-prs/${s}`,accept:"application/json",json:e}:{method:"GET",path:`/api/submitted-prs?pr_url=${encodeURIComponent(s)}`,accept:"application/json",json:e}}return/^\d+$/.test(r)?{method:"GET",path:`/api/submitted-prs/${r}`,accept:"application/json",json:e}:`usage: lmctl api pr <id|list|get>; got: ${r}`}function Y_(t){let e=[],r="json";for(let n of t)n==="--json"?r="json":n==="--text"?r="text":e.push(n);return{args:e,format:r}}function eo(t,e,r){return t.length>0?ne(t[0]):{method:"GET",path:e,accept:r?"application/json":"text/html",json:r}}function us(t,e,r,n,s,i=!1){let o;for(let l=0;l<t.length;l+=1){let c=t[l];if(c!==e)return ne(c);let d=t[++l];if(d===void 0||d.startsWith("--"))return`missing value for ${e}`;if(i&&(!/^\d+$/.test(d)||Number(d)<=0))return`invalid ${e}: ${d}`;o=d}let a=o===void 0?"":`?${n}=${encodeURIComponent(o)}`;return{method:"GET",path:`${r}${a}`,accept:s?"application/json":"text/html",json:s}}function H_(t,e,r,n,s){let i=!1;for(let o of t){if(o!==e)return ne(o);i=!0}return{method:"GET",path:`${r}${i?`?${n}=true`:""}`,accept:s?"application/json":"text/html",json:s}}function pA(t,e,r){if(t.length!==1)return`usage: lmctl api ${r} <id>`;let n=se(t[0],"id");return typeof n=="string"?n:{method:"GET",path:`${e}/${n}`,accept:"application/json",json:!0}}function _A(t,e){let[r,...n]=t;if(r!==void 0&&n.length===0&&r!=="enqueue"&&r!=="run")return pA([r],"/api/jobs","job");if(r==="enqueue"){let s,i,o="manual",a,l,c;for(let u=0;u<n.length;u+=1){let f=n[u],m=n[++u];if(m===void 0||m.startsWith("--"))return`missing value for ${f}`;if(f==="--project")s=m;else if(f==="--project-id"){let p=Number(m);if(!Number.isInteger(p))return`invalid --project-id: ${m}`;i=p}else if(f==="--source")o=m;else if(f==="--payload")a=m;else if(f==="--dedupe-key")l=m;else if(f==="--priority"){let p=Number(m);if(!Number.isInteger(p))return`invalid --priority: ${m}`;c=p}else return ne(f)}if(s===void 0&&i===void 0)return"usage: lmctl api job enqueue (--project NAME | --project-id ID) [--source S] [--payload JSON] [--dedupe-key K] [--priority N]";let d={source:o};return s!==void 0&&(d.project=s),i!==void 0&&(d.project_id=i),a!==void 0&&(d.payload=jc(a)),l!==void 0&&(d.dedupe_key=l),c!==void 0&&(d.priority=c),{method:"POST",path:"/api/jobs",accept:"application/json",json:e,body:JSON.stringify(d)}}if(r==="run"){if(n.length!==1)return"usage: lmctl api job run <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"POST",path:`/api/jobs/${s}/run`,accept:"application/json",json:e}}return"usage: lmctl api job <id|enqueue|run>"}function hA(t,e){let[r,...n]=t;if(r==="list"){let[s,...i]=n;if(s===void 0||s.startsWith("--"))return"usage: lmctl api issues list <project> [--status STATUS] [--severity SEVERITY] [--ai-test-path P]";let o=new URLSearchParams;for(let l=0;l<i.length;l+=1){let c=i[l],d=i[++l];if(d===void 0||d.startsWith("--"))return`missing value for ${c}`;if(c==="--status")o.set("status",d);else if(c==="--severity")o.set("severity",d);else if(c==="--ai-test-path")o.set("ai_test_path",d);else return ne(c)}let a=o.toString();return{method:"GET",path:`/api/projects/${encodeURIComponent(s)}/issues${a.length>0?`?${a}`:""}`,accept:e?"application/json":"text/html",json:e}}if(r==="show"){if(n.length!==1)return"usage: lmctl api issues show <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"GET",path:`/api/issues/${s}`,accept:"application/json",json:e}}return r==="create"?z_(n,e):r==="claim"?Z_(n,e):r==="claim-next"?Q_(n,e):r==="close"?eh(n,e):r==="reopen"?th(n,e):"usage: lmctl api issues <list|show|create|claim|claim-next|close|reopen>"}function z_(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api issues create <project> --title T --body B [--severity S] [--labels JSON] [--ai-test-path P]";let s=new Set(["--title","--body"]),i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0)return`missing value for ${a}`;if(!s.has(a)&&l.startsWith("--"))return`missing value for ${a}`;if(a==="--title")i.title=l;else if(a==="--body")i.body=l;else if(a==="--severity")i.severity=l;else if(a==="--labels")i.labels=jc(l);else if(a==="--ai-test-path")i.ai_test_path=l;else if(a==="--source-run-id"){let c=se(l,"--source-run-id");if(typeof c=="string")return c;i.source_run_id=c}else return ne(a)}return typeof i.title!="string"?"missing value for --title":typeof i.body!="string"?"missing value for --body":{method:"POST",path:`/api/projects/${encodeURIComponent(r)}/issues`,accept:"application/json",json:e,body:JSON.stringify(i)}}function Z_(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues claim <id> --assigned-run-id RUN";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--assigned-run-id"){let c=se(l,"--assigned-run-id");if(typeof c=="string")return c;i.assigned_run_id=c}else return ne(a)}return typeof i.assigned_run_id!="number"?"missing value for --assigned-run-id":{method:"POST",path:`/api/issues/${s}/claim`,accept:"application/json",json:e,body:JSON.stringify(i)}}function Q_(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api issues claim-next <project> --assigned-run-id RUN";let s={};for(let i=0;i<n.length;i+=1){let o=n[i],a=n[++i];if(a===void 0||a.startsWith("--"))return`missing value for ${o}`;if(o==="--assigned-run-id"){let l=se(a,"--assigned-run-id");if(typeof l=="string")return l;s.assigned_run_id=l}else return ne(o)}return typeof s.assigned_run_id!="number"?"missing value for --assigned-run-id":{method:"POST",path:`/api/projects/${encodeURIComponent(r)}/issues/claim-next`,accept:"application/json",json:e,body:JSON.stringify(s)}}function eh(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues close <id> [--commit-hash SHA] [--closed-run-id RUN]";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--commit-hash")i.commit_hash=l;else if(a==="--closed-run-id"){let c=se(l,"--closed-run-id");if(typeof c=="string")return c;i.closed_run_id=c}else return ne(a)}return{method:"POST",path:`/api/issues/${s}/close`,accept:"application/json",json:e,body:JSON.stringify(i)}}function th(t,e){let[r,...n]=t;if(r===void 0)return"usage: lmctl api issues reopen <id> [--source-run-id RUN]";let s=se(r,"id");if(typeof s=="string")return s;let i={};for(let o=0;o<n.length;o+=1){let a=n[o],l=n[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--source-run-id"){let c=se(l,"--source-run-id");if(typeof c=="string")return c;i.source_run_id=c}else return ne(a)}return{method:"POST",path:`/api/issues/${s}/reopen`,accept:"application/json",json:e,body:JSON.stringify(i)}}function gA(t,e){let[r,...n]=t;if(r===void 0||r.startsWith("--"))return"usage: lmctl api upload <file> [--project NAME] [--json]";let s;for(let i=0;i<n.length;i+=1){let o=n[i];if(o!=="--project")return ne(o);let a=n[++i];if(a===void 0||a.startsWith("--"))return"missing value for --project";s=a}return{method:"POST",path:"/api/uploads",accept:"application/json",json:e,upload:{filePath:r,project:s}}}function yA(t,e){let r,n,s,i;for(let a=0;a<t.length;a+=1){let l=t[a],c=t[++a];if(c===void 0||c.startsWith("--"))return`missing value for ${l}`;if(l==="--workflow")r=c;else if(l==="--workflow-id-override"){let d=Number(c);if(!Number.isInteger(d)||d<=0)return`invalid --workflow-id-override: ${c}`;n=d}else if(l==="--project")s=c;else if(l==="--inputs")try{let d=JSON.parse(c);if(d===null||typeof d!="object"||Array.isArray(d))return"--inputs must be a JSON object";i=d}catch{return"invalid --inputs JSON"}else return ne(l)}if(r===void 0&&n===void 0)return"missing value for --workflow";if(i===void 0)return"missing value for --inputs";let o={source:"api-submit-job",payload:i};return r!==void 0&&(o.workflow=r),n!==void 0&&(o.workflow_id_override=n),s!==void 0&&(o.project=s),{method:"POST",path:"/api/jobs",accept:"application/json",json:e,body:JSON.stringify(o),runAfterSubmit:!0}}function jc(t){try{return JSON.parse(t)}catch{return t}}function wA(t,e){let[r,n]=t;return r!=="show"||n===void 0||t.length!==2?"usage: lmctl api workflow show <name>":{method:"GET",path:`/api/workflows/${encodeURIComponent(n)}`,accept:"application/json",json:e}}function EA(t,e){for(let r of t)if(!(r==="--json"||r==="--text"))return ne(r);return{method:"GET",path:"/api/workflows/verify",accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}function TA(t,e){let[r,n,...s]=t;return r==="workflow"?bA([n,...s].filter(i=>i!==void 0),e):r!=="show"||n===void 0||t.length!==2?"usage: lmctl api project <show|workflow>":{method:"GET",path:`/api/projects/${encodeURIComponent(n)}`,accept:"application/json",json:e}}function bA(t,e){let[r,...n]=t;if(r==="list")return n.length!==1?"usage: lmctl api project workflow list <project>":{method:"GET",path:`/api/projects/${encodeURIComponent(n[0])}/workflows`,accept:e?"application/json":"text/html",json:e};if(r==="show"){if(n.length!==1)return"usage: lmctl api project workflow show <id>";let s=se(n[0],"id");return typeof s=="string"?s:{method:"GET",path:`/api/projects/workflows/${s}`,accept:e?"application/json":"text/html",json:e}}if(r==="remove"||r==="enable"||r==="disable"){if(n.length!==1)return`usage: lmctl api project workflow ${r} <id>`;let s=se(n[0],"id");if(typeof s=="string")return s;let i=r==="remove"?"DELETE":"POST",o=r==="remove"?"":`/${r}`;return{method:i,path:`/api/projects/workflows/${s}${o}`,accept:"application/json",json:e}}if(r==="add"){let s=SA(n);return typeof s=="string"?s:{method:"POST",path:`/api/projects/${encodeURIComponent(s.project)}/workflows`,accept:"application/json",json:e,body:JSON.stringify(s.body)}}return"usage: lmctl api project workflow <add|list|show|remove|enable|disable>"}function SA(t){let[e,r,...n]=t;if(e===void 0||r===void 0)return"usage: lmctl api project workflow add <project> <workflow> [--condition JEXL] [--params JSON] [--priority N]";let s={workflow:r};for(let i=0;i<n.length;i+=1){let o=n[i],a=n[++i];if(a===void 0||a.startsWith("--"))return`missing value for ${o}`;if(o==="--condition")s.condition=a;else if(o==="--params")s.params=jc(a);else if(o==="--priority"){let l=Number(a);if(!Number.isInteger(l))return`invalid --priority: ${a}`;s.priority=l}else return ne(o)}return{project:e,body:s}}function vA(t,e){if(t[0]!=="get")return"usage: lmctl api artifact get --run R --kind K [--raw]";let r,n,s=!1;for(let o=1;o<t.length;o+=1){let a=t[o];if(a==="--raw"){s=!0;continue}let l=t[++o];if(l===void 0||l.startsWith("--"))return`missing value for ${a}`;if(a==="--run"){let c=se(l,"run");if(typeof c=="string")return c;r=c}else if(a==="--kind")n=l;else return ne(a)}return r===void 0||n===void 0?"usage: lmctl api artifact get --run R --kind K [--raw]":{method:"GET",path:`/api/runs/${r}/artifacts/${encodeURIComponent(n)}${s?"?raw=true":""}`,accept:s?"text/plain":"application/json",json:!s&&e}}function kA(t,e){if(t[0]!=="ack"||t.length!==2)return"usage: lmctl api attention ack <id>";let r=se(t[1],"id");return typeof r=="string"?r:{method:"POST",path:`/api/attentions/${r}/ack`,accept:e?"application/json":"text/html",json:e}}function IA(t,e){return t.length!==1||t[0]!=="run-throughput"?"usage: lmctl api stats run-throughput":{method:"GET",path:"/api/stats/run-throughput",accept:e?"application/json":"text/html",json:e}}function NA(t,e){return t.length!==1||t[0]!=="state"&&t[0]!=="cycle"?"usage: lmctl api daemon <state|cycle>":{method:t[0]==="cycle"?"POST":"GET",path:t[0]==="cycle"?"/api/daemon/cycle":"/api/daemon/state",accept:e?"application/json":"text/html",json:e}}function xA(t,e){return t.length!==1||t[0]!=="state"&&t[0]!=="scan"?"usage: lmctl api intake <state|scan>":{method:t[0]==="scan"?"POST":"GET",path:t[0]==="scan"?"/api/intake/scan":"/api/intake/state",accept:e?"application/json":"text/html",json:e}}function AA(t,e){let r=t[0];if(r==="list")return t.length!==1?"usage: lmctl api session list":{method:"GET",path:"/api/sessions",accept:e?"application/json":"text/html",json:e};if(r==="history"||r==="compact"||r==="refresh"){if(t.length!==3)return`usage: lmctl api session ${r} <team_name> <alias>`;let n=Fi(t[1]),s=encodeURIComponent(t[2]);return{method:r==="history"?"GET":"POST",path:`/api/sessions/${n}/${s}/${r}`,accept:e?"application/json":"text/html",json:e}}return"usage: lmctl api session <list|history|compact|refresh>"}function RA(t,e){let[r,n,s,i]=t;if(r!==void 0&&/^\d+$/.test(r)&&n===void 0){let o=se(r,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}`,accept:"application/json",json:e!=="text"}}if(r==="resume"){if(n===void 0)return"usage: lmctl api run resume <run_id> --outcome <value>";let o=se(n,"run_id");if(typeof o=="string")return o;let a;for(let l=2;l<t.length;l+=1){let c=t[l];if(c!=="--outcome")return ne(c);let d=t[++l];if(d===void 0||d.startsWith("--"))return"missing value for --outcome";a=d}return a===void 0?"missing value for --outcome":{method:"POST",path:`/api/runs/${o}/resume?outcome=${encodeURIComponent(a)}`,accept:e==="text"?"text/html":"application/json",json:e!=="text"}}if(r==="get"){if(n===void 0||s!==void 0)return"usage: lmctl api run get <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}`,accept:"application/json",json:e!=="text"}}if(r==="step"||r==="transcript"||r==="messages"){if(n===void 0||s===void 0||i!==void 0)return`usage: lmctl api run ${r} <run_id> <step_id>`;let o=se(n,"run_id");if(typeof o=="string")return o;let a=se(s,"step_id");if(typeof a=="string")return a;let l=r==="step"?"":`/${r}`,c=r==="transcript"&&e==="text";return{method:"GET",path:`/api/runs/${o}/steps/${a}${l}`,accept:c?"text/plain":"application/json",json:!c}}if(r==="artifacts"){if(n===void 0)return"usage: lmctl api run artifacts <run_id> [--kind K]";let o=se(n,"run_id");if(typeof o=="string")return o;let a;for(let c=2;c<t.length;c+=1){let d=t[c];if(d!=="--kind")return ne(d);let u=t[++c];if(u===void 0)return"missing value for --kind";a=u}let l=a===void 0?"":`?kind=${encodeURIComponent(a)}`;return{method:"GET",path:`/api/runs/${o}/artifacts${l}`,accept:"application/json",json:e!=="text"}}if(r==="where"){if(n===void 0||s!==void 0)return"usage: lmctl api run where <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}/where`,accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}if(r==="timeline"){if(n===void 0||s!==void 0)return"usage: lmctl api run timeline <run_id>";let o=se(n,"run_id");return typeof o=="string"?o:{method:"GET",path:`/api/runs/${o}/timeline`,accept:e==="text"?"text/plain":"application/json",json:e!=="text"}}return"usage: lmctl api run <id|get|step|transcript|messages|resume|artifacts|where|timeline>"}function se(t,e){return t===void 0||t.startsWith("--")?`missing value for ${e}`:!/^\d+$/.test(t)||Number(t)<=0?`invalid ${e}: ${t}`:Number(t)}function ne(t){return t.startsWith("--")?`unknown flag: ${t}`:`unknown argument: ${t}`}function rh(t,e){let r=[],n=!1;for(let s of t){if(s===e){n=!0;continue}r.push(s)}return{rest:r,present:n}}async function LA(t,e){let r=Y_(t);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
1637
1719
|
`),2;let n=r.args,s=r.format!=="text",[i,...o]=n;if(i===void 0)return e.stderr.write(`error: --direct requires a subcommand (issues|status|projects|workflows|runs|attentions)
|
|
1638
1720
|
`),2;let a=e.dal===void 0,l=e.dal??ke({path:Z()});try{if(i==="issues"){let[c,...d]=o;return c===void 0?(e.stderr.write(`error: --direct issues requires a subcommand (list|show|create|claim|claim-next|close|reopen)
|
|
1639
1721
|
`),2):c==="create"?OA(l,d,e,s):c==="claim"?$A(l,d,e,s):c==="claim-next"?CA(l,d,e,s):c==="close"?MA(l,d,e,s):c==="reopen"?jA(l,d,e,s):c==="list"?UA(l,d,e,s):c==="show"?WA(l,d,e,s):(e.stderr.write(`error: --direct does not support: issues ${c} (supported: list, show, create, claim, claim-next, close, reopen)
|
|
1640
|
-
`),2)}return i==="status"?BA(l,o,e,s):i==="projects"?qA(l,o,e,s):i==="workflows"?HA(l,o,e,s):i==="runs"?
|
|
1722
|
+
`),2)}return i==="status"?BA(l,o,e,s):i==="projects"?qA(l,o,e,s):i==="workflows"?HA(l,o,e,s):i==="runs"?XA(l,o,e,s):i==="attentions"||i==="attention"?zA(l,o,e,s):i==="escalations"?nh(l,o,e):(e.stderr.write(`error: --direct is not supported for: ${i} (supported: issues, status, projects, workflows, runs, attentions, escalations, run where, run timeline)
|
|
1641
1723
|
`),2)}catch(c){return e.stderr.write(`error: ${c instanceof Error?c.message:String(c)}
|
|
1642
|
-
`),1}finally{a&&l.close()}}function
|
|
1724
|
+
`),1}finally{a&&l.close()}}function Je(t,e,r){t.stdout.write(`${r?JSON.stringify(e,null,2):JSON.stringify(e)}
|
|
1643
1725
|
`)}function OA(t,e,r,n){let s=z_(e,!0);if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1644
1726
|
`),2;let i=decodeURIComponent(s.path.replace(/^\/api\/projects\//,"").replace(/\/issues$/,"")),o=t.findProjectByName(i);if(o===null)return r.stderr.write(`error: project not found: ${i}
|
|
1645
1727
|
`),1;let a=JSON.parse(s.body),l=DA(a.severity);if(typeof l=="object"&&l!==null&&"error"in l)return r.stderr.write(`error: ${l.error}
|
|
1646
1728
|
`),2;let c=PA(a.labels);if(typeof c=="string"&&c.startsWith("error:"))return r.stderr.write(`error: ${c.slice(6)}
|
|
1647
|
-
`),2;let d=t.createIssue({project_id:o.id,title:a.title,body:a.body,...l!==void 0?{severity:l}:{},labels:c,ai_test_path:typeof a.ai_test_path=="string"?a.ai_test_path:null,source_run_id:typeof a.source_run_id=="number"?a.source_run_id:null});return
|
|
1729
|
+
`),2;let d=t.createIssue({project_id:o.id,title:a.title,body:a.body,...l!==void 0?{severity:l}:{},labels:c,ai_test_path:typeof a.ai_test_path=="string"?a.ai_test_path:null,source_run_id:typeof a.source_run_id=="number"?a.source_run_id:null});return Je(r,d,n),0}function $A(t,e,r,n){let s=Z_(e,!0);if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1648
1730
|
`),2;let i=Number(s.path.match(/\/api\/issues\/(\d+)\/claim$/)[1]),o=JSON.parse(s.body),a=t.getIssue(i);if(a===null)return r.stderr.write(`error: issue not found: ${i}
|
|
1649
1731
|
`),1;let l=t.claimIssue(i,o.assigned_run_id);return l===null?(r.stderr.write(`error: issue ${i} is not in a claimable state (status=${a.status})
|
|
1650
|
-
`),1):(
|
|
1732
|
+
`),1):(Je(r,l,n),0)}function CA(t,e,r,n){let s=Q_(e,!0);if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1651
1733
|
`),2;let i=decodeURIComponent(s.path.replace(/^\/api\/projects\//,"").replace(/\/issues\/claim-next$/,"")),o=t.findProjectByName(i);if(o===null)return r.stderr.write(`error: project not found: ${i}
|
|
1652
|
-
`),1;let a=JSON.parse(s.body),l=t.claimNextIssue(o.id,a.assigned_run_id);return l===null?(
|
|
1734
|
+
`),1;let a=JSON.parse(s.body),l=t.claimNextIssue(o.id,a.assigned_run_id);return l===null?(Je(r,{status:"queue_empty"},n),1):(Je(r,l,n),0)}function MA(t,e,r,n){let s=eh(e,!0);if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1653
1735
|
`),2;let i=Number(s.path.match(/\/api\/issues\/(\d+)\/close$/)[1]),o=JSON.parse(s.body),a=t.getIssue(i);if(a===null)return r.stderr.write(`error: issue not found: ${i}
|
|
1654
1736
|
`),1;let l=typeof o.closed_run_id=="number"?o.closed_run_id:a.assigned_run_id;if(l===null)return r.stderr.write(`error: missing closed_run_id
|
|
1655
|
-
`),2;let c=t.closeIssue(i,l,typeof o.commit_hash=="string"?o.commit_hash:null);return
|
|
1737
|
+
`),2;let c=t.closeIssue(i,l,typeof o.commit_hash=="string"?o.commit_hash:null);return Je(r,c,n),0}function jA(t,e,r,n){let s=th(e,!0);if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1656
1738
|
`),2;let i=Number(s.path.match(/\/api\/issues\/(\d+)\/reopen$/)[1]),o=JSON.parse(s.body),a=t.getIssue(i);if(a===null)return r.stderr.write(`error: issue not found: ${i}
|
|
1657
1739
|
`),1;let l=typeof o.source_run_id=="number"?o.source_run_id:a.closed_run_id??a.source_run_id;if(l===null)return r.stderr.write(`error: missing source_run_id
|
|
1658
|
-
`),2;let c=t.reopenIssue(i,l);return
|
|
1740
|
+
`),2;let c=t.reopenIssue(i,l);return Je(r,c,n),0}function DA(t){if(t!=null)return typeof t=="string"&&J_.includes(t)?t:{error:`invalid severity: ${String(t)}`}}function PA(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 UA(t,e,r,n){let[s,...i]=e;if(s===void 0||s.startsWith("--"))return r.stderr.write(`error: usage: lmctl api --direct issues list <project> [--status STATUS] [--severity SEVERITY] [--ai-test-path P]
|
|
1659
1741
|
`),2;let o,a,l;for(let u=0;u<i.length;u+=1){let f=i[u],m=i[++u];if(m===void 0||m.startsWith("--"))return r.stderr.write(`error: missing value for ${f}
|
|
1660
|
-
`),2;if(f==="--status"){let p=
|
|
1661
|
-
`),2;o=p}else if(f==="--severity"){let p=
|
|
1742
|
+
`),2;if(f==="--status"){let p=X_(m,FA);if(typeof p=="string")return r.stderr.write(`error: ${p}
|
|
1743
|
+
`),2;o=p}else if(f==="--severity"){let p=X_(m,J_);if(typeof p=="string")return r.stderr.write(`error: ${p}
|
|
1662
1744
|
`),2;a=p}else if(f==="--ai-test-path")l=m;else return r.stderr.write(`error: ${ne(f)}
|
|
1663
1745
|
`),2}let c=t.findProjectByName(s);if(c===null)return r.stderr.write(`error: project not found: ${s}
|
|
1664
|
-
`),1;let d=t.listIssues(c.id,{...o!==void 0?{status:o}:{},...a!==void 0?{severity:a}:{},...l!==void 0?{ai_test_path:l}:{}});return
|
|
1746
|
+
`),1;let d=t.listIssues(c.id,{...o!==void 0?{status:o}:{},...a!==void 0?{severity:a}:{},...l!==void 0?{ai_test_path:l}:{}});return Je(r,d,n),0}function WA(t,e,r,n){if(e.length!==1)return r.stderr.write(`error: usage: lmctl api --direct issues show <id>
|
|
1665
1747
|
`),2;let s=se(e[0],"id");if(typeof s=="string")return r.stderr.write(`error: ${s}
|
|
1666
1748
|
`),2;let i=t.getIssue(s);return i===null?(r.stderr.write(`error: issue not found: ${s}
|
|
1667
|
-
`),1):(
|
|
1668
|
-
`),2):(
|
|
1669
|
-
`),2):(
|
|
1670
|
-
`),2):(
|
|
1749
|
+
`),1):(Je(r,i,n),0)}function BA(t,e,r,n){return e.length>0?(r.stderr.write(`error: ${ne(e[0])}
|
|
1750
|
+
`),2):(Je(r,Hi(t),n),0)}function qA(t,e,r,n){return e.length>0?(r.stderr.write(`error: ${ne(e[0])}
|
|
1751
|
+
`),2):(Je(r,Xi(t),n),0)}function HA(t,e,r,n){return e.length>0?(r.stderr.write(`error: ${ne(e[0])}
|
|
1752
|
+
`),2):(Je(r,Ji(t),n),0)}function XA(t,e,r,n){let s;for(let i=0;i<e.length;i+=1){let o=e[i],a=e[++i];if(a===void 0||a.startsWith("--"))return r.stderr.write(`error: missing value for ${o}
|
|
1671
1753
|
`),2;if(o==="--limit"){if(!/^\d+$/.test(a)||Number(a)<=0)return r.stderr.write(`error: invalid --limit: ${a}
|
|
1672
1754
|
`),2;s=Number(a)}else return r.stderr.write(`error: ${ne(o)}
|
|
1673
|
-
`),2}return
|
|
1755
|
+
`),2}return Je(r,cn(t,s!==void 0?{limit:s}:{}),n),0}function JA(t,e){let[r,...n]=t;if(r===void 0)return e.stderr.write(`error: usage: lmctl api --direct run where <run_id> [--json]
|
|
1674
1756
|
`),2;if(!/^\d+$/.test(r)||Number(r)<=0)return e.stderr.write(`error: invalid run_id: ${r}
|
|
1675
1757
|
`),2;let s=!1;for(let a of n){if(a==="--json"){s=!0;continue}return e.stderr.write(`error: ${ne(a)}
|
|
1676
1758
|
`),2}let i=e.dal===void 0,o=e.dal??ke({path:Z()});try{let a=dn(o,Number(r));return a===null?(e.stderr.write(`error: run not found: ${r}
|
|
@@ -1700,7 +1782,7 @@ ${r}`:r}function Ip(t,e){let r=K0({input:t.stdout}),n=new Map,s=(o,a={})=>new Pr
|
|
|
1700
1782
|
`):(e.stdout.write(await o.text()),o.headers.get("content-type")?.includes("text/plain")||e.stdout.write(`
|
|
1701
1783
|
`)),0):(e.stderr.write(`error: HTTP ${o.status}: ${await o.text()}
|
|
1702
1784
|
`),o.status===400?2:1)}function zA(t,e,r,n){let s=!1;for(let i of e){if(i==="--unacked"){s=!0;continue}return r.stderr.write(`error: ${ne(i)}
|
|
1703
|
-
`),2}return
|
|
1785
|
+
`),2}return Je(r,dr(t,{unacked:s}),n),0}function nh(t,e,r){let[n,...s]=e;if(n===void 0)return r.stderr.write(`error: --direct escalations requires a subcommand (list|show|respond)
|
|
1704
1786
|
`),2;if(n==="list"){let i=K_(s);if(typeof i=="string")return r.stderr.write(`error: ${i}
|
|
1705
1787
|
`),2;let o={all:i.all};i.project!==void 0&&(o.project=i.project),i.since!==void 0&&(o.since=i.since);let a=Ki(t,o);return V_(a,i.json,r)}if(n==="show"){let i=s.filter(l=>l!=="--json"&&l!=="--text");if(i.length!==1)return r.stderr.write(`usage: lmctl api --direct escalations show <attention_id> [--json|--text]
|
|
1706
1788
|
`),2;let o=se(i[0],"attention_id");if(typeof o=="string")return r.stderr.write(`error: ${o}
|
|
@@ -1720,7 +1802,7 @@ ${r}`:r}function Ip(t,e){let r=K0({input:t.stdout}),n=new Map,s=(o,a={})=>new Pr
|
|
|
1720
1802
|
`),2;let d=t.resumeInteractive(l.step_id,a,s);if(!d.resumed)return r.stderr.write(`error: interactive respond failed: ${d.reason} (step_id=${l.step_id})
|
|
1721
1803
|
`),2;let u=t.acknowledgeAttention(o),f={ok:!0,attention_id:o,step_id:l.step_id,session_status:d.session.status,acknowledged_at:u?.acknowledged_at??null};return n?r.stdout.write(`${JSON.stringify(f,null,2)}
|
|
1722
1804
|
`):r.stdout.write(`ok: attention ${o} acknowledged; step ${l.step_id} resumed (session_status=${f.session_status})
|
|
1723
|
-
`),0}function
|
|
1805
|
+
`),0}function X_(t,e){let r=t.split(",").map(n=>n.trim()).filter(n=>n.length>0);if(r.length===0)return`invalid value: ${t}`;for(let n of r)if(!e.includes(n))return`invalid value: ${n}`;return r}var Gx,Kx,J_,Qi,Qx,eA,tA,rA,FA,Dc=E(()=>{"use strict";Qe();We();Ui();Rc();qt();Gx="http://127.0.0.1:8787",Kx=`usage: lmctl api [--direct] <subcommand> ...
|
|
1724
1806
|
|
|
1725
1807
|
Call the lmctl HTTP API using the configured daemon URL/token (see
|
|
1726
1808
|
\`api config\`). Most subcommands require a running \`lmctl serve\`.
|
|
@@ -1834,7 +1916,7 @@ Call the lmctl HTTP API using the configured daemon URL/token (see
|
|
|
1834
1916
|
Per-subcommand help: \`lmctl api run where --help\`,
|
|
1835
1917
|
\`lmctl api run timeline --help\`, \`lmctl api workflows verify --help\`,
|
|
1836
1918
|
and \`lmctl api escalations\` (no args) print detailed usage.
|
|
1837
|
-
`,
|
|
1919
|
+
`,J_=["low","medium","high","critical"];Qi=new Set(["api.url","api.port","api.token","project.docroot",Wi,Bi]);Qx=`usage: lmctl api escalations <list|show|respond>
|
|
1838
1920
|
|
|
1839
1921
|
list [--project P] [--all] [--since DURATION] [--json]
|
|
1840
1922
|
Print pending operator escalations (interactive_waiting_operator
|
|
@@ -1859,13 +1941,13 @@ and \`lmctl api escalations\` (no args) print detailed usage.
|
|
|
1859
1941
|
|
|
1860
1942
|
Verify every workflows/*.compound.json file: load/validate the workflow graph
|
|
1861
1943
|
and report the first step that would be started. Default output is the TTY
|
|
1862
|
-
table; --json emits the structured WorkflowVerifyReport payload.`;FA=["open","assigned","closed","reopened"]});import ih from"jexl";function un(t){ih.compile(oh(t))}async function Dr(t,e){return ih.eval(oh(t),e)}function oh(t){return t.replace(/([A-Za-z_$][\w$.[\]]*)\.includes\(([^()]+)\)/g,"($2 in $1)")}var ms=E(()=>{"use strict"});import{z as w}from"zod";function Hc(t){let e=t.trim();return e.startsWith("={{")&&e.endsWith("}}")?e.slice(3,-2).trim():t}var QA,ah,Pc,Fc,Uc,Wc,Bc,qc,lh,eR,tR,rR,ps,nR,ro,no,so,io,oo,ch,sR,iR,oR,aR,ao,fn=E(()=>{"use strict";ms();QA=w.object({kind:w.enum(["success","neutral","failure"])}),ah=w.enum(["string","number","boolean","object","array"]),Pc=w.object({name:w.string().min(1),type:ah,required:w.boolean().optional(),default:w.unknown().optional(),description:w.string().optional()}),Fc=w.object({name:w.string().min(1),type:ah,source_step_id:w.string().min(1),source_field:w.string().min(1),description:w.string().optional()}),Uc=w.object({id:w.string().min(1),type:w.string().min(1),parameters:w.record(w.string(),w.unknown()).default({})}),Wc="__failure__",Bc=w.object({tools:w.array(w.string().min(1)).optional(),auth:w.array(w.string().min(1)).optional()}).strict().optional(),qc=w.object({on_unhandled_failure:w.object({attention_kind:w.string().min(1).default("workflow_failed"),severity:w.enum(["warn","error","critical"]).default("warn"),capture_evidence:w.boolean().default(!0),recommend_recovery:w.string().min(1).optional()}).optional(),on_unhandled_failure_state:w.string().min(1).optional()}).optional(),lh=w.object({type:w.literal("AssertRepoClean"),fail_message:w.string().min(1).optional(),next:w.string().min(1)}),eR=w.object({name:w.string().min(1),command:w.string().min(1).optional(),args:w.array(w.string()).optional(),env:w.record(w.string(),w.string()).optional(),type:w.enum(["stdio","http","sse"]).optional(),url:w.string().min(1).optional(),headers:w.record(w.string(),w.string()).optional()}).strict(),tR=w.union([w.string().min(1),eR]),rR=w.union([w.string().min(1),w.object({name:w.string().min(1),content:w.string().min(1)}).strict()]),ps=w.object({team:w.string().min(1),alias:w.string().min(1),prompt_template:w.string().optional(),mcp:w.array(tR).optional(),skills:w.array(rR).optional()}),nR=w.object({kind:w.literal("shell"),command:w.string().min(1),description:w.string().optional()}),ro=w.object({type:w.literal("Review"),state_name:w.string().min(1),coder:ps,pre_checks:w.array(nR).optional(),reviewers:w.array(ps.extend({rubric_artifact:w.string().optional()})).optional(),outcomes:w.object({approve:w.string().min(1),request_changes:w.string().optional(),fail_pre_check:w.string().optional(),max_loops_exceeded:w.string().optional()}),writes_to_project_path:w.boolean().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional(),max_loops:w.number().int().positive().default(5),loop_feedback_artifact:w.string().optional(),outcomes_from_stance:w.record(w.string(),w.string().min(1)).optional()}).superRefine((t,e)=>{(t.reviewers??[]).length>0&&t.outcomes_from_stance!==void 0&&e.addIssue({code:"custom",path:["outcomes_from_stance"],message:"outcomes_from_stance cannot be used when reviewers is non-empty"})}),no=w.object({type:w.literal("Consolidate"),state_name:w.string().min(1),researchers:w.array(ps.extend({topic:w.string().min(1)})).optional(),consolidator:ps,outcomes:w.object({ok:w.string().min(1),error:w.string().optional()}),research_artifact_prefix:w.string().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional()}),so=w.object({type:w.literal("Interactive"),state_name:w.string().min(1),agent:ps.extend({initial_prompt_template:w.string().min(1)}),termination:w.object({operator_signal:w.boolean().default(!0),agent_signal:w.string().optional(),max_turns:w.number().int().positive().default(20),timeout_seconds:w.number().int().positive().optional()}),outcomes:w.object({done:w.string().min(1),timeout:w.string().optional()}),artifact_name:w.string().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional()}),io=w.object({type:w.literal("Loop"),state_name:w.string().min(1),over:w.string().min(1),item_var:w.string().min(1),body:w.string().min(1),outcomes:w.object({ok:w.string().min(1),error:w.string().optional()}),stop_on_error:w.boolean().default(!0),max_items:w.number().int().positive().default(1e3)}),oo=w.object({type:w.literal("ShellStep"),state_name:w.string().min(1),command:w.string().min(1),outcomes_from_exit:w.record(w.string(),w.string().min(1)),timeout_ms:w.number().int().nonnegative().optional(),capture_output_to:w.string().optional(),writes_to_project_path:w.boolean().optional()}),ch=w.object({type:w.literal("Choice"),state_name:w.string().min(1),branches:w.array(w.object({when:w.string().min(1),next:w.string().min(1)})).default([]),default_next:w.string().min(1).optional()}).superRefine((t,e)=>{for(let[r,n]of t.branches.entries())try{un(Hc(n.when))}catch(s){let i=s instanceof Error?s.message:"invalid expression";e.addIssue({code:"custom",path:["branches",r,"when"],message:`invalid jexl expression: ${i}`})}}),sR=w.discriminatedUnion("type",[lh,ro,no,so,io,oo,ch]),iR=w.object({type:w.literal("ForEach"),state_name:w.string().min(1),items_from:w.string().min(1),mode:w.enum(["sequential","parallel"]).default("sequential"),max_concurrency:w.number().int().positive().default(1),on_item_failure:w.enum(["continue","stop"]).default("stop"),body:sR,outcomes:w.object({all_ok:w.string().min(1),any_failed:w.string().optional()})}).superRefine((t,e)=>{try{un(Hc(t.items_from))}catch(r){let n=r instanceof Error?r.message:"invalid expression";e.addIssue({code:"custom",path:["items_from"],message:`invalid jexl expression: ${n}`})}}),oR=w.object({type:w.literal("Subflow"),state_name:w.string().min(1),workflow_name:w.string().min(1),inputs:w.record(w.string(),w.string().min(1)).optional(),outcomes:w.record(w.string(),w.string().min(1))}).superRefine((t,e)=>{for(let[r,n]of Object.entries(t.inputs??{}))try{un(Hc(n))}catch(s){let i=s instanceof Error?s.message:"invalid expression";e.addIssue({code:"custom",path:["inputs",r],message:`invalid jexl expression: ${i}`})}}),aR=w.discriminatedUnion("type",[lh,ro,no,so,io,oo,ch,iR,oR]),ao=w.object({name:w.string().min(1),version:w.number().int().positive(),definition_schema_version:w.union([w.literal(1),w.literal(2)]),description:w.string().optional(),estimated_duration_ms:w.number().int().nonnegative().optional(),primitive_version:w.union([w.literal(1),w.literal(2)]).default(1),start_at:w.string().min(1),states:w.record(w.string().min(1),aR),terminals:w.record(w.string().min(1),QA),errors:qc,concurrency_key:w.string().min(1).optional(),concurrent_limit:w.number().int().positive().optional(),default_task_timeout_ms:w.number().int().positive().max(216e5).optional(),inputs:w.array(Pc).optional(),outputs:w.array(Fc).optional(),triggers:w.array(Uc).optional(),read_only:w.boolean().optional(),requires:Bc}).superRefine((t,e)=>{t.definition_schema_version===1&&t.errors!==void 0&&e.addIssue({code:"custom",path:["errors"],message:"errors block requires definition_schema_version: 2"}),t.definition_schema_version===1&&t.concurrency_key!==void 0&&e.addIssue({code:"custom",path:["concurrency_key"],message:"concurrency_key requires definition_schema_version: 2"}),t.definition_schema_version===1&&t.default_task_timeout_ms!==void 0&&e.addIssue({code:"custom",path:["default_task_timeout_ms"],message:"default_task_timeout_ms requires definition_schema_version: 2"})})});import{z as V}from"zod";var lR,lo,cR,dR,uR,xt,mn=E(()=>{"use strict";fn();lR=/^s-[a-z0-9-]+-[a-f0-9]{4}$/,lo=V.string().regex(lR),cR=V.object({step_id:lo,type:V.literal("main"),index:V.number().int().min(0)}),dR=V.record(lo,V.record(V.string().min(1),V.array(V.array(cR)))),uR=V.object({id:lo,name:V.string().min(1),type:V.string().min(1),typeVersion:V.number().int().positive().default(1),parameters:V.record(V.string(),V.unknown()).default({}),members:V.record(V.string(),V.unknown()).optional(),estimated_duration_ms:V.number().int().nonnegative().optional()}),xt=V.object({schema_version:V.literal("lmctl/v3"),definition_schema_version:V.literal(3),name:V.string().min(1),version:V.number().int().positive(),description:V.string().optional(),estimated_duration_ms:V.number().int().nonnegative().optional(),default_task_timeout_ms:V.number().int().positive().max(216e5).optional(),concurrency_key:V.string().min(1).optional(),concurrent_limit:V.number().int().positive().optional(),errors:qc,inputs:V.array(Pc).optional(),outputs:V.array(Fc).optional(),steps:V.array(uR).min(1),connections:dR.default({}),entry_step_id:lo,triggers:V.array(Uc).optional(),read_only:V.boolean().optional(),requires:Bc}).superRefine((t,e)=>{let r=new Set;for(let[n,s]of t.steps.entries())r.has(s.id)&&e.addIssue({code:"custom",path:["steps",n,"id"],message:`duplicate step id: ${s.id}`}),r.add(s.id);r.has(t.entry_step_id)||e.addIssue({code:"custom",path:["entry_step_id"],message:`entry_step_id does not reference an existing step: ${t.entry_step_id}`});for(let[n,s]of Object.entries(t.connections)){r.has(n)||e.addIssue({code:"custom",path:["connections",n],message:`connection source does not reference an existing step: ${n}`});for(let[i,o]of Object.entries(s))for(let[a,l]of o.entries())for(let[c,d]of l.entries())r.has(d.step_id)||e.addIssue({code:"custom",path:["connections",n,i,a,c,"step_id"],message:`connection target does not reference an existing step: ${d.step_id}`})}})});function co(t){return Xc(t)}function Xc(t){if(Array.isArray(t))return t.map(Xc);if(t===null||typeof t!="object")return t;let e=t,r={};for(let n of Object.keys(e))r[n]=Xc(e[n]);if(typeof r.type=="string"){let n=mR[r.type];n!==void 0&&(r.type=n)}return r}var Jc,fR,mR,Gc=E(()=>{"use strict";Jc="lmctl.builtin.",fR={Review:`${Jc}Review`,Research:`${Jc}Research`,Consolidate:`${Jc}Consolidate`},mR=Object.fromEntries(Object.entries(fR).map(([t,e])=>[e,t]))});import{readFileSync as pR}from"node:fs";function fh(t){return _R(t)}function _R(t){let e=co(yR(t));if(gR(e),mh(e)===3)return hR(e);let r=ao.safeParse(e);if(!r.success)throw new Ht({errors:r.error.issues.map(s=>({path:s.path.length===0?"$":s.path.map(String).join("."),message:s.message}))});let n=wR(r.data);if(n.errors.length>0||n.unresolvedRefs.length>0)throw new Ht(n);return r.data}function hR(t){let e=xt.safeParse(t);if(!e.success)throw new Ht({errors:e.error.issues.map(r=>({path:r.path.length===0?"$":r.path.map(String).join("."),message:r.message}))});return e.data}function gR(t){if(typeof t!="object"||t===null||!("definition_schema_version"in t))return;let e=mh(t);if(!(e===null||dh.includes(e)))throw new Ht({errors:[{path:"definition_schema_version",message:`unsupported definition_schema_version ${e}; supported versions: ${dh.join(", ")}`}]})}function mh(t){if(typeof t!="object"||t===null||!("definition_schema_version"in t))return null;let e=t.definition_schema_version;return typeof e=="number"?e:null}function yR(t){if(typeof t!="string")return t;let e=t.trim();return t.includes(`
|
|
1944
|
+
table; --json emits the structured WorkflowVerifyReport payload.`;FA=["open","assigned","closed","reopened"]});import ih from"jexl";function un(t){ih.compile(oh(t))}async function Dr(t,e){return ih.eval(oh(t),e)}function oh(t){return t.replace(/([A-Za-z_$][\w$.[\]]*)\.includes\(([^()]+)\)/g,"($2 in $1)")}var ms=E(()=>{"use strict"});import{z as w}from"zod";function Hc(t){let e=t.trim();return e.startsWith("={{")&&e.endsWith("}}")?e.slice(3,-2).trim():t}var QA,ah,Pc,Fc,Uc,Wc,Bc,qc,lh,eR,tR,rR,ps,nR,ro,no,so,io,oo,ch,sR,iR,oR,aR,ao,fn=E(()=>{"use strict";ms();QA=w.object({kind:w.enum(["success","neutral","failure"])}),ah=w.enum(["string","number","boolean","object","array"]),Pc=w.object({name:w.string().min(1),type:ah,required:w.boolean().optional(),default:w.unknown().optional(),description:w.string().optional()}),Fc=w.object({name:w.string().min(1),type:ah,source_step_id:w.string().min(1),source_field:w.string().min(1),description:w.string().optional()}),Uc=w.object({id:w.string().min(1),type:w.string().min(1),parameters:w.record(w.string(),w.unknown()).default({})}),Wc="__failure__",Bc=w.object({tools:w.array(w.string().min(1)).optional(),auth:w.array(w.string().min(1)).optional()}).strict().optional(),qc=w.object({on_unhandled_failure:w.object({attention_kind:w.string().min(1).default("workflow_failed"),severity:w.enum(["warn","error","critical"]).default("warn"),capture_evidence:w.boolean().default(!0),recommend_recovery:w.string().min(1).optional()}).optional(),on_unhandled_failure_state:w.string().min(1).optional()}).optional(),lh=w.object({type:w.literal("AssertRepoClean"),fail_message:w.string().min(1).optional(),next:w.string().min(1)}),eR=w.object({name:w.string().min(1),command:w.string().min(1).optional(),args:w.array(w.string()).optional(),env:w.record(w.string(),w.string()).optional(),type:w.enum(["stdio","http","sse"]).optional(),url:w.string().min(1).optional(),headers:w.record(w.string(),w.string()).optional()}).strict(),tR=w.union([w.string().min(1),eR]),rR=w.union([w.string().min(1),w.object({name:w.string().min(1),content:w.string().min(1)}).strict()]),ps=w.object({team:w.string().min(1),alias:w.string().min(1),prompt_template:w.string().optional(),mcp:w.array(tR).optional(),skills:w.array(rR).optional()}),nR=w.object({kind:w.literal("shell"),command:w.string().min(1),description:w.string().optional()}),ro=w.object({type:w.literal("Review"),state_name:w.string().min(1),coder:ps,pre_checks:w.array(nR).optional(),reviewers:w.array(ps.extend({rubric_artifact:w.string().optional()})).optional(),outcomes:w.object({approve:w.string().min(1),request_changes:w.string().optional(),fail_pre_check:w.string().optional(),max_loops_exceeded:w.string().optional()}),writes_to_project_path:w.boolean().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional(),max_loops:w.number().int().positive().default(5),loop_feedback_artifact:w.string().optional(),outcomes_from_stance:w.record(w.string(),w.string().min(1)).optional()}).superRefine((t,e)=>{(t.reviewers??[]).length>0&&t.outcomes_from_stance!==void 0&&e.addIssue({code:"custom",path:["outcomes_from_stance"],message:"outcomes_from_stance cannot be used when reviewers is non-empty"})}),no=w.object({type:w.literal("Consolidate"),state_name:w.string().min(1),researchers:w.array(ps.extend({topic:w.string().min(1)})).optional(),consolidator:ps,outcomes:w.object({ok:w.string().min(1),error:w.string().optional()}),research_artifact_prefix:w.string().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional()}),so=w.object({type:w.literal("Interactive"),state_name:w.string().min(1),agent:ps.extend({initial_prompt_template:w.string().min(1)}),termination:w.object({operator_signal:w.boolean().default(!0),agent_signal:w.string().optional(),max_turns:w.number().int().positive().default(20),timeout_seconds:w.number().int().positive().optional()}),outcomes:w.object({done:w.string().min(1),timeout:w.string().optional()}),artifact_name:w.string().optional(),durable_memory_tags:w.array(w.string().min(1)).optional(),write_back_durable_memory:w.union([w.boolean(),w.string().min(1)]).optional()}),io=w.object({type:w.literal("Loop"),state_name:w.string().min(1),over:w.string().min(1),item_var:w.string().min(1),body:w.string().min(1),outcomes:w.object({ok:w.string().min(1),error:w.string().optional()}),stop_on_error:w.boolean().default(!0),max_items:w.number().int().positive().default(1e3)}),oo=w.object({type:w.literal("ShellStep"),state_name:w.string().min(1),command:w.string().min(1),outcomes_from_exit:w.record(w.string(),w.string().min(1)),timeout_ms:w.number().int().nonnegative().optional(),capture_output_to:w.string().optional(),writes_to_project_path:w.boolean().optional()}),ch=w.object({type:w.literal("Choice"),state_name:w.string().min(1),branches:w.array(w.object({when:w.string().min(1),next:w.string().min(1)})).default([]),default_next:w.string().min(1).optional()}).superRefine((t,e)=>{for(let[r,n]of t.branches.entries())try{un(Hc(n.when))}catch(s){let i=s instanceof Error?s.message:"invalid expression";e.addIssue({code:"custom",path:["branches",r,"when"],message:`invalid jexl expression: ${i}`})}}),sR=w.discriminatedUnion("type",[lh,ro,no,so,io,oo,ch]),iR=w.object({type:w.literal("ForEach"),state_name:w.string().min(1),items_from:w.string().min(1),mode:w.enum(["sequential","parallel"]).default("sequential"),max_concurrency:w.number().int().positive().default(1),on_item_failure:w.enum(["continue","stop"]).default("stop"),body:sR,outcomes:w.object({all_ok:w.string().min(1),any_failed:w.string().optional()})}).superRefine((t,e)=>{try{un(Hc(t.items_from))}catch(r){let n=r instanceof Error?r.message:"invalid expression";e.addIssue({code:"custom",path:["items_from"],message:`invalid jexl expression: ${n}`})}}),oR=w.object({type:w.literal("Subflow"),state_name:w.string().min(1),workflow_name:w.string().min(1),inputs:w.record(w.string(),w.string().min(1)).optional(),outcomes:w.record(w.string(),w.string().min(1))}).superRefine((t,e)=>{for(let[r,n]of Object.entries(t.inputs??{}))try{un(Hc(n))}catch(s){let i=s instanceof Error?s.message:"invalid expression";e.addIssue({code:"custom",path:["inputs",r],message:`invalid jexl expression: ${i}`})}}),aR=w.discriminatedUnion("type",[lh,ro,no,so,io,oo,ch,iR,oR]),ao=w.object({name:w.string().min(1),version:w.number().int().positive(),definition_schema_version:w.union([w.literal(1),w.literal(2)]),description:w.string().optional(),estimated_duration_ms:w.number().int().nonnegative().optional(),primitive_version:w.union([w.literal(1),w.literal(2)]).default(1),start_at:w.string().min(1),states:w.record(w.string().min(1),aR),terminals:w.record(w.string().min(1),QA),errors:qc,concurrency_key:w.string().min(1).optional(),concurrent_limit:w.number().int().positive().optional(),default_task_timeout_ms:w.number().int().positive().max(216e5).optional(),inputs:w.array(Pc).optional(),outputs:w.array(Fc).optional(),triggers:w.array(Uc).optional(),read_only:w.boolean().optional(),requires:Bc}).superRefine((t,e)=>{t.definition_schema_version===1&&t.errors!==void 0&&e.addIssue({code:"custom",path:["errors"],message:"errors block requires definition_schema_version: 2"}),t.definition_schema_version===1&&t.concurrency_key!==void 0&&e.addIssue({code:"custom",path:["concurrency_key"],message:"concurrency_key requires definition_schema_version: 2"}),t.definition_schema_version===1&&t.default_task_timeout_ms!==void 0&&e.addIssue({code:"custom",path:["default_task_timeout_ms"],message:"default_task_timeout_ms requires definition_schema_version: 2"})})});import{z as V}from"zod";var lR,lo,cR,dR,uR,xt,mn=E(()=>{"use strict";fn();lR=/^s-[a-z0-9-]+-[a-f0-9]{4}$/,lo=V.string().regex(lR),cR=V.object({step_id:lo,type:V.literal("main"),index:V.number().int().min(0)}),dR=V.record(lo,V.record(V.string().min(1),V.array(V.array(cR)))),uR=V.object({id:lo,name:V.string().min(1),type:V.string().min(1),typeVersion:V.number().int().positive().default(1),parameters:V.record(V.string(),V.unknown()).default({}),members:V.record(V.string(),V.unknown()).optional(),estimated_duration_ms:V.number().int().nonnegative().optional()}),xt=V.object({schema_version:V.literal("lmctl/v3"),definition_schema_version:V.literal(3),name:V.string().min(1),version:V.number().int().positive(),description:V.string().optional(),estimated_duration_ms:V.number().int().nonnegative().optional(),default_task_timeout_ms:V.number().int().positive().max(216e5).optional(),concurrency_key:V.string().min(1).optional(),concurrent_limit:V.number().int().positive().optional(),errors:qc,inputs:V.array(Pc).optional(),outputs:V.array(Fc).optional(),steps:V.array(uR).min(1),connections:dR.default({}),entry_step_id:lo,triggers:V.array(Uc).optional(),read_only:V.boolean().optional(),requires:Bc}).superRefine((t,e)=>{let r=new Set;for(let[n,s]of t.steps.entries())r.has(s.id)&&e.addIssue({code:"custom",path:["steps",n,"id"],message:`duplicate step id: ${s.id}`}),r.add(s.id);r.has(t.entry_step_id)||e.addIssue({code:"custom",path:["entry_step_id"],message:`entry_step_id does not reference an existing step: ${t.entry_step_id}`});for(let[n,s]of Object.entries(t.connections)){r.has(n)||e.addIssue({code:"custom",path:["connections",n],message:`connection source does not reference an existing step: ${n}`});for(let[i,o]of Object.entries(s))for(let[a,l]of o.entries())for(let[c,d]of l.entries())r.has(d.step_id)||e.addIssue({code:"custom",path:["connections",n,i,a,c,"step_id"],message:`connection target does not reference an existing step: ${d.step_id}`})}})});function co(t){return Jc(t)}function Jc(t){if(Array.isArray(t))return t.map(Jc);if(t===null||typeof t!="object")return t;let e=t,r={};for(let n of Object.keys(e))r[n]=Jc(e[n]);if(typeof r.type=="string"){let n=mR[r.type];n!==void 0&&(r.type=n)}return r}var Xc,fR,mR,Gc=E(()=>{"use strict";Xc="lmctl.builtin.",fR={Review:`${Xc}Review`,Research:`${Xc}Research`,Consolidate:`${Xc}Consolidate`},mR=Object.fromEntries(Object.entries(fR).map(([t,e])=>[e,t]))});import{readFileSync as pR}from"node:fs";function fh(t){return _R(t)}function _R(t){let e=co(yR(t));if(gR(e),mh(e)===3)return hR(e);let r=ao.safeParse(e);if(!r.success)throw new Ht({errors:r.error.issues.map(s=>({path:s.path.length===0?"$":s.path.map(String).join("."),message:s.message}))});let n=wR(r.data);if(n.errors.length>0||n.unresolvedRefs.length>0)throw new Ht(n);return r.data}function hR(t){let e=xt.safeParse(t);if(!e.success)throw new Ht({errors:e.error.issues.map(r=>({path:r.path.length===0?"$":r.path.map(String).join("."),message:r.message}))});return e.data}function gR(t){if(typeof t!="object"||t===null||!("definition_schema_version"in t))return;let e=mh(t);if(!(e===null||dh.includes(e)))throw new Ht({errors:[{path:"definition_schema_version",message:`unsupported definition_schema_version ${e}; supported versions: ${dh.join(", ")}`}]})}function mh(t){if(typeof t!="object"||t===null||!("definition_schema_version"in t))return null;let e=t.definition_schema_version;return typeof e=="number"?e:null}function yR(t){if(typeof t!="string")return t;let e=t.trim();return t.includes(`
|
|
1863
1945
|
`)||e.startsWith("{")||e.startsWith("[")?uh(t,"$"):e.endsWith(".json")?uh(pR(e,"utf8"),e):t}function uh(t,e){try{return JSON.parse(t)}catch(r){let n=r instanceof Error?r.message:"invalid JSON";throw new Ht({errors:[{path:e,message:`invalid JSON: ${n}`}]})}}function wR(t){let e=[],r=[],n=new Set(Object.keys(t.states));n.has(t.start_at)||r.push({state:"$",ref:t.start_at,kind:"next"}),ER(t,n,r);for(let[s,i]of Object.entries(t.states))new Set(Object.keys(t.terminals));return{errors:e,unresolvedRefs:r}}function ER(t,e,r){let n=t.errors?.on_unhandled_failure_state;n!==void 0&&(e.has(n)||r.push({state:"$",ref:n,kind:"next"}))}var dh,Ht,ph=E(()=>{"use strict";fn();mn();Gc();dh=[1,2,3],Ht=class extends Error{errors;unresolvedRefs;constructor(e){super(e.message??"workflow validation failed"),this.name="WorkflowValidationError",this.errors=e.errors??[],this.unresolvedRefs=e.unresolvedRefs??[]}}});import{createHash as TR}from"node:crypto";function _h(t,e){let r=bR(e),n=TR("sha1").update(`${t}:${e}`).digest("hex").slice(0,4);return`s-${r}-${n}`}function bR(t){let e=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e:"step"}var hh=E(()=>{"use strict";mn()});function kR(t,e){let r=vR[t]??[],n={},s={};for(let[i,o]of Object.entries(e))r.includes(i)?s[i]=o:n[i]=o;return{params:n,members:s}}function Eh(t){let e=[],r=(k,N)=>{throw new pn([{line:k,message:N}])},n=t.split(`
|
|
1864
1946
|
`),s=[];for(let k=0;k<n.length;k+=1){let L=xR(n[k]).trim();L.length>0&&s.push({n:k+1,text:L})}s.length===0&&r(1,"empty composition: expected a `workflow <name> v<version>` header");let i=/^workflow\s+(\S+)\s+v(\d+)$/.exec(s[0].text)??r(s[0].n,`expected header \`workflow <name> v<version>\`, got: ${s[0].text}`),o=i[1],a=Number.parseInt(i[2],10),l=new Map,c=[],d=[],u=[],f,m={},p=new Map,h=new Map,g=new Map,_=(k,N,L,W,D,M)=>{l.has(k)&&r(W,`duplicate step/terminal id: ${k}`),/^[A-Za-z][\w-]*$/.test(k)||r(W,`invalid id (must start with a letter): ${k}`),l.set(k,{declId:k,type:N,params:L,line:W,isTerminal:D,...M?{members:M}:{}}),d.push(k)},y=k=>{let N=[],L=k+1;for(;L<s.length;L+=1){let W=/^([A-Za-z][\w-]*|default)\s*->\s*([A-Za-z][\w-]*)$/.exec(s[L].text);if(W===null)break;N.push({label:W[1],dst:W[2]})}return{branches:N,nextIdx:L-1}};for(let k=1;k<s.length;k+=1){let{n:N,text:L}=s[k],W=L.split(/\s+/,1)[0];if(/^meta\s*\(/.test(L)){k!==1&&r(N,"`meta(...)` must be the preamble \u2014 the FIRST line after the `workflow` header (at most one, before any construct)");let D=/^meta\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`meta\` (expected \`meta({ "requires"?:\u2026, "default_task_timeout_ms"?:\u2026, "errors"?:\u2026, "concurrency_key"?:\u2026, "concurrent_limit"?:\u2026 })\`): ${L}`),M=fr(D[1],N,r);for(let z of Object.keys(M))yh.has(z)||r(N,`unknown \`meta\` key \`${z}\` \u2014 only workflow-level runtime metadata is allowed: ${[...yh].join(", ")} (no grammar inflation; bounded)`);m=M;continue}if(W==="step"){let D=/^step\s+([A-Za-z][\w-]*)\s*=\s*([a-z][a-z0-9-]*)\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`step\` (expected \`step <id> = <archetype>(k=v, ...)\`): ${L}`),M=D[1],z=D[2],he=D[3],oe=gh[z];oe===void 0&&r(N,`unknown step type: ${z} (supported \`step\` archetypes: ${Object.keys(gh).join(", ")}; choice/terminal/loop/foreach/call/decide have their own constructs)`);let{params:Te,members:Ct}=kR(oe,fr(he,N,r));_(M,oe,Te,N,!1,Object.keys(Ct).length>0?Ct:void 0);continue}if(W==="trigger"){let D=/^trigger\s+([A-Za-z][\w-]*)\s*=\s*([a-z][a-z0-9-]*)\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`trigger\` (expected \`trigger <id> = <trigger-type>({ ...json... })\`): ${L}`),M=D[1],z=D[2],he=D[3],oe=wh[z];oe===void 0&&r(N,`unknown trigger type: ${z} (registered trigger archetypes: ${Object.keys(wh).join(", ")})`),p.has(M)&&r(N,`duplicate trigger id: ${M}`),p.set(M,{id:M,type:oe,parameters:fr(he,N,r)});continue}if(W==="mcp"||W==="skill"){let D=new RegExp(`^${W}\\s+([A-Za-z][\\w-]*)\\s*=\\s*(.+)$`).exec(L)??r(N,`malformed \`${W}\` decl (expected \`${W} <name> = {json} | ${W} <name> = "<file|url>"\`): ${L}`),M=D[1],z=D[2].trim(),he=W==="mcp"?h:g;he.has(M)&&r(N,`duplicate ${W} declaration: ${M}`);let oe;if(z.startsWith("{")){let Te=fr(z,N,r);W==="mcp"?oe={...Te,name:M}:((typeof Te.content!="string"||Te.content.length===0)&&r(N,`\`skill ${M}\`: inline form requires a non-empty string \`content\` (a SKILL.md body)`),oe={name:M,content:Te.content})}else{let Te=Th(z);(typeof Te!="string"||Te.length===0)&&r(N,`\`${W} ${M}\`: string form must be a non-empty file path or http(s) URL`),oe=Te}he.set(M,oe);continue}if(W==="terminal"){let D=/^terminal\s+([A-Za-z][\w-]*)\s*=\s*([A-Za-z][\w-]*)(?:\s+(success|failure|neutral))?\s*$/.exec(L)??r(N,`malformed \`terminal\` (expected \`terminal <id> = <name> [success|failure|neutral]\`): ${L}`);_(D[1],"lmctl/terminal",{name:D[2],kind:D[3]??"neutral"},N,!0);continue}if(W==="seq"){let M=L.slice(3).trim().split(/\s*(->|-[a-z0-9_]+->)\s*/).map(z=>z.trim()).filter(z=>z.length>0);(M.length<3||M.length%2===0)&&r(N,`malformed \`seq\` (expected \`<id> -> <id> [ -> <id> ... ]\`, optional \`-<port>->\`): ${L}`);for(let z=0;z+2<M.length+1&&!(z+2>M.length-1);z+=2){let he=M[z],oe=M[z+1],Te=M[z+2],Ct=oe==="->"?"main":oe.slice(1,-2);c.push({srcDeclId:he,port:Ct,dstDeclId:Te,line:N})}continue}if(W==="choice"){let M=(/^choice\s+([A-Za-z][\w-]*)\s*:$/.exec(L)??r(N,`malformed \`choice\` (expected \`choice <id>:\` then \`when <predicate> -<port>-> <id>\` lines): ${L}`))[1],z=[],he,oe=k+1;for(;oe<s.length;oe+=1){let Te=s[oe].text,Ct=/^when\s+(.+)\s+-([a-z0-9_]+)->\s+([A-Za-z][\w-]*)$/.exec(Te);if(Ct!==null){he!==void 0&&r(s[oe].n,`\`choice ${M}\`: a \`when\` branch may not follow \`default\` (branches are ordered, default is the fallback)`);let Wn=Ct[2];z.push({when:Ct[1].trim(),next:`@terminal:${Wn}`}),c.push({srcDeclId:M,port:Wn,dstDeclId:Ct[3],line:s[oe].n});continue}let Ya=/^default\s+-([a-z0-9_]+)->\s+([A-Za-z][\w-]*)$/.exec(Te);if(Ya!==null){he!==void 0&&r(s[oe].n,`\`choice ${M}\` has more than one \`default\``);let Wn=Ya[1];he=`@terminal:${Wn}`,c.push({srcDeclId:M,port:Wn,dstDeclId:Ya[2],line:s[oe].n});continue}break}z.length===0&&r(N,`\`choice ${M}\` has no \`when\` branches (need \u22651 \`when <jexl-predicate> -<port>-> <id>\`)`),_(M,"lmctl/choice",{branches:z,...he!==void 0?{default_next:he}:{}},N,!1),k=oe-1;continue}if(W==="loop"){let D=/^loop\s+([A-Za-z][\w-]*)\s*=\s*loop\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`loop\` (expected \`loop <id> = loop(k=v, ...)\`): ${L}`);_(D[1],"lmctl/loop",fr(D[2],N,r),N,!1);continue}if(W==="foreach"){let D=/^foreach\s+([A-Za-z][\w-]*)\s*=\s*foreach\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`foreach\` (expected \`foreach <id> = foreach(items=<expr>, ...)\`): ${L}`),M=fr(D[2],N,r);"mode"in M&&r(N,"foreach is SEQUENTIAL-ONLY: `mode` is not permitted (single-thread; durable-memory/composition-language-design.md \xA7Execution model)"),_(D[1],"lmctl/foreach",M,N,!1);continue}if(W==="call"){let D=/^call\s+([A-Za-z][\w-]*)\s*=\s*call\s*\((.*)\)\s*$/.exec(L)??r(N,`malformed \`call\` (expected \`call <id> = call(workflow=<name>, ...)\`): ${L}`),M=D[1],z=fr(D[2],N,r),he=z.workflow;(typeof he!="string"||he.length===0)&&r(N,`\`call ${M}\` requires a \`workflow=<name>\` argument`);let{workflow:oe,...Te}=z;_(M,"lmctl/subflow",{workflow_name:he,...Te},N,!1),u.push({declId:M,target:he,line:N});continue}if(W==="decide"){let D=/^decide\s+([A-Za-z][\w-]*)\s+by\s+agent\s*\((.*)\)\s*:$/.exec(L)??r(N,`malformed \`decide\` (expected \`decide <id> by agent(k=v, ...):\`): ${L}`),M=D[1],z=fr(D[2],N,r),{branches:he,nextIdx:oe}=y(k);he.length===0&&r(N,`\`decide ${M}\` has no outcomes (need at least one \`<outcome> -> <id>\`)`),_(M,"lmctl/interactive",{termination:{operator_signal:!0}},N,!1,{agent:z});for(let Te of he)c.push({srcDeclId:M,port:Te.label,dstDeclId:Te.dst,line:N});k=oe;continue}if(W==="entry"){let D=/^entry\s+([A-Za-z][\w-]*)$/.exec(L)??r(N,`malformed \`entry\` (expected \`entry <id>\`): ${L}`);f!==void 0&&r(N,`duplicate \`entry\` (already set to ${f})`),f=D[1];continue}r(N,`unknown statement \`${W}\` (grammar: workflow / meta / trigger / mcp / skill / step / terminal / seq / choice / loop / foreach / call / decide / entry)`)}d.length===0&&r(s[0].n,"composition declares no steps"),f===void 0&&(f=d[0]),l.has(f)||r(s[0].n,`entry references undeclared step: ${f}`);let T=k=>{if(Array.isArray(k)){for(let L of k)T(L);return}if(typeof k!="object"||k===null)return;let N=k;if(typeof N.alias=="string")for(let[L,W]of[["mcp",h],["skills",g]]){let D=N[L];Array.isArray(D)&&(N[L]=D.map(M=>typeof M=="string"&&W.has(M)?structuredClone(W.get(M)):M))}for(let L of Object.values(N))T(L)};for(let k of d){let N=l.get(k);N.members!==void 0&&T(N.members)}let b=k=>_h(o,k),I=d.map(k=>{let N=l.get(k);return{id:b(k),name:k,type:N.type,typeVersion:1,parameters:N.params,...N.members?{members:N.members}:{}}}),x={};for(let k of c){l.has(k.srcDeclId)||r(k.line,`edge source references undeclared step: ${k.srcDeclId}`),l.has(k.dstDeclId)||r(k.line,`dangling edge target: ${k.dstDeclId} is not declared`),l.get(k.srcDeclId).isTerminal&&r(k.line,`terminal \`${k.srcDeclId}\` cannot have an outgoing edge`);let N=b(k.srcDeclId);x[N]??={},x[N][k.port]!==void 0&&r(k.line,`duplicate edge port \`${k.port}\` on step \`${k.srcDeclId}\``),x[N][k.port]=[[{step_id:b(k.dstDeclId),type:"main",index:0}]]}for(let k of d){let N=l.get(k);IR.has(N.type)||r(N.line,`unknown archetype \`${N.type}\` for step \`${k}\` \u2014 not a registered builtin (src/engine/archetypes/index.ts:17-32)`)}for(let k of u)k.target===o&&r(k.line,`subflow cycle: \`call ${k.declId}\` invokes this workflow (\`${o}\`) \u2014 direct recursion is not allowed (cross-workflow A\u2192B\u2192A cycle detection is deferred to the M3 compile.ts seam)`);let H=new Map;for(let k of c){let N=H.get(k.srcDeclId);N===void 0?H.set(k.srcDeclId,[k.dstDeclId]):N.push(k.dstDeclId)}for(let k of d){let N=l.get(k);if(N.type!=="lmctl/loop")continue;let L=N.params.body;if(typeof L=="string"&&l.has(L)){let W=H.get(k);W===void 0?H.set(k,[L]):W.push(L)}}let pe=new Set([f]),U=[f];for(;U.length>0;){let k=U.shift();for(let N of H.get(k)??[])pe.has(N)||(pe.add(N),U.push(N))}for(let k of d)pe.has(k)||r(l.get(k).line,`step \`${k}\` is unreachable from entry \`${f}\``);let j=new Map;for(let k of c){let N=j.get(k.srcDeclId);N===void 0&&(N=new Set,j.set(k.srcDeclId,N)),N.add(k.port)}let A=new Set(["approve","request_changes","fail_pre_check","max_loops_exceeded"]);for(let k of d){let N=l.get(k);if(N.isTerminal)continue;let L=j.get(k)??new Set;if(N.type==="lmctl/review"){let D=[...L].some(M=>!A.has(M));!L.has("approve")&&!D&&r(N.line,`uncovered outcome: review step \`${k}\` wires neither \`approve\` nor any stance outcome \u2014 route \`approve\` (\`seq ${k} -approve-> <target>\`) or a stance port (run.ts:423-438 synthesizes outcomes_from_stance; review.ts:88-102 routes a stance before default approve)`);continue}let W=NR[N.type];if(W!==void 0)for(let D of W)L.has(D)||r(N.line,`uncovered outcome: required outcome \`${D}\` of step \`${k}\` (\`${N.type}\`) has no connection \u2014 route it (\`seq ${k} -${D}-> <target|terminal>\`)`);else L.size===0&&r(N.line,`uncovered outcome: non-terminal step \`${k}\` (\`${N.type}\`) has no outgoing connection \u2014 wire it with \`seq\` or route to a \`terminal\``)}for(let k of d){let N=l.get(k),L=SR[N.type];if(L===void 0)continue;let W={...N.params,...N.members??{},type:L.v2type,state_name:k,...Object.keys(L.outcomes).length>0?{outcomes:L.outcomes}:{}},D=L.schema.safeParse(W);if(!D.success){let M=D.error.issues[0],z=M.path.length===0?"$":M.path.map(String).join(".");r(N.line,`step \`${k}\` (\`${N.type}\`) has invalid params for archetype \`${L.v2type}\` at \`${z}\`: ${M.message} \u2014 this would crash the engine (it derefs this field unguarded). Provide it via the structured form: \`step ${k} = ${N.type.replace("lmctl/","")}({ ... })\``)}}let ee={schema_version:"lmctl/v3",definition_schema_version:3,name:o,version:a,...m,...p.size>0?{triggers:[...p.values()]}:{},steps:I,connections:x,entry_step_id:b(f)},B=xt.safeParse(ee);if(!B.success)throw new pn(B.error.issues.map(k=>({line:s[0].n,message:`emitted V3 invalid at ${k.path.length===0?"$":k.path.map(String).join(".")}: ${k.message}`})));return B.data}function xR(t){let e=null;for(let r=0;r<t.length;r+=1){let n=t[r];if(e!==null){if(n==="\\"){r+=1;continue}n===e&&(e=null);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return t.slice(0,r)}return t}function fr(t,e,r){let n=t.trim();if(n.length===0)return{};if(n.startsWith("{")){let i;try{i=JSON.parse(n)}catch(o){r(e,`malformed structured args (expected a single-line JSON object): ${o.message}`)}return(i===null||typeof i!="object"||Array.isArray(i))&&r(e,"structured args must be a JSON object"),i}let s={};for(let i of AR(n)){let o=i.indexOf("=");o===-1&&r(e,`malformed arg (expected k=v): ${i}`);let a=i.slice(0,o).trim(),l=i.slice(o+1).trim();/^[A-Za-z_][\w-]*$/.test(a)||r(e,`invalid arg name: ${a}`),s[a]=Th(l)}return s}function AR(t){return t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function Th(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t==="true"?!0:t==="false"?!1:/^-?\d+$/.test(t)?Number.parseInt(t,10):/^-?\d*\.\d+$/.test(t)?Number.parseFloat(t):t}var SR,vR,gh,pn,IR,NR,yh,wh,bh=E(()=>{"use strict";mn();hh();fn();SR={"lmctl/review":{v2type:"Review",outcomes:{approve:"_"},schema:ro},"lmctl/consolidate":{v2type:"Consolidate",outcomes:{ok:"_"},schema:no},"lmctl/interactive":{v2type:"Interactive",outcomes:{done:"_"},schema:so},"lmctl/loop":{v2type:"Loop",outcomes:{ok:"_"},schema:io},"lmctl/shell-step":{v2type:"ShellStep",outcomes:{},schema:oo}},vR={"lmctl/review":["coder","reviewers"],"lmctl/consolidate":["researchers","consolidator"],"lmctl/interactive":["agent"]};gh={review:"lmctl/review",consolidate:"lmctl/consolidate",interactive:"lmctl/interactive","shell-step":"lmctl/shell-step","assert-repo-clean":"lmctl/assert-repo-clean","render-docx":"lmctl/render-docx","render-xlsx":"lmctl/render-xlsx"},pn=class extends Error{issues;constructor(e){super(`composition DSL compile failed:
|
|
1865
1947
|
${e.map(r=>` line ${r.line}: ${r.message}`).join(`
|
|
1866
1948
|
`)}`),this.issues=e,this.name="DslCompileError"}},IR=new Set(["lmctl/assert-repo-clean","lmctl/review","lmctl/consolidate","lmctl/interactive","lmctl/loop","lmctl/render-docx","lmctl/render-xlsx","lmctl/shell-step","lmctl/choice","lmctl/foreach","lmctl/subflow","lmctl/terminal","lmctl/trigger-schedule","lmctl/trigger-gh-issue"]),NR={"lmctl/consolidate":["ok"],"lmctl/interactive":["done"],"lmctl/loop":["ok"],"lmctl/foreach":["all_ok"]},yh=new Set(["requires","default_task_timeout_ms","errors","concurrency_key","concurrent_limit"]),wh={"trigger-schedule":"lmctl/trigger-schedule","trigger-gh-issue":"lmctl/trigger-gh-issue"}});import{readFileSync as RR}from"node:fs";function LR(){let t=process.env.LMCTL_DSL;return t===void 0?!0:!["0","false","off"].includes(t.trim().toLowerCase())}function OR(t){for(let e of t.split(`
|
|
1867
|
-
`)){let r=e.replace(/#.*/,"").trim();if(r.length!==0)return/^workflow\s+\S+\s+v\d+\s*$/.test(r)}return!1}function dt(t){if(typeof t=="string"&&LR()&&OR(t)){let r;try{r=Eh(t)}catch(s){throw s instanceof pn?new
|
|
1868
|
-
`)||e.startsWith("{")||e.startsWith("[")?Sh(t):e.endsWith(".json")?Sh(RR(e,"utf8")):t}function Sh(t){return JSON.parse(t)}function MR(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Kc,Jt,_s=E(()=>{"use strict";fn();ph();Gc();mn();bh();Kc=class extends Error{causeError;constructor(e){super("compiler emitted invalid atomic workflow"),this.causeError=e,this.name="CompilerInvariantError"}},Jt=class extends Error{issues;constructor(e){super("compound workflow validation failed"),this.issues=e,this.name="CompilerValidationError"}}});function uo(t){let e=t.workflow?.concurrent_limit??1,r=t.job.concurrency_key_resolved??t.workflow?.concurrency_key??null;return r===null||r.trim().length===0?{concurrency_key:null,concurrent_limit:e}:{concurrency_key:jR(r,{job:{id:t.job.id,kind:t.job.source,source:t.job.source,source_ref:t.job.source_ref,payload:PR(t.job.payload)},project:t.project===null?null:{id:t.project.id,name:t.project.name}}),concurrent_limit:e}}function jR(t,e){return t.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(r,n)=>{let s=DR(e,n.trim());return s==null?"":typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)})}function DR(t,e){let r=t;for(let n of e.split(".")){if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,n))return;r=r[n]}return r}function PR(t){if(t===null||t.trim().length===0)return null;try{return JSON.parse(t)}catch{return t}}var Vc=E(()=>{"use strict"});var vh={};Ee(vh,{enqueueFromAgentOutput:()=>UR,enqueueFromGitHubIssue:()=>Yc,enqueueManual:()=>FR,enqueueScheduled:()=>WR});function Yc(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:e.workflow_id_override??null,source:"gh_issue",source_ref:e.issue_url,dedupe_key:e.dedupe_key??e.issue_url,payload:fo(e.payload),concurrency_key:e.concurrency_key,priority:e.priority})}function FR(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"manual",source_ref:e.source_ref??null,dedupe_key:e.source_ref??null,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function UR(t,e){let r=e.sequence===void 0?`run:${e.parent_run_id}`:`run:${e.parent_run_id}:${e.sequence}`;return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"agent_output",source_ref:r,dedupe_key:r,available_at:e.available_at,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function WR(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"schedule",source_ref:e.source_ref,dedupe_key:e.source_ref,available_at:e.available_at,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function fo(t){return t==null?null:typeof t=="string"?t:JSON.stringify(t)}function mo(t,e){let r=e.concurrency_key;if(r!==void 0)return t.enqueueJob({...e,concurrency_key:r});let n=t.getProject(e.project_id),s=n===null?null:e.workflow_id_override!==void 0&&e.workflow_id_override!==null?t.getWorkflow(e.workflow_id_override):t.getWorkflowByName(n.workflow_name);if(n===null||s===null)return t.enqueueJob(e);try{let i=dt(s.definition),o={id:-1,project_id:e.project_id,workflow_id_override:e.workflow_id_override??null,source:e.source,source_ref:e.source_ref??null,payload:e.payload??null,status:"queued",priority:e.priority??0,available_at:e.available_at??new Date().toISOString(),locked_by:null,locked_until:null,attempt_count:0,last_error:null,dedupe_key:e.dedupe_key??null,concurrency_key_resolved:null,enqueued_at:new Date().toISOString(),started_at:null,ended_at:null,run_id:null},a=uo({workflow:i,job:o,project:n});return t.enqueueJob({...e,concurrency_key:a.concurrency_key})}catch{return t.enqueueJob(e)}}var zc=E(()=>{"use strict";_s();Vc()});async function Ih(t){let e=t.dal.listProjectWorkflows(t.project.id,{enabled_only:!0});if(e.length===0)return kh(t.dal,t.project.id,t.issue,t.issue.url,null,t.issue,void 0);let r={event:{kind:"github_issue",issue:t.issue}},n=[],s=0;for(let i of e){if(!await BR(i.condition,r))continue;let o=`${t.issue.url}#workflow:${i.workflow_id}`,a={issue:t.issue,...qR(i.parameters_override)},l=kh(t.dal,t.project.id,t.issue,o,i.workflow_id,a,-i.priority);n.push(...l.jobs),s+=l.new_jobs}return{jobs:n,new_jobs:s}}function kh(t,e,r,n,s,i,o){let a=t.findJobBySourceAndDedupe("gh_issue",n);return{jobs:[Yc(t,{project_id:e,issue_url:r.url,payload:i,workflow_id_override:s,dedupe_key:n,priority:o})],new_jobs:a===null?1:0}}async function BR(t,e){if(t===null||t.trim().length===0)return!0;try{return await Dr(t,e)===!0}catch{return!1}}function qR(t){if(t===null||t.trim().length===0)return{};try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{return{}}return{}}var Nh=E(()=>{"use strict";ms();zc()});import{spawnSync as HR}from"node:child_process";async function JR(t){let e=t.labels??["bug"],r=t.state??"open",n=["issue","list","--repo",t.project.name,"--state",r,"--json","number,title,url,body,state,labels","--limit","100"];e.length>0&&n.splice(4,0,"--label",e.join(","));let s=HR(t.binary??"gh",n,{encoding:"utf8",timeout:t.timeoutMs??6e4,maxBuffer:10*1024*1024});if(s.error!==void 0)throw s.error;if(s.status!==0)throw new Error(`gh issue list failed: ${s.stderr??""}`.trim());let i;try{i=JSON.parse(s.stdout??"[]")}catch{throw new Error("gh issue list returned malformed JSON")}if(!GR(i))throw new Error("gh issue list returned unexpected JSON shape");let o=0;for(let a of i){let l=await Ih({dal:t.dal,project:t.project,issue:KR(a)});o+=l.new_jobs}return{scanned:i.length,new_jobs:o}}async function po(t){if(process.env.LMCTL_INTAKE_DISABLED==="1")return[];let e=[];for(let r of t.listProjectsWithIntakeEnabled()){let n=XR(r.intake_config);try{let s=await JR({dal:t,project:r,labels:n.labels,state:n.state});e.push({project_id:r.id,project_name:r.name,...s})}catch(s){let i=s instanceof Error?s.message:String(s);e.push({project_id:r.id,project_name:r.name,scanned:0,new_jobs:0,error:i});try{t.raiseAttention({kind:"daemon_intake_scan_failed",severity:"warn",project_id:r.id,payload:JSON.stringify({project_id:r.id,project_name:r.name,error:i})})}catch{}}}return e}function XR(t){if(t===null)return{};try{let e=JSON.parse(t);if(!Zc(e))return{};let r=e.state==="open"||e.state==="closed"||e.state==="all"?e.state:void 0,n=Array.isArray(e.labels)?e.labels.filter(s=>typeof s=="string"&&s.length>0):void 0;return{scan_github_issues:e.scan_github_issues===!0,labels:n,state:r}}catch{return{}}}function GR(t){return Array.isArray(t)&&t.every(e=>{if(!Zc(e))return!1;let r=e.labels;return typeof e.number=="number"&&typeof e.title=="string"&&typeof e.url=="string"&&(typeof e.body=="string"||e.body===null||e.body===void 0)&&(e.state===void 0||typeof e.state=="string")&&(r===void 0||Array.isArray(r)&&r.every(n=>typeof n=="string"?!0:Zc(n)&&typeof n.name=="string"))})}function KR(t){let e=t.labels?.map(s=>typeof s=="string"?s:s.name),{labels:r,...n}=t;return e===void 0?n:{...n,labels:e}}function Zc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Qc=E(()=>{"use strict";Nh()});function Ah(t){return async e=>YR(t.app,e,t.log!==void 0?{log:t.log}:{})}async function YR(t,e,r={}){let n=zR(e.path),s={"content-type":"application/json",...e.headers??{},[_o]:ed},i={method:e.method,headers:s};e.body!==void 0&&e.method!=="GET"&&e.method!=="DELETE"&&(i.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let o=new Request(n,i),a=Date.now();try{let l=await t.fetch(o),c=await ZR(l);if(r.log!==void 0){let d=Date.now()-a;r.log(`[mailbox-dispatch] ${e.method} ${xh(e.path)} \u2192 ${c.status} (${d}ms)`)}return c}catch(l){if(r.log!==void 0){let c=Date.now()-a;r.log(`[mailbox-dispatch] ${e.method} ${xh(e.path)} \u2192 ERR (${c}ms)`)}throw l}}function xh(t){let e=t.startsWith("/")?t:`/${t}`,r=e.search(/[?#]/);return r===-1?e:e.slice(0,r)}function zR(t){let e=t.startsWith("/")?t:`/${t}`;return`${VR}${e}`}async function ZR(t){let e=await t.text(),r;if(e==="")r=void 0;else try{r=JSON.parse(e)}catch{r=e}let n={};t.headers.forEach((i,o)=>{o.toLowerCase()!==_o&&(n[o]=i)});let s={status:t.status};return Object.keys(n).length>0&&(s.headers=n),r!==void 0&&(s.body=r),s}var _o,ed,VR,td=E(()=>{"use strict";_o="x-mailbox-channel",ed="1",VR="http://mailbox.local"});import{createHash as Rh,createHmac as QR,timingSafeEqual as eL}from"node:crypto";function Lh(t={}){return async(e,r)=>{if(t.disabled===!0){await r();return}let n=Oh();if(n===null||iL(e.req.path)){await r();return}if(e.req.path.startsWith("/mailbox/")&&e.req.header(_o)===ed){await r();return}let s=e.req.query("token");if(s!==void 0&&ho(s,n)){nd(e,n),await r();return}if(sL(e,n)){await r();return}return e.req.path.startsWith("/api/")||e.req.path.startsWith("/mailbox/")?e.json({error:"API requires auth; set LMCTL_API_TOKEN"},401):e.redirect("/login",302)}}function Oh(){let t=process.env.LMCTL_API_TOKEN;return t&&t.length>0?t:null}function $h(t){let e=Oh();return e!==null&&ho(t,e)}function nd(t,e,r=new Date){t.header("Set-Cookie",`${rd}=${rL(e,r)}; Path=/; HttpOnly; SameSite=Lax`)}function Ch(t){t.header("Set-Cookie",`${rd}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`)}function rL(t,e=new Date){let n=`auth=ok|${new Date(e.getTime()+tL*24*60*60*1e3).toISOString()}`;return Buffer.from(`${n}|${Mh(t,n)}`,"utf8").toString("base64url")}function nL(t,e,r=new Date){let n;try{n=Buffer.from(t,"base64url").toString("utf8")}catch{return!1}let s=n.split("|");if(s.length!==3||s[0]!=="auth=ok")return!1;let i=new Date(s[1]);return Number.isNaN(i.getTime())||i.getTime()<=r.getTime()?!1:ho(s[2],Mh(e,`${s[0]}|${s[1]}`))}function ho(t,e){return eL(Rh("sha256").update(t).digest(),Rh("sha256").update(e).digest())}function sL(t,e){let r=/^Bearer\s+(.+)$/i.exec(t.req.header("authorization")??"")?.[1];if(r!==void 0&&ho(r,e))return!0;let n=oL(t.req.header("cookie")??"")[rd];return n!==void 0&&nL(n,e)}function iL(t){return t==="/login"||t==="/logout"}function oL(t){let e={};for(let r of t.split(";")){let[n,...s]=r.trim().split("=");n===void 0||n.length===0||s.length===0||(e[n]=s.join("="))}return e}function Mh(t,e){return QR("sha256",t).update(e).digest("hex")}var rd,tL,jh=E(()=>{"use strict";td();rd="lmctl_next_session",tL=30});import{existsSync as _n,mkdirSync as aL,readdirSync as lL,readFileSync as go,unlinkSync as cL,writeFileSync as od}from"node:fs";import{join as Pr}from"node:path";function rt(t){if(!dL.test(t))throw new Error(`invalid memory name "${t}": only alphanumeric characters, underscores, and hyphens are allowed`)}function Ph(t,e){let r=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(r===null)return null;let n=r[1],s=r[2].trimStart(),i=n.match(/^type:\s*(.+)$/m),o=n.match(/^description:\s*(.+)$/m),a=i?.[1]?.trim()??"";return pL(a)?{name:t,type:a,description:o?.[1]?.trim()??null,body:s,created_at:Dh,updated_at:Dh}:null}function uL(t,e,r,n){let s=r!==null?`
|
|
1949
|
+
`)){let r=e.replace(/#.*/,"").trim();if(r.length!==0)return/^workflow\s+\S+\s+v\d+\s*$/.test(r)}return!1}function dt(t){if(typeof t=="string"&&LR()&&OR(t)){let r;try{r=Eh(t)}catch(s){throw s instanceof pn?new Xt(s.issues.map(i=>({path:`dsl:${i.line}`,message:i.message}))):s}let n=xt.safeParse(r);if(!n.success)throw new Xt(n.error.issues.map(s=>({path:s.path.length===0?"$":s.path.map(String).join("."),message:s.message})));return n.data}let e=co(CR(t));if(MR(e)&&e.definition_schema_version===3){let r=xt.safeParse(e);if(!r.success)throw new Xt(r.error.issues.map(n=>({path:n.path.length===0?"$":n.path.map(String).join("."),message:n.message})));return r.data}return $R(e)}function $R(t){let e=ao.safeParse(t);if(!e.success)throw new Xt(e.error.issues.map(s=>({path:s.path.length===0?"$":s.path.map(String).join("."),message:s.message})));let r=e.data,n=new Set(["Task","Pause","Parallel","LoopUntil","Pass","Fail","Succeed"]);for(let[s,i]of Object.entries(r.states))if(n.has(i.type))throw new Xt([{path:`states.${s}`,message:`v2 workflows (primitive_version: 2) may not use v1 primitive type: ${i.type}`}]);try{return fh(r)}catch(s){throw s instanceof Ht?new Kc(s):s}}function CR(t){if(typeof t!="string")return t;let e=t.trim();return t.includes(`
|
|
1950
|
+
`)||e.startsWith("{")||e.startsWith("[")?Sh(t):e.endsWith(".json")?Sh(RR(e,"utf8")):t}function Sh(t){return JSON.parse(t)}function MR(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Kc,Xt,_s=E(()=>{"use strict";fn();ph();Gc();mn();bh();Kc=class extends Error{causeError;constructor(e){super("compiler emitted invalid atomic workflow"),this.causeError=e,this.name="CompilerInvariantError"}},Xt=class extends Error{issues;constructor(e){super("compound workflow validation failed"),this.issues=e,this.name="CompilerValidationError"}}});function uo(t){let e=t.workflow?.concurrent_limit??1,r=t.job.concurrency_key_resolved??t.workflow?.concurrency_key??null;return r===null||r.trim().length===0?{concurrency_key:null,concurrent_limit:e}:{concurrency_key:jR(r,{job:{id:t.job.id,kind:t.job.source,source:t.job.source,source_ref:t.job.source_ref,payload:PR(t.job.payload)},project:t.project===null?null:{id:t.project.id,name:t.project.name}}),concurrent_limit:e}}function jR(t,e){return t.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(r,n)=>{let s=DR(e,n.trim());return s==null?"":typeof s=="string"?s:typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)})}function DR(t,e){let r=t;for(let n of e.split(".")){if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,n))return;r=r[n]}return r}function PR(t){if(t===null||t.trim().length===0)return null;try{return JSON.parse(t)}catch{return t}}var Vc=E(()=>{"use strict"});var vh={};Ee(vh,{enqueueFromAgentOutput:()=>UR,enqueueFromGitHubIssue:()=>Yc,enqueueManual:()=>FR,enqueueScheduled:()=>WR});function Yc(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:e.workflow_id_override??null,source:"gh_issue",source_ref:e.issue_url,dedupe_key:e.dedupe_key??e.issue_url,payload:fo(e.payload),concurrency_key:e.concurrency_key,priority:e.priority})}function FR(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"manual",source_ref:e.source_ref??null,dedupe_key:e.source_ref??null,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function UR(t,e){let r=e.sequence===void 0?`run:${e.parent_run_id}`:`run:${e.parent_run_id}:${e.sequence}`;return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"agent_output",source_ref:r,dedupe_key:r,available_at:e.available_at,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function WR(t,e){return mo(t,{project_id:e.project_id,workflow_id_override:null,source:"schedule",source_ref:e.source_ref,dedupe_key:e.source_ref,available_at:e.available_at,payload:fo(e.payload),concurrency_key:e.concurrency_key})}function fo(t){return t==null?null:typeof t=="string"?t:JSON.stringify(t)}function mo(t,e){let r=e.concurrency_key;if(r!==void 0)return t.enqueueJob({...e,concurrency_key:r});let n=t.getProject(e.project_id),s=n===null?null:e.workflow_id_override!==void 0&&e.workflow_id_override!==null?t.getWorkflow(e.workflow_id_override):t.getWorkflowByName(n.workflow_name);if(n===null||s===null)return t.enqueueJob(e);try{let i=dt(s.definition),o={id:-1,project_id:e.project_id,workflow_id_override:e.workflow_id_override??null,source:e.source,source_ref:e.source_ref??null,payload:e.payload??null,status:"queued",priority:e.priority??0,available_at:e.available_at??new Date().toISOString(),locked_by:null,locked_until:null,attempt_count:0,last_error:null,dedupe_key:e.dedupe_key??null,concurrency_key_resolved:null,enqueued_at:new Date().toISOString(),started_at:null,ended_at:null,run_id:null},a=uo({workflow:i,job:o,project:n});return t.enqueueJob({...e,concurrency_key:a.concurrency_key})}catch{return t.enqueueJob(e)}}var zc=E(()=>{"use strict";_s();Vc()});async function Ih(t){let e=t.dal.listProjectWorkflows(t.project.id,{enabled_only:!0});if(e.length===0)return kh(t.dal,t.project.id,t.issue,t.issue.url,null,t.issue,void 0);let r={event:{kind:"github_issue",issue:t.issue}},n=[],s=0;for(let i of e){if(!await BR(i.condition,r))continue;let o=`${t.issue.url}#workflow:${i.workflow_id}`,a={issue:t.issue,...qR(i.parameters_override)},l=kh(t.dal,t.project.id,t.issue,o,i.workflow_id,a,-i.priority);n.push(...l.jobs),s+=l.new_jobs}return{jobs:n,new_jobs:s}}function kh(t,e,r,n,s,i,o){let a=t.findJobBySourceAndDedupe("gh_issue",n);return{jobs:[Yc(t,{project_id:e,issue_url:r.url,payload:i,workflow_id_override:s,dedupe_key:n,priority:o})],new_jobs:a===null?1:0}}async function BR(t,e){if(t===null||t.trim().length===0)return!0;try{return await Dr(t,e)===!0}catch{return!1}}function qR(t){if(t===null||t.trim().length===0)return{};try{let e=JSON.parse(t);if(e!==null&&typeof e=="object"&&!Array.isArray(e))return e}catch{return{}}return{}}var Nh=E(()=>{"use strict";ms();zc()});import{spawnSync as HR}from"node:child_process";async function XR(t){let e=t.labels??["bug"],r=t.state??"open",n=["issue","list","--repo",t.project.name,"--state",r,"--json","number,title,url,body,state,labels","--limit","100"];e.length>0&&n.splice(4,0,"--label",e.join(","));let s=HR(t.binary??"gh",n,{encoding:"utf8",timeout:t.timeoutMs??6e4,maxBuffer:10*1024*1024});if(s.error!==void 0)throw s.error;if(s.status!==0)throw new Error(`gh issue list failed: ${s.stderr??""}`.trim());let i;try{i=JSON.parse(s.stdout??"[]")}catch{throw new Error("gh issue list returned malformed JSON")}if(!GR(i))throw new Error("gh issue list returned unexpected JSON shape");let o=0;for(let a of i){let l=await Ih({dal:t.dal,project:t.project,issue:KR(a)});o+=l.new_jobs}return{scanned:i.length,new_jobs:o}}async function po(t){if(process.env.LMCTL_INTAKE_DISABLED==="1")return[];let e=[];for(let r of t.listProjectsWithIntakeEnabled()){let n=JR(r.intake_config);try{let s=await XR({dal:t,project:r,labels:n.labels,state:n.state});e.push({project_id:r.id,project_name:r.name,...s})}catch(s){let i=s instanceof Error?s.message:String(s);e.push({project_id:r.id,project_name:r.name,scanned:0,new_jobs:0,error:i});try{t.raiseAttention({kind:"daemon_intake_scan_failed",severity:"warn",project_id:r.id,payload:JSON.stringify({project_id:r.id,project_name:r.name,error:i})})}catch{}}}return e}function JR(t){if(t===null)return{};try{let e=JSON.parse(t);if(!Zc(e))return{};let r=e.state==="open"||e.state==="closed"||e.state==="all"?e.state:void 0,n=Array.isArray(e.labels)?e.labels.filter(s=>typeof s=="string"&&s.length>0):void 0;return{scan_github_issues:e.scan_github_issues===!0,labels:n,state:r}}catch{return{}}}function GR(t){return Array.isArray(t)&&t.every(e=>{if(!Zc(e))return!1;let r=e.labels;return typeof e.number=="number"&&typeof e.title=="string"&&typeof e.url=="string"&&(typeof e.body=="string"||e.body===null||e.body===void 0)&&(e.state===void 0||typeof e.state=="string")&&(r===void 0||Array.isArray(r)&&r.every(n=>typeof n=="string"?!0:Zc(n)&&typeof n.name=="string"))})}function KR(t){let e=t.labels?.map(s=>typeof s=="string"?s:s.name),{labels:r,...n}=t;return e===void 0?n:{...n,labels:e}}function Zc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Qc=E(()=>{"use strict";Nh()});function Ah(t){return async e=>YR(t.app,e,t.log!==void 0?{log:t.log}:{})}async function YR(t,e,r={}){let n=zR(e.path),s={"content-type":"application/json",...e.headers??{},[_o]:ed},i={method:e.method,headers:s};e.body!==void 0&&e.method!=="GET"&&e.method!=="DELETE"&&(i.body=typeof e.body=="string"?e.body:JSON.stringify(e.body));let o=new Request(n,i),a=Date.now();try{let l=await t.fetch(o),c=await ZR(l);if(r.log!==void 0){let d=Date.now()-a;r.log(`[mailbox-dispatch] ${e.method} ${xh(e.path)} \u2192 ${c.status} (${d}ms)`)}return c}catch(l){if(r.log!==void 0){let c=Date.now()-a;r.log(`[mailbox-dispatch] ${e.method} ${xh(e.path)} \u2192 ERR (${c}ms)`)}throw l}}function xh(t){let e=t.startsWith("/")?t:`/${t}`,r=e.search(/[?#]/);return r===-1?e:e.slice(0,r)}function zR(t){let e=t.startsWith("/")?t:`/${t}`;return`${VR}${e}`}async function ZR(t){let e=await t.text(),r;if(e==="")r=void 0;else try{r=JSON.parse(e)}catch{r=e}let n={};t.headers.forEach((i,o)=>{o.toLowerCase()!==_o&&(n[o]=i)});let s={status:t.status};return Object.keys(n).length>0&&(s.headers=n),r!==void 0&&(s.body=r),s}var _o,ed,VR,td=E(()=>{"use strict";_o="x-mailbox-channel",ed="1",VR="http://mailbox.local"});import{createHash as Rh,createHmac as QR,timingSafeEqual as eL}from"node:crypto";function Lh(t={}){return async(e,r)=>{if(t.disabled===!0){await r();return}let n=Oh();if(n===null||iL(e.req.path)){await r();return}if(e.req.path.startsWith("/mailbox/")&&e.req.header(_o)===ed){await r();return}let s=e.req.query("token");if(s!==void 0&&ho(s,n)){nd(e,n),await r();return}if(sL(e,n)){await r();return}return e.req.path.startsWith("/api/")||e.req.path.startsWith("/mailbox/")?e.json({error:"API requires auth; set LMCTL_API_TOKEN"},401):e.redirect("/login",302)}}function Oh(){let t=process.env.LMCTL_API_TOKEN;return t&&t.length>0?t:null}function $h(t){let e=Oh();return e!==null&&ho(t,e)}function nd(t,e,r=new Date){t.header("Set-Cookie",`${rd}=${rL(e,r)}; Path=/; HttpOnly; SameSite=Lax`)}function Ch(t){t.header("Set-Cookie",`${rd}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`)}function rL(t,e=new Date){let n=`auth=ok|${new Date(e.getTime()+tL*24*60*60*1e3).toISOString()}`;return Buffer.from(`${n}|${Mh(t,n)}`,"utf8").toString("base64url")}function nL(t,e,r=new Date){let n;try{n=Buffer.from(t,"base64url").toString("utf8")}catch{return!1}let s=n.split("|");if(s.length!==3||s[0]!=="auth=ok")return!1;let i=new Date(s[1]);return Number.isNaN(i.getTime())||i.getTime()<=r.getTime()?!1:ho(s[2],Mh(e,`${s[0]}|${s[1]}`))}function ho(t,e){return eL(Rh("sha256").update(t).digest(),Rh("sha256").update(e).digest())}function sL(t,e){let r=/^Bearer\s+(.+)$/i.exec(t.req.header("authorization")??"")?.[1];if(r!==void 0&&ho(r,e))return!0;let n=oL(t.req.header("cookie")??"")[rd];return n!==void 0&&nL(n,e)}function iL(t){return t==="/login"||t==="/logout"}function oL(t){let e={};for(let r of t.split(";")){let[n,...s]=r.trim().split("=");n===void 0||n.length===0||s.length===0||(e[n]=s.join("="))}return e}function Mh(t,e){return QR("sha256",t).update(e).digest("hex")}var rd,tL,jh=E(()=>{"use strict";td();rd="lmctl_next_session",tL=30});import{existsSync as _n,mkdirSync as aL,readdirSync as lL,readFileSync as go,unlinkSync as cL,writeFileSync as od}from"node:fs";import{join as Pr}from"node:path";function rt(t){if(!dL.test(t))throw new Error(`invalid memory name "${t}": only alphanumeric characters, underscores, and hyphens are allowed`)}function Ph(t,e){let r=e.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(r===null)return null;let n=r[1],s=r[2].trimStart(),i=n.match(/^type:\s*(.+)$/m),o=n.match(/^description:\s*(.+)$/m),a=i?.[1]?.trim()??"";return pL(a)?{name:t,type:a,description:o?.[1]?.trim()??null,body:s,created_at:Dh,updated_at:Dh}:null}function uL(t,e,r,n){let s=r!==null?`
|
|
1869
1951
|
description: ${r}`:"";return`---
|
|
1870
1952
|
name: ${t}${s}
|
|
1871
1953
|
type: ${e}
|
|
@@ -1874,12 +1956,12 @@ ${n}`}function fL(t,e,r,n){let s=Pr(t,ad),i=`- [${e}.md](${e}.md)${n!==null?` \u
|
|
|
1874
1956
|
`)?`${o}
|
|
1875
1957
|
${i}
|
|
1876
1958
|
`:`${o}${i}
|
|
1877
|
-
`,od(s,o,"utf8")}function mL(t,e){let r=Pr(t,ad);if(!_n(r))return;let n=go(r,"utf8"),s=new RegExp(`^- \\[${Fh(e)}\\.md\\].*$\\r?\\n?`,"m");s.test(n)&&od(r,n.replace(s,""),"utf8")}function Fh(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pL(t){return t==="user"||t==="feedback"||t==="project"||t==="reference"}function ut(t,e){return t.durable_memory_mode==="db"?new id(e,t.id):new sd(t.local_path)}var dL,ad,Dh,sd,id,ld=E(()=>{"use strict";dL=/^[a-zA-Z0-9_-]+$/;ad="MEMORY.md",Dh="1970-01-01T00:00:00.000Z",sd=class{dir;constructor(e){this.dir=Pr(e,"durable-memory")}read(e){rt(e);let r=Pr(this.dir,`${e}.md`);if(!_n(r))return null;let n=go(r,"utf8");return Ph(e,n)}write(e){rt(e.name),aL(this.dir,{recursive:!0});let r=Pr(this.dir,`${e.name}.md`),n=!_n(r),s=uL(e.name,e.type,e.description??null,e.body);return od(r,s,"utf8"),fL(this.dir,e.name,e.type,e.description??null),{created:n}}index(e){return this.listFiles().filter(r=>e===void 0||e.length===0||e.includes(r.type)).map(({name:r,type:n,description:s,updated_at:i})=>({name:r,type:n,description:s,updated_at:i}))}list(e){return this.listFiles().filter(r=>e===void 0||r.type===e).map(({name:r,type:n,updated_at:s})=>({name:r,type:n,updated_at:s}))}delete(e){rt(e);let r=Pr(this.dir,`${e}.md`);return _n(r)?(cL(r),mL(this.dir,e),!0):!1}listFiles(){if(!_n(this.dir))return[];let e=lL(this.dir).filter(n=>n.endsWith(".md")&&n!==ad),r=[];for(let n of e){let s=n.slice(0,-3),i=go(Pr(this.dir,n),"utf8"),o=Ph(s,i);o!==null&&r.push(o)}return r.sort((n,s)=>n.name.localeCompare(s.name))}};id=class{dal;projectId;constructor(e,r){this.dal=e,this.projectId=r}read(e){rt(e);let r=this.dal.getDurableMemoryByName(this.projectId,e);return r===null?null:{name:r.name,type:r.type,description:r.description,body:r.body,created_at:r.created_at,updated_at:r.updated_at}}write(e){rt(e.name);let r=this.dal.getDurableMemoryByName(this.projectId,e.name);return this.dal.upsertDurableMemory({project_id:this.projectId,type:e.type,name:e.name,description:e.description??null,body:e.body}),{created:r===null}}index(e){return this.dal.indexDurableMemory(this.projectId,e).map(n=>({name:n.name,type:n.type,description:n.description,updated_at:n.updated_at}))}list(e){return this.dal.listDurableMemory(this.projectId,e).map(n=>({name:n.name,type:n.type,updated_at:n.updated_at}))}delete(e){return rt(e),this.dal.deleteDurableMemory(this.projectId,e)}}});function Wh(t,e){let{dal:r}=e;t.get("/api/durable-memory/index/:project_id",n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o=ut(i,r),a=n.req.query("types"),l=a!==void 0&&a.length>0?a.split(",").map(c=>c.trim()).filter(Boolean):void 0;return n.json(o.index(l))}),t.get("/api/durable-memory/read/:project_id/:name",n=>{let s=Number(n.req.param("project_id")),i=n.req.param("name"),o=r.getProject(s);if(o===null)return n.json({error:"project not found"},404);let a=ut(o,r),l;try{l=a.read(i)}catch(c){return n.json({error:c.message},400)}return l===null?n.json({error:`memory entry not found: ${i}`},404):n.json(l)}),t.post("/api/durable-memory/write/:project_id",async n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o;try{o=await n.req.json()}catch{return n.json({error:"invalid JSON body"},400)}let a=typeof o.type=="string"?o.type:null,l=typeof o.name=="string"?o.name:null,c=typeof o.body=="string"?o.body:null,d=typeof o.description=="string"?o.description:null;if(a===null||!Uh.has(a))return n.json({error:`invalid type: must be one of ${[...Uh].join("|")}`},400);if(l===null)return n.json({error:"missing name"},400);if(c===null)return n.json({error:"missing body"},400);let u=ut(i,r),f;try{({created:f}=u.write({type:a,name:l,description:d,body:c}))}catch(m){return n.json({error:m.message},400)}return n.json({success:!0,created_or_updated:f?"created":"updated"})}),t.get("/api/durable-memory/list/:project_id",n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o=ut(i,r),a=n.req.query("type");return n.json(o.list(a))})}var Uh,Bh=E(()=>{"use strict";ld();Uh=new Set(["user","feedback","project","reference"])});function hL(t){let e=4294967295;for(let r=0;r<t.length;r+=1)e=(_L[(e^t[r])&255]^e>>>8)>>>0;return(e^4294967295)>>>0}function gL(t){let e=Math.max(1980,t.getFullYear()),r=(t.getHours()&31)<<11|(t.getMinutes()&63)<<5|Math.floor(t.getSeconds()/2)&31,n=(e-1980&127)<<9|(t.getMonth()+1&15)<<5|t.getDate()&31;return{time:r,date:n}}function qh(t,e=new Date){let{time:r,date:n}=gL(e),s=[],i=[],o=0,a=new TextEncoder;for(let h of t){let g=a.encode(h.name),_=hL(h.data),y=h.data.length,T=new Uint8Array(30+g.length),b=new DataView(T.buffer);b.setUint32(0,67324752,!0),b.setUint16(4,20,!0),b.setUint16(6,0,!0),b.setUint16(8,0,!0),b.setUint16(10,r,!0),b.setUint16(12,n,!0),b.setUint32(14,_,!0),b.setUint32(18,y,!0),b.setUint32(22,y,!0),b.setUint16(26,g.length,!0),b.setUint16(28,0,!0),T.set(g,30),s.push(T,h.data);let I=new Uint8Array(46+g.length),x=new DataView(I.buffer);x.setUint32(0,33639248,!0),x.setUint16(4,20,!0),x.setUint16(6,20,!0),x.setUint16(8,0,!0),x.setUint16(10,0,!0),x.setUint16(12,r,!0),x.setUint16(14,n,!0),x.setUint32(16,_,!0),x.setUint32(20,y,!0),x.setUint32(24,y,!0),x.setUint16(28,g.length,!0),x.setUint16(30,0,!0),x.setUint16(32,0,!0),x.setUint16(34,0,!0),x.setUint16(36,0,!0),x.setUint32(38,0,!0),x.setUint32(42,o,!0),I.set(g,46),i.push(I),o+=T.length+h.data.length}let l=o,c=0;for(let h of i)c+=h.length;let d=new Uint8Array(22),u=new DataView(d.buffer);u.setUint32(0,101010256,!0),u.setUint16(4,0,!0),u.setUint16(6,0,!0),u.setUint16(8,t.length,!0),u.setUint16(10,t.length,!0),u.setUint32(12,c,!0),u.setUint32(16,l,!0),u.setUint16(20,0,!0);let f=l+c+d.length,m=new Uint8Array(f),p=0;for(let h of s)m.set(h,p),p+=h.length;for(let h of i)m.set(h,p),p+=h.length;return m.set(d,p),m}var _L,Hh=E(()=>{"use strict";_L=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let n=0;n<8;n+=1)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})()});import{existsSync as Eo,mkdirSync as yL,readdirSync as wL,readFileSync as Gh,statSync as EL,unlinkSync as TL,writeFileSync as bL}from"node:fs";import{join as ys}from"node:path";function Kh(t,e){let{dal:r}=e;t.post("/api/projects",async n=>{let s=await ft(n);if(typeof s=="string")return R(n,s,400);let i=ae(s,"name"),o=ae(s,"local_path");if(i===null||i.length===0)return R(n,"missing or empty name",400);if(o===null||o.length===0)return R(n,"missing or empty local_path",400);if(r.findProjectByName(i)!==null)return R(n,`project already exists: ${i}`,409);let a=ae(s,"workflow_name")??"bugfix",l,c=ae(s,"team_name");if(c!==null&&c.length>0){let u=r.findTeamByName(c);if(u===null)return R(n,`team not found: ${c}`,404);l=u.id}else{let u=r.listTeams();if(u.length===0)return R(n,"no teams exist; create a team first",400);l=u[0].id}let d=r.insertProject({name:i,local_path:o,workflow_name:a,team_id:l,default_branch:ae(s,"default_branch")});return n.json(d,201)}),t.patch("/api/projects/:name",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o={};if(Object.prototype.hasOwnProperty.call(i,"local_path")){let l=i.local_path;if(typeof l!="string"||l.length===0)return R(n,"local_path must be a non-empty string",400);o.local_path=l}if(Object.prototype.hasOwnProperty.call(i,"durable_memory_mode")){let l=i.durable_memory_mode;if(l!=="folder"&&l!=="db")return R(n,'durable_memory_mode must be "folder" or "db"',400);o.durable_memory_mode=l}if(Object.prototype.hasOwnProperty.call(i,"default_branch")){let l=i.default_branch;if(l!==null&&typeof l!="string")return R(n,"default_branch must be string or null",400);o.default_branch=l}if(Object.prototype.hasOwnProperty.call(i,"intake_config")){let l=i.intake_config;if(l===null)o.intake_config=null;else if(typeof l=="string")o.intake_config=l;else if(typeof l=="object"&&!Array.isArray(l))o.intake_config=JSON.stringify(l);else return R(n,"intake_config must be a JSON object, string, or null",400)}let a=r.updateProjectSettings(s.id,o);return a===null?R(n,"project not found",404):n.json(a)}),t.post("/api/teams",async n=>{let s=await ft(n);if(typeof s=="string")return R(n,s,400);let i=ae(s,"name");if(i===null||i.length===0)return R(n,"missing or empty name",400);if(r.findTeamByName(i)!==null)return R(n,`team already exists: ${i}`,409);let o=r.insertTeam({name:i});return n.json(o,201)}),t.post("/api/teams/:name/members",async n=>{let s=r.findTeamByName(n.req.param("name"));if(s===null)return R(n,"team not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"alias"),a=ae(i,"provider");if(o===null||o.length===0)return R(n,"missing or empty alias",400);if(a===null||a.length===0)return R(n,"missing or empty provider",400);if(r.findTeamMemberByAlias(s.id,o)!==null)return R(n,`member already exists: ${o}`,409);let l=ae(i,"model"),c=r.insertTeamMember({team_id:s.id,alias:o,provider:a,model:l,sessiondir:`.lmctl/sessions/${s.name}/${o}`}),d=ae(i,"role_prompt");d!==null&&r.setMemberRolePrompt(c.id,d);let u=r.findTeamMemberByAlias(s.id,o);return n.json(u??c,201)}),t.put("/api/teams/:name/members/:alias",async n=>{let s=r.findTeamByName(n.req.param("name"));if(s===null)return R(n,"team not found",404);let i=r.findTeamMemberByAlias(s.id,n.req.param("alias"));if(i===null)return R(n,"member not found",404);let o=await ft(n);if(typeof o=="string")return R(n,o,400);let a={};if(Object.prototype.hasOwnProperty.call(o,"role_prompt")){let c=o.role_prompt;if(c!==null&&typeof c!="string")return R(n,"role_prompt must be string or null",400);a.role_prompt=c}if(Object.prototype.hasOwnProperty.call(o,"model")){let c=o.model;if(c!==null&&typeof c!="string")return R(n,"model must be string or null",400);a.model=c}if(Object.prototype.hasOwnProperty.call(o,"provider")){let c=o.provider;if(typeof c!="string"||c.length===0)return R(n,"provider must be a non-empty string",400);a.provider=c}if(Object.keys(a).length===0)return R(n,"no updatable fields provided",400);let l=r.updateTeamMemberMeta(i.id,a);return l===null?R(n,"member not found",404):n.json(l)}),t.get("/api/projects/:name/durable-memory",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r);return n.json(i.index())}),t.post("/api/projects/:name/durable-memory",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"name"),a=ae(i,"body"),l=ae(i,"type");if(o===null||o.length===0)return R(n,"missing or empty name",400);if(a===null)return R(n,"missing body",400);if(l===null||!yo.includes(l))return R(n,`invalid type: must be one of ${yo.join("|")}`,400);try{rt(o)}catch(u){return R(n,u.message,400)}let c=ut(s,r);try{if(c.read(o)!==null)return R(n,`chapter already exists: ${o}`,409)}catch(u){return R(n,u.message,400)}try{c.write({type:l,name:o,description:ae(i,"description"),body:a})}catch(u){return R(n,u.message,400)}let d=c.read(o);return d===null?R(n,"chapter created but unreadable",500):n.json(d,201)}),t.get("/api/projects/:name/durable-memory/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r),o;try{o=i.read(n.req.param("chapter"))}catch(a){return R(n,a.message,400)}return o===null?R(n,"chapter not found",404):n.json(o)}),t.put("/api/projects/:name/durable-memory/:chapter",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter"),o=await ft(n);if(typeof o=="string")return R(n,o,400);let a=ut(s,r),l;try{l=a.read(i)}catch(m){return R(n,m.message,400)}if(l===null)return R(n,"chapter not found",404);let c=ae(o,"body")??l.body,d=Object.prototype.hasOwnProperty.call(o,"description")?ae(o,"description"):l.description,u=ae(o,"type")??l.type;if(!yo.includes(u))return R(n,`invalid type: must be one of ${yo.join("|")}`,400);try{a.write({type:u,name:i,description:d,body:c})}catch(m){return R(n,m.message,400)}let f=a.read(i);return f===null?R(n,"chapter updated but unreadable",500):n.json(f)}),t.delete("/api/projects/:name/durable-memory/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r),o;try{o=i.delete(n.req.param("chapter"))}catch(a){return R(n,a.message,400)}return o?n.json({removed:!0}):R(n,"chapter not found",404)}),t.get("/api/projects/:name/ai-test",n=>{let s=r.findProjectByName(n.req.param("name"));return s===null?R(n,"project not found",404):n.json(vL(s.local_path))}),t.post("/api/projects/:name/ai-test",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"name"),a=ae(i,"body"),l=ae(i,"type");if(o===null||o.length===0)return R(n,"missing or empty name",400);if(a===null)return R(n,"missing body",400);if(l===null||!wo.has(l))return R(n,`invalid type: must be one of ${[...wo].join("|")}`,400);try{rt(o)}catch(f){return R(n,f.message,400)}let c=hs(s.local_path),d=ys(c,`${o}.md`);if(Eo(d))return R(n,`chapter already exists: ${o}`,409);yL(c,{recursive:!0}),Xh(d,o,l,ae(i,"description"),a);let u=gs(c,o);return u===null?R(n,"chapter created but unreadable",500):n.json(u,201)}),t.get("/api/projects/:name/ai-test/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);try{rt(n.req.param("chapter"))}catch(o){return R(n,o.message,400)}let i=gs(hs(s.local_path),n.req.param("chapter"));return i===null?R(n,"chapter not found",404):n.json(i)}),t.put("/api/projects/:name/ai-test/:chapter",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter");try{rt(i)}catch(m){return R(n,m.message,400)}let o=hs(s.local_path),a=gs(o,i);if(a===null)return R(n,"chapter not found",404);let l=await ft(n);if(typeof l=="string")return R(n,l,400);let c=ae(l,"body")??a.body,d=Object.prototype.hasOwnProperty.call(l,"description")?ae(l,"description"):a.description,u=ae(l,"type")??a.type;if(!wo.has(u))return R(n,`invalid type: must be one of ${[...wo].join("|")}`,400);Xh(ys(o,`${i}.md`),i,u,d,c);let f=gs(o,i);return f===null?R(n,"chapter updated but unreadable",500):n.json(f)}),t.delete("/api/projects/:name/ai-test/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter");try{rt(i)}catch(a){return R(n,a.message,400)}let o=ys(hs(s.local_path),`${i}.md`);return Eo(o)?(TL(o),n.json({removed:!0})):R(n,"chapter not found",404)}),t.get("/api/tokens",n=>n.json([])),t.post("/api/tokens",n=>R(n,"scoped-tokens table not yet migrated; see briefs/scoped-tokens-design.md",501)),t.get("/api/settings",n=>n.json({})),t.patch("/api/settings",async n=>{let s=await ft(n);return typeof s=="string"?R(n,s,400):n.json({accepted:s,note:"settings persistence not yet implemented"})}),t.get("/api/chat/sessions",n=>n.json(r.listChatbotSessions(Jh))),t.post("/api/chat/sessions",async n=>{let s=await SL(n);if(typeof s=="string")return R(n,s,400);let i=s!==null?ae(s,"title"):null,o=r.createChatbotSession(Jh,i);return n.json(o,201)}),t.get("/api/chat/sessions/:id/messages",n=>{let s=n.req.param("id");return r.getChatbotSession(s)===null?R(n,"chat session not found",404):n.json(r.listChatbotMessages(s))}),t.post("/api/chat/sessions/:id/messages",async n=>{let s=n.req.param("id");if(r.getChatbotSession(s)===null)return R(n,"chat session not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"role"),a=ae(i,"content");if(o===null||o!=="user"&&o!=="assistant"&&o!=="tool")return R(n,"role must be one of user|assistant|tool",400);if(a===null)return R(n,"missing content",400);let l=r.appendChatbotMessage(s,o,a);return n.json(l,201)}),t.get("/api/runs/:id/artifacts.zip",n=>{let s=Number(n.req.param("id"));if(!Number.isInteger(s))return R(n,"invalid run id",400);if(r.getRun(s)===null)return R(n,"run not found",404);let o=Mr(r,s),a=[];for(let c of o){let d=IL(c),u=null;if(c.content!==null&&c.content!==void 0)u=new TextEncoder().encode(c.content);else if(c.path!==null&&c.path!==void 0)try{let f=Gh(c.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength);u=new Uint8Array(m)}catch{u=new Uint8Array(0)}u!==null&&a.push({name:d,data:u})}let l=qh(a);return new Response(l,{status:200,headers:{"Content-Type":"application/zip","Content-Disposition":`attachment; filename="run-${s}-artifacts.zip"`,"Content-Length":String(l.byteLength)}})})}function R(t,e,r){return t.json({error:e},r)}async function ft(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"}}async function SL(t){let e=await t.req.text().catch(()=>"");if(e.trim().length===0)return null;try{let r=JSON.parse(e);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:"invalid JSON body"}catch{return"invalid JSON body"}}function ae(t,e){let r=t[e];return typeof r!="string"?null:r}function hs(t){return ys(t,"ai-test")}function gs(t,e){let r=ys(t,`${e}.md`);if(!Eo(r))return null;let n=Gh(r,"utf8"),s=kL(n),i=EL(r).mtime.toISOString();return{name:e,type:s.type,description:s.description,body:s.body,updated_at:i}}function vL(t){let e=hs(t);return Eo(e)?wL(e).filter(r=>r.endsWith(".md")&&r!=="index.md").map(r=>r.slice(0,-3)).sort().map(r=>{let n=gs(e,r);if(n===null)return null;let{name:s,type:i,description:o,updated_at:a}=n;return{name:s,type:i,description:o,updated_at:a}}).filter(r=>r!==null):[]}function Xh(t,e,r,n,s){let i=n!==null&&n.length>0?`
|
|
1959
|
+
`,od(s,o,"utf8")}function mL(t,e){let r=Pr(t,ad);if(!_n(r))return;let n=go(r,"utf8"),s=new RegExp(`^- \\[${Fh(e)}\\.md\\].*$\\r?\\n?`,"m");s.test(n)&&od(r,n.replace(s,""),"utf8")}function Fh(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pL(t){return t==="user"||t==="feedback"||t==="project"||t==="reference"}function ut(t,e){return t.durable_memory_mode==="db"?new id(e,t.id):new sd(t.local_path)}var dL,ad,Dh,sd,id,ld=E(()=>{"use strict";dL=/^[a-zA-Z0-9_-]+$/;ad="MEMORY.md",Dh="1970-01-01T00:00:00.000Z",sd=class{dir;constructor(e){this.dir=Pr(e,"durable-memory")}read(e){rt(e);let r=Pr(this.dir,`${e}.md`);if(!_n(r))return null;let n=go(r,"utf8");return Ph(e,n)}write(e){rt(e.name),aL(this.dir,{recursive:!0});let r=Pr(this.dir,`${e.name}.md`),n=!_n(r),s=uL(e.name,e.type,e.description??null,e.body);return od(r,s,"utf8"),fL(this.dir,e.name,e.type,e.description??null),{created:n}}index(e){return this.listFiles().filter(r=>e===void 0||e.length===0||e.includes(r.type)).map(({name:r,type:n,description:s,updated_at:i})=>({name:r,type:n,description:s,updated_at:i}))}list(e){return this.listFiles().filter(r=>e===void 0||r.type===e).map(({name:r,type:n,updated_at:s})=>({name:r,type:n,updated_at:s}))}delete(e){rt(e);let r=Pr(this.dir,`${e}.md`);return _n(r)?(cL(r),mL(this.dir,e),!0):!1}listFiles(){if(!_n(this.dir))return[];let e=lL(this.dir).filter(n=>n.endsWith(".md")&&n!==ad),r=[];for(let n of e){let s=n.slice(0,-3),i=go(Pr(this.dir,n),"utf8"),o=Ph(s,i);o!==null&&r.push(o)}return r.sort((n,s)=>n.name.localeCompare(s.name))}};id=class{dal;projectId;constructor(e,r){this.dal=e,this.projectId=r}read(e){rt(e);let r=this.dal.getDurableMemoryByName(this.projectId,e);return r===null?null:{name:r.name,type:r.type,description:r.description,body:r.body,created_at:r.created_at,updated_at:r.updated_at}}write(e){rt(e.name);let r=this.dal.getDurableMemoryByName(this.projectId,e.name);return this.dal.upsertDurableMemory({project_id:this.projectId,type:e.type,name:e.name,description:e.description??null,body:e.body}),{created:r===null}}index(e){return this.dal.indexDurableMemory(this.projectId,e).map(n=>({name:n.name,type:n.type,description:n.description,updated_at:n.updated_at}))}list(e){return this.dal.listDurableMemory(this.projectId,e).map(n=>({name:n.name,type:n.type,updated_at:n.updated_at}))}delete(e){return rt(e),this.dal.deleteDurableMemory(this.projectId,e)}}});function Wh(t,e){let{dal:r}=e;t.get("/api/durable-memory/index/:project_id",n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o=ut(i,r),a=n.req.query("types"),l=a!==void 0&&a.length>0?a.split(",").map(c=>c.trim()).filter(Boolean):void 0;return n.json(o.index(l))}),t.get("/api/durable-memory/read/:project_id/:name",n=>{let s=Number(n.req.param("project_id")),i=n.req.param("name"),o=r.getProject(s);if(o===null)return n.json({error:"project not found"},404);let a=ut(o,r),l;try{l=a.read(i)}catch(c){return n.json({error:c.message},400)}return l===null?n.json({error:`memory entry not found: ${i}`},404):n.json(l)}),t.post("/api/durable-memory/write/:project_id",async n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o;try{o=await n.req.json()}catch{return n.json({error:"invalid JSON body"},400)}let a=typeof o.type=="string"?o.type:null,l=typeof o.name=="string"?o.name:null,c=typeof o.body=="string"?o.body:null,d=typeof o.description=="string"?o.description:null;if(a===null||!Uh.has(a))return n.json({error:`invalid type: must be one of ${[...Uh].join("|")}`},400);if(l===null)return n.json({error:"missing name"},400);if(c===null)return n.json({error:"missing body"},400);let u=ut(i,r),f;try{({created:f}=u.write({type:a,name:l,description:d,body:c}))}catch(m){return n.json({error:m.message},400)}return n.json({success:!0,created_or_updated:f?"created":"updated"})}),t.get("/api/durable-memory/list/:project_id",n=>{let s=Number(n.req.param("project_id")),i=r.getProject(s);if(i===null)return n.json({error:"project not found"},404);let o=ut(i,r),a=n.req.query("type");return n.json(o.list(a))})}var Uh,Bh=E(()=>{"use strict";ld();Uh=new Set(["user","feedback","project","reference"])});function hL(t){let e=4294967295;for(let r=0;r<t.length;r+=1)e=(_L[(e^t[r])&255]^e>>>8)>>>0;return(e^4294967295)>>>0}function gL(t){let e=Math.max(1980,t.getFullYear()),r=(t.getHours()&31)<<11|(t.getMinutes()&63)<<5|Math.floor(t.getSeconds()/2)&31,n=(e-1980&127)<<9|(t.getMonth()+1&15)<<5|t.getDate()&31;return{time:r,date:n}}function qh(t,e=new Date){let{time:r,date:n}=gL(e),s=[],i=[],o=0,a=new TextEncoder;for(let h of t){let g=a.encode(h.name),_=hL(h.data),y=h.data.length,T=new Uint8Array(30+g.length),b=new DataView(T.buffer);b.setUint32(0,67324752,!0),b.setUint16(4,20,!0),b.setUint16(6,0,!0),b.setUint16(8,0,!0),b.setUint16(10,r,!0),b.setUint16(12,n,!0),b.setUint32(14,_,!0),b.setUint32(18,y,!0),b.setUint32(22,y,!0),b.setUint16(26,g.length,!0),b.setUint16(28,0,!0),T.set(g,30),s.push(T,h.data);let I=new Uint8Array(46+g.length),x=new DataView(I.buffer);x.setUint32(0,33639248,!0),x.setUint16(4,20,!0),x.setUint16(6,20,!0),x.setUint16(8,0,!0),x.setUint16(10,0,!0),x.setUint16(12,r,!0),x.setUint16(14,n,!0),x.setUint32(16,_,!0),x.setUint32(20,y,!0),x.setUint32(24,y,!0),x.setUint16(28,g.length,!0),x.setUint16(30,0,!0),x.setUint16(32,0,!0),x.setUint16(34,0,!0),x.setUint16(36,0,!0),x.setUint32(38,0,!0),x.setUint32(42,o,!0),I.set(g,46),i.push(I),o+=T.length+h.data.length}let l=o,c=0;for(let h of i)c+=h.length;let d=new Uint8Array(22),u=new DataView(d.buffer);u.setUint32(0,101010256,!0),u.setUint16(4,0,!0),u.setUint16(6,0,!0),u.setUint16(8,t.length,!0),u.setUint16(10,t.length,!0),u.setUint32(12,c,!0),u.setUint32(16,l,!0),u.setUint16(20,0,!0);let f=l+c+d.length,m=new Uint8Array(f),p=0;for(let h of s)m.set(h,p),p+=h.length;for(let h of i)m.set(h,p),p+=h.length;return m.set(d,p),m}var _L,Hh=E(()=>{"use strict";_L=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e+=1){let r=e;for(let n=0;n<8;n+=1)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})()});import{existsSync as Eo,mkdirSync as yL,readdirSync as wL,readFileSync as Gh,statSync as EL,unlinkSync as TL,writeFileSync as bL}from"node:fs";import{join as ys}from"node:path";function Kh(t,e){let{dal:r}=e;t.post("/api/projects",async n=>{let s=await ft(n);if(typeof s=="string")return R(n,s,400);let i=ae(s,"name"),o=ae(s,"local_path");if(i===null||i.length===0)return R(n,"missing or empty name",400);if(o===null||o.length===0)return R(n,"missing or empty local_path",400);if(r.findProjectByName(i)!==null)return R(n,`project already exists: ${i}`,409);let a=ae(s,"workflow_name")??"bugfix",l,c=ae(s,"team_name");if(c!==null&&c.length>0){let u=r.findTeamByName(c);if(u===null)return R(n,`team not found: ${c}`,404);l=u.id}else{let u=r.listTeams();if(u.length===0)return R(n,"no teams exist; create a team first",400);l=u[0].id}let d=r.insertProject({name:i,local_path:o,workflow_name:a,team_id:l,default_branch:ae(s,"default_branch")});return n.json(d,201)}),t.patch("/api/projects/:name",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o={};if(Object.prototype.hasOwnProperty.call(i,"local_path")){let l=i.local_path;if(typeof l!="string"||l.length===0)return R(n,"local_path must be a non-empty string",400);o.local_path=l}if(Object.prototype.hasOwnProperty.call(i,"durable_memory_mode")){let l=i.durable_memory_mode;if(l!=="folder"&&l!=="db")return R(n,'durable_memory_mode must be "folder" or "db"',400);o.durable_memory_mode=l}if(Object.prototype.hasOwnProperty.call(i,"default_branch")){let l=i.default_branch;if(l!==null&&typeof l!="string")return R(n,"default_branch must be string or null",400);o.default_branch=l}if(Object.prototype.hasOwnProperty.call(i,"intake_config")){let l=i.intake_config;if(l===null)o.intake_config=null;else if(typeof l=="string")o.intake_config=l;else if(typeof l=="object"&&!Array.isArray(l))o.intake_config=JSON.stringify(l);else return R(n,"intake_config must be a JSON object, string, or null",400)}let a=r.updateProjectSettings(s.id,o);return a===null?R(n,"project not found",404):n.json(a)}),t.post("/api/teams",async n=>{let s=await ft(n);if(typeof s=="string")return R(n,s,400);let i=ae(s,"name");if(i===null||i.length===0)return R(n,"missing or empty name",400);if(r.findTeamByName(i)!==null)return R(n,`team already exists: ${i}`,409);let o=r.insertTeam({name:i});return n.json(o,201)}),t.post("/api/teams/:name/members",async n=>{let s=r.findTeamByName(n.req.param("name"));if(s===null)return R(n,"team not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"alias"),a=ae(i,"provider");if(o===null||o.length===0)return R(n,"missing or empty alias",400);if(a===null||a.length===0)return R(n,"missing or empty provider",400);if(r.findTeamMemberByAlias(s.id,o)!==null)return R(n,`member already exists: ${o}`,409);let l=ae(i,"model"),c=r.insertTeamMember({team_id:s.id,alias:o,provider:a,model:l,sessiondir:`.lmctl/sessions/${s.name}/${o}`}),d=ae(i,"role_prompt");d!==null&&r.setMemberRolePrompt(c.id,d);let u=r.findTeamMemberByAlias(s.id,o);return n.json(u??c,201)}),t.put("/api/teams/:name/members/:alias",async n=>{let s=r.findTeamByName(n.req.param("name"));if(s===null)return R(n,"team not found",404);let i=r.findTeamMemberByAlias(s.id,n.req.param("alias"));if(i===null)return R(n,"member not found",404);let o=await ft(n);if(typeof o=="string")return R(n,o,400);let a={};if(Object.prototype.hasOwnProperty.call(o,"role_prompt")){let c=o.role_prompt;if(c!==null&&typeof c!="string")return R(n,"role_prompt must be string or null",400);a.role_prompt=c}if(Object.prototype.hasOwnProperty.call(o,"model")){let c=o.model;if(c!==null&&typeof c!="string")return R(n,"model must be string or null",400);a.model=c}if(Object.prototype.hasOwnProperty.call(o,"provider")){let c=o.provider;if(typeof c!="string"||c.length===0)return R(n,"provider must be a non-empty string",400);a.provider=c}if(Object.keys(a).length===0)return R(n,"no updatable fields provided",400);let l=r.updateTeamMemberMeta(i.id,a);return l===null?R(n,"member not found",404):n.json(l)}),t.get("/api/projects/:name/durable-memory",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r);return n.json(i.index())}),t.post("/api/projects/:name/durable-memory",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"name"),a=ae(i,"body"),l=ae(i,"type");if(o===null||o.length===0)return R(n,"missing or empty name",400);if(a===null)return R(n,"missing body",400);if(l===null||!yo.includes(l))return R(n,`invalid type: must be one of ${yo.join("|")}`,400);try{rt(o)}catch(u){return R(n,u.message,400)}let c=ut(s,r);try{if(c.read(o)!==null)return R(n,`chapter already exists: ${o}`,409)}catch(u){return R(n,u.message,400)}try{c.write({type:l,name:o,description:ae(i,"description"),body:a})}catch(u){return R(n,u.message,400)}let d=c.read(o);return d===null?R(n,"chapter created but unreadable",500):n.json(d,201)}),t.get("/api/projects/:name/durable-memory/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r),o;try{o=i.read(n.req.param("chapter"))}catch(a){return R(n,a.message,400)}return o===null?R(n,"chapter not found",404):n.json(o)}),t.put("/api/projects/:name/durable-memory/:chapter",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter"),o=await ft(n);if(typeof o=="string")return R(n,o,400);let a=ut(s,r),l;try{l=a.read(i)}catch(m){return R(n,m.message,400)}if(l===null)return R(n,"chapter not found",404);let c=ae(o,"body")??l.body,d=Object.prototype.hasOwnProperty.call(o,"description")?ae(o,"description"):l.description,u=ae(o,"type")??l.type;if(!yo.includes(u))return R(n,`invalid type: must be one of ${yo.join("|")}`,400);try{a.write({type:u,name:i,description:d,body:c})}catch(m){return R(n,m.message,400)}let f=a.read(i);return f===null?R(n,"chapter updated but unreadable",500):n.json(f)}),t.delete("/api/projects/:name/durable-memory/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=ut(s,r),o;try{o=i.delete(n.req.param("chapter"))}catch(a){return R(n,a.message,400)}return o?n.json({removed:!0}):R(n,"chapter not found",404)}),t.get("/api/projects/:name/ai-test",n=>{let s=r.findProjectByName(n.req.param("name"));return s===null?R(n,"project not found",404):n.json(vL(s.local_path))}),t.post("/api/projects/:name/ai-test",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"name"),a=ae(i,"body"),l=ae(i,"type");if(o===null||o.length===0)return R(n,"missing or empty name",400);if(a===null)return R(n,"missing body",400);if(l===null||!wo.has(l))return R(n,`invalid type: must be one of ${[...wo].join("|")}`,400);try{rt(o)}catch(f){return R(n,f.message,400)}let c=hs(s.local_path),d=ys(c,`${o}.md`);if(Eo(d))return R(n,`chapter already exists: ${o}`,409);yL(c,{recursive:!0}),Jh(d,o,l,ae(i,"description"),a);let u=gs(c,o);return u===null?R(n,"chapter created but unreadable",500):n.json(u,201)}),t.get("/api/projects/:name/ai-test/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);try{rt(n.req.param("chapter"))}catch(o){return R(n,o.message,400)}let i=gs(hs(s.local_path),n.req.param("chapter"));return i===null?R(n,"chapter not found",404):n.json(i)}),t.put("/api/projects/:name/ai-test/:chapter",async n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter");try{rt(i)}catch(m){return R(n,m.message,400)}let o=hs(s.local_path),a=gs(o,i);if(a===null)return R(n,"chapter not found",404);let l=await ft(n);if(typeof l=="string")return R(n,l,400);let c=ae(l,"body")??a.body,d=Object.prototype.hasOwnProperty.call(l,"description")?ae(l,"description"):a.description,u=ae(l,"type")??a.type;if(!wo.has(u))return R(n,`invalid type: must be one of ${[...wo].join("|")}`,400);Jh(ys(o,`${i}.md`),i,u,d,c);let f=gs(o,i);return f===null?R(n,"chapter updated but unreadable",500):n.json(f)}),t.delete("/api/projects/:name/ai-test/:chapter",n=>{let s=r.findProjectByName(n.req.param("name"));if(s===null)return R(n,"project not found",404);let i=n.req.param("chapter");try{rt(i)}catch(a){return R(n,a.message,400)}let o=ys(hs(s.local_path),`${i}.md`);return Eo(o)?(TL(o),n.json({removed:!0})):R(n,"chapter not found",404)}),t.get("/api/tokens",n=>n.json([])),t.post("/api/tokens",n=>R(n,"scoped-tokens table not yet migrated; see briefs/scoped-tokens-design.md",501)),t.get("/api/settings",n=>n.json({})),t.patch("/api/settings",async n=>{let s=await ft(n);return typeof s=="string"?R(n,s,400):n.json({accepted:s,note:"settings persistence not yet implemented"})}),t.get("/api/chat/sessions",n=>n.json(r.listChatbotSessions(Xh))),t.post("/api/chat/sessions",async n=>{let s=await SL(n);if(typeof s=="string")return R(n,s,400);let i=s!==null?ae(s,"title"):null,o=r.createChatbotSession(Xh,i);return n.json(o,201)}),t.get("/api/chat/sessions/:id/messages",n=>{let s=n.req.param("id");return r.getChatbotSession(s)===null?R(n,"chat session not found",404):n.json(r.listChatbotMessages(s))}),t.post("/api/chat/sessions/:id/messages",async n=>{let s=n.req.param("id");if(r.getChatbotSession(s)===null)return R(n,"chat session not found",404);let i=await ft(n);if(typeof i=="string")return R(n,i,400);let o=ae(i,"role"),a=ae(i,"content");if(o===null||o!=="user"&&o!=="assistant"&&o!=="tool")return R(n,"role must be one of user|assistant|tool",400);if(a===null)return R(n,"missing content",400);let l=r.appendChatbotMessage(s,o,a);return n.json(l,201)}),t.get("/api/runs/:id/artifacts.zip",n=>{let s=Number(n.req.param("id"));if(!Number.isInteger(s))return R(n,"invalid run id",400);if(r.getRun(s)===null)return R(n,"run not found",404);let o=Mr(r,s),a=[];for(let c of o){let d=IL(c),u=null;if(c.content!==null&&c.content!==void 0)u=new TextEncoder().encode(c.content);else if(c.path!==null&&c.path!==void 0)try{let f=Gh(c.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength);u=new Uint8Array(m)}catch{u=new Uint8Array(0)}u!==null&&a.push({name:d,data:u})}let l=qh(a);return new Response(l,{status:200,headers:{"Content-Type":"application/zip","Content-Disposition":`attachment; filename="run-${s}-artifacts.zip"`,"Content-Length":String(l.byteLength)}})})}function R(t,e,r){return t.json({error:e},r)}async function ft(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"}}async function SL(t){let e=await t.req.text().catch(()=>"");if(e.trim().length===0)return null;try{let r=JSON.parse(e);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:"invalid JSON body"}catch{return"invalid JSON body"}}function ae(t,e){let r=t[e];return typeof r!="string"?null:r}function hs(t){return ys(t,"ai-test")}function gs(t,e){let r=ys(t,`${e}.md`);if(!Eo(r))return null;let n=Gh(r,"utf8"),s=kL(n),i=EL(r).mtime.toISOString();return{name:e,type:s.type,description:s.description,body:s.body,updated_at:i}}function vL(t){let e=hs(t);return Eo(e)?wL(e).filter(r=>r.endsWith(".md")&&r!=="index.md").map(r=>r.slice(0,-3)).sort().map(r=>{let n=gs(e,r);if(n===null)return null;let{name:s,type:i,description:o,updated_at:a}=n;return{name:s,type:i,description:o,updated_at:a}}).filter(r=>r!==null):[]}function Jh(t,e,r,n,s){let i=n!==null&&n.length>0?`
|
|
1878
1960
|
description: ${n}`:"",o=`---
|
|
1879
1961
|
name: ${e}${i}
|
|
1880
1962
|
type: ${r}
|
|
1881
1963
|
---
|
|
1882
|
-
${s}`;bL(t,o,"utf8")}function kL(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return{type:"scenario",description:null,body:t};let r=e[1],n=e[2].trimStart(),s=r.match(/^type:\s*(.+)$/m),i=r.match(/^description:\s*(.+)$/m);return{type:s?.[1]?.trim()??"scenario",description:i?.[1]?.trim()??null,body:n}}function IL(t){let e=t.state_name.replace(/[^a-zA-Z0-9_-]+/g,"_"),r=t.kind.replace(/[^a-zA-Z0-9_-]+/g,"_"),n=t.path!==null?NL(t.path):xL(t.kind);return`step-${t.step_id}-${e}/${t.id}-${r}${n}`}function NL(t){let e=t.lastIndexOf(".");if(e<0)return"";let r=t.slice(e);return/^\.[A-Za-z0-9]+$/.test(r)?r:""}function xL(t){return t.endsWith("_md")||t.includes("markdown")?".md":t.endsWith("_json")||t.includes("json")?".json":".txt"}var yo,wo,
|
|
1964
|
+
${s}`;bL(t,o,"utf8")}function kL(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return{type:"scenario",description:null,body:t};let r=e[1],n=e[2].trimStart(),s=r.match(/^type:\s*(.+)$/m),i=r.match(/^description:\s*(.+)$/m);return{type:s?.[1]?.trim()??"scenario",description:i?.[1]?.trim()??null,body:n}}function IL(t){let e=t.state_name.replace(/[^a-zA-Z0-9_-]+/g,"_"),r=t.kind.replace(/[^a-zA-Z0-9_-]+/g,"_"),n=t.path!==null?NL(t.path):xL(t.kind);return`step-${t.step_id}-${e}/${t.id}-${r}${n}`}function NL(t){let e=t.lastIndexOf(".");if(e<0)return"";let r=t.slice(e);return/^\.[A-Za-z0-9]+$/.test(r)?r:""}function xL(t){return t.endsWith("_md")||t.includes("markdown")?".md":t.endsWith("_json")||t.includes("json")?".json":".txt"}var yo,wo,Xh,Vh=E(()=>{"use strict";qt();Hh();ld();yo=["user","feedback","project","reference"],wo=new Set(["smoke","integration","vision","scenario","regression"]),Xh="operator"});function Re(t,e){return`<!doctype html>
|
|
1883
1965
|
<html lang="en">
|
|
1884
1966
|
<head>
|
|
1885
1967
|
<meta charset="utf-8">
|
|
@@ -1947,40 +2029,40 @@ ${s}`;bL(t,o,"utf8")}function kL(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r
|
|
|
1947
2029
|
JOIN step s ON s.id = sa.step_id
|
|
1948
2030
|
WHERE s.run_id = ? ORDER BY sa.id ASC`,t),l=new Map;for(let A of a){let ee=l.get(A.step_id)??[];ee.push({kind:A.kind,id:A.id}),l.set(A.step_id,ee)}let c=o.map(A=>({id:A.id,state_name:A.state_name,outcome:A.outcome,duration_ms:A.started_at!==null&&A.ended_at!==null?Math.max(0,new Date(A.ended_at).getTime()-new Date(A.started_at).getTime()):null,artifacts:l.get(A.id)??[]})),d=e.query("SELECT kind, COUNT(*) AS count FROM session_event WHERE run_id = ? GROUP BY kind",t),u=e.query("SELECT payload FROM session_event WHERE run_id = ? AND kind = 'tool_result' AND payload_truncated = 0",t),f=0;for(let A of u)try{let ee=JSON.parse(A.payload);typeof ee.elapsedMs=="number"&&ee.elapsedMs>0&&(f+=ee.elapsedMs)}catch{}let m=d.map(A=>({kind:A.kind,count:A.count,total_elapsed_ms:A.kind==="tool_result"?f:0})),p=c.filter(A=>A.outcome==="request_changes"),h=[...new Set(p.map(A=>A.state_name))],g=new Date(n.started_at).getTime(),_=n.ended_at!==null?new Date(n.ended_at).getTime():Date.now(),T=e.query("SELECT project_id FROM job WHERE id = ?",n.job_id)[0]?.project_id??null,b=T!==null?e.query(`SELECT id, signal_kind, severity, description, detected_at FROM drift_signal
|
|
1949
2031
|
WHERE project_id = ? AND detected_at >= ? AND detected_at <= ? ORDER BY detected_at ASC`,T,g,_):[],x=e.query(`SELECT SUM(input_tokens) AS input, SUM(output_tokens) AS output
|
|
1950
|
-
FROM session_size WHERE observed_at >= ? AND observed_at <= ?`,n.started_at,n.ended_at??new Date().toISOString())[0],H=x?.input!==null&&x?.input!==void 0?`input: ${x.input}, output: ${x.output??0}`:"n/a",pe=e.getWorkflow(n.workflow_id),U=n.started_at!==null&&n.ended_at!==null?Math.max(0,new Date(n.ended_at).getTime()-new Date(n.started_at).getTime()):null,j={run_id:t,workflow_name:pe?.name??null,started_at:n.started_at,ended_at:n.ended_at,terminal_state:n.terminal_state,duration_ms:U,steps:c,tool_stats:m,reviewer_interventions:{count:p.length,state_names:h},drift_signals:b,token_totals:H};e.insertStepArtifact({step_id:i,kind:"run_report",content:JSON.stringify(j)})}var sg=E(()=>{"use strict"});import{spawnSync as og}from"node:child_process";function _d(t){return qL[t]??`no install hint; ensure '${t}' is on PATH`}function HL(t){switch(t){case"gh":return{args:["auth","status"]};case"claude":case"codex":case"gemini":case"qwen":return{args:["auth","status"]};case"opencode":return{args:["auth","list"]};default:return null}}function ig(t){return og("which",[t],{encoding:"utf8"}).status===0}function ag(t){if(t===void 0)return null;for(let e of t.tools??[])if(!ig(e)){let r=_d(e);return{kind:"missing_tool",tool:e,install_hint:r,message:`missing dependency: ${e}; ${r}`}}for(let e of t.auth??[]){if(!ig(e)){let s=_d(e);return{kind:"missing_tool",tool:e,install_hint:s,message:`missing dependency: ${e}; ${s}`}}let r=HL(e);if(r===null)continue;let n=og(e,r.args,{encoding:"utf8"});if(n.status!==0){let s=typeof n.stderr=="string"?n.stderr.trim():"";return{kind:"auth_failed",tool:e,install_hint:_d(e),message:`${e} not authenticated; run \`${e} login\` or equivalent`,detail:s.length>0?s:void 0}}}return null}var qL,lg=E(()=>{"use strict";qL={gh:"install: https://cli.github.com/",git:"install: apt-get install git OR brew install git",node:"install: https://nodejs.org/",claude:"install: https://docs.anthropic.com/en/docs/claude-code/quickstart",codex:"install: https://github.com/openai/codex",gemini:"install: https://github.com/google-gemini/gemini-cli",opencode:"install: https://opencode.ai/",qwen:"install: https://github.com/QwenLM/qwen-code"}});import{existsSync as
|
|
1951
|
-
`).map(i=>i.replace(/^\s*-\s+/,"").trim()).filter(Boolean):[]}function dg(t,e){let r=t.match(/^---\n([\s\S]*?)\n---/);if(!r)return null;let s=r[1].match(new RegExp(`^${e}:\\s*(.+)$`,"m"));return s?s[1].trim():null}function ug(t,e){if(e.length===0)return null;let r=cg(t,"durable-memory");if(!
|
|
2032
|
+
FROM session_size WHERE observed_at >= ? AND observed_at <= ?`,n.started_at,n.ended_at??new Date().toISOString())[0],H=x?.input!==null&&x?.input!==void 0?`input: ${x.input}, output: ${x.output??0}`:"n/a",pe=e.getWorkflow(n.workflow_id),U=n.started_at!==null&&n.ended_at!==null?Math.max(0,new Date(n.ended_at).getTime()-new Date(n.started_at).getTime()):null,j={run_id:t,workflow_name:pe?.name??null,started_at:n.started_at,ended_at:n.ended_at,terminal_state:n.terminal_state,duration_ms:U,steps:c,tool_stats:m,reviewer_interventions:{count:p.length,state_names:h},drift_signals:b,token_totals:H};e.insertStepArtifact({step_id:i,kind:"run_report",content:JSON.stringify(j)})}var sg=E(()=>{"use strict"});import{spawnSync as og}from"node:child_process";function _d(t){return qL[t]??`no install hint; ensure '${t}' is on PATH`}function HL(t){switch(t){case"gh":return{args:["auth","status"]};case"claude":case"codex":case"gemini":case"qwen":return{args:["auth","status"]};case"opencode":return{args:["auth","list"]};default:return null}}function ig(t){return og("which",[t],{encoding:"utf8"}).status===0}function ag(t){if(t===void 0)return null;for(let e of t.tools??[])if(!ig(e)){let r=_d(e);return{kind:"missing_tool",tool:e,install_hint:r,message:`missing dependency: ${e}; ${r}`}}for(let e of t.auth??[]){if(!ig(e)){let s=_d(e);return{kind:"missing_tool",tool:e,install_hint:s,message:`missing dependency: ${e}; ${s}`}}let r=HL(e);if(r===null)continue;let n=og(e,r.args,{encoding:"utf8"});if(n.status!==0){let s=typeof n.stderr=="string"?n.stderr.trim():"";return{kind:"auth_failed",tool:e,install_hint:_d(e),message:`${e} not authenticated; run \`${e} login\` or equivalent`,detail:s.length>0?s:void 0}}}return null}var qL,lg=E(()=>{"use strict";qL={gh:"install: https://cli.github.com/",git:"install: apt-get install git OR brew install git",node:"install: https://nodejs.org/",claude:"install: https://docs.anthropic.com/en/docs/claude-code/quickstart",codex:"install: https://github.com/openai/codex",gemini:"install: https://github.com/google-gemini/gemini-cli",opencode:"install: https://opencode.ai/",qwen:"install: https://github.com/QwenLM/qwen-code"}});import{existsSync as XL,readdirSync as JL,readFileSync as GL}from"node:fs";import{join as cg}from"node:path";function KL(t){let e=t.match(/^---\n([\s\S]*?)\n---/);if(!e)return[];let r=e[1],n=r.match(/^tags:\s*\[([^\]]*)\]/m);if(n)return n[1].split(",").map(i=>i.trim()).filter(Boolean);let s=r.match(/^tags:\s*\n((?:\s*-\s+.+\n?)*)/m);return s?s[1].split(`
|
|
2033
|
+
`).map(i=>i.replace(/^\s*-\s+/,"").trim()).filter(Boolean):[]}function dg(t,e){let r=t.match(/^---\n([\s\S]*?)\n---/);if(!r)return null;let s=r[1].match(new RegExp(`^${e}:\\s*(.+)$`,"m"));return s?s[1].trim():null}function ug(t,e){if(e.length===0)return null;let r=cg(t,"durable-memory");if(!XL(r))return null;let n;try{n=JL(r).filter(i=>i.endsWith(".md")&&i!=="index.md")}catch{return null}let s=[];for(let i of n)try{let o=GL(cg(r,i),"utf8");if(KL(o).some(l=>e.includes(l))){let l=dg(o,"name")??i.replace(".md",""),c=dg(o,"description");s.push(c?`${l} (${c})`:l)}}catch{}return s.length===0?null:`[Durable-memory entries relevant to this task: ${s.join(", ")}. Pull the full chapter as needed.]`}var fg=E(()=>{"use strict"});function yd(t){let e=t.trim().replace(VL,"").trim();for(let r=0;r<4;r+=1){let n=YL.exec(e);if(n===null)break;e=n[2].trim()}return e}function mg(t){let e=t.trim(),r=zL.exec(e);if(r!==null)return r[2];let n=ZL.exec(e);return n!==null?n[0]:null}function Ts(t,e){let r=t.split(`
|
|
1952
2034
|
`),n=null,s=-1;for(let o=0;o<r.length;o+=1){let a=yd(r[o]),l=hd.exec(a);if(l===null)continue;let c=l[1].trim();if(gd.test(c))continue;let d=mg(c);d!==null&&(n=d,s=o)}if(n===null)return{outcome:null,reason:"no_stance"};if(!e.includes(n))return{outcome:null,reason:"unknown_outcome",actual:n};let i={};for(let o=s-1;o>=0;o-=1){let a=yd(r[o]),l=hd.exec(a);if(l===null)break;let c=gd.exec(l[1].trim());if(c===null)break;i[c[1]]=c[2].trim()}return{outcome:n,evidence:i}}function pg(t){let e=t.split(`
|
|
1953
|
-
`),r=null;for(let n=0;n<e.length;n+=1){let s=yd(e[n]),i=hd.exec(s);if(i===null)continue;let o=i[1].trim();if(gd.test(o))continue;let a=mg(o);if(a===null||!zr(a))continue;let c=o.slice(o.indexOf(a)+a.length).replace(/^[`*_:\s\-–—]+/,"").trim();r={token:a,reason:c}}return r}var VL,YL,hd,gd,zL,ZL,wd=E(()=>{"use strict";Zn();VL=/^#{1,6}\s+/,YL=/^(```|\*\*|__|`|\*|_)([\s\S]+?)\1$/,hd=/^STANCE:\s+(.+)$/,gd=/^([A-Z][A-Z0-9_]*):\s*(.+)$/,zL=/^(```|\*\*|__|`|\*|_)([A-Za-z0-9_-]+)\1/,ZL=/^[A-Za-z0-9_-]+/});function _g(t,e,r){return n=>{let s=r(),i=Date.now(),o=JSON.stringify({kind:n.kind,tool:n.tool??null,summary:n.summary??null,id:n.id??null,elapsedMs:n.elapsedMs??null,status:n.status??null}),a=Buffer.byteLength(o,"utf8");if(a<=262144){t.insertSessionEvent({run_id:e,step_id:s,kind:n.kind,timestamp_ms:i,payload:o});return}let l=o.slice(0,1024),c=JSON.stringify({truncated:!0,size:a,preview:l});if(s!==null){let d=t.insertStepArtifact({step_id:s,kind:"session_event_overflow",content:o});t.insertSessionEvent({run_id:e,step_id:s,kind:n.kind,timestamp_ms:i,payload:c,payload_truncated:1,overflow_artifact_id:d.id})}else t.insertSessionEvent({run_id:e,step_id:null,kind:n.kind,timestamp_ms:i,payload:c,payload_truncated:1,overflow_artifact_id:null})}}var hg=E(()=>{"use strict"});import{readFileSync as QL}from"node:fs";import{dirname as eO,join as tO}from"node:path";import{fileURLToPath as rO}from"node:url";function iO(t){return t.rules.map(e=>({command:e.command,subcommands:e.argv_patterns.map(r=>r.trim().split(/\s+/)),kind:e.kind}))}function cO(t){let e=[],r=[];for(let n of t)nO.has(n)?(r.length>0&&e.push(r),r=[]):r.push(n);return r.length>0&&e.push(r),e}function dO(t,e){if(t.length===0)return{matched:!1};let r=0;for(;r<t.length&&sO.test(t[r]);)r+=1;if(r>=t.length)return{matched:!1};let n=t[r],s=t.slice(r+1);for(let i of e)if(n===i.command){for(let o of i.subcommands)if(o.every((l,c)=>s[c]===l))return{matched:!0,kind:i.kind}}return{matched:!1}}function uO(t,e){if(t.length===0)return{matched:!1};let r=cO(t);for(let n of r){let s=dO(n,e);if(s.matched)return s}return{matched:!1}}function Ed(t){return uO(t,lO)}function fO(t){return t.replace(/&&/g," && ").replace(/\|\|/g," || ").replace(/;/g," ; ").replace(/\|/g," | ").replace(/(?<!\d)>{1,2}/g,e=>` ${e} `).replace(/(?<!\d)<{1,2}/g,e=>` ${e} `).replace(/\s+/g," ").trim()}function Td(t){return fO(t).split(" ").filter(e=>e.length>0)}var nO,sO,oO,aO,lO,gg=E(()=>{"use strict";nO=new Set(["&&","||",";","|",">",">>","<","<<"]),sO=/^[A-Za-z_][A-Za-z0-9_]*=/;oO=eO(rO(import.meta.url)),aO=JSON.parse(QL(tO(oO,"side_effect_classifier.json"),"utf-8")),lO=iO(aO)});function vo(t){return{context:{outcomes:t.outcomes,inputs:t.inputs,item:t.iteration?.item,index:t.iteration?.index},outcomes:t.outcomes,inputs:t.inputs,item:t.iteration?.item,index:t.iteration?.index}}async function yg(t,e){try{return await Dr(bd(t)??t,vo(e))===!0}catch{return!1}}async function ko(t,e){try{return await Dr(bd(t)??t,vo(e))}catch{return}}async function wg(t,e){if(typeof t!="string")return t;let r=bd(t);if(r===null)return t;try{return await Dr(r,vo(e))}catch{return}}async function Eg(t,e){let r=Array.from(t.matchAll(/=\{\{([\s\S]*?)\}\}/g));if(r.length===0)return t;let n="",s=0;for(let i of r){let o=i.index??0;n+=t.slice(s,o);let a=i[1]?.trim()??"";try{n+=mO(await Dr(a,vo(e)))}catch{n+=""}s=o+i[0].length}return n+=t.slice(s),n}function bd(t){let e=t.trim();return!e.startsWith("={{")||!e.endsWith("}}")?null:e.slice(3,-2).trim()}function mO(t){return t==null?"":typeof t=="string"?t:JSON.stringify(t)}var bs=E(()=>{"use strict";ms()});import{existsSync as Tg,readdirSync as bg,readFileSync as pO,statSync as Sg}from"node:fs";import{join as No}from"node:path";function vg(t,e,r,n){return Object.assign(t,{stateId:e,state:r,displayName:n})}function q(t,e){return t.dal.insertStep({...e,parent_step_id:t.parent_step_id})}function
|
|
1954
|
-
\u2026[truncated ${t.length-8e3} chars]`:t}function G(t,e,r,n){t.outcomes[e]=n,r!==e&&(t.outcomes[r]=n)}function Y(t){return t.terminals.aborted?.kind==="failure"?"aborted":Object.entries(t.terminals).find(([,r])=>r.kind==="failure")?.[0]??Object.keys(t.terminals)[0]??"aborted"}function kg(t,e){let r=e.trim();if(r.startsWith("[")){try{let n=JSON.parse(r);if(Array.isArray(n)&&n.every(s=>typeof s=="string"))return n}catch{return null}return null}if(r.startsWith("job.payload.")){let n=r.slice(12);if(n.length===0)return null;let i=mr(t.job.payload)?.[n];if(Array.isArray(i)&&i.every(o=>typeof o=="string"))return i}return null}async function Ge(t,e,r){let n=t.replace(/(?<!=)\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}/g,(s,i)=>{if(i==="run_id")return String(e.run_id);if(i==="state_id")return r;if(i==="item")return e.iteration?.item??"";if(i==="index")return e.iteration===null?"":String(e.iteration.index);if(i.startsWith("project.")){let o=i.slice(8);if(o==="id")return String(e.project.id);if(o==="name")return e.project.name;if(o==="local_path")return e.project.local_path;if(o==="default_branch")return e.project.default_branch??"";if(o==="owner"){let a=e.project.name.indexOf("/");return a>0?e.project.name.slice(0,a):""}if(o==="repo"){let a=e.project.name.indexOf("/");return a>0?e.project.name.slice(a+1):e.project.name}if(o==="test_command"){let a=e.project.test_command;return a===null||a===""?"npm test":a}return""}if(i==="job_payload"){let o=mr(e.job.payload);return o===null?"":JSON.stringify(o)}if(i.startsWith("job_payload.")){let o=i.slice(12),l=mr(e.job.payload)?.[o];return l==null?"":String(l)}if(i.startsWith("outcomes.")){let o=hO(e.outcomes,i.slice(9));return o==null?"":typeof o=="string"?o:JSON.stringify(o)}return""});return Eg(n,e)}function hO(t,e){let r=t;for(let n of e.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[n]}return r}function mr(t){if(t===null)return null;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}async function vs(t){let{context:e,stateId:r,member:n,prompt:s,stepId:i,timeoutMs:o,writesToProjectPath:a}=t,l=_g(e.dal,e.run_id,()=>i),c=Sd(e,r),d={violation:null},u=y=>{if(l(y),d.violation===null&&y.kind==="tool_use"&&y.tool==="Bash"&&y.summary){let T=Td(y.summary),b=Ed(T);b.matched&&!c&&(d.violation={summary:y.summary,kind:b.kind})}},f=new Date(Date.now()-1),m=0,p=0,h=y=>{u(y),gO(y,(T,b)=>{m+=T,p+=b})},g=await ji({sessionid:n.sessionid,sessiondir:n.sessiondir,prompt:s,timeoutMs:o,dal:e.dal,team_member_id:n.id,onProgress:h});e.dal.insertSessionEvent({run_id:e.run_id,step_id:i,kind:"agent_call",timestamp_ms:Date.now(),payload:JSON.stringify({alias:n.alias,provider:Be(n),model:n.model??"unknown",tokens_in:m,tokens_out:p,wall_time_ms:g.ms})}),yO(e.project,e.dal,f);let _=d.violation;return _!==null?{kind:"g3_violation",summary:_.summary,violationKind:_.kind}:!a&&e.project.local_path.trim().length>0&&vd(e.project.local_path,f)?{kind:"g2_violation"}:{kind:"ok",text:g.text,ms:g.ms,argv:g.argv}}function gO(t,e){let r=t.raw;if(r==null)return;let s=r.message?.usage;if(s!==void 0){let o=Io(s.input_tokens),a=Io(s.output_tokens);(o>0||a>0)&&e(o,a);return}let i=r.usage;if(i!==void 0){let o=Io(i.input_tokens),a=Io(i.output_tokens);(o>0||a>0)&&e(o,a)}}function Io(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:0}async function
|
|
2035
|
+
`),r=null;for(let n=0;n<e.length;n+=1){let s=yd(e[n]),i=hd.exec(s);if(i===null)continue;let o=i[1].trim();if(gd.test(o))continue;let a=mg(o);if(a===null||!zr(a))continue;let c=o.slice(o.indexOf(a)+a.length).replace(/^[`*_:\s\-–—]+/,"").trim();r={token:a,reason:c}}return r}var VL,YL,hd,gd,zL,ZL,wd=E(()=>{"use strict";Zn();VL=/^#{1,6}\s+/,YL=/^(```|\*\*|__|`|\*|_)([\s\S]+?)\1$/,hd=/^STANCE:\s+(.+)$/,gd=/^([A-Z][A-Z0-9_]*):\s*(.+)$/,zL=/^(```|\*\*|__|`|\*|_)([A-Za-z0-9_-]+)\1/,ZL=/^[A-Za-z0-9_-]+/});function _g(t,e,r){return n=>{let s=r(),i=Date.now(),o=JSON.stringify({kind:n.kind,tool:n.tool??null,summary:n.summary??null,id:n.id??null,elapsedMs:n.elapsedMs??null,status:n.status??null}),a=Buffer.byteLength(o,"utf8");if(a<=262144){t.insertSessionEvent({run_id:e,step_id:s,kind:n.kind,timestamp_ms:i,payload:o});return}let l=o.slice(0,1024),c=JSON.stringify({truncated:!0,size:a,preview:l});if(s!==null){let d=t.insertStepArtifact({step_id:s,kind:"session_event_overflow",content:o});t.insertSessionEvent({run_id:e,step_id:s,kind:n.kind,timestamp_ms:i,payload:c,payload_truncated:1,overflow_artifact_id:d.id})}else t.insertSessionEvent({run_id:e,step_id:null,kind:n.kind,timestamp_ms:i,payload:c,payload_truncated:1,overflow_artifact_id:null})}}var hg=E(()=>{"use strict"});import{readFileSync as QL}from"node:fs";import{dirname as eO,join as tO}from"node:path";import{fileURLToPath as rO}from"node:url";function iO(t){return t.rules.map(e=>({command:e.command,subcommands:e.argv_patterns.map(r=>r.trim().split(/\s+/)),kind:e.kind}))}function cO(t){let e=[],r=[];for(let n of t)nO.has(n)?(r.length>0&&e.push(r),r=[]):r.push(n);return r.length>0&&e.push(r),e}function dO(t,e){if(t.length===0)return{matched:!1};let r=0;for(;r<t.length&&sO.test(t[r]);)r+=1;if(r>=t.length)return{matched:!1};let n=t[r],s=t.slice(r+1);for(let i of e)if(n===i.command){for(let o of i.subcommands)if(o.every((l,c)=>s[c]===l))return{matched:!0,kind:i.kind}}return{matched:!1}}function uO(t,e){if(t.length===0)return{matched:!1};let r=cO(t);for(let n of r){let s=dO(n,e);if(s.matched)return s}return{matched:!1}}function Ed(t){return uO(t,lO)}function fO(t){return t.replace(/&&/g," && ").replace(/\|\|/g," || ").replace(/;/g," ; ").replace(/\|/g," | ").replace(/(?<!\d)>{1,2}/g,e=>` ${e} `).replace(/(?<!\d)<{1,2}/g,e=>` ${e} `).replace(/\s+/g," ").trim()}function Td(t){return fO(t).split(" ").filter(e=>e.length>0)}var nO,sO,oO,aO,lO,gg=E(()=>{"use strict";nO=new Set(["&&","||",";","|",">",">>","<","<<"]),sO=/^[A-Za-z_][A-Za-z0-9_]*=/;oO=eO(rO(import.meta.url)),aO=JSON.parse(QL(tO(oO,"side_effect_classifier.json"),"utf-8")),lO=iO(aO)});function vo(t){return{context:{outcomes:t.outcomes,inputs:t.inputs,item:t.iteration?.item,index:t.iteration?.index},outcomes:t.outcomes,inputs:t.inputs,item:t.iteration?.item,index:t.iteration?.index}}async function yg(t,e){try{return await Dr(bd(t)??t,vo(e))===!0}catch{return!1}}async function ko(t,e){try{return await Dr(bd(t)??t,vo(e))}catch{return}}async function wg(t,e){if(typeof t!="string")return t;let r=bd(t);if(r===null)return t;try{return await Dr(r,vo(e))}catch{return}}async function Eg(t,e){let r=Array.from(t.matchAll(/=\{\{([\s\S]*?)\}\}/g));if(r.length===0)return t;let n="",s=0;for(let i of r){let o=i.index??0;n+=t.slice(s,o);let a=i[1]?.trim()??"";try{n+=mO(await Dr(a,vo(e)))}catch{n+=""}s=o+i[0].length}return n+=t.slice(s),n}function bd(t){let e=t.trim();return!e.startsWith("={{")||!e.endsWith("}}")?null:e.slice(3,-2).trim()}function mO(t){return t==null?"":typeof t=="string"?t:JSON.stringify(t)}var bs=E(()=>{"use strict";ms()});import{existsSync as Tg,readdirSync as bg,readFileSync as pO,statSync as Sg}from"node:fs";import{join as No}from"node:path";function vg(t,e,r,n){return Object.assign(t,{stateId:e,state:r,displayName:n})}function q(t,e){return t.dal.insertStep({...e,parent_step_id:t.parent_step_id})}function J(t,e){return e.startsWith("@terminal:")?{kind:"terminal",terminal:e.slice(10)}:t.states[e]===void 0?{kind:"escalate",token:e,reason:`unknown state ref '${e}'`}:{kind:"state",state:e}}function nt(t,e,r,n,s={}){let i=O(),o=q(t,{run_id:t.run_id,state_name:e.name});t.steps_executed+=1,t.dal.finishStep(o.id,null,`escalation:${n}`.slice(0,480)),t.dal.setRunPausedState(t.run_id,`${Ss}${e.id}`,i);let a=t.dal.getRun(t.run_id),l=zr(r)?"generic":"unhandled";return t.dal.raiseAttention({kind:oi,severity:"attn",project_id:t.project.id,run_id:t.run_id,requires_user:!0,payload:JSON.stringify({run_id:t.run_id,step_id:o.id,project_id:t.project.id,workflow_name:t.workflow.name,workflow_version_id:a?.workflow_version_id??null,step:{id:e.id,name:e.name,type:e.type},tier:l,token:r,reason:n,declared_outcomes:[...s.declared_outcomes??[]],agent_output:_O(s.agent_output??n),paused_at:i,created_at:i})}),t.dal.pauseJob(t.job.id),{kind:"paused"}}function _O(t){return t.length>8e3?`${t.slice(0,8e3)}
|
|
2036
|
+
\u2026[truncated ${t.length-8e3} chars]`:t}function G(t,e,r,n){t.outcomes[e]=n,r!==e&&(t.outcomes[r]=n)}function Y(t){return t.terminals.aborted?.kind==="failure"?"aborted":Object.entries(t.terminals).find(([,r])=>r.kind==="failure")?.[0]??Object.keys(t.terminals)[0]??"aborted"}function kg(t,e){let r=e.trim();if(r.startsWith("[")){try{let n=JSON.parse(r);if(Array.isArray(n)&&n.every(s=>typeof s=="string"))return n}catch{return null}return null}if(r.startsWith("job.payload.")){let n=r.slice(12);if(n.length===0)return null;let i=mr(t.job.payload)?.[n];if(Array.isArray(i)&&i.every(o=>typeof o=="string"))return i}return null}async function Ge(t,e,r){let n=t.replace(/(?<!=)\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}/g,(s,i)=>{if(i==="run_id")return String(e.run_id);if(i==="state_id")return r;if(i==="item")return e.iteration?.item??"";if(i==="index")return e.iteration===null?"":String(e.iteration.index);if(i.startsWith("project.")){let o=i.slice(8);if(o==="id")return String(e.project.id);if(o==="name")return e.project.name;if(o==="local_path")return e.project.local_path;if(o==="default_branch")return e.project.default_branch??"";if(o==="owner"){let a=e.project.name.indexOf("/");return a>0?e.project.name.slice(0,a):""}if(o==="repo"){let a=e.project.name.indexOf("/");return a>0?e.project.name.slice(a+1):e.project.name}if(o==="test_command"){let a=e.project.test_command;return a===null||a===""?"npm test":a}return""}if(i==="job_payload"){let o=mr(e.job.payload);return o===null?"":JSON.stringify(o)}if(i.startsWith("job_payload.")){let o=i.slice(12),l=mr(e.job.payload)?.[o];return l==null?"":String(l)}if(i.startsWith("outcomes.")){let o=hO(e.outcomes,i.slice(9));return o==null?"":typeof o=="string"?o:JSON.stringify(o)}return""});return Eg(n,e)}function hO(t,e){let r=t;for(let n of e.split(".")){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[n]}return r}function mr(t){if(t===null)return null;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}async function vs(t){let{context:e,stateId:r,member:n,prompt:s,stepId:i,timeoutMs:o,writesToProjectPath:a}=t,l=_g(e.dal,e.run_id,()=>i),c=Sd(e,r),d={violation:null},u=y=>{if(l(y),d.violation===null&&y.kind==="tool_use"&&y.tool==="Bash"&&y.summary){let T=Td(y.summary),b=Ed(T);b.matched&&!c&&(d.violation={summary:y.summary,kind:b.kind})}},f=new Date(Date.now()-1),m=0,p=0,h=y=>{u(y),gO(y,(T,b)=>{m+=T,p+=b})},g=await ji({sessionid:n.sessionid,sessiondir:n.sessiondir,prompt:s,timeoutMs:o,dal:e.dal,team_member_id:n.id,onProgress:h});e.dal.insertSessionEvent({run_id:e.run_id,step_id:i,kind:"agent_call",timestamp_ms:Date.now(),payload:JSON.stringify({alias:n.alias,provider:Be(n),model:n.model??"unknown",tokens_in:m,tokens_out:p,wall_time_ms:g.ms})}),yO(e.project,e.dal,f);let _=d.violation;return _!==null?{kind:"g3_violation",summary:_.summary,violationKind:_.kind}:!a&&e.project.local_path.trim().length>0&&vd(e.project.local_path,f)?{kind:"g2_violation"}:{kind:"ok",text:g.text,ms:g.ms,argv:g.argv}}function gO(t,e){let r=t.raw;if(r==null)return;let s=r.message?.usage;if(s!==void 0){let o=Io(s.input_tokens),a=Io(s.output_tokens);(o>0||a>0)&&e(o,a);return}let i=r.usage;if(i!==void 0){let o=Io(i.input_tokens),a=Io(i.output_tokens);(o>0||a>0)&&e(o,a)}}function Io(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:0}async function Jt(t,e,r,n){if(r.sessionid===null)return;let s=`${e}:write_back`,i=q(t,{run_id:t.run_id,state_name:s});t.steps_executed+=1;let a=`This state completed successfully.${typeof n=="string"?` Category hint: "${n}".`:""} Did you learn anything worth preserving in durable-memory? If yes, use Write to create/update an entry under <project>/durable-memory/<descriptive-name>.md. Include YAML frontmatter (name/description/type[/tags]). Be brief \u2014 one entry per insight. If you didn't learn anything new, respond with \`STANCE: no_writeback\` and the engine moves on.`;try{let l=await vs({context:t,stateId:s,member:r,prompt:a,stepId:i.id,timeoutMs:t.workflow.default_task_timeout_ms,writesToProjectPath:!1});if(l.kind==="ok"){t.dal.insertStepArtifact({step_id:i.id,kind:"write_back_transcript",content:l.text});let c=!l.text.includes("STANCE: no_writeback");t.dal.finishStep(i.id,c?"wrote_back":"no_writeback","write_back_turn")}else t.dal.finishStep(i.id,null,`write_back_${l.kind}`)}catch{t.dal.finishStep(i.id,null,"write_back_error")}}async function gn(t,e,r,n,s,i,o,a=!1,l){let c=t.membersByAlias.get(r.alias);if(c===void 0||c.sessionid===null)return{outcome:null,text:"",status_detail:`missing_agent:${r.alias}`};let d=q(t,{run_id:t.run_id,state_name:e});t.steps_executed+=1;let u=[];c.prompt_snapshot!==null&&c.prompt_snapshot.length>0&&u.push(c.prompt_snapshot),i&&u.push(Bm(s)),l!=null&&l.length>0&&u.push(l);let f=r.prompt_template!==void 0?await Ge(r.prompt_template,t,e):"";f.length>0&&u.push(f),n!==null&&n.length>0&&u.push(n);let m=u.join(`
|
|
1955
2037
|
|
|
1956
2038
|
`);try{let p=await vs({context:t,stateId:e,member:c,prompt:m,stepId:d.id,timeoutMs:o,writesToProjectPath:a});if(p.kind==="g3_violation"||p.kind==="g2_violation"){let g=p.kind==="g3_violation"?`policy_violation:side_effect_without_pause:${p.violationKind}`:"policy_violation:writes_to_project_path";return t.dal.insertSessionEvent({run_id:t.run_id,step_id:d.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify(p.kind==="g3_violation"?{violation:"side_effect_without_pause",state_id:e,kind:p.violationKind,command_summary:p.summary,message:`State ${e} ran a classified side-effect command (${p.violationKind}) without a preceding approved Pause`}:{violation:"writes_to_project_path",state_id:e,message:`State ${e} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(d.id,null,g),{outcome:null,text:"",status_detail:g}}if(t.dal.insertStepArtifact({step_id:d.id,kind:`${e}_transcript`,content:p.text}),t.transcripts[e]=p.text,!i)return t.dal.finishStep(d.id,"done",`chat_ms=${p.ms}`),t.outcomes[e]="done",{outcome:"done",text:p.text,status_detail:`chat_ms=${p.ms}`};let h=Ts(p.text,s);return t.dal.finishStep(d.id,h.outcome,h.outcome!==null?`chat_ms=${p.ms}`:h.reason),h.outcome!==null&&(t.outcomes[e]=h.outcome),{outcome:h.outcome,text:p.text,status_detail:h.outcome!==null?`chat_ms=${p.ms}`:h.reason}}catch(p){let h=p instanceof Se?`chat_${p.kind}`:"chat_other";return t.dal.finishStep(d.id,null,h),{outcome:null,text:"",status_detail:h}}}function yn(t,e){return(e?.length??0)>0?ug(t.project.local_path,e):null}function Ig(t){return Ed(Td(t))}function Sd(t,e){let r=t.dal.query(`SELECT state_name, outcome FROM step
|
|
1957
2039
|
WHERE run_id = ? AND state_name != ? AND ended_at IS NOT NULL
|
|
1958
2040
|
ORDER BY started_at DESC, id DESC LIMIT 1`,t.run_id,e);if(r.length===0)return!1;let n=r[0];return t.workflow.states[n.state_name]?.type==="Interactive"&&n.outcome==="done"}function vd(t,e){if(!Tg(t))return!1;let r=No(t,"durable-memory");function n(s){let i;try{i=bg(s,{withFileTypes:!0})}catch{return!1}for(let o of i){if(o.name===".git")continue;let a=No(s,o.name);if(a!==r)if(o.isDirectory()){if(n(a))return!0}else try{if(Sg(a).mtime>e)return!0}catch{}}return!1}return n(t)}function yO(t,e,r){let n=No(t.local_path,"durable-memory");if(!Tg(n))return;let s;try{s=bg(n)}catch{return}for(let i of s){if(!i.endsWith(".md")||i==="MEMORY.md")continue;let o=No(n,i),a;try{a=Sg(o).mtime}catch{continue}if(a<=r)continue;let l;try{l=pO(o,"utf8")}catch{continue}let c=EO(l);if(c===null){process.stderr.write(`[durable-memory-sync] warning: ${i} has no valid frontmatter, skipping
|
|
1959
|
-
`),C({event:"durable_memory_frontmatter_invalid",project_id:t.id,file:i,path:o});continue}if(t.durable_memory_mode==="db")try{e.upsertDurableMemory({project_id:t.id,type:c.type,name:c.name,description:c.description,body:c.body})}catch{}}}function EO(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return null;let r=e[1],n=e[2].trimStart(),s=r.match(/^name:\s*(.+)$/m),i=r.match(/^type:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),a=s?.[1]?.trim(),l=i?.[1]?.trim();return a===void 0||a.length===0||l===void 0||!wO.has(l)?null:{name:a,type:l,description:o?.[1]?.trim()??null,body:n}}var Ss,wO,He=E(()=>{"use strict";Qe();fn();Di();fg();wd();Zn();hg();de();gg();bs();Ss="__paused__:";wO=new Set(["user","feedback","project","reference"])});import{spawnSync as Ng}from"node:child_process";function TO(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let i=t.project.local_path,o=Ng("git",["diff","--quiet"],{cwd:i}).status!==0,a=Ng("git",["diff","--cached","--quiet"],{cwd:i}).status!==0;if(o||a){let l=e.fail_message??"repository has uncommitted changes";return t.dal.finishStep(s.id,null,l),G(t,r,n,Wc),{kind:"terminal",terminal:Y(t.workflow)}}return t.dal.finishStep(s.id,"clean","repo_clean"),G(t,r,n,"clean"),
|
|
2041
|
+
`),C({event:"durable_memory_frontmatter_invalid",project_id:t.id,file:i,path:o});continue}if(t.durable_memory_mode==="db")try{e.upsertDurableMemory({project_id:t.id,type:c.type,name:c.name,description:c.description,body:c.body})}catch{}}}function EO(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return null;let r=e[1],n=e[2].trimStart(),s=r.match(/^name:\s*(.+)$/m),i=r.match(/^type:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),a=s?.[1]?.trim(),l=i?.[1]?.trim();return a===void 0||a.length===0||l===void 0||!wO.has(l)?null:{name:a,type:l,description:o?.[1]?.trim()??null,body:n}}var Ss,wO,He=E(()=>{"use strict";Qe();fn();Di();fg();wd();Zn();hg();de();gg();bs();Ss="__paused__:";wO=new Set(["user","feedback","project","reference"])});import{spawnSync as Ng}from"node:child_process";function TO(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let i=t.project.local_path,o=Ng("git",["diff","--quiet"],{cwd:i}).status!==0,a=Ng("git",["diff","--cached","--quiet"],{cwd:i}).status!==0;if(o||a){let l=e.fail_message??"repository has uncommitted changes";return t.dal.finishStep(s.id,null,l),G(t,r,n,Wc),{kind:"terminal",terminal:Y(t.workflow)}}return t.dal.finishStep(s.id,"clean","repo_clean"),G(t,r,n,"clean"),J(t.workflow,e.next)}var xg,Ag=E(()=>{"use strict";He();xg={description:{displayName:"Assert Repo Clean",name:"assert-repo-clean",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],builtin:!0},execute:t=>TO(t,t.state)}});async function bO(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;for(let i of e.branches)if(await yg(i.when,t))return t.dal.finishStep(s.id,"matched",i.when),G(t,r,n,"matched"),J(t.workflow,i.next);return t.dal.finishStep(s.id,"no_match","choice_no_match"),G(t,r,n,"no_match"),e.default_next!==void 0?J(t.workflow,e.default_next):{kind:"terminal",terminal:t.workflow.terminals.no_match?"no_match":Y(t.workflow)}}var Rg,Lg=E(()=>{"use strict";He();bs();Rg={description:{displayName:"Choice",name:"choice",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[{name:"branches",displayName:"Branches",type:"json",description:"Jexl predicates evaluated against input-only context: context.outcomes and context.inputs. Globals and functions such as process.exit(1) and Math.random() are not exposed."}],builtin:!0},execute:async t=>bO(t,t.state)}});async function SO(t,e){let r=t.stateId,n=t.displayName,s=t.workflow.default_task_timeout_ms,i=e.researchers??[],o=yn(t,e.durable_memory_tags),a=new Array(i.length).fill(null);await Promise.all(i.map(async(m,p)=>{let h=`${n}:researcher_${m.alias}[${p}]`,g=await gn(t,h,m,`TOPIC: ${m.topic}`,[],!1,s,!1,o);g.text.length>0&&(a[p]=g.text)}));let l=a.map((m,p)=>m!==null?`# Research ${p+1}: ${i[p]?.topic??""}
|
|
1960
2042
|
${m}`:null).filter(m=>m!==null).join(`
|
|
1961
2043
|
|
|
1962
|
-
`),c=`${n}:consolidator`,d=await gn(t,c,e.consolidator,l.length>0?l:null,["ok","error"],!0,s,!1,o),u=q(t,{run_id:t.run_id,state_name:n});if(t.steps_executed+=1,d.outcome===null||d.outcome==="error"){t.dal.finishStep(u.id,d.outcome,d.status_detail),d.outcome==="error"&&G(t,r,n,"error");let m=e.outcomes.error;return m!==void 0?
|
|
2044
|
+
`),c=`${n}:consolidator`,d=await gn(t,c,e.consolidator,l.length>0?l:null,["ok","error"],!0,s,!1,o),u=q(t,{run_id:t.run_id,state_name:n});if(t.steps_executed+=1,d.outcome===null||d.outcome==="error"){t.dal.finishStep(u.id,d.outcome,d.status_detail),d.outcome==="error"&&G(t,r,n,"error");let m=e.outcomes.error;return m!==void 0?J(t.workflow,m):{kind:"terminal",terminal:Y(t.workflow)}}let f=e.research_artifact_prefix??n;if(t.dal.insertStepArtifact({step_id:u.id,kind:`${f}_consolidated`,content:d.text}),t.dal.finishStep(u.id,"ok","consolidated"),G(t,r,n,"ok"),e.write_back_durable_memory){let m=t.membersByAlias.get(e.consolidator.alias);m!==void 0&&await Jt(t,n,m,e.write_back_durable_memory)}return J(t.workflow,e.outcomes.ok)}var Og,$g=E(()=>{"use strict";He();Og={description:{displayName:"Consolidate",name:"consolidate",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],emits_progress:!0,builtin:!0},execute:async t=>SO(t,t.state)}});async function vO(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let i=t.progress_step_id;t.progress_step_id=s.id;try{let o=await ko(e.items_from,t),a=xO(o);if(a===null){t.dal.finishStep(s.id,null,`foreach_invalid_items:${e.items_from}`);let f=e.outcomes.any_failed;return f!==void 0?J(t.workflow,f):{kind:"terminal",terminal:Y(t.workflow)}}let l={routed:null},c=e.mode==="parallel"?await IO(t,e,s.id,a,l):await kO(t,e,s.id,a,l);if(l.routed!==null)return t.dal.finishStep(s.id,null,`foreach_propagated:${l.routed.kind}`),l.routed;let d=c.some(f=>f.outcome===null||f.outcome==="__failure__"),u=d?"any_failed":"all_ok";if(t.dal.finishStep(s.id,u,JSON.stringify({iterations:c,count:a.length})),G(t,r,n,u),d){let f=e.outcomes.any_failed;return f!==void 0?J(t.workflow,f):{kind:"terminal",terminal:Y(t.workflow)}}return J(t.workflow,e.outcomes.all_ok)}finally{t.progress_step_id=i}}async function kO(t,e,r,n,s){let i=[];for(let o=0;o<n.length;o+=1){let a=await Mg(t,e,r,n[o],o,s);if(s.routed!==null||(i.push(a),(a.outcome===null||a.outcome==="__failure__")&&e.on_item_failure==="stop"))break}return i}async function IO(t,e,r,n,s){let i=new Array(n.length),o=0,a=Array.from({length:Math.min(e.max_concurrency,n.length)},async()=>{for(;o<n.length&&s.routed===null;){let l=o;o+=1,i[l]=await Mg(t,e,r,n[l],l,s)}});return await Promise.all(a),i}async function Mg(t,e,r,n,s,i){let o=t.iteration;t.iteration={item:n,index:s};let a=`${t.displayName}[${s}]`;t.emit_progress?.({kind:"item_started",data:{index:s,item:n}});let l;try{l=await t.dispatchState(a,e.body,{parent_step_id:r,iteration:{item:n,index:s}})}finally{t.iteration=o}(l.kind==="paused"||l.kind==="escalate")&&i.routed===null&&(i.routed=l);let d=l.kind==="terminal"&&t.workflow.terminals[l.terminal]?.kind==="failure"?"__failure__":NO(t.outcomes[a]);return t.emit_progress?.({kind:d===null||d==="__failure__"?"item_failed":"item_completed",data:{index:s,item:n,outcome:d}}),{index:s,value:n,outcome:d}}function NO(t){return t==null?null:typeof t=="string"?t:JSON.stringify(t)}function xO(t){if(!Array.isArray(t))return null;let e=[];for(let r of t)if(typeof r=="string")e.push(r);else if(typeof r=="number"||typeof r=="boolean")e.push(String(r));else return null;return e}var Cg,jg=E(()=>{"use strict";He();bs();Cg={description:{displayName:"For Each",name:"foreach",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],emits_progress:!0,builtin:!0},execute:async t=>vO(t,t.state)}});async function AO(t,e){let r=t.stateId,n=t.displayName,s=e.termination.timeout_seconds!==void 0?e.termination.timeout_seconds*1e3:void 0,i=t.membersByAlias.get(e.agent.alias);if(i===void 0||i.sessionid===null){let f=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(f.id,null,`missing_agent:${e.agent.alias}`),{kind:"terminal",terminal:Y(t.workflow)}}let o=yn(t,e.durable_memory_tags),a=t.dal.getInteractiveSessionByRunAndState(t.run_id,r);if(a!==null){if(a.status==="done")return t.dal.finishStep(a.step_id,"done","operator_done"),t.outcomes[n]="done",e.write_back_durable_memory&&await Jt(t,n,i,e.write_back_durable_memory),J(t.workflow,e.outcomes.done);if(a.status==="waiting_agent"){if(a.turn_count>=e.termination.max_turns){t.dal.finishStep(a.step_id,"timeout",`max_turns=${e.termination.max_turns}`),G(t,r,n,"timeout");let m=e.outcomes.timeout;return m!==void 0?J(t.workflow,m):{kind:"terminal",terminal:Y(t.workflow)}}let f=a.last_operator_input??"";try{let m=await vs({context:t,stateId:n,member:i,prompt:f,stepId:a.step_id,timeoutMs:s,writesToProjectPath:!1});if(m.kind==="g3_violation"||m.kind==="g2_violation"){let p=m.kind==="g3_violation"?`policy_violation:side_effect_without_pause:${m.violationKind}`:"policy_violation:writes_to_project_path";return t.dal.insertSessionEvent({run_id:t.run_id,step_id:a.step_id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify(m.kind==="g3_violation"?{violation:"side_effect_without_pause",state_id:n,kind:m.violationKind,command_summary:m.summary,message:`State ${n} ran a classified side-effect command (${m.violationKind}) without a preceding approved gate`}:{violation:"writes_to_project_path",state_id:n,message:`State ${n} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(a.step_id,null,p),{kind:"terminal",terminal:Y(t.workflow)}}return t.dal.setInteractiveAgentOutput(a.id,m.text,"waiting_operator"),e.termination.agent_signal!==void 0&&m.text.includes(e.termination.agent_signal)?(e.artifact_name!==void 0&&t.dal.insertStepArtifact({step_id:a.step_id,kind:e.artifact_name,content:m.text}),t.dal.finishStep(a.step_id,"done","agent_signal"),G(t,r,n,"done"),e.write_back_durable_memory&&await Jt(t,n,i,e.write_back_durable_memory),J(t.workflow,e.outcomes.done)):(Dg({context:t,state:e,stateId:r,displayName:n,stepId:a.step_id,agentText:m.text}),{kind:"paused"})}catch(m){let p=m instanceof Se?`chat_${m.kind}`:"chat_other";return t.dal.finishStep(a.step_id,null,p),{kind:"terminal",terminal:Y(t.workflow)}}}return{kind:"paused"}}let l=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let c=t.dal.insertInteractiveSession({run_id:t.run_id,step_id:l.id,state_name:r,status:"waiting_agent"}),d=await Ge(e.agent.initial_prompt_template,t,n),u=o?`${o}
|
|
1963
2045
|
|
|
1964
|
-
${d}`:d;try{let f=await vs({context:t,stateId:n,member:i,prompt:u,stepId:l.id,timeoutMs:s,writesToProjectPath:!1});if(f.kind==="g3_violation"||f.kind==="g2_violation"){let m=f.kind==="g3_violation"?`policy_violation:side_effect_without_pause:${f.violationKind}`:"policy_violation:writes_to_project_path";return t.dal.insertSessionEvent({run_id:t.run_id,step_id:l.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify(f.kind==="g3_violation"?{violation:"side_effect_without_pause",state_id:n,kind:f.violationKind,command_summary:f.summary,message:`State ${n} ran a classified side-effect command (${f.violationKind}) without a preceding approved gate`}:{violation:"writes_to_project_path",state_id:n,message:`State ${n} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(l.id,null,m),{kind:"terminal",terminal:Y(t.workflow)}}return t.dal.setInteractiveAgentOutput(c.id,f.text,"waiting_operator"),e.artifact_name!==void 0&&t.dal.insertStepArtifact({step_id:l.id,kind:e.artifact_name,content:f.text}),e.termination.agent_signal!==void 0&&f.text.includes(e.termination.agent_signal)?(t.dal.finishStep(l.id,"done","agent_signal"),t.outcomes[n]="done",e.write_back_durable_memory&&await
|
|
2046
|
+
${d}`:d;try{let f=await vs({context:t,stateId:n,member:i,prompt:u,stepId:l.id,timeoutMs:s,writesToProjectPath:!1});if(f.kind==="g3_violation"||f.kind==="g2_violation"){let m=f.kind==="g3_violation"?`policy_violation:side_effect_without_pause:${f.violationKind}`:"policy_violation:writes_to_project_path";return t.dal.insertSessionEvent({run_id:t.run_id,step_id:l.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify(f.kind==="g3_violation"?{violation:"side_effect_without_pause",state_id:n,kind:f.violationKind,command_summary:f.summary,message:`State ${n} ran a classified side-effect command (${f.violationKind}) without a preceding approved gate`}:{violation:"writes_to_project_path",state_id:n,message:`State ${n} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(l.id,null,m),{kind:"terminal",terminal:Y(t.workflow)}}return t.dal.setInteractiveAgentOutput(c.id,f.text,"waiting_operator"),e.artifact_name!==void 0&&t.dal.insertStepArtifact({step_id:l.id,kind:e.artifact_name,content:f.text}),e.termination.agent_signal!==void 0&&f.text.includes(e.termination.agent_signal)?(t.dal.finishStep(l.id,"done","agent_signal"),t.outcomes[n]="done",e.write_back_durable_memory&&await Jt(t,n,i,e.write_back_durable_memory),J(t.workflow,e.outcomes.done)):(Dg({context:t,state:e,stateId:r,displayName:n,stepId:l.id,agentText:f.text}),{kind:"paused"})}catch(f){let m=f instanceof Se?`chat_${f.kind}`:"chat_other";return t.dal.finishStep(l.id,null,m),{kind:"terminal",terminal:Y(t.workflow)}}}function Dg(t){let{context:e,state:r,stateId:n,displayName:s,stepId:i,agentText:o}=t,a=O();e.dal.setRunPausedState(e.run_id,`${Ss}${n}`,a),e.dal.raiseAttention({kind:"interactive_waiting_operator",severity:"attn",project_id:e.project.id,run_id:e.run_id,requires_user:!0,payload:JSON.stringify(RO({context:e,stateId:s,state:r,stepId:i,agentText:o,pausedAt:a}))}),e.dal.pauseJob(e.job.id)}function RO(t){let{context:e,stateId:r,state:n,stepId:s,agentText:i,pausedAt:o}=t,a=e.dal.getRun(e.run_id),l=LO(e,r),c={kind:"free_text",choices:null};return{run_id:e.run_id,step_id:s,state_name:r,workflow_name:e.workflow.name,workflow_version_id:a?.workflow_version_id??null,node_path:l,prompt:i,expected_response:c,transcript_tail:OO(i,3),paused_at:o,created_run_inputs:mr(e.job.payload)}}function LO(t,e){let r=[],s=t.dal.getRun(t.run_id)?.parent_run_id??null;for(let i=0;i<32&&s!==null;i+=1){let o=t.dal.getRun(s);if(o===null)break;o.current_state!==null&&r.unshift(o.current_state),s=o.parent_run_id}return r.push(e),r}function OO(t,e){if(typeof t!="string"||t.length===0)return[];let r=t.split(/\r?\n/);return(r.length>0&&r[r.length-1]===""?r.slice(0,-1):r).slice(-e)}var Pg,Fg=E(()=>{"use strict";Di();He();Pg={description:{displayName:"Interactive",name:"interactive",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],emits_progress:!0,builtin:!0},execute:async t=>AO(t,t.state)}});async function $O(t,e){let r=t.stateId,n=t.displayName,s=kg(t,e.over);if(s===null){let u=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1,t.dal.finishStep(u.id,null,`loop_invalid_items:${e.over}`);let f=e.outcomes.error;return f!==void 0?J(t.workflow,f):{kind:"terminal",terminal:Y(t.workflow)}}let i=t.workflow.states[e.body];if(i===void 0){let u=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(u.id,null,`loop_body_not_found:${e.body}`),{kind:"terminal",terminal:Y(t.workflow)}}let o=s.slice(0,e.max_items),a=[],l=!1;for(let u=0;u<o.length;u+=1){let f=o[u],m=`${n}[${u}]`,p=t.iteration;t.iteration={item:f,index:u};let h;try{h=await t.dispatchState(m,i,{iteration:{item:f,index:u}})}finally{t.iteration=p}if(h.kind==="paused"||h.kind==="escalate")return h;let g=CO(t.outcomes[m]);if(a.push({index:u,value:f,outcome:g}),g===null&&e.stop_on_error){l=!0;break}}let c=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let d=l?"error":"ok";if(t.dal.finishStep(c.id,d,JSON.stringify({iterations:a,count:o.length})),G(t,r,n,d),l){let u=e.outcomes.error;return u!==void 0?J(t.workflow,u):{kind:"terminal",terminal:Y(t.workflow)}}return J(t.workflow,e.outcomes.ok)}function CO(t){return t==null?null:typeof t=="string"?t:JSON.stringify(t)}var Ug,Wg=E(()=>{"use strict";He();Ug={description:{displayName:"Loop",name:"loop",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],builtin:!0},execute:async t=>$O(t,t.state)}});import{createHash as MO}from"node:crypto";import{existsSync as jO,mkdirSync as DO,readFileSync as PO,writeFileSync as FO}from"node:fs";import{dirname as UO,isAbsolute as qg,normalize as WO,resolve as ks}from"node:path";import{Document as BO,ExternalHyperlink as qO,HeadingLevel as wn,LevelFormat as HO,Packer as XO,Paragraph as pt,Table as JO,TableCell as GO,TableRow as KO,TextRun as _t,WidthType as VO}from"docx";import{marked as YO}from"marked";async function zO(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;try{let i=await ZO(t,e,n),o=await QO(t,e),a=await e$(t,e.title),l=await i$(i,a??t.workflow.name);if(l.length===0)throw new Error("rendered DOCX buffer was empty");return DO(UO(o),{recursive:!0}),FO(o,l),t.dal.insertStepArtifact({step_id:s.id,kind:"render_docx",path:o,sha:MO("sha256").update(l).digest("hex"),provider_call_mode:"library"}),t.dal.finishStep(s.id,"done",`wrote:${o}`),G(t,r,n,{output_path:o,path:o,bytes:l.length}),J(t.workflow,e.outcomes?.done??"@terminal:done")}catch(i){let o=i instanceof Error?i.message:String(i);return t.dal.finishStep(s.id,"error",o),G(t,r,n,{error:o}),J(t.workflow,e.outcomes?.error??"@terminal:error")}}async function ZO(t,e,r){if(typeof e.markdown_source!="string"||e.markdown_source.trim().length===0)throw new Error("markdown_source is required");let n=(await Ge(e.markdown_source,t,r)).trim(),i=(n.length===0?s$(t,e.markdown_source):null)??n;if(i.length===0)throw new Error("markdown_source resolved empty");let o=r$(t.project.local_path,i);if(o!==null){if(!jO(o))throw new Error(`markdown_source file not found: ${o}`);return xo(PO(o,"utf8"))}return xo(i)}async function QO(t,e){if(typeof e.output_path!="string"||e.output_path.trim().length===0)throw new Error("output_path is required");let r=(await Ge(e.output_path,t,t.stateId)).trim();if(r.length===0)throw new Error("output_path resolved empty");let n=t$(t.project.local_path,r);if(!n.endsWith(".docx"))throw new Error(`output_path must end with .docx: ${n}`);return n}async function e$(t,e){if(typeof e!="string"||e.trim().length===0)return null;let r=(await Ge(e,t,t.stateId)).trim();return r.length===0?null:r}function t$(t,e){let r=ks(t);return WO(qg(e)?ks(e):ks(r,e))}function r$(t,e){return n$(e)?qg(e)?ks(e):ks(t,e):null}function n$(t){return t.endsWith(".md")||t.endsWith(".markdown")||t.startsWith("./")||t.startsWith("../")||t.startsWith("/")}function s$(t,e){let n=/context\.outcomes\.([A-Za-z0-9_-]+)\.output/.exec(e)?.[1];if(n===void 0)return null;let s=Object.entries(t.transcripts).filter(([o])=>o.startsWith(`${n}:coder[`)).sort(([o],[a])=>a.localeCompare(o))[0]?.[1];if(s!==void 0)return xo(s);let i=t.dal.query(`SELECT sa.content
|
|
1965
2047
|
FROM step_artifact sa
|
|
1966
2048
|
JOIN step s ON s.id = sa.step_id
|
|
1967
2049
|
WHERE s.run_id = ?
|
|
1968
2050
|
AND s.state_name LIKE ?
|
|
1969
2051
|
AND sa.content IS NOT NULL
|
|
1970
2052
|
ORDER BY sa.id DESC
|
|
1971
|
-
LIMIT 1`,t.run_id,`${n}:coder[%`);return i[0]?.content===void 0?null:xo(i[0].content)}function xo(t){return t.replace(/\n*STANCE:\s+\S+\s*$/,"").trimEnd()}async function i$(t,e){let r=
|
|
1972
|
-
`).map(r=>new pt({children:[new _t({text:r.length===0?" ":r,font:"Courier New"})]}))}function pr(t){let e=t.tokens;return Array.isArray(e)?e:[]}function c$(t){return t.type==="list"&&Array.isArray(t.items)}function d$(t){let e=t;return t.type==="table"&&Array.isArray(e.header)&&Array.isArray(e.rows)}function u$(t){return t.type==="code"&&typeof t.text=="string"}function f$(t){switch(t){case 1:return wn.HEADING_1;case 2:return wn.HEADING_2;case 3:return wn.HEADING_3;case 4:return wn.HEADING_4;case 5:return wn.HEADING_5;default:return wn.HEADING_6}}var Hg,
|
|
1973
|
-
${a}`:null,c,l,s,e.writes_to_project_path===!0,i);if(l){let g=pg(p.text);if(g!==null){let _=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(_.id,null,`escalation_vocab:${g.token}`),{kind:"escalate",token:g.token,reason:g.reason.length>0?`${g.token}: ${g.reason}`:g.token}}}if(p.outcome===null){let g=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(g.id,null,p.status_detail),{kind:"escalate",token:"",reason:`coder_no_outcome:${p.status_detail}`}}if(o.length===0){if(e.outcomes_from_stance!==void 0){let y=Object.keys(e.outcomes_from_stance),T=Ts(p.text,y);if(T.outcome===null){let I=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(I.id,null,`unhandled_stance:${T.reason}`),{kind:"escalate",token:"",reason:`no_stance:${T.reason}`}}let b=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(b.id,T.outcome,"outcomes_from_stance"),G(t,r,n,T.outcome),
|
|
1974
|
-
${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));if(h.every(g=>g.outcome==="approve")){let g=q(t,{run_id:t.run_id,state_name:n});if(t.steps_executed+=1,t.dal.finishStep(g.id,"approve",`loop=${f}`),G(t,r,n,"approve"),e.write_back_durable_memory){let _=t.membersByAlias.get(e.coder.alias);_!==void 0&&await
|
|
2053
|
+
LIMIT 1`,t.run_id,`${n}:coder[%`);return i[0]?.content===void 0?null:xo(i[0].content)}function xo(t){return t.replace(/\n*STANCE:\s+\S+\s*$/,"").trimEnd()}async function i$(t,e){let r=Xg(YO.lexer(t,{gfm:!0})),n=new BO({title:e,numbering:{config:[{reference:"ordered-list",levels:[{level:0,format:HO.DECIMAL,text:"%1."}]}]},sections:[{children:r.length===0?[new pt("")]:r}]});return XO.toBuffer(n)}function Xg(t){let e=[];for(let r of t)switch(r.type){case"space":break;case"heading":e.push(new pt({heading:f$(r.depth),children:_r(pr(r))}));break;case"paragraph":e.push(new pt({children:_r(pr(r))}));break;case"text":e.push(new pt({children:pr(r).length===0?[new _t(r.text)]:_r(pr(r))}));break;case"blockquote":e.push(...Xg(pr(r)).map(n=>n instanceof pt?n:new pt({children:[new _t(r.text)]})));break;case"list":c$(r)&&e.push(...o$(r));break;case"table":d$(r)&&e.push(a$(r));break;case"code":u$(r)&&e.push(...l$(r));break;case"hr":e.push(new pt(""));break;case"html":r.text.trim().length>0&&e.push(new pt({children:[new _t(r.text)]}));break;default:break}return e}function _r(t,e){let r=[];for(let n of t)switch(n.type){case"text":case"escape":r.push(new _t({text:n.text,...kd(e)}));break;case"strong":r.push(..._r(pr(n),{...e,bold:!0}));break;case"em":r.push(..._r(pr(n),{...e,italics:!0}));break;case"codespan":r.push(new _t({text:n.text,...kd({...e,code:!0})}));break;case"link":r.push(new qO({link:n.href,children:_r(pr(n),{...e})}));break;case"br":r.push(new _t({text:"",break:1}));break;case"image":r.push(new _t({text:`[image: ${n.text}]`,italics:!0}));break;case"del":r.push(new _t({text:n.text,strike:!0}));break;default:r.push(new _t({text:n.raw,...kd(e)}));break}return r.length===0?[new _t("")]:r}function kd(t){return{...t?.bold===!0?{bold:!0}:{},...t?.italics===!0?{italics:!0}:{},...t?.code===!0?{font:"Courier New"}:{}}}function o$(t){return t.items.map(e=>new pt({children:_r(e.tokens.length===1&&e.tokens[0]?.type==="text"?[{...e.tokens[0],text:Bg(e)+e.tokens[0].text}]:[{type:"text",raw:e.text,text:Bg(e)+e.text}]),...t.ordered?{numbering:{reference:"ordered-list",level:0}}:{bullet:{level:0}}}))}function Bg(t){return t.task?`[${t.checked?"x":" "}] `:""}function a$(t){let e=[t.header,...t.rows].map(r=>new KO({children:r.map(n=>new GO({children:[new pt({children:_r(n.tokens,n.header?{bold:!0}:void 0)})]}))}));return new JO({width:{size:100,type:VO.PERCENTAGE},rows:e})}function l$(t){return t.text.split(`
|
|
2054
|
+
`).map(r=>new pt({children:[new _t({text:r.length===0?" ":r,font:"Courier New"})]}))}function pr(t){let e=t.tokens;return Array.isArray(e)?e:[]}function c$(t){return t.type==="list"&&Array.isArray(t.items)}function d$(t){let e=t;return t.type==="table"&&Array.isArray(e.header)&&Array.isArray(e.rows)}function u$(t){return t.type==="code"&&typeof t.text=="string"}function f$(t){switch(t){case 1:return wn.HEADING_1;case 2:return wn.HEADING_2;case 3:return wn.HEADING_3;case 4:return wn.HEADING_4;case 5:return wn.HEADING_5;default:return wn.HEADING_6}}var Hg,Jg=E(()=>{"use strict";He();Hg={description:{displayName:"Render DOCX",name:"render-docx",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"done"},{name:"error"}],properties:[{name:"markdown_source",displayName:"Markdown Source",type:"string",required:!0,description:"Markdown string or project-relative .md path. Expressions are evaluated before rendering."},{name:"output_path",displayName:"Output Path",type:"string",required:!0,description:"Absolute or project-relative .docx path to write."},{name:"title",displayName:"Title",type:"string",required:!1,description:"Optional document metadata title."}],mutates_external_state:!0,builtin:!0},execute:async t=>zO(t,t.state)}});import{createHash as m$}from"node:crypto";import{existsSync as p$,mkdirSync as _$,readFileSync as Gg,statSync as h$}from"node:fs";import{dirname as g$,isAbsolute as Kg,normalize as y$,resolve as Is}from"node:path";import{marked as w$}from"marked";import E$ from"write-excel-file/node";async function T$(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;try{let i=await b$(t,e),o=S$(e.input_format),a=await v$(t,e),l=await k$(t,e.title),c=o==="markdown"?C$(i):A$(i);await M$({sheets:c.length===0?[{name:"Sheet1",headers:[],rows:[]}]:c,outputPath:a,title:l??t.workflow.name});let d=h$(a).size;if(d===0)throw new Error("rendered XLSX file was empty");let u=m$("sha256").update(Gg(a)).digest("hex");return t.dal.insertStepArtifact({step_id:s.id,kind:"render_xlsx",path:a,sha:u,provider_call_mode:"library"}),t.dal.finishStep(s.id,"done",`wrote:${a}`),G(t,r,n,{output_path:a,path:a,bytes:d}),J(t.workflow,e.outcomes?.done??"@terminal:done")}catch(i){let o=i instanceof Error?i.message:String(i);return t.dal.finishStep(s.id,"error",o),G(t,r,n,{error:o}),J(t.workflow,e.outcomes?.error??"@terminal:error")}}async function b$(t,e){if(typeof e.source!="string"||e.source.trim().length===0)return"";let r=(await Ge(e.source,t,t.stateId)).trim(),n=N$(t.project.local_path,r);if(n!==null){if(!p$(n))throw new Error(`source file not found: ${n}`);return Gg(n,"utf8")}return r}function S$(t){if(t==null||t==="")return"json";if(t==="json"||t==="markdown")return t;throw new Error(`unsupported input_format: ${String(t)}`)}async function v$(t,e){if(typeof e.output_path!="string"||e.output_path.trim().length===0)throw new Error("output_path is required");let r=(await Ge(e.output_path,t,t.stateId)).trim();if(r.length===0)throw new Error("output_path resolved empty");let n=I$(t.project.local_path,r);if(!n.endsWith(".xlsx"))throw new Error(`output_path must end with .xlsx: ${n}`);return n}async function k$(t,e){if(typeof e!="string"||e.trim().length===0)return null;let r=(await Ge(e,t,t.stateId)).trim();return r.length===0?null:r}function I$(t,e){let r=Is(t);return y$(Kg(e)?Is(e):Is(r,e))}function N$(t,e){return x$(e)?Kg(e)?Is(e):Is(t,e):null}function x$(t){return t.endsWith(".json")||t.endsWith(".md")||t.endsWith(".markdown")||t.startsWith("./")||t.startsWith("../")||t.startsWith("/")}function A$(t){if(t.trim().length===0)return[];let e;try{e=JSON.parse(t)}catch(r){let n=r instanceof Error?r.message:String(r);throw new Error(`invalid JSON source: ${n}`)}if(!Ao(e)||!Array.isArray(e.sheets))throw new Error("JSON source must be an object with sheets[]");return e.sheets.map((r,n)=>R$(r,n))}function R$(t,e){if(!Ao(t))throw new Error(`sheets[${e}] must be an object`);let r=L$(t.headers,`sheets[${e}].headers`),n=O$(t.rows,`sheets[${e}].rows`);return{name:typeof t.name=="string"&&t.name.trim().length>0?t.name:`Sheet${e+1}`,headers:r,rows:n,headerStyle:$$(t.styles)}}function L$(t,e){if(t===void 0)return[];if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))throw new Error(`${e} must be an array of strings`);return t}function O$(t,e){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((r,n)=>{if(!Array.isArray(r))throw new Error(`${e}[${n}] must be an array`);return r.map((s,i)=>{if(s===null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")return s;throw new Error(`${e}[${n}][${i}] must be string, number, boolean, or null`)})})}function $$(t){if(!Ao(t)||!Ao(t.headers))return;let e={};return t.headers.bold===!0&&(e.bold=!0),typeof t.headers.fill=="string"&&(e.fill=t.headers.fill),Object.keys(e).length===0?void 0:e}function C$(t){let e=w$.lexer(t,{gfm:!0}),r=[],n=null;for(let s of e){if(B$(s)){n=s.text;continue}q$(s)&&(r.push({name:n??`Sheet${r.length+1}`,headers:s.header.map(i=>i.text),rows:s.rows.map(i=>i.map(o=>o.text)),headerStyle:{bold:!0}}),n=null)}return r}async function M$(t){_$(g$(t.outputPath),{recursive:!0});let e=new Set,r=t.sheets.map(n=>({sheet:F$(n.name,e),data:j$(n),columns:P$(n)}));await E$(r).toFile(t.outputPath)}function j$(t){let e=[];if(t.headers.length>0){let r=W$(t.headerStyle?.fill);e.push(t.headers.map(n=>({value:n,type:String,fontWeight:t.headerStyle?.bold===!1?void 0:"bold",backgroundColor:r??void 0})))}for(let r of t.rows)e.push(r.map(D$));return e.length===0?[[{}]]:e}function D$(t){return t===null?{}:typeof t=="string"?{value:t,type:String}:typeof t=="number"?{value:t,type:Number}:typeof t=="boolean"?{value:t,type:Boolean}:{}}function P$(t){let e=Math.max(t.headers.length,...t.rows.map(n=>n.length),1),r=[];for(let n=1;n<=e;n+=1){let s=[t.headers[n-1],...t.rows.map(o=>o[n-1])],i=Math.min(60,Math.max(10,...s.map(o=>String(o??"").length+2)));r.push({width:i})}return r}function F$(t,e){let r=U$(t),n=r,s=2;for(;e.has(n.toLowerCase());){let i=` ${s}`;n=`${r.slice(0,31-i.length)}${i}`,s+=1}return e.add(n.toLowerCase()),n}function U$(t){let e=t.replace(/[\[\]:*?/\\]/g," ").trim();return(e.length===0?"Sheet":e).slice(0,31)}function W$(t){if(t===void 0)return null;let e=t.startsWith("#")?t.slice(1):t;return/^[0-9a-fA-F]{6}$/.test(e)?`#${e.toUpperCase()}`:null}function B$(t){return t.type==="heading"&&typeof t.text=="string"}function q$(t){let e=t;return t.type==="table"&&Array.isArray(e.header)&&Array.isArray(e.rows)}function Ao(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Vg,Yg=E(()=>{"use strict";He();Vg={description:{displayName:"Render XLSX",name:"render-xlsx",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"done"},{name:"error"}],properties:[{name:"source",displayName:"Source",type:"string",required:!0,description:"JSON string, markdown table text, or path to a .json/.md/.markdown file."},{name:"input_format",displayName:"Input Format",type:"options",default:"json",options:[{name:"JSON",value:"json"},{name:"Markdown",value:"markdown"}]},{name:"output_path",displayName:"Output Path",type:"string",required:!0,description:"Absolute or project-relative .xlsx path to write."},{name:"title",displayName:"Title",type:"string",required:!1,description:"Optional workbook title."}],mutates_external_state:!0,builtin:!0},execute:async t=>T$(t,t.state)}});import{spawnSync as H$}from"node:child_process";async function J$(t,e){let r=t.stateId,n=t.displayName,s=t.workflow.default_task_timeout_ms;for(let f of e.pre_checks??[])if(H$("sh",["-c",f.command],{cwd:t.project.local_path}).status!==0){let p=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1,t.dal.finishStep(p.id,"fail_pre_check",`pre_check_failed:${f.description??f.command}`),G(t,r,n,"fail_pre_check");let h=e.outcomes.fail_pre_check;return h!==void 0?J(t.workflow,h):{kind:"terminal",terminal:Y(t.workflow)}}let i=yn(t,e.durable_memory_tags),o=e.reviewers??[],a=null,l=o.length===0&&e.outcomes_from_stance!==void 0,c=l?Object.keys(e.outcomes_from_stance):[];for(let f=0;f<e.max_loops;f+=1){let m=`${n}:coder[${f}]`,p=await gn(t,m,e.coder,a!==null?`PRIOR REVIEW FEEDBACK:
|
|
2055
|
+
${a}`:null,c,l,s,e.writes_to_project_path===!0,i);if(l){let g=pg(p.text);if(g!==null){let _=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(_.id,null,`escalation_vocab:${g.token}`),{kind:"escalate",token:g.token,reason:g.reason.length>0?`${g.token}: ${g.reason}`:g.token}}}if(p.outcome===null){let g=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(g.id,null,p.status_detail),{kind:"escalate",token:"",reason:`coder_no_outcome:${p.status_detail}`}}if(o.length===0){if(e.outcomes_from_stance!==void 0){let y=Object.keys(e.outcomes_from_stance),T=Ts(p.text,y);if(T.outcome===null){let I=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(I.id,null,`unhandled_stance:${T.reason}`),{kind:"escalate",token:"",reason:`no_stance:${T.reason}`}}let b=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(b.id,T.outcome,"outcomes_from_stance"),G(t,r,n,T.outcome),J(t.workflow,e.outcomes_from_stance[T.outcome])}let g=Ts(p.text,X$);if(g.outcome!==null){let y=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(y.id,g.outcome,"default_failure_stance"),G(t,r,n,g.outcome),{kind:"escalate",token:g.outcome,reason:`failure_stance:${g.outcome}`}}let _=q(t,{run_id:t.run_id,state_name:n});if(t.steps_executed+=1,t.dal.finishStep(_.id,"approve","no_reviewers"),G(t,r,n,"approve"),e.write_back_durable_memory){let y=t.membersByAlias.get(e.coder.alias);y!==void 0&&await Jt(t,n,y,e.write_back_durable_memory)}return J(t.workflow,e.outcomes.approve)}let h=await Promise.all(o.map(g=>gn(t,`${n}:reviewer_${g.alias}[${f}]`,g,`CODER OUTPUT:
|
|
2056
|
+
${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));if(h.every(g=>g.outcome==="approve")){let g=q(t,{run_id:t.run_id,state_name:n});if(t.steps_executed+=1,t.dal.finishStep(g.id,"approve",`loop=${f}`),G(t,r,n,"approve"),e.write_back_durable_memory){let _=t.membersByAlias.get(e.coder.alias);_!==void 0&&await Jt(t,n,_,e.write_back_durable_memory)}return J(t.workflow,e.outcomes.approve)}if(a=h.filter(g=>g.outcome==="request_changes").map(g=>g.text).join(`
|
|
1975
2057
|
|
|
1976
|
-
`),e.loop_feedback_artifact!==void 0){let g=q(t,{run_id:t.run_id,state_name:`${n}:feedback[${f}]`});t.steps_executed+=1,t.dal.finishStep(g.id,"feedback_captured",`loop=${f}`),t.dal.insertStepArtifact({step_id:g.id,kind:e.loop_feedback_artifact,content:a})}}let d=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1,t.dal.finishStep(d.id,"max_loops_exceeded",`loops=${e.max_loops}`),G(t,r,n,"max_loops_exceeded");let u=e.outcomes.max_loops_exceeded;return u!==void 0?X(t.workflow,u):{kind:"terminal",terminal:Y(t.workflow)}}var J$,zg,Zg=E(()=>{"use strict";wd();He();J$=["blocked","failed","aborted"],zg={description:{displayName:"Review",name:"review",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],emits_progress:!0,builtin:!0},execute:async t=>X$(t,t.state)}});import{spawnSync as G$}from"node:child_process";async function K$(t,e){let r=t.stateId,n=t.displayName,s=await Ge(e.command,t,n),i=Sd(t,n),o=Ig(s);if(o.matched&&!i){let h=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.insertSessionEvent({run_id:t.run_id,step_id:h.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify({violation:"side_effect_without_pause",state_id:n,kind:o.kind,command:s,message:`ShellStep ${n} runs a classified side-effect command (${o.kind}) without a preceding approved gate`})}),t.dal.finishStep(h.id,null,`policy_violation:side_effect_without_pause:${o.kind}`),{kind:"terminal",terminal:Y(t.workflow)}}let a=new Date(Date.now()-1),l=typeof e.timeout_ms=="number"&&e.timeout_ms>0,c=G$("sh",["-c",s],{cwd:t.project.local_path,...l?{timeout:e.timeout_ms}:{},encoding:"utf8",env:{...process.env}}),d=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let u=typeof c.stderr=="string"?c.stderr:"",f=c.error;if((u.length>0||f!==void 0)&&t.dal.insertSessionEvent({run_id:t.run_id,step_id:d.id,kind:"shellstep_stderr",timestamp_ms:Date.now(),payload:JSON.stringify({state_id:n,exit_status:c.status,stderr:u,spawn_error:f===void 0?null:f instanceof Error?f.message:String(f),command:s})}),c.status===null)return l?(t.dal.finishStep(d.id,null,`timeout:${e.timeout_ms}ms`),{kind:"terminal",terminal:"shell_step_timeout"}):(t.dal.finishStep(d.id,null,"shell_step_signal_terminated"),{kind:"terminal",terminal:Y(t.workflow)});if(e.writes_to_project_path!==!0&&t.project.local_path.trim().length>0&&vd(t.project.local_path,a))return t.dal.insertSessionEvent({run_id:t.run_id,step_id:d.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify({violation:"writes_to_project_path",state_id:n,message:`ShellStep ${n} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(d.id,null,"policy_violation:writes_to_project_path"),{kind:"terminal",terminal:Y(t.workflow)};if(e.capture_output_to!==void 0){let h=c.stdout??"";t.dal.insertStepArtifact({step_id:d.id,kind:e.capture_output_to,content:h})}let m=String(c.status),p=e.outcomes_from_exit[m]??e.outcomes_from_exit.default;return p===void 0?(t.dal.insertStepArtifact({step_id:d.id,kind:"unhandled_exit",content:m}),t.dal.finishStep(d.id,null,`shell_step_unhandled_exit:${m}`),{kind:"terminal",terminal:"shell_step_unhandled_exit"}):(t.dal.finishStep(d.id,m,`exit=${c.status}`),G(t,r,n,m),X(t.workflow,p))}var Qg,ey=E(()=>{"use strict";He();Qg={description:{displayName:"Shell Step",name:"shell-step",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],mutates_external_state:!0,builtin:!0},execute:async t=>K$(t,t.state)}});async function V$(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let i=t.dal.getWorkflowByName(e.workflow_name);if(i===null)return t.dal.finishStep(s.id,null,`subflow_missing_workflow:${e.workflow_name}`),{kind:"terminal",terminal:Y(t.workflow)};let o=dt(i.definition),a=await Y$(t,e),l=await t.runChildWorkflow(i,o,a);if(l.paused===!0)return t.dal.finishStep(s.id,null,`subflow_paused:${l.run_id}`),{kind:"paused"};let c=l.terminal_state;if(c===null)return t.dal.finishStep(s.id,null,`subflow_no_terminal:${l.run_id}`),{kind:"terminal",terminal:Y(t.workflow)};G(t,r,n,z$(t,l.run_id,o.outputs??[])),t.dal.finishStep(s.id,c,`child_run=${l.run_id}`);let d=e.outcomes[c]??e.outcomes.default;return d===void 0?{kind:"terminal",terminal:Y(t.workflow)}:X(t.workflow,d)}async function Y$(t,e){let r={};for(let[n,s]of Object.entries(e.inputs??{})){let i=await wg(s,t);r[n]=i===s?await ko(s,t):i}return r}function z$(t,e,r){let n={};for(let s of r)n[s.name]=Z$(t,e,s);return n}function Z$(t,e,r){let s=t.dal.query("SELECT * FROM step WHERE run_id = ? AND state_name = ? ORDER BY id DESC LIMIT 1",e,r.source_step_id)[0];if(s===void 0)return null;let i=Q$(s,r.source_field);if(i.found)return i.value;let a=t.dal.query("SELECT * FROM step_artifact WHERE step_id = ? AND kind = ? ORDER BY id DESC LIMIT 1",s.id,r.source_field)[0];return a===void 0?null:a.content??a.path??a.sha??null}function Q$(t,e){switch(e){case"id":return{found:!0,value:t.id};case"run_id":return{found:!0,value:t.run_id};case"parent_step_id":return{found:!0,value:t.parent_step_id};case"state_name":return{found:!0,value:t.state_name};case"outcome":return{found:!0,value:t.outcome};case"status_detail":return{found:!0,value:t.status_detail};case"started_at":return{found:!0,value:t.started_at};case"ended_at":return{found:!0,value:t.ended_at};default:return{found:!1}}}var ty,ry=E(()=>{"use strict";_s();He();bs();ty={description:{displayName:"Subflow",name:"subflow",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[{name:"workflow_name",displayName:"Workflow Name",type:"string",description:"Latest saved workflow name to execute as a child run."}],builtin:!0},execute:async t=>V$(t,t.state)}});function eC(t,e){let r=t.stateId,n=t.displayName,s=e.name??n,i=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(i.id,s,e.kind??"neutral"),G(t,r,n,s),{kind:"terminal",terminal:s}}var ny,sy=E(()=>{"use strict";He();ny={description:{displayName:"Terminal",name:"terminal",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[],outputs:[],properties:[{name:"kind",displayName:"Kind",type:"options",required:!0,options:[{name:"success",value:"success"},{name:"failure",value:"failure"},{name:"neutral",value:"neutral"}]},{name:"name",displayName:"Name",type:"string",required:!0}],builtin:!0},execute:t=>eC(t,t.state)}});async function tC(t){let e=typeof t.parameters.org=="string"?t.parameters.org:"",r=typeof t.parameters.repo=="string"?t.parameters.repo:"";if(e.length===0||r.length===0)return null;let n=new URL(`https://api.github.com/repos/${e}/${r}/issues`);n.searchParams.set("state","open"),typeof t.parameters.label=="string"&&t.parameters.label.length>0&&n.searchParams.set("labels",t.parameters.label),typeof t.parameters.since=="string"&&t.parameters.since.length>0&&n.searchParams.set("since",t.parameters.since);let s=await fetch(n);if(!s.ok)throw new Error(`github issue trigger failed: HTTP ${s.status}`);let i=await s.json();if(!Array.isArray(i))throw new Error("github issue trigger returned unexpected JSON");let o=rC(t.cursor),a=i.filter(nC).filter(c=>c.id>o);if(a.length===0)return null;let l=Math.max(...a.map(c=>c.id));return{main:a.map(c=>({trigger_id:t.trigger_id,issue_id:c.id,issue_number:c.number,issue_url:c.html_url,title:c.title,cursor:String(l)}))}}function rC(t){if(t===void 0)return 0;let e=Number(t);return Number.isFinite(e)?e:0}function nC(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.id=="number"&&typeof e.number=="number"&&typeof e.html_url=="string"&&typeof e.title=="string"}var iy,oy=E(()=>{"use strict";iy={description:{displayName:"GitHub Issue Trigger",name:"trigger-gh-issue",namespace:"lmctl",group:["trigger"],version:[1],inputs:[],outputs:[{name:"main"}],properties:[{name:"org",displayName:"Org",type:"string",required:!0},{name:"repo",displayName:"Repo",type:"string",required:!0},{name:"label",displayName:"Label",type:"string"}],requires_credentials:["github"],builtin:!0},poll:async t=>tC(t)}});async function sC(t){let e=typeof t.parameters.cron=="string"?t.parameters.cron.trim():"";if(e.length===0)return null;let r=new Date(Date.now()).toISOString().slice(0,16);return t.cursor===r?null:{main:[{trigger_id:t.trigger_id,fired_at:new Date(Date.now()).toISOString(),cursor:r,cron:e}]}}var ay,ly=E(()=>{"use strict";ay={description:{displayName:"Schedule Trigger",name:"trigger-schedule",namespace:"lmctl",group:["trigger"],version:[1],inputs:[],outputs:[{name:"main"}],properties:[{name:"cron",displayName:"Cron",type:"string",required:!0}],builtin:!0},poll:async t=>sC(t)}});function cy(t){t.register(xg),t.register(zg),t.register(Og),t.register(Pg),t.register(Ug),t.register(Hg),t.register(Vg),t.register(Qg),t.register(Rg),t.register(Cg),t.register(ty),t.register(ny),t.register(ay),t.register(iy)}var dy=E(()=>{"use strict";Ag();Lg();$g();jg();Fg();Wg();Xg();Yg();Zg();ey();ry();sy();oy();ly()});function uy(){return Ro===null&&(Ro=new Id,cy(Ro)),Ro}var iC,Id,Ro,fy=E(()=>{"use strict";dy();iC={Review:"lmctl/review",Consolidate:"lmctl/consolidate",Interactive:"lmctl/interactive",Loop:"lmctl/loop",ShellStep:"lmctl/shell-step",AssertRepoClean:"lmctl/assert-repo-clean",Choice:"lmctl/choice",ForEach:"lmctl/foreach",Subflow:"lmctl/subflow",Terminal:"lmctl/terminal"},Id=class{types=new Map;register(e){let r=`${e.description.namespace}/${e.description.name}`;if(this.types.has(r))throw new Error(`archetype already registered: ${r}`);this.types.set(r,e)}get(e){let r=e.includes("/")?e:iC[e];return r?this.types.get(r):void 0}list(){return Array.from(this.types.values())}},Ro=null});async function _y(t){Ey(t.workflow);let e=t.workflowRow??t.dal.getWorkflowByName(t.workflow.name,t.workflow.version);if(e===null)throw new Error(`workflow ${t.workflow.name}@${t.workflow.version} is not registered`);let r=t.dal.getProjectByJob(t.job.id);if(r===null)throw new Error(`job ${t.job.id} has no project`);let n=aC(e.definition,t.workflow),s=t.job.run_id===null?null:t.dal.getRun(t.job.run_id),i=Ns(n)?n.entry_step_id:n.start_at,o=s?.terminal_state===null?s:t.dal.insertRun({job_id:t.job.id,workflow_id:e.id,team_id:t.team.id,current_state:i}),a=n.requires,l=ag(a);if(l!==null)return t.dal.setRunTerminalState(o.id,"aborted"),t.dal.raiseAttention({kind:"missing_workflow_dependency",severity:"error",project_id:r.id,run_id:o.id,payload:JSON.stringify({run_id:o.id,workflow_name:n.name,kind:l.kind,tool:l.tool,install_hint:l.install_hint,last_error:l.message,detail:l.detail??null})}),{run_id:o.id,terminal_state:"aborted",steps_executed:0};let c=new Map(t.members.map(m=>[m.alias,m]));if(Ns(n)){let m=Nd({dal:t.dal,workflow:Oo(n),job:t.job,project:r,run:o,membersByAlias:c,outcomes:s!==null&&o===s?t.dal.listLatestStepOutcomesByState(o.id):{},inputs:mr(t.job.payload)??{},team_id:t.team.id}),p=await gy(n,m,o.current_state??n.entry_step_id);return py(t.dal,r.id,o.id,n.name,p),p}let d=s!==null&&o===s?t.dal.listLatestStepOutcomesByState(o.id):{},u=Nd({dal:t.dal,workflow:n,job:t.job,project:r,run:o,membersByAlias:c,outcomes:d,inputs:mr(t.job.payload)??{},team_id:t.team.id}),f=await hy(u,o.current_state??n.start_at);return py(t.dal,r.id,o.id,n.name,f),f}function py(t,e,r,n,s){if(s.paused===!0)return;let i=s.terminal_state;if(i===null)return;let o="unknown",a=!1;try{let d=t.getRun(r);if(d!==null){let u=t.getWorkflow(d.workflow_id);if(u!==null){let f=JSON.parse(u.definition),p=(f.terminals??{})[i];if(p!==void 0&&typeof p.kind=="string"&&(p.kind==="success"||p.kind==="failure"||p.kind==="neutral")&&(o=p.kind),o==="unknown"&&Array.isArray(f.steps)){for(let g of f.steps)if(g.type==="lmctl/terminal"&&g.parameters!==null&&typeof g.parameters=="object"){let _=g.parameters;if(_.name===i&&(_.kind==="success"||_.kind==="failure"||_.kind==="neutral")){o=_.kind;break}}}let h=f.errors;if(h!==null&&typeof h=="object"){let g=h;(g.on_unhandled_failure!==void 0||g.on_unhandled_failure_state!==void 0)&&(a=!0)}}}}catch{}if(o==="success"||o==="failure"&&a)return;let l=null;try{l=t.query("SELECT status_detail FROM step WHERE run_id = ? ORDER BY id DESC LIMIT 1",r)[0]?.status_detail??null}catch{l=null}let c=o==="failure"?"workflow_failed":"workflow_has_issues";t.raiseAttention({kind:c,severity:o==="failure"?"error":"warn",project_id:e,run_id:r,payload:JSON.stringify({run_id:r,workflow_name:n,terminal_state:i,terminal_kind:o,last_error:l})})}function Nd(t){let e={dal:t.dal,workflow:t.workflow,job:t.job,project:t.project,run_id:t.run.id,membersByAlias:t.membersByAlias,inputs:t.inputs,outcomes:t.outcomes,transcripts:{},progress_step_id:null,steps_executed:0,last_state_id:null,errors_block_fired:!1,iteration:null,parent_step_id:null,dispatchState:async(r,n,s)=>{let i=e.parent_step_id,o=e.iteration;e.parent_step_id=s?.parent_step_id??i,e.iteration=s?.iteration??o;try{return await xd(e,r,n,s?.display_name??r)}finally{e.parent_step_id=i,e.iteration=o}},runChildWorkflow:async(r,n,s)=>{Ey(n);let i=Ns(n)?n.entry_step_id:n.start_at,o=t.dal.insertRun({job_id:t.job.id,workflow_id:r.id,team_id:t.team_id,current_state:i,parent_run_id:e.run_id}),a=Nd({dal:t.dal,workflow:Ns(n)?Oo(n):n,job:t.job,project:t.project,run:o,membersByAlias:t.membersByAlias,outcomes:{},inputs:s,team_id:t.team_id});return Ns(n)?gy(n,a,o.current_state??n.entry_step_id):hy(a,o.current_state??n.start_at)}};return e}async function hy(t,e){let r=e;if(r.startsWith(Ss))return{run_id:t.run_id,terminal_state:null,steps_executed:0,paused:!0};for(let s=0;s<1e3;s+=1){if(r.startsWith("@terminal:"))return Gt(t,r.slice(10));t.dal.setRunCurrentState(t.run_id,r),t.last_state_id=r;let i=t.workflow.states[r];if(i===void 0){let l=Lo(t,Y(t.workflow));if(l.kind==="paused")return De(t);if(l.kind==="escalate")return nt(t,{id:r,name:r,type:"unknown"},l.token,l.reason),De(t);if(l.kind==="terminal")return Gt(t,l.terminal);r=l.state;continue}let o,a=wy(t,r);if(a!==null){let l=q(t,{run_id:t.run_id,state_name:r});if(t.steps_executed+=1,t.dal.finishStep(l.id,a,"escalation_resume"),G(t,r,r,a),a===zn)return Gt(t,fl);let c=i.outcomes?.[a];o=c!==void 0?X(t.workflow,c):nt(t,{id:r,name:r,type:i.type},a,`no declared edge for resumed outcome '${a}' from state '${r}'`)}else o=await xd(t,r,i);if(o.kind==="paused")return De(t);if(o.kind==="escalate")return nt(t,{id:r,name:r,type:i.type},o.token,o.reason),De(t);if(o.kind==="terminal"){let l=Lo(t,o.terminal);if(l.kind==="paused")return De(t);if(l.kind==="escalate")return nt(t,{id:r,name:r,type:i.type},l.token,l.reason),De(t);if(l.kind==="terminal")return Gt(t,l.terminal);r=l.state;continue}r=o.state}t.dal.raiseAttention({kind:"engine_step_limit_exceeded",severity:"error",project_id:t.project.id,run_id:t.run_id,payload:JSON.stringify({run_id:t.run_id})});let n=Lo(t,Y(t.workflow));return n.kind==="terminal"?Gt(t,n.terminal):Gt(t,Y(t.workflow))}async function gy(t,e,r){let n=new Map(t.steps.map(o=>[o.id,o])),s=new Map(t.steps.map(o=>[o.name,o])),i=r;for(let o=0;o<1e3;o+=1){e.dal.setRunCurrentState(e.run_id,i);let a=n.get(i);if(a===void 0)return nt(e,{id:i,name:i,type:"unknown"},"",`internal:unknown v3 step '${i}'`),De(e);let l=wy(e,a.id);if(l!==null){let m=q(e,{run_id:e.run_id,state_name:a.name});if(e.steps_executed+=1,e.dal.finishStep(m.id,l,"escalation_resume"),G(e,a.id,a.name,l),l===zn)return Gt(e,fl);let p=Object.keys(t.connections[a.id]??{}),h=t.connections[a.id]?.[l]?.[0]?.[0]?.step_id??t.connections[a.id]?.main?.[0]?.[0]?.step_id;if(h===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},l,`no declared edge for resumed outcome '${l}' from step '${a.id}'`,{declared_outcomes:p}),De(e);i=h;continue}let c=await oC(e,t,a);if(c.kind==="paused")return De(e);let d=Object.keys(t.connections[a.id]??{});if(c.kind==="escalate")return nt(e,{id:a.id,name:a.name,type:a.type},c.token,c.reason,{declared_outcomes:d}),De(e);let u=c.kind==="terminal"?c.terminal:c.state;if(a.type==="lmctl/terminal"){let m=e.workflow;e.workflow=Oo(t,a);try{let p=Lo(e,u);if(p.kind==="paused")return De(e);if(p.kind==="escalate")return nt(e,{id:a.id,name:a.name,type:a.type},p.token,p.reason),De(e);if(p.kind==="terminal")return Gt(e,p.terminal);let h=s.get(p.state);if(h===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},"",`internal:unknown v3 error handler step '${p.state}'`),De(e);i=h.id;continue}finally{e.workflow=m}}if(zr(u))return nt(e,{id:a.id,name:a.name,type:a.type},u,`generic escalation '${u}' from step '${a.id}'`,{declared_outcomes:d}),De(e);let f=t.connections[a.id]?.[u]?.[0]?.[0]?.step_id??t.connections[a.id]?.main?.[0]?.[0]?.step_id;if(f===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},u,`no declared edge for outcome '${u}' from step '${a.id}'`,{declared_outcomes:d}),De(e);i=f}return e.dal.raiseAttention({kind:"engine_step_limit_exceeded",severity:"error",project_id:e.project.id,run_id:e.run_id,payload:JSON.stringify({run_id:e.run_id})}),Gt(e,"aborted")}async function oC(t,e,r){let n=yy(e,r),s=t.workflow;t.workflow=Oo(e,r);try{return await xd(t,r.id,n,r.name)}finally{t.workflow=s}}function yy(t,e){let r=e.parameters,n=e.members??{},s=Object.keys(t.connections[e.id]??{}),i=Object.fromEntries(s.map(a=>[a,`@terminal:${a}`])),o={state_name:e.name};switch(e.type){case"lmctl/review":{let a=s.filter(l=>!["approve","request_changes","fail_pre_check","max_loops_exceeded"].includes(l));return{...o,type:"Review",...r,coder:n.coder,reviewers:n.reviewers,outcomes:{approve:i.approve??"@terminal:approve",...i.request_changes!==void 0?{request_changes:i.request_changes}:{},...i.fail_pre_check!==void 0?{fail_pre_check:i.fail_pre_check}:{},...i.max_loops_exceeded!==void 0?{max_loops_exceeded:i.max_loops_exceeded}:{}},...a.length>0?{outcomes_from_stance:Object.fromEntries(a.map(l=>[l,`@terminal:${l}`]))}:{}}}case"lmctl/consolidate":return{...o,type:"Consolidate",...r,researchers:n.researchers,consolidator:n.consolidator,outcomes:{ok:i.ok??"@terminal:ok",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/interactive":return{...o,type:"Interactive",...r,agent:n.agent,outcomes:{done:i.done??"@terminal:done",...i.timeout!==void 0?{timeout:i.timeout}:{}}};case"lmctl/loop":return{...o,type:"Loop",...r,outcomes:{ok:i.ok??"@terminal:ok",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/render-docx":return{...o,type:"lmctl/render-docx",...r,outcomes:{done:i.done??"@terminal:done",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/render-xlsx":return{...o,type:"lmctl/render-xlsx",...r,outcomes:{done:i.done??"@terminal:done",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/shell-step":return{...o,type:"ShellStep",...r,outcomes_from_exit:r.outcomes_from_exit??Object.fromEntries(s.map(a=>[a.slice(5),`@terminal:${a}`]))};case"lmctl/assert-repo-clean":return{...o,type:"AssertRepoClean",...r,next:i.main??"@terminal:main"};case"lmctl/choice":return{...o,type:"Choice",...r};case"lmctl/foreach":return{...o,type:"ForEach",...r,outcomes:{all_ok:i.all_ok??"@terminal:all_ok",...i.any_failed!==void 0?{any_failed:i.any_failed}:{}}};case"lmctl/subflow":return{...o,type:"Subflow",...r,outcomes:i};case"lmctl/terminal":return{...o,type:"Terminal",name:r.name,kind:r.kind};default:return{...o,type:e.type,...r}}}async function xd(t,e,r,n){let s=uy().get(r.type);if(s===void 0)throw new Error(`unknown archetype: ${r.type}`);if(s.execute===void 0)throw new Error(`archetype ${r.type} has no execute() - is it a trigger-only archetype used as a step?`);let i=t.emit_progress,o=t.progress_step_id;t.emit_progress=s.description.emits_progress===!0?dC(t,s):void 0,t.progress_step_id=null;try{return await s.execute(vg(t,e,r,n??e))}finally{t.emit_progress=i,t.progress_step_id=o}}function aC(t,e){try{let r=JSON.parse(t);if(cC(r)&&r.definition_schema_version===3)return xt.parse(r)}catch{return e}return e}function Ns(t){return t.definition_schema_version===3}function Oo(t,e){let r=e===void 0?[]:Object.keys(t.connections[e.id]??{}),n=Object.fromEntries(r.map(i=>[i,{kind:i==="aborted"?"failure":"neutral"}])),s={};if(e?.type==="lmctl/loop"&&typeof e.parameters.body=="string"){let i=t.steps.find(o=>o.name===e.parameters.body);i!==void 0&&(s[e.parameters.body]=yy(t,i))}return e?.type==="lmctl/terminal"&&typeof e.parameters.name=="string"&&(n[e.parameters.name]={kind:lC(e.parameters.kind)}),n.aborted??={kind:"failure"},{name:t.name,version:t.version,definition_schema_version:2,primitive_version:2,start_at:e?.name??t.entry_step_id,states:s,terminals:n,...t.default_task_timeout_ms!==void 0?{default_task_timeout_ms:t.default_task_timeout_ms}:{},...t.concurrency_key!==void 0?{concurrency_key:t.concurrency_key}:{},...t.concurrent_limit!==void 0?{concurrent_limit:t.concurrent_limit}:{},...t.errors!==void 0?{errors:t.errors}:{}}}function lC(t){return t==="success"||t==="failure"||t==="neutral"?t:"neutral"}function cC(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dC(t,e){let r=`progress.${e.description.namespace}/${e.description.name}`;return n=>{try{if(typeof n.kind!="string"||n.kind.length===0)return;t.dal.insertSessionEvent({run_id:t.run_id,step_id:t.progress_step_id,kind:`${r}.${n.kind}`,timestamp_ms:Date.now(),payload:JSON.stringify({message:n.message,data:n.data})})}catch(s){let i=s instanceof Error?s.message:String(s);console.warn(`[progress] dropped ${r} event: ${i}`)}}}function Gt(t,e){t.dal.setRunTerminalState(t.run_id,e);try{ng(t.run_id,t.dal)}catch{}return{run_id:t.run_id,terminal_state:e,steps_executed:t.steps_executed}}function De(t){return{run_id:t.run_id,terminal_state:null,steps_executed:t.steps_executed,paused:!0}}function wy(t,e){let n=t.dal.getRun(t.run_id)?.pending_escalation_decision??null;if(n===null)return null;let s;try{let a=JSON.parse(n);if(a===null||typeof a!="object"||Array.isArray(a))return null;s=a}catch{return null}let i=s[e];if(typeof i!="string")return null;delete s[e];let o=Object.keys(s).length>0?JSON.stringify(s):null;return t.dal.setRunPendingEscalationDecision(t.run_id,o),i}function Lo(t,e){if(!uC(t.workflow,e)||t.errors_block_fired)return{kind:"terminal",terminal:e};let r=t.workflow.errors;return r===void 0?{kind:"terminal",terminal:e}:(t.errors_block_fired=!0,r.on_unhandled_failure_state!==void 0?{kind:"state",state:r.on_unhandled_failure_state}:(r.on_unhandled_failure!==void 0&&fC(t,e,r.on_unhandled_failure),{kind:"terminal",terminal:e}))}function uC(t,e){return t.definition_schema_version===2&&t.terminals[e]?.kind==="failure"}function fC(t,e,r){let n=mC(t),s=r.capture_evidence&&n!==null?pC(t,n.id):[];t.dal.raiseAttention({kind:r.attention_kind,severity:r.severity,project_id:t.project.id,run_id:t.run_id,payload:JSON.stringify({run_id:t.run_id,terminal_state:e,current_state:t.last_state_id,last_step_id:n?.id??null,last_error:n?.status_detail??null,evidence_paths:s,recommend_recovery:r.recommend_recovery??null})})}function mC(t){return t.dal.query("SELECT id, state_name, outcome, status_detail FROM step WHERE run_id = ? ORDER BY id DESC LIMIT 1",t.run_id)[0]??null}function pC(t,e){return t.dal.query("SELECT path FROM step_artifact WHERE step_id = ? AND path IS NOT NULL ORDER BY id DESC",e).map(n=>n.path)}function Ey(t){if(!my.includes(t.definition_schema_version))throw new Error(`unsupported definition_schema_version ${t.definition_schema_version}; supported versions: ${my.join(", ")}`)}var my,Ty=E(()=>{"use strict";mn();sg();lg();He();fy();Zn();my=[1,2,3]});import{readFileSync as _C,readdirSync as hC}from"node:fs";import{basename as gC,join as yC,resolve as wC}from"node:path";function vy(t={}){let e=wC(t.workflowsDir??"workflows"),r=hC(e).filter(n=>n.endsWith(".compound.json")).sort((n,s)=>n.localeCompare(s));return{generated_at:new Date().toISOString(),workflows_dir:e,rows:r.map(n=>EC(yC(e,n)))}}function EC(t){let e=gC(t);try{let r=_C(t,"utf8"),n=dt(r);return Ny(e,n)}catch(r){return{file:e,workflow_name:null,status:"FAIL",first_step_id:null,first_step_type:null,first_step_disposition:null,note:xy(r)}}}function ky(t,e){try{let r=dt(e);return Ny(t,r)}catch(r){return{file:t,workflow_name:t,status:"FAIL",first_step_id:null,first_step_type:null,first_step_disposition:null,note:xy(r)}}}function Iy(t){let e=[];e.push(`workflow verification - ${t.generated_at}`),e.push(`dir: ${t.workflows_dir}`),e.push(""),e.push(`${"status".padEnd(17)} ${"workflow".padEnd(36)} ${"first step".padEnd(52)} note`),e.push(`${"-".repeat(17)} ${"-".repeat(36)} ${"-".repeat(52)} ${"-".repeat(30)}`);for(let i of t.rows){let o=(i.workflow_name??i.file).slice(0,36).padEnd(36),a=`${i.first_step_id??"-"}${i.first_step_type===null?"":` (${i.first_step_type})`}`;e.push(`${i.status.padEnd(17)} ${o} ${a.slice(0,52).padEnd(52)} ${i.note}`)}let r=t.rows.filter(i=>i.status==="PASS").length,n=t.rows.filter(i=>i.status==="PASS_NEEDS_INPUTS").length,s=t.rows.filter(i=>i.status==="FAIL").length;return e.push(""),e.push(`summary: ${r} pass, ${n} pass_needs_inputs, ${s} fail`),`${e.join(`
|
|
2058
|
+
`),e.loop_feedback_artifact!==void 0){let g=q(t,{run_id:t.run_id,state_name:`${n}:feedback[${f}]`});t.steps_executed+=1,t.dal.finishStep(g.id,"feedback_captured",`loop=${f}`),t.dal.insertStepArtifact({step_id:g.id,kind:e.loop_feedback_artifact,content:a})}}let d=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1,t.dal.finishStep(d.id,"max_loops_exceeded",`loops=${e.max_loops}`),G(t,r,n,"max_loops_exceeded");let u=e.outcomes.max_loops_exceeded;return u!==void 0?J(t.workflow,u):{kind:"terminal",terminal:Y(t.workflow)}}var X$,zg,Zg=E(()=>{"use strict";wd();He();X$=["blocked","failed","aborted"],zg={description:{displayName:"Review",name:"review",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],emits_progress:!0,builtin:!0},execute:async t=>J$(t,t.state)}});import{spawnSync as G$}from"node:child_process";async function K$(t,e){let r=t.stateId,n=t.displayName,s=await Ge(e.command,t,n),i=Sd(t,n),o=Ig(s);if(o.matched&&!i){let h=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.insertSessionEvent({run_id:t.run_id,step_id:h.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify({violation:"side_effect_without_pause",state_id:n,kind:o.kind,command:s,message:`ShellStep ${n} runs a classified side-effect command (${o.kind}) without a preceding approved gate`})}),t.dal.finishStep(h.id,null,`policy_violation:side_effect_without_pause:${o.kind}`),{kind:"terminal",terminal:Y(t.workflow)}}let a=new Date(Date.now()-1),l=typeof e.timeout_ms=="number"&&e.timeout_ms>0,c=G$("sh",["-c",s],{cwd:t.project.local_path,...l?{timeout:e.timeout_ms}:{},encoding:"utf8",env:{...process.env}}),d=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let u=typeof c.stderr=="string"?c.stderr:"",f=c.error;if((u.length>0||f!==void 0)&&t.dal.insertSessionEvent({run_id:t.run_id,step_id:d.id,kind:"shellstep_stderr",timestamp_ms:Date.now(),payload:JSON.stringify({state_id:n,exit_status:c.status,stderr:u,spawn_error:f===void 0?null:f instanceof Error?f.message:String(f),command:s})}),c.status===null)return l?(t.dal.finishStep(d.id,null,`timeout:${e.timeout_ms}ms`),{kind:"terminal",terminal:"shell_step_timeout"}):(t.dal.finishStep(d.id,null,"shell_step_signal_terminated"),{kind:"terminal",terminal:Y(t.workflow)});if(e.writes_to_project_path!==!0&&t.project.local_path.trim().length>0&&vd(t.project.local_path,a))return t.dal.insertSessionEvent({run_id:t.run_id,step_id:d.id,kind:"policy_violation",timestamp_ms:Date.now(),payload:JSON.stringify({violation:"writes_to_project_path",state_id:n,message:`ShellStep ${n} wrote to project.local_path without writes_to_project_path: true`})}),t.dal.finishStep(d.id,null,"policy_violation:writes_to_project_path"),{kind:"terminal",terminal:Y(t.workflow)};if(e.capture_output_to!==void 0){let h=c.stdout??"";t.dal.insertStepArtifact({step_id:d.id,kind:e.capture_output_to,content:h})}let m=String(c.status),p=e.outcomes_from_exit[m]??e.outcomes_from_exit.default;return p===void 0?(t.dal.insertStepArtifact({step_id:d.id,kind:"unhandled_exit",content:m}),t.dal.finishStep(d.id,null,`shell_step_unhandled_exit:${m}`),{kind:"terminal",terminal:"shell_step_unhandled_exit"}):(t.dal.finishStep(d.id,m,`exit=${c.status}`),G(t,r,n,m),J(t.workflow,p))}var Qg,ey=E(()=>{"use strict";He();Qg={description:{displayName:"Shell Step",name:"shell-step",namespace:"lmctl",group:["action"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[],mutates_external_state:!0,builtin:!0},execute:async t=>K$(t,t.state)}});async function V$(t,e){let r=t.stateId,n=t.displayName,s=q(t,{run_id:t.run_id,state_name:n});t.steps_executed+=1;let i=t.dal.getWorkflowByName(e.workflow_name);if(i===null)return t.dal.finishStep(s.id,null,`subflow_missing_workflow:${e.workflow_name}`),{kind:"terminal",terminal:Y(t.workflow)};let o=dt(i.definition),a=await Y$(t,e),l=await t.runChildWorkflow(i,o,a);if(l.paused===!0)return t.dal.finishStep(s.id,null,`subflow_paused:${l.run_id}`),{kind:"paused"};let c=l.terminal_state;if(c===null)return t.dal.finishStep(s.id,null,`subflow_no_terminal:${l.run_id}`),{kind:"terminal",terminal:Y(t.workflow)};G(t,r,n,z$(t,l.run_id,o.outputs??[])),t.dal.finishStep(s.id,c,`child_run=${l.run_id}`);let d=e.outcomes[c]??e.outcomes.default;return d===void 0?{kind:"terminal",terminal:Y(t.workflow)}:J(t.workflow,d)}async function Y$(t,e){let r={};for(let[n,s]of Object.entries(e.inputs??{})){let i=await wg(s,t);r[n]=i===s?await ko(s,t):i}return r}function z$(t,e,r){let n={};for(let s of r)n[s.name]=Z$(t,e,s);return n}function Z$(t,e,r){let s=t.dal.query("SELECT * FROM step WHERE run_id = ? AND state_name = ? ORDER BY id DESC LIMIT 1",e,r.source_step_id)[0];if(s===void 0)return null;let i=Q$(s,r.source_field);if(i.found)return i.value;let a=t.dal.query("SELECT * FROM step_artifact WHERE step_id = ? AND kind = ? ORDER BY id DESC LIMIT 1",s.id,r.source_field)[0];return a===void 0?null:a.content??a.path??a.sha??null}function Q$(t,e){switch(e){case"id":return{found:!0,value:t.id};case"run_id":return{found:!0,value:t.run_id};case"parent_step_id":return{found:!0,value:t.parent_step_id};case"state_name":return{found:!0,value:t.state_name};case"outcome":return{found:!0,value:t.outcome};case"status_detail":return{found:!0,value:t.status_detail};case"started_at":return{found:!0,value:t.started_at};case"ended_at":return{found:!0,value:t.ended_at};default:return{found:!1}}}var ty,ry=E(()=>{"use strict";_s();He();bs();ty={description:{displayName:"Subflow",name:"subflow",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[{name:"main"}],outputs:[{name:"main"}],properties:[{name:"workflow_name",displayName:"Workflow Name",type:"string",description:"Latest saved workflow name to execute as a child run."}],builtin:!0},execute:async t=>V$(t,t.state)}});function eC(t,e){let r=t.stateId,n=t.displayName,s=e.name??n,i=q(t,{run_id:t.run_id,state_name:n});return t.steps_executed+=1,t.dal.finishStep(i.id,s,e.kind??"neutral"),G(t,r,n,s),{kind:"terminal",terminal:s}}var ny,sy=E(()=>{"use strict";He();ny={description:{displayName:"Terminal",name:"terminal",namespace:"lmctl",group:["flow-control"],version:[1],inputs:[],outputs:[],properties:[{name:"kind",displayName:"Kind",type:"options",required:!0,options:[{name:"success",value:"success"},{name:"failure",value:"failure"},{name:"neutral",value:"neutral"}]},{name:"name",displayName:"Name",type:"string",required:!0}],builtin:!0},execute:t=>eC(t,t.state)}});async function tC(t){let e=typeof t.parameters.org=="string"?t.parameters.org:"",r=typeof t.parameters.repo=="string"?t.parameters.repo:"";if(e.length===0||r.length===0)return null;let n=new URL(`https://api.github.com/repos/${e}/${r}/issues`);n.searchParams.set("state","open"),typeof t.parameters.label=="string"&&t.parameters.label.length>0&&n.searchParams.set("labels",t.parameters.label),typeof t.parameters.since=="string"&&t.parameters.since.length>0&&n.searchParams.set("since",t.parameters.since);let s=await fetch(n);if(!s.ok)throw new Error(`github issue trigger failed: HTTP ${s.status}`);let i=await s.json();if(!Array.isArray(i))throw new Error("github issue trigger returned unexpected JSON");let o=rC(t.cursor),a=i.filter(nC).filter(c=>c.id>o);if(a.length===0)return null;let l=Math.max(...a.map(c=>c.id));return{main:a.map(c=>({trigger_id:t.trigger_id,issue_id:c.id,issue_number:c.number,issue_url:c.html_url,title:c.title,cursor:String(l)}))}}function rC(t){if(t===void 0)return 0;let e=Number(t);return Number.isFinite(e)?e:0}function nC(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.id=="number"&&typeof e.number=="number"&&typeof e.html_url=="string"&&typeof e.title=="string"}var iy,oy=E(()=>{"use strict";iy={description:{displayName:"GitHub Issue Trigger",name:"trigger-gh-issue",namespace:"lmctl",group:["trigger"],version:[1],inputs:[],outputs:[{name:"main"}],properties:[{name:"org",displayName:"Org",type:"string",required:!0},{name:"repo",displayName:"Repo",type:"string",required:!0},{name:"label",displayName:"Label",type:"string"}],requires_credentials:["github"],builtin:!0},poll:async t=>tC(t)}});async function sC(t){let e=typeof t.parameters.cron=="string"?t.parameters.cron.trim():"";if(e.length===0)return null;let r=new Date(Date.now()).toISOString().slice(0,16);return t.cursor===r?null:{main:[{trigger_id:t.trigger_id,fired_at:new Date(Date.now()).toISOString(),cursor:r,cron:e}]}}var ay,ly=E(()=>{"use strict";ay={description:{displayName:"Schedule Trigger",name:"trigger-schedule",namespace:"lmctl",group:["trigger"],version:[1],inputs:[],outputs:[{name:"main"}],properties:[{name:"cron",displayName:"Cron",type:"string",required:!0}],builtin:!0},poll:async t=>sC(t)}});function cy(t){t.register(xg),t.register(zg),t.register(Og),t.register(Pg),t.register(Ug),t.register(Hg),t.register(Vg),t.register(Qg),t.register(Rg),t.register(Cg),t.register(ty),t.register(ny),t.register(ay),t.register(iy)}var dy=E(()=>{"use strict";Ag();Lg();$g();jg();Fg();Wg();Jg();Yg();Zg();ey();ry();sy();oy();ly()});function uy(){return Ro===null&&(Ro=new Id,cy(Ro)),Ro}var iC,Id,Ro,fy=E(()=>{"use strict";dy();iC={Review:"lmctl/review",Consolidate:"lmctl/consolidate",Interactive:"lmctl/interactive",Loop:"lmctl/loop",ShellStep:"lmctl/shell-step",AssertRepoClean:"lmctl/assert-repo-clean",Choice:"lmctl/choice",ForEach:"lmctl/foreach",Subflow:"lmctl/subflow",Terminal:"lmctl/terminal"},Id=class{types=new Map;register(e){let r=`${e.description.namespace}/${e.description.name}`;if(this.types.has(r))throw new Error(`archetype already registered: ${r}`);this.types.set(r,e)}get(e){let r=e.includes("/")?e:iC[e];return r?this.types.get(r):void 0}list(){return Array.from(this.types.values())}},Ro=null});async function _y(t){Ey(t.workflow);let e=t.workflowRow??t.dal.getWorkflowByName(t.workflow.name,t.workflow.version);if(e===null)throw new Error(`workflow ${t.workflow.name}@${t.workflow.version} is not registered`);let r=t.dal.getProjectByJob(t.job.id);if(r===null)throw new Error(`job ${t.job.id} has no project`);let n=aC(e.definition,t.workflow),s=t.job.run_id===null?null:t.dal.getRun(t.job.run_id),i=Ns(n)?n.entry_step_id:n.start_at,o=s?.terminal_state===null?s:t.dal.insertRun({job_id:t.job.id,workflow_id:e.id,team_id:t.team.id,current_state:i}),a=n.requires,l=ag(a);if(l!==null)return t.dal.setRunTerminalState(o.id,"aborted"),t.dal.raiseAttention({kind:"missing_workflow_dependency",severity:"error",project_id:r.id,run_id:o.id,payload:JSON.stringify({run_id:o.id,workflow_name:n.name,kind:l.kind,tool:l.tool,install_hint:l.install_hint,last_error:l.message,detail:l.detail??null})}),{run_id:o.id,terminal_state:"aborted",steps_executed:0};let c=new Map(t.members.map(m=>[m.alias,m]));if(Ns(n)){let m=Nd({dal:t.dal,workflow:Oo(n),job:t.job,project:r,run:o,membersByAlias:c,outcomes:s!==null&&o===s?t.dal.listLatestStepOutcomesByState(o.id):{},inputs:mr(t.job.payload)??{},team_id:t.team.id}),p=await gy(n,m,o.current_state??n.entry_step_id);return py(t.dal,r.id,o.id,n.name,p),p}let d=s!==null&&o===s?t.dal.listLatestStepOutcomesByState(o.id):{},u=Nd({dal:t.dal,workflow:n,job:t.job,project:r,run:o,membersByAlias:c,outcomes:d,inputs:mr(t.job.payload)??{},team_id:t.team.id}),f=await hy(u,o.current_state??n.start_at);return py(t.dal,r.id,o.id,n.name,f),f}function py(t,e,r,n,s){if(s.paused===!0)return;let i=s.terminal_state;if(i===null)return;let o="unknown",a=!1;try{let d=t.getRun(r);if(d!==null){let u=t.getWorkflow(d.workflow_id);if(u!==null){let f=JSON.parse(u.definition),p=(f.terminals??{})[i];if(p!==void 0&&typeof p.kind=="string"&&(p.kind==="success"||p.kind==="failure"||p.kind==="neutral")&&(o=p.kind),o==="unknown"&&Array.isArray(f.steps)){for(let g of f.steps)if(g.type==="lmctl/terminal"&&g.parameters!==null&&typeof g.parameters=="object"){let _=g.parameters;if(_.name===i&&(_.kind==="success"||_.kind==="failure"||_.kind==="neutral")){o=_.kind;break}}}let h=f.errors;if(h!==null&&typeof h=="object"){let g=h;(g.on_unhandled_failure!==void 0||g.on_unhandled_failure_state!==void 0)&&(a=!0)}}}}catch{}if(o==="success"||o==="failure"&&a)return;let l=null;try{l=t.query("SELECT status_detail FROM step WHERE run_id = ? ORDER BY id DESC LIMIT 1",r)[0]?.status_detail??null}catch{l=null}let c=o==="failure"?"workflow_failed":"workflow_has_issues";t.raiseAttention({kind:c,severity:o==="failure"?"error":"warn",project_id:e,run_id:r,payload:JSON.stringify({run_id:r,workflow_name:n,terminal_state:i,terminal_kind:o,last_error:l})})}function Nd(t){let e={dal:t.dal,workflow:t.workflow,job:t.job,project:t.project,run_id:t.run.id,membersByAlias:t.membersByAlias,inputs:t.inputs,outcomes:t.outcomes,transcripts:{},progress_step_id:null,steps_executed:0,last_state_id:null,errors_block_fired:!1,iteration:null,parent_step_id:null,dispatchState:async(r,n,s)=>{let i=e.parent_step_id,o=e.iteration;e.parent_step_id=s?.parent_step_id??i,e.iteration=s?.iteration??o;try{return await xd(e,r,n,s?.display_name??r)}finally{e.parent_step_id=i,e.iteration=o}},runChildWorkflow:async(r,n,s)=>{Ey(n);let i=Ns(n)?n.entry_step_id:n.start_at,o=t.dal.insertRun({job_id:t.job.id,workflow_id:r.id,team_id:t.team_id,current_state:i,parent_run_id:e.run_id}),a=Nd({dal:t.dal,workflow:Ns(n)?Oo(n):n,job:t.job,project:t.project,run:o,membersByAlias:t.membersByAlias,outcomes:{},inputs:s,team_id:t.team_id});return Ns(n)?gy(n,a,o.current_state??n.entry_step_id):hy(a,o.current_state??n.start_at)}};return e}async function hy(t,e){let r=e;if(r.startsWith(Ss))return{run_id:t.run_id,terminal_state:null,steps_executed:0,paused:!0};for(let s=0;s<1e3;s+=1){if(r.startsWith("@terminal:"))return Gt(t,r.slice(10));t.dal.setRunCurrentState(t.run_id,r),t.last_state_id=r;let i=t.workflow.states[r];if(i===void 0){let l=Lo(t,Y(t.workflow));if(l.kind==="paused")return De(t);if(l.kind==="escalate")return nt(t,{id:r,name:r,type:"unknown"},l.token,l.reason),De(t);if(l.kind==="terminal")return Gt(t,l.terminal);r=l.state;continue}let o,a=wy(t,r);if(a!==null){let l=q(t,{run_id:t.run_id,state_name:r});if(t.steps_executed+=1,t.dal.finishStep(l.id,a,"escalation_resume"),G(t,r,r,a),a===zn)return Gt(t,fl);let c=i.outcomes?.[a];o=c!==void 0?J(t.workflow,c):nt(t,{id:r,name:r,type:i.type},a,`no declared edge for resumed outcome '${a}' from state '${r}'`)}else o=await xd(t,r,i);if(o.kind==="paused")return De(t);if(o.kind==="escalate")return nt(t,{id:r,name:r,type:i.type},o.token,o.reason),De(t);if(o.kind==="terminal"){let l=Lo(t,o.terminal);if(l.kind==="paused")return De(t);if(l.kind==="escalate")return nt(t,{id:r,name:r,type:i.type},l.token,l.reason),De(t);if(l.kind==="terminal")return Gt(t,l.terminal);r=l.state;continue}r=o.state}t.dal.raiseAttention({kind:"engine_step_limit_exceeded",severity:"error",project_id:t.project.id,run_id:t.run_id,payload:JSON.stringify({run_id:t.run_id})});let n=Lo(t,Y(t.workflow));return n.kind==="terminal"?Gt(t,n.terminal):Gt(t,Y(t.workflow))}async function gy(t,e,r){let n=new Map(t.steps.map(o=>[o.id,o])),s=new Map(t.steps.map(o=>[o.name,o])),i=r;for(let o=0;o<1e3;o+=1){e.dal.setRunCurrentState(e.run_id,i);let a=n.get(i);if(a===void 0)return nt(e,{id:i,name:i,type:"unknown"},"",`internal:unknown v3 step '${i}'`),De(e);let l=wy(e,a.id);if(l!==null){let m=q(e,{run_id:e.run_id,state_name:a.name});if(e.steps_executed+=1,e.dal.finishStep(m.id,l,"escalation_resume"),G(e,a.id,a.name,l),l===zn)return Gt(e,fl);let p=Object.keys(t.connections[a.id]??{}),h=t.connections[a.id]?.[l]?.[0]?.[0]?.step_id??t.connections[a.id]?.main?.[0]?.[0]?.step_id;if(h===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},l,`no declared edge for resumed outcome '${l}' from step '${a.id}'`,{declared_outcomes:p}),De(e);i=h;continue}let c=await oC(e,t,a);if(c.kind==="paused")return De(e);let d=Object.keys(t.connections[a.id]??{});if(c.kind==="escalate")return nt(e,{id:a.id,name:a.name,type:a.type},c.token,c.reason,{declared_outcomes:d}),De(e);let u=c.kind==="terminal"?c.terminal:c.state;if(a.type==="lmctl/terminal"){let m=e.workflow;e.workflow=Oo(t,a);try{let p=Lo(e,u);if(p.kind==="paused")return De(e);if(p.kind==="escalate")return nt(e,{id:a.id,name:a.name,type:a.type},p.token,p.reason),De(e);if(p.kind==="terminal")return Gt(e,p.terminal);let h=s.get(p.state);if(h===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},"",`internal:unknown v3 error handler step '${p.state}'`),De(e);i=h.id;continue}finally{e.workflow=m}}if(zr(u))return nt(e,{id:a.id,name:a.name,type:a.type},u,`generic escalation '${u}' from step '${a.id}'`,{declared_outcomes:d}),De(e);let f=t.connections[a.id]?.[u]?.[0]?.[0]?.step_id??t.connections[a.id]?.main?.[0]?.[0]?.step_id;if(f===void 0)return nt(e,{id:a.id,name:a.name,type:a.type},u,`no declared edge for outcome '${u}' from step '${a.id}'`,{declared_outcomes:d}),De(e);i=f}return e.dal.raiseAttention({kind:"engine_step_limit_exceeded",severity:"error",project_id:e.project.id,run_id:e.run_id,payload:JSON.stringify({run_id:e.run_id})}),Gt(e,"aborted")}async function oC(t,e,r){let n=yy(e,r),s=t.workflow;t.workflow=Oo(e,r);try{return await xd(t,r.id,n,r.name)}finally{t.workflow=s}}function yy(t,e){let r=e.parameters,n=e.members??{},s=Object.keys(t.connections[e.id]??{}),i=Object.fromEntries(s.map(a=>[a,`@terminal:${a}`])),o={state_name:e.name};switch(e.type){case"lmctl/review":{let a=s.filter(l=>!["approve","request_changes","fail_pre_check","max_loops_exceeded"].includes(l));return{...o,type:"Review",...r,coder:n.coder,reviewers:n.reviewers,outcomes:{approve:i.approve??"@terminal:approve",...i.request_changes!==void 0?{request_changes:i.request_changes}:{},...i.fail_pre_check!==void 0?{fail_pre_check:i.fail_pre_check}:{},...i.max_loops_exceeded!==void 0?{max_loops_exceeded:i.max_loops_exceeded}:{}},...a.length>0?{outcomes_from_stance:Object.fromEntries(a.map(l=>[l,`@terminal:${l}`]))}:{}}}case"lmctl/consolidate":return{...o,type:"Consolidate",...r,researchers:n.researchers,consolidator:n.consolidator,outcomes:{ok:i.ok??"@terminal:ok",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/interactive":return{...o,type:"Interactive",...r,agent:n.agent,outcomes:{done:i.done??"@terminal:done",...i.timeout!==void 0?{timeout:i.timeout}:{}}};case"lmctl/loop":return{...o,type:"Loop",...r,outcomes:{ok:i.ok??"@terminal:ok",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/render-docx":return{...o,type:"lmctl/render-docx",...r,outcomes:{done:i.done??"@terminal:done",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/render-xlsx":return{...o,type:"lmctl/render-xlsx",...r,outcomes:{done:i.done??"@terminal:done",...i.error!==void 0?{error:i.error}:{}}};case"lmctl/shell-step":return{...o,type:"ShellStep",...r,outcomes_from_exit:r.outcomes_from_exit??Object.fromEntries(s.map(a=>[a.slice(5),`@terminal:${a}`]))};case"lmctl/assert-repo-clean":return{...o,type:"AssertRepoClean",...r,next:i.main??"@terminal:main"};case"lmctl/choice":return{...o,type:"Choice",...r};case"lmctl/foreach":return{...o,type:"ForEach",...r,outcomes:{all_ok:i.all_ok??"@terminal:all_ok",...i.any_failed!==void 0?{any_failed:i.any_failed}:{}}};case"lmctl/subflow":return{...o,type:"Subflow",...r,outcomes:i};case"lmctl/terminal":return{...o,type:"Terminal",name:r.name,kind:r.kind};default:return{...o,type:e.type,...r}}}async function xd(t,e,r,n){let s=uy().get(r.type);if(s===void 0)throw new Error(`unknown archetype: ${r.type}`);if(s.execute===void 0)throw new Error(`archetype ${r.type} has no execute() - is it a trigger-only archetype used as a step?`);let i=t.emit_progress,o=t.progress_step_id;t.emit_progress=s.description.emits_progress===!0?dC(t,s):void 0,t.progress_step_id=null;try{return await s.execute(vg(t,e,r,n??e))}finally{t.emit_progress=i,t.progress_step_id=o}}function aC(t,e){try{let r=JSON.parse(t);if(cC(r)&&r.definition_schema_version===3)return xt.parse(r)}catch{return e}return e}function Ns(t){return t.definition_schema_version===3}function Oo(t,e){let r=e===void 0?[]:Object.keys(t.connections[e.id]??{}),n=Object.fromEntries(r.map(i=>[i,{kind:i==="aborted"?"failure":"neutral"}])),s={};if(e?.type==="lmctl/loop"&&typeof e.parameters.body=="string"){let i=t.steps.find(o=>o.name===e.parameters.body);i!==void 0&&(s[e.parameters.body]=yy(t,i))}return e?.type==="lmctl/terminal"&&typeof e.parameters.name=="string"&&(n[e.parameters.name]={kind:lC(e.parameters.kind)}),n.aborted??={kind:"failure"},{name:t.name,version:t.version,definition_schema_version:2,primitive_version:2,start_at:e?.name??t.entry_step_id,states:s,terminals:n,...t.default_task_timeout_ms!==void 0?{default_task_timeout_ms:t.default_task_timeout_ms}:{},...t.concurrency_key!==void 0?{concurrency_key:t.concurrency_key}:{},...t.concurrent_limit!==void 0?{concurrent_limit:t.concurrent_limit}:{},...t.errors!==void 0?{errors:t.errors}:{}}}function lC(t){return t==="success"||t==="failure"||t==="neutral"?t:"neutral"}function cC(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dC(t,e){let r=`progress.${e.description.namespace}/${e.description.name}`;return n=>{try{if(typeof n.kind!="string"||n.kind.length===0)return;t.dal.insertSessionEvent({run_id:t.run_id,step_id:t.progress_step_id,kind:`${r}.${n.kind}`,timestamp_ms:Date.now(),payload:JSON.stringify({message:n.message,data:n.data})})}catch(s){let i=s instanceof Error?s.message:String(s);console.warn(`[progress] dropped ${r} event: ${i}`)}}}function Gt(t,e){t.dal.setRunTerminalState(t.run_id,e);try{ng(t.run_id,t.dal)}catch{}return{run_id:t.run_id,terminal_state:e,steps_executed:t.steps_executed}}function De(t){return{run_id:t.run_id,terminal_state:null,steps_executed:t.steps_executed,paused:!0}}function wy(t,e){let n=t.dal.getRun(t.run_id)?.pending_escalation_decision??null;if(n===null)return null;let s;try{let a=JSON.parse(n);if(a===null||typeof a!="object"||Array.isArray(a))return null;s=a}catch{return null}let i=s[e];if(typeof i!="string")return null;delete s[e];let o=Object.keys(s).length>0?JSON.stringify(s):null;return t.dal.setRunPendingEscalationDecision(t.run_id,o),i}function Lo(t,e){if(!uC(t.workflow,e)||t.errors_block_fired)return{kind:"terminal",terminal:e};let r=t.workflow.errors;return r===void 0?{kind:"terminal",terminal:e}:(t.errors_block_fired=!0,r.on_unhandled_failure_state!==void 0?{kind:"state",state:r.on_unhandled_failure_state}:(r.on_unhandled_failure!==void 0&&fC(t,e,r.on_unhandled_failure),{kind:"terminal",terminal:e}))}function uC(t,e){return t.definition_schema_version===2&&t.terminals[e]?.kind==="failure"}function fC(t,e,r){let n=mC(t),s=r.capture_evidence&&n!==null?pC(t,n.id):[];t.dal.raiseAttention({kind:r.attention_kind,severity:r.severity,project_id:t.project.id,run_id:t.run_id,payload:JSON.stringify({run_id:t.run_id,terminal_state:e,current_state:t.last_state_id,last_step_id:n?.id??null,last_error:n?.status_detail??null,evidence_paths:s,recommend_recovery:r.recommend_recovery??null})})}function mC(t){return t.dal.query("SELECT id, state_name, outcome, status_detail FROM step WHERE run_id = ? ORDER BY id DESC LIMIT 1",t.run_id)[0]??null}function pC(t,e){return t.dal.query("SELECT path FROM step_artifact WHERE step_id = ? AND path IS NOT NULL ORDER BY id DESC",e).map(n=>n.path)}function Ey(t){if(!my.includes(t.definition_schema_version))throw new Error(`unsupported definition_schema_version ${t.definition_schema_version}; supported versions: ${my.join(", ")}`)}var my,Ty=E(()=>{"use strict";mn();sg();lg();He();fy();Zn();my=[1,2,3]});import{readFileSync as _C,readdirSync as hC}from"node:fs";import{basename as gC,join as yC,resolve as wC}from"node:path";function vy(t={}){let e=wC(t.workflowsDir??"workflows"),r=hC(e).filter(n=>n.endsWith(".compound.json")).sort((n,s)=>n.localeCompare(s));return{generated_at:new Date().toISOString(),workflows_dir:e,rows:r.map(n=>EC(yC(e,n)))}}function EC(t){let e=gC(t);try{let r=_C(t,"utf8"),n=dt(r);return Ny(e,n)}catch(r){return{file:e,workflow_name:null,status:"FAIL",first_step_id:null,first_step_type:null,first_step_disposition:null,note:xy(r)}}}function ky(t,e){try{let r=dt(e);return Ny(t,r)}catch(r){return{file:t,workflow_name:t,status:"FAIL",first_step_id:null,first_step_type:null,first_step_disposition:null,note:xy(r)}}}function Iy(t){let e=[];e.push(`workflow verification - ${t.generated_at}`),e.push(`dir: ${t.workflows_dir}`),e.push(""),e.push(`${"status".padEnd(17)} ${"workflow".padEnd(36)} ${"first step".padEnd(52)} note`),e.push(`${"-".repeat(17)} ${"-".repeat(36)} ${"-".repeat(52)} ${"-".repeat(30)}`);for(let i of t.rows){let o=(i.workflow_name??i.file).slice(0,36).padEnd(36),a=`${i.first_step_id??"-"}${i.first_step_type===null?"":` (${i.first_step_type})`}`;e.push(`${i.status.padEnd(17)} ${o} ${a.slice(0,52).padEnd(52)} ${i.note}`)}let r=t.rows.filter(i=>i.status==="PASS").length,n=t.rows.filter(i=>i.status==="PASS_NEEDS_INPUTS").length,s=t.rows.filter(i=>i.status==="FAIL").length;return e.push(""),e.push(`summary: ${r} pass, ${n} pass_needs_inputs, ${s} fail`),`${e.join(`
|
|
1977
2059
|
`)}
|
|
1978
|
-
`}function Ny(t,e){let r=bC(e),n=SC(e);if(r===null||n===null)return{file:t,workflow_name:e.name,status:"FAIL",first_step_id:r,first_step_type:n,first_step_disposition:null,note:"entry step missing after validation"};let s=TC(e.inputs);return s.length>0?{file:t,workflow_name:e.name,status:"PASS_NEEDS_INPUTS",first_step_id:r,first_step_type:n,first_step_disposition:`needs_inputs:${n}`,note:`load ok; graph ok; entry step is ${r}; requires inputs: ${s.join(", ")}`}:{file:t,workflow_name:e.name,status:"PASS",first_step_id:r,first_step_type:n,first_step_disposition:`ready:${n}`,note:"load ok; graph ok; first step entered without inputs"}}function TC(t){return(t??[]).filter(e=>e.required===!0&&e.default===void 0).map(e=>e.name)}function bC(t){return Ad(t)?t.entry_step_id:t.start_at}function SC(t){return Ad(t)?t.steps.find(e=>e.id===t.entry_step_id)?.type??null:t.states[t.start_at]?.type??null}function Ad(t){return t.definition_schema_version===3}function xy(t){return t instanceof
|
|
2060
|
+
`}function Ny(t,e){let r=bC(e),n=SC(e);if(r===null||n===null)return{file:t,workflow_name:e.name,status:"FAIL",first_step_id:r,first_step_type:n,first_step_disposition:null,note:"entry step missing after validation"};let s=TC(e.inputs);return s.length>0?{file:t,workflow_name:e.name,status:"PASS_NEEDS_INPUTS",first_step_id:r,first_step_type:n,first_step_disposition:`needs_inputs:${n}`,note:`load ok; graph ok; entry step is ${r}; requires inputs: ${s.join(", ")}`}:{file:t,workflow_name:e.name,status:"PASS",first_step_id:r,first_step_type:n,first_step_disposition:`ready:${n}`,note:"load ok; graph ok; first step entered without inputs"}}function TC(t){return(t??[]).filter(e=>e.required===!0&&e.default===void 0).map(e=>e.name)}function bC(t){return Ad(t)?t.entry_step_id:t.start_at}function SC(t){return Ad(t)?t.steps.find(e=>e.id===t.entry_step_id)?.type??null:t.states[t.start_at]?.type??null}function Ad(t){return t.definition_schema_version===3}function xy(t){return t instanceof Xt?t.issues.map(e=>`${e.path}: ${e.message}`).join("; "):t instanceof SyntaxError?`JSON parse failed: ${t.message}`:t instanceof Error?t.message:String(t)}function Ay(t){let e=new Set;if(Ad(t))for(let r of t.steps){let n=r.members??{};by(n,e)}else for(let r of Object.values(t.states))by(r,e);return[...e].sort()}function by(t,e){let r=["coder","agent","consolidator"],n=["reviewers","researchers"];for(let s of r){let i=t[s],o=Sy(i);o!==null&&e.add(o)}for(let s of n){let i=t[s];if(Array.isArray(i))for(let o of i){let a=Sy(o);a!==null&&e.add(a)}}}function Sy(t){if(t===null||typeof t!="object")return null;let e=t.alias;return typeof e=="string"&&e.length>0?e:null}var $o=E(()=>{"use strict";_s()});function vC({dal:t}){let e=t.listProjects();for(let r of e){let s=t.query("SELECT * FROM job WHERE project_id = ? AND source = ? ORDER BY id DESC LIMIT 1",r.id,Co)[0]??null;if(s!==null&&(s.status==="queued"||s.status==="running"))continue;let o=(s?.payload?JSON.parse(s.payload):null)?.max_run_id??null,{count:a,maxRunId:l}=kC(t,r,o);if(a<20)continue;let c=o??"initial",d=`${xs}:${r.id}:${c}`;t.enqueueJob({project_id:r.id,source:Co,source_ref:xs,payload:JSON.stringify({kind:xs,project_id:r.id,completed_sessions:a,max_run_id:l,since_run_id:o}),dedupe_key:d})}}function kC(t,e,r){let n=t.query(`SELECT COUNT(*) AS cnt, MAX(r.id) AS max_id
|
|
1979
2061
|
FROM run r
|
|
1980
2062
|
JOIN job j ON j.id = r.job_id
|
|
1981
2063
|
WHERE j.project_id = ?
|
|
1982
2064
|
AND r.terminal_state IS NOT NULL
|
|
1983
|
-
${r!==null?"AND r.id > ?":""}`,...r!==null?[e.id,r]:[e.id]);return{count:n[0]?.cnt??0,maxRunId:n[0]?.max_id??0}}function Ry(t){for(let e of IC)try{e(t)}catch{}}var Co,xs,IC,Rd=E(()=>{"use strict";Co="memory_policy",xs="memory_consolidation_request";IC=[vC]});var jy={};Ee(jy,{getOrInsertConsolidationWorkflow:()=>Oy,runJobById:()=>LC,runOnce:()=>Ur,startWorker:()=>OC});import{createHash as NC}from"node:crypto";import{readFileSync as xC}from"node:fs";import{pathToFileURL as AC}from"node:url";function Oy(t,e="durable-memory-consolidation-v2"){let r=t.getWorkflowByName(e);if(r!==null)return r;try{rg({swallow:!0});let n=So(e);if(n===null)return null;let s=xC(n,"utf8"),i=dt(s);return t.insertWorkflow({name:e,version:i.version,definition_schema_version:i.definition_schema_version,definition:s,source_uri:AC(n).href,source_sha256:NC("sha256").update(s).digest("hex")})}catch{return null}}async function Ur(t){let e=Date.now(),r=null;try{return r=t.dal.claimNextJobWithConcurrency({worker_id:t.worker_id,lease_ms:t.lease_ms??Ly,evaluator:n=>Cy(t.dal,n)}),r===null?null:await $y(t.dal,r,e)}catch(n){if(r!==null)return hr(t.dal,r,"worker_run_failed",Fr(n),e);try{t.dal.raiseAttention({kind:"worker_run_failed",severity:"error",payload:JSON.stringify({error:Mo(Fr(n))})})}catch{}return null}finally{t.max_concurrent}}async function LC(t){let e=Date.now(),r=null;try{let n=t.dal.claimJobByIdWithConcurrency({job_id:t.job_id,worker_id:t.worker_id,lease_ms:t.lease_ms??Ly,evaluator:s=>Cy(t.dal,s)});return n.claimed?(r=n.job,{claimed:!0,...await $y(t.dal,r,e)}):n}catch(n){if(r!==null)return{claimed:!0,...hr(t.dal,r,"worker_run_failed",Fr(n),e)};try{t.dal.raiseAttention({kind:"worker_run_failed",severity:"error",payload:JSON.stringify({error:Mo(Fr(n)),job_id:t.job_id})})}catch{}return{claimed:!1,reason:"not_claimable",job_id:t.job_id}}finally{t.max_concurrent}}async function $y(t,e,r){let n=t.getProjectByJob(e.id);if(n===null)return hr(t,e,"worker_project_missing","project_not_found",r);let s=e.source===Co&&e.source_ref===xs,i=e.run_id===null?null:t.getRun(e.run_id),o;if(i!==null?o=t.getWorkflow(i.workflow_id):s?o=Oy(t):o=My(t,e,n),o===null)return hr(t,e,"worker_workflow_missing","workflow_not_found",r,n);let a=t.getTeam(i?.team_id??n.team_id),l=a===null?[]:t.listTeamMembers(a.id);if(a===null||l.length===0)return hr(t,e,"worker_team_missing","team_not_found",r,n);let c;try{c=dt(o.definition)}catch(u){return hr(t,e,"worker_workflow_invalid",Fr(u),r,n)}let d=$C(c,l);if(d.length>0)return hr(t,e,"worker_team_missing_aliases",`missing_aliases:${d.join(",")}`,r,n,a);try{let u=await _y({dal:t,job:e,workflow:c,team:a,members:l,workflowRow:o});return t.setJobRun(e.id,u.run_id),u.paused===!0?{job_id:e.id,run_id:u.run_id,status:"paused",terminal_state:null,ms:Date.now()-r}:(t.releaseJob(e.id,"done",null),{job_id:e.id,run_id:u.run_id,status:"done",terminal_state:u.terminal_state,ms:Date.now()-r})}catch(u){return hr(t,e,"worker_run_failed",Fr(u),r,n,a)}}function Cy(t,e){let r=t.getProjectByJob(e.id);if(r===null)return{concurrency_key:e.concurrency_key_resolved,concurrent_limit:1};let n=My(t,e,r);if(n===null)return{concurrency_key:e.concurrency_key_resolved,concurrent_limit:1};let s=null;try{s=dt(n.definition)}catch{s=null}return uo({workflow:s,job:e,project:r})}function My(t,e,r){return e.workflow_id_override!==null?t.getWorkflow(e.workflow_id_override):t.getWorkflowByName(r.workflow_name)}async function OC(t){let e=!1,r=null,n=Promise.resolve(),s=async()=>{if(!e){try{let i;do i=await Ur(t);while(!e&&i!==null)}catch(i){try{t.dal.raiseAttention({kind:"worker_loop_error",severity:"error",payload:JSON.stringify({error:Mo(Fr(i))})})}catch{}}e||(r=setTimeout(()=>{n=s()},t.poll_interval_ms??RC))}};return n=s(),{stop:async()=>{e=!0,r!==null&&clearTimeout(r),await n.catch(()=>{})}}}function hr(t,e,r,n,s,i,o){let a=Mo(n);return t.releaseJob(e.id,"failed",a),t.raiseAttention({kind:r,severity:"error",project_id:i?.id??e.project_id,payload:JSON.stringify({job_id:e.id,team_id:o?.id??null,error:a})}),{job_id:e.id,run_id:null,status:"failed",terminal_state:null,ms:Date.now()-s}}function Fr(t){return t instanceof Error?t.message:String(t)}function Mo(t){return t.length>4096?t.slice(0,4096):t}function $C(t,e){let r=Ay(t);if(r.length===0)return[];let n=new Set(e.map(s=>s.alias));return r.filter(s=>!n.has(s))}var Ly,RC,jo=E(()=>{"use strict";pd();Ty();_s();$o();Vc();Rd();Ly=6e5,RC=5e3});import{existsSync as CC,readFileSync as MC}from"node:fs";import{marked as jC}from"marked";function Uy(t,e){t.get("/layman",r=>r.html(Re("Layman Home",DC(e.dal)))),t.get("/api/layman",r=>r.json(Hy(e.dal))),t.get("/layman/start/:workflow",r=>{let n=Fy(r);return n===null?r.notFound():r.html(Re(`Start ${En(n)}`,UC(e.dal,n)))}),t.post("/layman/start/:workflow",async r=>{let n=Fy(r);return n===null?r.notFound():n==="newspaper"?Dy(r,e.dal):WC(r,e.dal,n)}),t.get("/layman/run/:id",r=>{let n=Cr(e.dal,Do(r,"id"));return n===null?r.notFound():r.html(Re(`Run ${n.id}`,HC(e.dal,n)))}),t.get("/api/layman/run/:id",r=>{let n=Cr(e.dal,Do(r,"id"));return n===null?r.notFound():r.json(tM(e.dal,n))}),t.post("/layman/run/:id/respond",async r=>
|
|
2065
|
+
${r!==null?"AND r.id > ?":""}`,...r!==null?[e.id,r]:[e.id]);return{count:n[0]?.cnt??0,maxRunId:n[0]?.max_id??0}}function Ry(t){for(let e of IC)try{e(t)}catch{}}var Co,xs,IC,Rd=E(()=>{"use strict";Co="memory_policy",xs="memory_consolidation_request";IC=[vC]});var jy={};Ee(jy,{getOrInsertConsolidationWorkflow:()=>Oy,runJobById:()=>LC,runOnce:()=>Ur,startWorker:()=>OC});import{createHash as NC}from"node:crypto";import{readFileSync as xC}from"node:fs";import{pathToFileURL as AC}from"node:url";function Oy(t,e="durable-memory-consolidation-v2"){let r=t.getWorkflowByName(e);if(r!==null)return r;try{rg({swallow:!0});let n=So(e);if(n===null)return null;let s=xC(n,"utf8"),i=dt(s);return t.insertWorkflow({name:e,version:i.version,definition_schema_version:i.definition_schema_version,definition:s,source_uri:AC(n).href,source_sha256:NC("sha256").update(s).digest("hex")})}catch{return null}}async function Ur(t){let e=Date.now(),r=null;try{return r=t.dal.claimNextJobWithConcurrency({worker_id:t.worker_id,lease_ms:t.lease_ms??Ly,evaluator:n=>Cy(t.dal,n)}),r===null?null:await $y(t.dal,r,e)}catch(n){if(r!==null)return hr(t.dal,r,"worker_run_failed",Fr(n),e);try{t.dal.raiseAttention({kind:"worker_run_failed",severity:"error",payload:JSON.stringify({error:Mo(Fr(n))})})}catch{}return null}finally{t.max_concurrent}}async function LC(t){let e=Date.now(),r=null;try{let n=t.dal.claimJobByIdWithConcurrency({job_id:t.job_id,worker_id:t.worker_id,lease_ms:t.lease_ms??Ly,evaluator:s=>Cy(t.dal,s)});return n.claimed?(r=n.job,{claimed:!0,...await $y(t.dal,r,e)}):n}catch(n){if(r!==null)return{claimed:!0,...hr(t.dal,r,"worker_run_failed",Fr(n),e)};try{t.dal.raiseAttention({kind:"worker_run_failed",severity:"error",payload:JSON.stringify({error:Mo(Fr(n)),job_id:t.job_id})})}catch{}return{claimed:!1,reason:"not_claimable",job_id:t.job_id}}finally{t.max_concurrent}}async function $y(t,e,r){let n=t.getProjectByJob(e.id);if(n===null)return hr(t,e,"worker_project_missing","project_not_found",r);let s=e.source===Co&&e.source_ref===xs,i=e.run_id===null?null:t.getRun(e.run_id),o;if(i!==null?o=t.getWorkflow(i.workflow_id):s?o=Oy(t):o=My(t,e,n),o===null)return hr(t,e,"worker_workflow_missing","workflow_not_found",r,n);let a=t.getTeam(i?.team_id??n.team_id),l=a===null?[]:t.listTeamMembers(a.id);if(a===null||l.length===0)return hr(t,e,"worker_team_missing","team_not_found",r,n);let c;try{c=dt(o.definition)}catch(u){return hr(t,e,"worker_workflow_invalid",Fr(u),r,n)}let d=$C(c,l);if(d.length>0)return hr(t,e,"worker_team_missing_aliases",`missing_aliases:${d.join(",")}`,r,n,a);try{let u=await _y({dal:t,job:e,workflow:c,team:a,members:l,workflowRow:o});return t.setJobRun(e.id,u.run_id),u.paused===!0?{job_id:e.id,run_id:u.run_id,status:"paused",terminal_state:null,ms:Date.now()-r}:(t.releaseJob(e.id,"done",null),{job_id:e.id,run_id:u.run_id,status:"done",terminal_state:u.terminal_state,ms:Date.now()-r})}catch(u){return hr(t,e,"worker_run_failed",Fr(u),r,n,a)}}function Cy(t,e){let r=t.getProjectByJob(e.id);if(r===null)return{concurrency_key:e.concurrency_key_resolved,concurrent_limit:1};let n=My(t,e,r);if(n===null)return{concurrency_key:e.concurrency_key_resolved,concurrent_limit:1};let s=null;try{s=dt(n.definition)}catch{s=null}return uo({workflow:s,job:e,project:r})}function My(t,e,r){return e.workflow_id_override!==null?t.getWorkflow(e.workflow_id_override):t.getWorkflowByName(r.workflow_name)}async function OC(t){let e=!1,r=null,n=Promise.resolve(),s=async()=>{if(!e){try{let i;do i=await Ur(t);while(!e&&i!==null)}catch(i){try{t.dal.raiseAttention({kind:"worker_loop_error",severity:"error",payload:JSON.stringify({error:Mo(Fr(i))})})}catch{}}e||(r=setTimeout(()=>{n=s()},t.poll_interval_ms??RC))}};return n=s(),{stop:async()=>{e=!0,r!==null&&clearTimeout(r),await n.catch(()=>{})}}}function hr(t,e,r,n,s,i,o){let a=Mo(n);return t.releaseJob(e.id,"failed",a),t.raiseAttention({kind:r,severity:"error",project_id:i?.id??e.project_id,payload:JSON.stringify({job_id:e.id,team_id:o?.id??null,error:a})}),{job_id:e.id,run_id:null,status:"failed",terminal_state:null,ms:Date.now()-s}}function Fr(t){return t instanceof Error?t.message:String(t)}function Mo(t){return t.length>4096?t.slice(0,4096):t}function $C(t,e){let r=Ay(t);if(r.length===0)return[];let n=new Set(e.map(s=>s.alias));return r.filter(s=>!n.has(s))}var Ly,RC,jo=E(()=>{"use strict";pd();Ty();_s();$o();Vc();Rd();Ly=6e5,RC=5e3});import{existsSync as CC,readFileSync as MC}from"node:fs";import{marked as jC}from"marked";function Uy(t,e){t.get("/layman",r=>r.html(Re("Layman Home",DC(e.dal)))),t.get("/api/layman",r=>r.json(Hy(e.dal))),t.get("/layman/start/:workflow",r=>{let n=Fy(r);return n===null?r.notFound():r.html(Re(`Start ${En(n)}`,UC(e.dal,n)))}),t.post("/layman/start/:workflow",async r=>{let n=Fy(r);return n===null?r.notFound():n==="newspaper"?Dy(r,e.dal):WC(r,e.dal,n)}),t.get("/layman/run/:id",r=>{let n=Cr(e.dal,Do(r,"id"));return n===null?r.notFound():r.html(Re(`Run ${n.id}`,HC(e.dal,n)))}),t.get("/api/layman/run/:id",r=>{let n=Cr(e.dal,Do(r,"id"));return n===null?r.notFound():r.json(tM(e.dal,n))}),t.post("/layman/run/:id/respond",async r=>JC(r,e.dal)),t.get("/layman/newspaper",r=>r.html(Re("Newspaper Subscriptions",QC(e.dal)))),t.post("/layman/newspaper",r=>Dy(r,e.dal)),t.delete("/layman/newspaper/:id",r=>Py(r,e.dal)),t.post("/layman/newspaper/:id/delete",r=>Py(r,e.dal))}function DC(t){let e=Hy(t);return`<section class="layman-home">
|
|
1984
2066
|
<h1>Welcome</h1>
|
|
1985
2067
|
<p class="muted">Choose a workflow and answer a few plain-language prompts.</p>
|
|
1986
2068
|
<div class="grid">${Po.map(PC).join("")}</div>
|
|
@@ -2009,11 +2091,11 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2009
2091
|
<label>Output directory<input name="output_dir" value="drafts"></label>
|
|
2010
2092
|
<button type="submit">Start Document Wizard</button>
|
|
2011
2093
|
</form>`:qy(n,"/layman/start/newspaper")}function Wy(t){return`<label>Project<select name="project_id" required>${t.map(e=>`<option value="${S(e.id)}">${S(e.name)}</option>`).join("")}</select></label>`}async function WC(t,e,r){let n=await t.req.parseBody(),s=Gy(e,n);if(s===null)return t.html(Re("Start workflow",'<p class="error">Choose a valid project.</p>'),400);let i=e.getWorkflowByName(r);if(i===null)return t.html(Re("Start workflow",`<p class="error">${S(En(r))} is not loaded.</p>`),400);let o=r==="info-qa"?BC(n):qC(n);if(typeof o=="string")return t.html(Re("Start workflow",`<p class="error">${S(o)}</p>`),400);let a=e.enqueueJob({project_id:s.id,workflow_id_override:i.id,source:"layman",source_ref:r,dedupe_key:`layman:${r}:${Date.now()}:${Math.random()}`,payload:JSON.stringify(o)}),l=await Ur({dal:e,worker_id:`layman-start-${Date.now()}`}),c=e.getJob(a.id),d=l?.job_id===a.id?l.run_id:c?.run_id??null;return d===null?t.redirect("/layman?queued=1",302):t.redirect(`/layman/run/${d}`,302)}function BC(t){let e=Ke(t.question).trim();if(e.length===0)return"Enter a question.";let r=Ke(t.output_path).trim();return{question:e,...r.length>0?{output_path:r}:{}}}function qC(t){let e=Ke(t.task_description).trim(),r=lM(Ke(t.slug).trim()),n=Ke(t.output_dir).trim()||"drafts";return e.length===0?"Describe the document you want.":r.length===0?"Enter a document slug.":{task_description:e,slug:r,output_dir:n}}function HC(t,e){let r=e.workflow?.name??"unknown",n=`<h1>${S(En(r))}</h1>
|
|
2012
|
-
<p><a href="/layman">Layman home</a></p>`;if(e.terminal_state!==null)return`${n}${KC(t,e,r)}`;let s=
|
|
2094
|
+
<p><a href="/layman">Layman home</a></p>`;if(e.terminal_state!==null)return`${n}${KC(t,e,r)}`;let s=Jy(t,e);return s!==null&&s.status==="waiting_operator"?`${n}${XC(e,s)}`:`${n}<section hx-get="/layman/run/${S(e.id)}" hx-trigger="every 2s" hx-swap="outerHTML">
|
|
2013
2095
|
<h2>Running</h2>
|
|
2014
2096
|
<p class="muted">Current stage: <strong>${S(e.current_state??"starting")}</strong></p>
|
|
2015
2097
|
${By(e)}
|
|
2016
|
-
</section>`}function By(t){let e=t.steps.map(r=>[S(r.id),S(`\u25B6 ${r.state_name}`),S(r.outcome??"running"),S(r.status_detail??"")]);return me(["step","stage","outcome","detail"],e)}function
|
|
2098
|
+
</section>`}function By(t){let e=t.steps.map(r=>[S(r.id),S(`\u25B6 ${r.state_name}`),S(r.outcome??"running"),S(r.status_detail??"")]);return me(["step","stage","outcome","detail"],e)}function XC(t,e){return`<section class="metric paused-interactive">
|
|
2017
2099
|
<h2>${S(sM(e.state_name))}</h2>
|
|
2018
2100
|
<p class="muted">The agent is waiting for your response.</p>
|
|
2019
2101
|
<h3>Agent output</h3>
|
|
@@ -2024,7 +2106,7 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2024
2106
|
<button type="submit" name="done" value="false">Send response</button>
|
|
2025
2107
|
<button type="submit" name="done" value="true">Done with this stage</button>
|
|
2026
2108
|
</form>
|
|
2027
|
-
</section>`}async function
|
|
2109
|
+
</section>`}async function JC(t,e){let r=Do(t,"id"),n=await t.req.parseBody(),s=Number(Ke(n.step_id)),i=Ke(n.input),o=Ke(n.done)==="true";if(!Number.isInteger(s))return t.html(Re("Interactive response",'<p class="error">Missing interactive step.</p>'),400);let a=e.resumeInteractive(s,i,o);return a.resumed?(GC(e,a.run.id),await Ur({dal:e,worker_id:`layman-respond-${Date.now()}`}),t.redirect(`/layman/run/${r}`,302)):t.html(Re("Interactive response",`<p class="error">Could not submit response: ${S(a.reason)}</p>`),400)}function GC(t,e){let r=t.getRun(e);if(r===null||r.current_state===null)return;let n=t.getWorkflow(r.workflow_id);if(n!==null)try{let s=JSON.parse(n.definition);if(!Od(s)||s.definition_schema_version!==3||!Array.isArray(s.steps))return;let i=s.steps.find(o=>Od(o)&&o.name===r.current_state&&typeof o.id=="string");Od(i)&&typeof i.id=="string"&&t.setRunCurrentState(r.id,i.id)}catch{return}}function KC(t,e,r){let n=iM(e.terminal_state);return`<section class="metric terminal-run">
|
|
2028
2110
|
<h2>${n?"Complete":"Stopped"}</h2>
|
|
2029
2111
|
<p>Status: <strong>${S(e.terminal_state)}</strong></p>
|
|
2030
2112
|
${n?VC(t,e,r):zC(e)}
|
|
@@ -2034,7 +2116,7 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2034
2116
|
<pre>${S(aM(oM(i??"No preview available."),30))}</pre>
|
|
2035
2117
|
<h3>Downloads</h3>
|
|
2036
2118
|
${o.length>0?`<ul>${o}</ul>`:'<p class="muted">No rendered files found yet.</p>'}`}function zC(t){let e=[...t.steps].reverse().find(r=>r.status_detail!==null);return`<p class="error">${S(e?.status_detail??"The workflow did not complete successfully.")}</p>`}function Cd(t,e){for(let r of[...t.steps].reverse())for(let n of e){let s=[...r.artifacts].reverse().find(i=>i.kind===n&&i.content!==null);if(s?.content!==null&&s?.content!==void 0)return s.content}return null}function Ld(t,e){for(let r of[...t].reverse())if(e.includes(r.kind)&&r.path!==null)return r.path;return null}function ZC(t){if(t===null||!CC(t)||!t.endsWith(".md"))return null;try{return MC(t,"utf8")}catch{return null}}function QC(t){let e=t.listProjects();return`<h1>Newspaper Subscriptions</h1>
|
|
2037
|
-
${eM(
|
|
2119
|
+
${eM(Xy(t))}
|
|
2038
2120
|
<h2>Add Subscription</h2>
|
|
2039
2121
|
${e.length===0?'<p class="error">Create a project before subscribing.</p>':qy(e,"/layman/newspaper")}`}function qy(t,e){return`<form method="post" action="${S(e)}">
|
|
2040
2122
|
${Wy(t)}
|
|
@@ -2047,31 +2129,31 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2047
2129
|
<label>Custom cron<input name="cron" placeholder="0 6 * * *"></label>
|
|
2048
2130
|
<label>Output directory<input name="output_dir" value="digests"></label>
|
|
2049
2131
|
<button type="submit">Create subscription</button>
|
|
2050
|
-
</form>`}async function Dy(t,e){let r=await t.req.parseBody(),n=Gy(e,r);if(n===null)return t.html(Re("Newspaper",'<p class="error">Choose a valid project.</p>'),400);let s=e.getWorkflowByName("newspaper");if(s===null)return t.html(Re("Newspaper",'<p class="error">The newspaper workflow is not loaded.</p>'),400);let i=Ke(r.topics).split(/[\n,]/).map(a=>a.trim()).filter(a=>a.length>0);if(i.length===0)return t.html(Re("Newspaper",'<p class="error">Enter at least one topic.</p>'),400);let o={topics:i,output_dir:Ke(r.output_dir).trim()||"digests",schedule:nM(r)};return e.insertProjectWorkflow({project_id:n.id,workflow_id:s.id,condition:null,parameters_override:JSON.stringify(o),priority:100,enabled:!0}),t.redirect("/layman/newspaper?created=1",302)}function Py(t,e){let r=Do(t,"id");return e.removeProjectWorkflow(r)?t.redirect("/layman/newspaper?removed=1",302):t.notFound()}function eM(t){return me(["id","project","topics","status","action"],t.map(e=>{let r=cM(e.parameters_override),n=Array.isArray(r.topics)?r.topics.join(", "):"";return[S(e.id),S(e.project_name),S(n),e.enabled===1?"enabled":"disabled",`<form method="post" action="/layman/newspaper/${e.id}/delete"><button type="submit">Remove</button></form>`]}))}function Hy(t){let e=
|
|
2132
|
+
</form>`}async function Dy(t,e){let r=await t.req.parseBody(),n=Gy(e,r);if(n===null)return t.html(Re("Newspaper",'<p class="error">Choose a valid project.</p>'),400);let s=e.getWorkflowByName("newspaper");if(s===null)return t.html(Re("Newspaper",'<p class="error">The newspaper workflow is not loaded.</p>'),400);let i=Ke(r.topics).split(/[\n,]/).map(a=>a.trim()).filter(a=>a.length>0);if(i.length===0)return t.html(Re("Newspaper",'<p class="error">Enter at least one topic.</p>'),400);let o={topics:i,output_dir:Ke(r.output_dir).trim()||"digests",schedule:nM(r)};return e.insertProjectWorkflow({project_id:n.id,workflow_id:s.id,condition:null,parameters_override:JSON.stringify(o),priority:100,enabled:!0}),t.redirect("/layman/newspaper?created=1",302)}function Py(t,e){let r=Do(t,"id");return e.removeProjectWorkflow(r)?t.redirect("/layman/newspaper?removed=1",302):t.notFound()}function eM(t){return me(["id","project","topics","status","action"],t.map(e=>{let r=cM(e.parameters_override),n=Array.isArray(r.topics)?r.topics.join(", "):"";return[S(e.id),S(e.project_name),S(n),e.enabled===1?"enabled":"disabled",`<form method="post" action="/layman/newspaper/${e.id}/delete"><button type="submit">Remove</button></form>`]}))}function Hy(t){let e=Xy(t);return{workflows:Po,recent_runs:rM(t),newspaper_subscriptions:e.length}}function tM(t,e){let r=Jy(t,e);return{id:e.id,workflow:e.workflow?.name??null,current_state:e.current_state,terminal_state:e.terminal_state,paused_interactive:r?.status==="waiting_operator"?{step_id:r.step_id,state_name:r.state_name,last_agent_output:r.last_agent_output}:null,steps:e.steps.map(n=>({id:n.id,state_name:n.state_name,outcome:n.outcome,status_detail:n.status_detail}))}}function rM(t){return t.query(`SELECT r.*, w.name AS workflow_name
|
|
2051
2133
|
FROM run r
|
|
2052
2134
|
JOIN workflow w ON w.id = r.workflow_id
|
|
2053
2135
|
WHERE w.name IN (${$d.map(()=>"?").join(",")})
|
|
2054
2136
|
ORDER BY r.id DESC
|
|
2055
|
-
LIMIT 10`,...$d)}function
|
|
2137
|
+
LIMIT 10`,...$d)}function Xy(t){return t.query(`SELECT pw.*, p.name AS project_name
|
|
2056
2138
|
FROM project_workflow pw
|
|
2057
2139
|
JOIN workflow w ON w.id = pw.workflow_id
|
|
2058
2140
|
JOIN project p ON p.id = pw.project_id
|
|
2059
2141
|
WHERE w.name = ?
|
|
2060
|
-
ORDER BY pw.id DESC`,"newspaper")}function
|
|
2142
|
+
ORDER BY pw.id DESC`,"newspaper")}function Jy(t,e){for(let r of[...e.steps].reverse()){let n=t.getInteractiveSessionByStepId(r.id);if(n!==null)return n}return null}function Gy(t,e){let r=Number(Ke(e.project_id));return Number.isInteger(r)?t.getProject(r):null}function nM(t){let e=Ke(t.schedule)||"daily";return e==="weekly"?{preset:e,cron:"0 6 * * 1"}:e==="custom"?{preset:e,cron:Ke(t.cron).trim()||"0 6 * * *"}:{preset:"daily",cron:"0 6 * * *"}}function Fy(t){let e=t.req.param("workflow");return $d.includes(e)?e:null}function En(t){return Po.find(e=>e.name===t)?.title??t}function sM(t){return t.split(/[_:-]/).filter(Boolean).map(e=>`${e[0]?.toUpperCase()??""}${e.slice(1)}`).join(" ")}function Md(t){return jC.parse(t,{async:!1})}function iM(t){return t==="done"||t==="pr_ready"||t==="merged"}function oM(t){return t.replace(/\n*STANCE:\s+\S+\s*$/,"").trimEnd()}function aM(t,e){return t.split(`
|
|
2061
2143
|
`).slice(0,e).join(`
|
|
2062
|
-
`)}function lM(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ke(t){return typeof t=="string"?t:""}function cM(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 Od(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Do(t,e){return Number(t.req.param(e))}var Po,$d,Ky=E(()=>{"use strict";jo();qt();cd();Po=[{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."}],$d=Po.map(t=>t.name)});function uM(t){return t.replace(/^\/+/,"")}function Vy(t){return typeof t=="string"&&t!==""&&!t.includes("/")&&!t.includes("\\")}function Tn(t){if(t.mailboxKey!==void 0&&t.mailboxKey!==null&&t.mailboxKey!==""){let e=uM(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 Vy(t.userId)&&Vy(t.deviceId)?`${t.userId}/${t.deviceId}/`:`${dM}/${t.identityId}/`}function mM(t){return String(Math.max(0,Math.floor(t))).padStart(fM,"0")}function jd(t,e,r){return`${t}${e}${mM(r)}.json`}function Fo(t,e){return`${t}${e}`}function Uo(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 i=Number(s[1]);return Number.isSafeInteger(i)?i:void 0}var dM,fM,Wo=E(()=>{"use strict";dM="mailbox";fM=12});function Kt(t,e){let r=Math.floor(t),n="",s=r;for(let d=0;d<12;d++)n=Bo[s&15]+n,s=Math.floor(s/16);let i=Math.floor(e()*4096)&4095,o="",a=i;for(let d=0;d<3;d++)o=Bo[a&15]+o,a=a>>4;let l=Bo[8|Math.floor(e()*4)&3],c="";for(let d=0;d<15;d++)c+=Bo[Math.floor(e()*16)&15];return n.slice(0,8)+"-"+n.slice(8,12)+"-7"+o+"-"+l+c.slice(0,3)+"-"+c.slice(3,15)}var Bo,qo=E(()=>{"use strict";Bo="0123456789abcdef"});function Pd(t,e){return!Number.isFinite(t)||t<=0?e:t}function Fd(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 ew(t){return t.conversation_id===Qy&&hM(t.payload)}function hM(t){return typeof t=="object"&&t!==null&&t.kind==="heartbeat"}function gM(t){let e=typeof t.hb=="string"&&t.hb!==""?t.hb:ew(t)?t.timestamp:void 0;if(e===void 0)return;let r=Date.parse(e);return Number.isFinite(r)?r:void 0}var Yy,zy,Zy,pM,Qy,_M,Dd,Wr,Ho=E(()=>{"use strict";Wo();qo();Yy=3e3,zy=1e4,Zy=12e3,pM=1e3,Qy="__lmctl_heartbeat__",_M={kind:"heartbeat"},Dd={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Wr=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=Tn({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=Pd(e.readIntervalMs??e.pollIntervalMs??Yy,Yy),this.heartbeatIdleMs=Pd(e.heartbeatIdleMs??zy,zy),this.backoffReadIntervalMs=Pd(e.backoffReadIntervalMs??e.pollIntervalMs??Zy,Zy)}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??Dd;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=Fo(this.basePrefix,e),n=0,s;do{let i=await this.opts.s3.send(new this.opts.commands.ListObjectsV2Command({Bucket:this.opts.bucket,Prefix:r,MaxKeys:pM,...s!==void 0&&{ContinuationToken:s}}));this.opts.onS3Op?.("list");for(let o of i.Contents??[]){let a=Uo(o.Key??"",this.basePrefix,e);a!==void 0&&a>n&&(n=a)}s=i.IsTruncated===!0?i.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(),i={message_id:Kt(n,this.opts.random??Math.random),from:this.opts.selfRole,timestamp:s,hb:s,conversation_id:e,payload:r},o=(this.ownSeq??0)+1,a=jd(this.basePrefix,this.ownStream,o);return await this.opts.s3.send(new this.opts.commands.PutObjectCommand({Bucket:this.opts.bucket,Key:a,Body:JSON.stringify(i),ContentType:"application/json"})),this.opts.onS3Op?.("put"),this.ownSeq=o,this.recordWrite(n),a}scheduleNextTick(e){if(this.stopRequested)return;let r=this.opts.timers??Dd;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=jd(this.basePrefix,this.peerStream,e),n;try{let i=await this.opts.s3.send(new this.opts.commands.GetObjectCommand({Bucket:this.opts.bucket,Key:r}));if(this.opts.onS3Op?.("get"),i.Body===void 0){this.emitError(new Error(`GetObject ${r}: empty body`),"get"),this.advanceCursor(e);continue}n=await i.Body.transformToString("utf-8")}catch(i){if(Fd(i)){this.opts.onS3Op?.("get");return}this.emitError(i,"get");return}let s;try{s=JSON.parse(n)}catch(i){this.emitError(i,"get"),this.advanceCursor(e);continue}if(this.recordPeerHeartbeat(s),ew(s)){this.advanceCursor(e);continue}try{await this.opts.onMessage(s)}catch(i){this.emitError(i,"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=gM(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??Dd;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(Qy,_M)}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 yM}from"@hono/node-server/conninfo";function tw(t,e){let r=e.bucket??wM,n=e.remoteAddressOf??(i=>TM(i)),s=i=>{let o=n(i);return bM(o)?null:i.json({error:"forbidden",message:"local-mailbox is loopback-only"},403)};t.get("/local-mailbox/object",async i=>{let o=s(i);if(o!==null)return o;let a=Ud(i.req.query("key"));if(typeof a!="string")return i.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 i.json({error:"empty_body"},404);let c=await l.Body.transformToString("utf-8");return i.body(c,200,{"Content-Type":"application/octet-stream"})}catch(l){return Fd(l)?i.json({error:"not_found"},404):i.json({error:"internal",message:Wd(l)},500)}}),t.put("/local-mailbox/object",async i=>{let o=s(i);if(o!==null)return o;let a=Ud(i.req.query("key"));if(typeof a!="string")return i.json({error:"bad_request",message:a.error},400);let l=new Uint8Array(await i.req.arrayBuffer());try{return await e.s3.send(new e.commands.PutObjectCommand({Bucket:r,Key:a,Body:l})),i.json({ok:!0})}catch(c){return i.json({error:"internal",message:Wd(c)},500)}}),t.get("/local-mailbox/list",async i=>{let o=s(i);if(o!==null)return o;let a=i.req.query("prefix")??"",l=Ud(a,{allowEmpty:!0});if(typeof l!="string")return i.json({error:"bad_request",message:l.error},400);let c=EM(i.req.query("maxKeys")),d=i.req.query("token");try{let u=await e.s3.send(new e.commands.ListObjectsV2Command({Bucket:r,Prefix:l,...c!==void 0?{MaxKeys:c}:{},...d!==void 0&&d!==""?{ContinuationToken:d}:{}}));return i.json({Contents:(u.Contents??[]).map(f=>({Key:f.Key,LastModified:f.LastModified instanceof Date?f.LastModified.toISOString():f.LastModified})),IsTruncated:u.IsTruncated??!1,...u.NextContinuationToken!==void 0?{NextContinuationToken:u.NextContinuationToken}:{}})}catch(u){return i.json({error:"internal",message:Wd(u)},500)}})}function Ud(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 EM(t){if(t===void 0||t==="")return;let e=Number(t);return Number.isInteger(e)&&e>0?e:void 0}function TM(t){try{return yM(t).remote.address}catch{return}}function bM(t){return t===void 0||t===""?!1:!!(t==="127.0.0.1"||t==="::1"||t.startsWith("::ffff:127.")||t.startsWith("127."))}function Wd(t){return t instanceof Error?t.message:String(t)}var wM,rw=E(()=>{"use strict";Ho();wM="local"});function nw(t,e){t.get("/mailbox/workspace",r=>kM(r,e)),t.get("/mailbox/projects",r=>IM(r,e)),t.get("/mailbox/projects/:id",r=>NM(r,e)),t.post("/mailbox/projects",r=>xM(r,e)),t.patch("/mailbox/projects/:id",r=>AM(r,e)),t.delete("/mailbox/projects/:id",r=>RM(r,e)),t.post("/mailbox/projects/:project_id/prompts",r=>LM(r,e)),t.get("/mailbox/prompts/:id",r=>OM(r,e))}function kM(t,e){e.dal.ensureWorkspace({id:Sn,name:Bd});let r=sw(e.dal),n={id:Sn,name:Bd,created_at:vM,projects:r};return t.json({workspace:n})}function IM(t,e){return t.json({projects:sw(e.dal)})}function NM(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(bn)){let s=qd(e.dal,r);return s===null||s.deleted_at!==null?t.json({project:null},404):t.json({project:Go(s)})}let n=ow(e.dal,r);return n===null?t.json({project:null},404):t.json({project:iw(n)})}async function xM(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:Sn,name:Bd});let s=e.dal.insertWebProject({workspace_id:Sn,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:Go(s)},201)}async function AM(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(bn)){let i=qd(e.dal,r);if(i===null||i.deleted_at!==null)return t.json({error:"project_not_found",message:`project not found: ${r}`},404);let o=e.dal.updateWebProject({id:i.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 o===null?t.json({error:"project_not_found",message:`project not found: ${r}`},404):t.json({project:Go(o)})}return t.json({error:"project_not_found",message:`project not found: ${r}`},404)}function RM(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(bn)){let n=qd(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 LM(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 i=s.project_id??r;if(typeof s.text!="string"||s.text==="")return t.json({error:"bad_request",message:"input.text is required"},400);let o=ow(e.dal,i);if(o===null)return t.json({error:"project_not_found",message:`project not found: ${i}`},404);if(e.dal.getWorkflowByName(o.workflow_name)===null)return t.json({error:"workflow_not_registered",message:`project ${o.name} has no registered workflow "${o.workflow_name}"`},400);let l=`${SM}${crypto.randomUUID()}`,c={text:s.text,context_json:s.context_json??null},d;e.enqueueProjectJob!==void 0?d=e.enqueueProjectJob({dal:e.dal,project_id:o.id,source_ref:l,payload:c}):d=await $M({dal:e.dal,project_id:o.id,source_ref:l,payload:c}),e.dal.insertPromptDispatch({prompt_id:l,project_id:o.id,job_id:d.id,text:s.text,context_json:s.context_json===void 0?null:JSON.stringify(s.context_json)});let u={id:l,project_id:`${Xo}${o.id}`,text:s.text,status:"pending",created_at:new Date().toISOString(),completed_at:null};return t.json({prompt:u},201)}function OM(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=CM(e.dal,r);return t.json({result:n})}function sw(t){let e=t.listProjects().map(iw),r=t.listWebProjectsActive(Sn).map(Go);return[...e,...r].sort(HM)}function iw(t){return{id:`${Xo}${t.id}`,workspace_id:Sn,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 Go(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:`${bn}${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 qd(t,e){if(!e.startsWith(bn))return null;let r=e.slice(bn.length),n=Number.parseInt(r,10);return!Number.isFinite(n)||String(n)!==r?null:t.getWebProject(n)}function ow(t,e){if(e.startsWith(Xo)){let n=e.slice(Xo.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 $M(t){let{enqueueManual:e}=await Promise.resolve().then(()=>(zc(),vh));return{id:e(t.dal,{project_id:t.project_id,source_ref:t.source_ref,payload:t.payload}).id}}function CM(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),i=t.getProject(r.project_id),o=WM(t,i?.team_id??null),a=UM(s),l=BM(n,a,o.length>0),c=qM(r.created_at,s),d=i===null?{totalEstimatedMs:void 0,perStep:new Map}:MM(t,i.workflow_name),u=d.totalEstimatedMs,f=aw(r.created_at),m=i?.workflow_name,p=d.perStep.size>0?d.perStep.size:void 0,h=s===null?[]:jM(t,s.id),g=DM(s,a,h,d.perStep,o),_=PM(h,d.perStep),y=FM(g,_,u,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,...Jo(u,f),...y},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,...Jo(u,f),...y},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:o,...Jo(u,f),...y},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,...Jo(u,f),...y},errors_json:null,duration_ms:c}}function MM(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 i=s,o=typeof i.estimated_duration_ms=="number"&&Number.isFinite(i.estimated_duration_ms)&&i.estimated_duration_ms>=0?i.estimated_duration_ms:void 0,a=new Map;if(Array.isArray(i.steps))for(let l of i.steps){if(l===null||typeof l!="object")continue;let c=l;if(typeof c.id!="string"||c.id.length===0)continue;let d=typeof c.name=="string"&&c.name.length>0?c.name:c.id,u=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,u===void 0?{name:d}:{name:d,estimated_duration_ms:u})}if(i.steps===void 0&&i.states!==null&&typeof i.states=="object")for(let[l,c]of Object.entries(i.states)){if(c===null||typeof c!="object")continue;let d=c,u=typeof d.estimated_duration_ms=="number"&&Number.isFinite(d.estimated_duration_ms)&&d.estimated_duration_ms>=0?d.estimated_duration_ms:void 0;a.set(l,u===void 0?{name:l}:{name:l,estimated_duration_ms:u})}return{totalEstimatedMs:o,perStep:a}}function jM(t,e){try{return t.listStepsForRun(e)}catch{return[]}}function DM(t,e,r,n,s){if(t===null||t.terminal_state!==null)return;let i=e!==null?e:t.current_state;if(i===null||i.length===0)return;let a=[...r].reverse().find(f=>f.state_name===i&&f.ended_at===null)?.started_at??t.paused_at??t.started_at,l=n.get(i),c=l?.name??i,d=aw(a),u={id:i,name:c,started_at:a,elapsed_ms:d};return l?.estimated_duration_ms!==void 0&&(u.estimated_duration_ms=l.estimated_duration_ms),s.length>0&&(u.attention_needed=s),u}function PM(t,e){let r=[];for(let n of t){if(n.ended_at===null)continue;let s=Date.parse(n.started_at),i=Date.parse(n.ended_at),o=Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-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:o,status:l})}return r}function FM(t,e,r,n,s,i){let o={completed_steps:e,total_elapsed_ms:n};return t!==void 0&&(o.current_step=t),r!==void 0&&(o.total_estimated_ms=r),s!==void 0&&s.length>0&&(o.workflow_name=s),i!==void 0&&(o.total_steps=i),o}function aw(t){let e=Date.parse(t);return Number.isNaN(e)?0:Math.max(0,Date.now()-e)}function Jo(t,e){return t===void 0?{elapsed_ms:e}:{elapsed_ms:e,estimated_duration_ms:t}}function UM(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 WM(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 BM(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 qM(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 HM(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 Xo,bn,SM,Sn,Bd,vM,lw=E(()=>{"use strict";Xo="project:",bn="web_project:",SM="prompt:",Sn="default",Bd="Default workspace",vM=new Date(0).toISOString()});import{Buffer as cw}from"node:buffer";function dw(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 uw(t){return GM[t]}function fw(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 JM,XM,Ko,GM,Hd=E(()=>{"use strict";JM=1e4,XM=256*1024,Ko=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=dw(e.pushWindowMs,process.env.LMCTL_TERMINAL_PUSH_WINDOW_MS,JM),this.pushByteCap=dw(e.pushByteCap,process.env.LMCTL_TERMINAL_PUSH_BYTE_CAP,XM),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+=cw.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=${cw.byteLength(n,"utf8")}`)}catch(i){this.opts.log?.(`[dt-2] publish failed session=${e.session_id} reason=${r}: ${i instanceof Error?i.message:String(i)}`)}}async onPtyExit(e,r){if(e.closed)return;await this.flush(e,"pty_exit");let n=`\r
|
|
2144
|
+
`)}function lM(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ke(t){return typeof t=="string"?t:""}function cM(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 Od(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Do(t,e){return Number(t.req.param(e))}var Po,$d,Ky=E(()=>{"use strict";jo();qt();cd();Po=[{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."}],$d=Po.map(t=>t.name)});function uM(t){return t.replace(/^\/+/,"")}function Vy(t){return typeof t=="string"&&t!==""&&!t.includes("/")&&!t.includes("\\")}function Tn(t){if(t.mailboxKey!==void 0&&t.mailboxKey!==null&&t.mailboxKey!==""){let e=uM(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 Vy(t.userId)&&Vy(t.deviceId)?`${t.userId}/${t.deviceId}/`:`${dM}/${t.identityId}/`}function mM(t){return String(Math.max(0,Math.floor(t))).padStart(fM,"0")}function jd(t,e,r){return`${t}${e}${mM(r)}.json`}function Fo(t,e){return`${t}${e}`}function Uo(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 i=Number(s[1]);return Number.isSafeInteger(i)?i:void 0}var dM,fM,Wo=E(()=>{"use strict";dM="mailbox";fM=12});function Kt(t,e){let r=Math.floor(t),n="",s=r;for(let d=0;d<12;d++)n=Bo[s&15]+n,s=Math.floor(s/16);let i=Math.floor(e()*4096)&4095,o="",a=i;for(let d=0;d<3;d++)o=Bo[a&15]+o,a=a>>4;let l=Bo[8|Math.floor(e()*4)&3],c="";for(let d=0;d<15;d++)c+=Bo[Math.floor(e()*16)&15];return n.slice(0,8)+"-"+n.slice(8,12)+"-7"+o+"-"+l+c.slice(0,3)+"-"+c.slice(3,15)}var Bo,qo=E(()=>{"use strict";Bo="0123456789abcdef"});function Pd(t,e){return!Number.isFinite(t)||t<=0?e:t}function Fd(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 ew(t){return t.conversation_id===Qy&&hM(t.payload)}function hM(t){return typeof t=="object"&&t!==null&&t.kind==="heartbeat"}function gM(t){let e=typeof t.hb=="string"&&t.hb!==""?t.hb:ew(t)?t.timestamp:void 0;if(e===void 0)return;let r=Date.parse(e);return Number.isFinite(r)?r:void 0}var Yy,zy,Zy,pM,Qy,_M,Dd,Wr,Ho=E(()=>{"use strict";Wo();qo();Yy=3e3,zy=1e4,Zy=12e3,pM=1e3,Qy="__lmctl_heartbeat__",_M={kind:"heartbeat"},Dd={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Wr=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=Tn({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=Pd(e.readIntervalMs??e.pollIntervalMs??Yy,Yy),this.heartbeatIdleMs=Pd(e.heartbeatIdleMs??zy,zy),this.backoffReadIntervalMs=Pd(e.backoffReadIntervalMs??e.pollIntervalMs??Zy,Zy)}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??Dd;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=Fo(this.basePrefix,e),n=0,s;do{let i=await this.opts.s3.send(new this.opts.commands.ListObjectsV2Command({Bucket:this.opts.bucket,Prefix:r,MaxKeys:pM,...s!==void 0&&{ContinuationToken:s}}));this.opts.onS3Op?.("list");for(let o of i.Contents??[]){let a=Uo(o.Key??"",this.basePrefix,e);a!==void 0&&a>n&&(n=a)}s=i.IsTruncated===!0?i.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(),i={message_id:Kt(n,this.opts.random??Math.random),from:this.opts.selfRole,timestamp:s,hb:s,conversation_id:e,payload:r},o=(this.ownSeq??0)+1,a=jd(this.basePrefix,this.ownStream,o);return await this.opts.s3.send(new this.opts.commands.PutObjectCommand({Bucket:this.opts.bucket,Key:a,Body:JSON.stringify(i),ContentType:"application/json"})),this.opts.onS3Op?.("put"),this.ownSeq=o,this.recordWrite(n),a}scheduleNextTick(e){if(this.stopRequested)return;let r=this.opts.timers??Dd;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=jd(this.basePrefix,this.peerStream,e),n;try{let i=await this.opts.s3.send(new this.opts.commands.GetObjectCommand({Bucket:this.opts.bucket,Key:r}));if(this.opts.onS3Op?.("get"),i.Body===void 0){this.emitError(new Error(`GetObject ${r}: empty body`),"get"),this.advanceCursor(e);continue}n=await i.Body.transformToString("utf-8")}catch(i){if(Fd(i)){this.opts.onS3Op?.("get");return}this.emitError(i,"get");return}let s;try{s=JSON.parse(n)}catch(i){this.emitError(i,"get"),this.advanceCursor(e);continue}if(this.recordPeerHeartbeat(s),ew(s)){this.advanceCursor(e);continue}try{await this.opts.onMessage(s)}catch(i){this.emitError(i,"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=gM(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??Dd;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(Qy,_M)}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 yM}from"@hono/node-server/conninfo";function tw(t,e){let r=e.bucket??wM,n=e.remoteAddressOf??(i=>TM(i)),s=i=>{let o=n(i);return bM(o)?null:i.json({error:"forbidden",message:"local-mailbox is loopback-only"},403)};t.get("/local-mailbox/object",async i=>{let o=s(i);if(o!==null)return o;let a=Ud(i.req.query("key"));if(typeof a!="string")return i.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 i.json({error:"empty_body"},404);let c=await l.Body.transformToString("utf-8");return i.body(c,200,{"Content-Type":"application/octet-stream"})}catch(l){return Fd(l)?i.json({error:"not_found"},404):i.json({error:"internal",message:Wd(l)},500)}}),t.put("/local-mailbox/object",async i=>{let o=s(i);if(o!==null)return o;let a=Ud(i.req.query("key"));if(typeof a!="string")return i.json({error:"bad_request",message:a.error},400);let l=new Uint8Array(await i.req.arrayBuffer());try{return await e.s3.send(new e.commands.PutObjectCommand({Bucket:r,Key:a,Body:l})),i.json({ok:!0})}catch(c){return i.json({error:"internal",message:Wd(c)},500)}}),t.get("/local-mailbox/list",async i=>{let o=s(i);if(o!==null)return o;let a=i.req.query("prefix")??"",l=Ud(a,{allowEmpty:!0});if(typeof l!="string")return i.json({error:"bad_request",message:l.error},400);let c=EM(i.req.query("maxKeys")),d=i.req.query("token");try{let u=await e.s3.send(new e.commands.ListObjectsV2Command({Bucket:r,Prefix:l,...c!==void 0?{MaxKeys:c}:{},...d!==void 0&&d!==""?{ContinuationToken:d}:{}}));return i.json({Contents:(u.Contents??[]).map(f=>({Key:f.Key,LastModified:f.LastModified instanceof Date?f.LastModified.toISOString():f.LastModified})),IsTruncated:u.IsTruncated??!1,...u.NextContinuationToken!==void 0?{NextContinuationToken:u.NextContinuationToken}:{}})}catch(u){return i.json({error:"internal",message:Wd(u)},500)}})}function Ud(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 EM(t){if(t===void 0||t==="")return;let e=Number(t);return Number.isInteger(e)&&e>0?e:void 0}function TM(t){try{return yM(t).remote.address}catch{return}}function bM(t){return t===void 0||t===""?!1:!!(t==="127.0.0.1"||t==="::1"||t.startsWith("::ffff:127.")||t.startsWith("127."))}function Wd(t){return t instanceof Error?t.message:String(t)}var wM,rw=E(()=>{"use strict";Ho();wM="local"});function nw(t,e){t.get("/mailbox/workspace",r=>kM(r,e)),t.get("/mailbox/projects",r=>IM(r,e)),t.get("/mailbox/projects/:id",r=>NM(r,e)),t.post("/mailbox/projects",r=>xM(r,e)),t.patch("/mailbox/projects/:id",r=>AM(r,e)),t.delete("/mailbox/projects/:id",r=>RM(r,e)),t.post("/mailbox/projects/:project_id/prompts",r=>LM(r,e)),t.get("/mailbox/prompts/:id",r=>OM(r,e))}function kM(t,e){e.dal.ensureWorkspace({id:Sn,name:Bd});let r=sw(e.dal),n={id:Sn,name:Bd,created_at:vM,projects:r};return t.json({workspace:n})}function IM(t,e){return t.json({projects:sw(e.dal)})}function NM(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(bn)){let s=qd(e.dal,r);return s===null||s.deleted_at!==null?t.json({project:null},404):t.json({project:Go(s)})}let n=ow(e.dal,r);return n===null?t.json({project:null},404):t.json({project:iw(n)})}async function xM(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:Sn,name:Bd});let s=e.dal.insertWebProject({workspace_id:Sn,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:Go(s)},201)}async function AM(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(bn)){let i=qd(e.dal,r);if(i===null||i.deleted_at!==null)return t.json({error:"project_not_found",message:`project not found: ${r}`},404);let o=e.dal.updateWebProject({id:i.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 o===null?t.json({error:"project_not_found",message:`project not found: ${r}`},404):t.json({project:Go(o)})}return t.json({error:"project_not_found",message:`project not found: ${r}`},404)}function RM(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(bn)){let n=qd(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 LM(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 i=s.project_id??r;if(typeof s.text!="string"||s.text==="")return t.json({error:"bad_request",message:"input.text is required"},400);let o=ow(e.dal,i);if(o===null)return t.json({error:"project_not_found",message:`project not found: ${i}`},404);if(e.dal.getWorkflowByName(o.workflow_name)===null)return t.json({error:"workflow_not_registered",message:`project ${o.name} has no registered workflow "${o.workflow_name}"`},400);let l=`${SM}${crypto.randomUUID()}`,c={text:s.text,context_json:s.context_json??null},d;e.enqueueProjectJob!==void 0?d=e.enqueueProjectJob({dal:e.dal,project_id:o.id,source_ref:l,payload:c}):d=await $M({dal:e.dal,project_id:o.id,source_ref:l,payload:c}),e.dal.insertPromptDispatch({prompt_id:l,project_id:o.id,job_id:d.id,text:s.text,context_json:s.context_json===void 0?null:JSON.stringify(s.context_json)});let u={id:l,project_id:`${Jo}${o.id}`,text:s.text,status:"pending",created_at:new Date().toISOString(),completed_at:null};return t.json({prompt:u},201)}function OM(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=CM(e.dal,r);return t.json({result:n})}function sw(t){let e=t.listProjects().map(iw),r=t.listWebProjectsActive(Sn).map(Go);return[...e,...r].sort(HM)}function iw(t){return{id:`${Jo}${t.id}`,workspace_id:Sn,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 Go(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:`${bn}${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 qd(t,e){if(!e.startsWith(bn))return null;let r=e.slice(bn.length),n=Number.parseInt(r,10);return!Number.isFinite(n)||String(n)!==r?null:t.getWebProject(n)}function ow(t,e){if(e.startsWith(Jo)){let n=e.slice(Jo.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 $M(t){let{enqueueManual:e}=await Promise.resolve().then(()=>(zc(),vh));return{id:e(t.dal,{project_id:t.project_id,source_ref:t.source_ref,payload:t.payload}).id}}function CM(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),i=t.getProject(r.project_id),o=WM(t,i?.team_id??null),a=UM(s),l=BM(n,a,o.length>0),c=qM(r.created_at,s),d=i===null?{totalEstimatedMs:void 0,perStep:new Map}:MM(t,i.workflow_name),u=d.totalEstimatedMs,f=aw(r.created_at),m=i?.workflow_name,p=d.perStep.size>0?d.perStep.size:void 0,h=s===null?[]:jM(t,s.id),g=DM(s,a,h,d.perStep,o),_=PM(h,d.perStep),y=FM(g,_,u,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,...Xo(u,f),...y},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,...Xo(u,f),...y},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:o,...Xo(u,f),...y},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,...Xo(u,f),...y},errors_json:null,duration_ms:c}}function MM(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 i=s,o=typeof i.estimated_duration_ms=="number"&&Number.isFinite(i.estimated_duration_ms)&&i.estimated_duration_ms>=0?i.estimated_duration_ms:void 0,a=new Map;if(Array.isArray(i.steps))for(let l of i.steps){if(l===null||typeof l!="object")continue;let c=l;if(typeof c.id!="string"||c.id.length===0)continue;let d=typeof c.name=="string"&&c.name.length>0?c.name:c.id,u=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,u===void 0?{name:d}:{name:d,estimated_duration_ms:u})}if(i.steps===void 0&&i.states!==null&&typeof i.states=="object")for(let[l,c]of Object.entries(i.states)){if(c===null||typeof c!="object")continue;let d=c,u=typeof d.estimated_duration_ms=="number"&&Number.isFinite(d.estimated_duration_ms)&&d.estimated_duration_ms>=0?d.estimated_duration_ms:void 0;a.set(l,u===void 0?{name:l}:{name:l,estimated_duration_ms:u})}return{totalEstimatedMs:o,perStep:a}}function jM(t,e){try{return t.listStepsForRun(e)}catch{return[]}}function DM(t,e,r,n,s){if(t===null||t.terminal_state!==null)return;let i=e!==null?e:t.current_state;if(i===null||i.length===0)return;let a=[...r].reverse().find(f=>f.state_name===i&&f.ended_at===null)?.started_at??t.paused_at??t.started_at,l=n.get(i),c=l?.name??i,d=aw(a),u={id:i,name:c,started_at:a,elapsed_ms:d};return l?.estimated_duration_ms!==void 0&&(u.estimated_duration_ms=l.estimated_duration_ms),s.length>0&&(u.attention_needed=s),u}function PM(t,e){let r=[];for(let n of t){if(n.ended_at===null)continue;let s=Date.parse(n.started_at),i=Date.parse(n.ended_at),o=Number.isFinite(s)&&Number.isFinite(i)?Math.max(0,i-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:o,status:l})}return r}function FM(t,e,r,n,s,i){let o={completed_steps:e,total_elapsed_ms:n};return t!==void 0&&(o.current_step=t),r!==void 0&&(o.total_estimated_ms=r),s!==void 0&&s.length>0&&(o.workflow_name=s),i!==void 0&&(o.total_steps=i),o}function aw(t){let e=Date.parse(t);return Number.isNaN(e)?0:Math.max(0,Date.now()-e)}function Xo(t,e){return t===void 0?{elapsed_ms:e}:{elapsed_ms:e,estimated_duration_ms:t}}function UM(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 WM(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 BM(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 qM(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 HM(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 Jo,bn,SM,Sn,Bd,vM,lw=E(()=>{"use strict";Jo="project:",bn="web_project:",SM="prompt:",Sn="default",Bd="Default workspace",vM=new Date(0).toISOString()});import{Buffer as cw}from"node:buffer";function dw(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 uw(t){return GM[t]}function fw(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 XM,JM,Ko,GM,Hd=E(()=>{"use strict";XM=1e4,JM=256*1024,Ko=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=dw(e.pushWindowMs,process.env.LMCTL_TERMINAL_PUSH_WINDOW_MS,XM),this.pushByteCap=dw(e.pushByteCap,process.env.LMCTL_TERMINAL_PUSH_BYTE_CAP,JM),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+=cw.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=${cw.byteLength(n,"utf8")}`)}catch(i){this.opts.log?.(`[dt-2] publish failed session=${e.session_id} reason=${r}: ${i instanceof Error?i.message:String(i)}`)}}async onPtyExit(e,r){if(e.closed)return;await this.flush(e,"pty_exit");let n=`\r
|
|
2063
2145
|
[process exited with code ${r.exitCode}${r.signal!==void 0?` signal ${r.signal}`:""}]\r
|
|
2064
|
-
`,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(i){this.opts.log?.(`[dt-2] publish (exit) failed session=${e.session_id}: ${i instanceof Error?i.message:String(i)}`)}e.closed=!0,this.sessions.delete(e.session_id)}};GM={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 pw(t,e){t.post("/mailbox/terminal/launch",r=>KM(r,e)),t.post("/mailbox/terminal/end/:session_id",r=>VM(r,e)),t.get("/mailbox/terminal/sessions",r=>YM(r,e))}async function KM(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"||!mw.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let i=n.provider;if(typeof i!="string"||i==="")return t.json({error:"bad_request",message:"provider is required"},400);let o;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(o=fw(n.command_line),o===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=uw(i);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no TERMINAL_LAUNCH_DEFAULTS entry for provider "${i}"`},400);o={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=r.startSession({session_id:s,command:o.cmd,args:o.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,pid:a,command:o.cmd,args:o.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 VM(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||!mw.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 YM(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 mw,_w=E(()=>{"use strict";Hd();mw=/^[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 zM}from"node:buffer";function ej(t){try{return zM.byteLength(JSON.stringify(t),"utf8")}catch{return 256}}function hw(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 gw(t){return tj[t]}function yw(t){let e=t.trim();if(e==="")return;let r=[],n=0;for(;n<e.length;){let i=e[n];if(i===" "||i===" "){n+=1;continue}if(i==='"'){let a=n+1,l="";for(;a<e.length&&e[a]!=='"';)l+=e[a],a+=1;r.push(l),n=a+1;continue}let o=n;for(;o<e.length&&e[o]!==" "&&e[o]!==" ";)o+=1;r.push(e.slice(n,o)),n=o}if(r.length===0)return;let s=r.shift();if(!(s===void 0||s===""))return{cmd:s,args:r}}var ZM,QM,Vo,tj,Jd=E(()=>{"use strict";ZM=2e3,QM=64*1024,Vo=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=hw(e.pushWindowMs,process.env.LMCTL_PROVIDER_PUSH_WINDOW_MS,ZM),this.pushByteCap=hw(e.pushByteCap,process.env.LMCTL_PROVIDER_PUSH_BYTE_CAP,QM),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 i=await r.start(e,s);return n.child=i,this.wireChildExit(n,i),this.opts.log?.(`[dt-3] persistent session ${e.session_id} started provider=${e.provider} pid=${i.pid??"?"}`),{pid:i.pid}}catch(i){throw this.sessions.delete(e.session_id),i}}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 i=s instanceof Error?s.message:String(s);this.opts.log?.(`[dt-3] adapter.sendTurn failed session=${e.session_id}: ${i}`),this.appendEvent(r,{event_type:"error",payload:{message:`sendTurn failed: ${i}`}})}}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=ej(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(i){this.opts.log?.(`[dt-3] publish failed session=${e.session_id} reason=${r}: ${i instanceof Error?i.message:String(i)}`)}}wireChildExit(e,r){let n=e.generation;r.on("exit",(s,i)=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child exited code=${s??"?"} signal=${i??""}; 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")))})}};tj={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 Ew(t,e){t.post("/mailbox/chat/launch",r=>rj(r,e)),t.post("/mailbox/chat/end/:session_id",r=>nj(r,e)),t.get("/mailbox/chat/sessions",r=>sj(r,e))}async function rj(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"||!ww.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let i=n.provider;if(typeof i!="string"||i==="")return t.json({error:"bad_request",message:"provider is required"},400);let o;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(o=yw(n.command_line),o===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=gw(i);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no PERSISTENT_LAUNCH_DEFAULTS entry for provider "${i}"`},400);o={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=await r.startSession({session_id:s,provider:i,command:o.cmd,args:o.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,provider:i,pid:a,command:o.cmd,args:o.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 nj(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||!ww.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 sj(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 ww,Tw=E(()=>{"use strict";Jd();ww=/^[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 ij}from"node:fs";function Sw(t){let e=t.artifacts.find(r=>r.kind===`${t.state_name}_transcript`);if(e?.content!==void 0&&e.content!==null)return bw(e.content);if(e?.path===void 0||e.path===null)return[];try{let r=ij(e.path,{encoding:"utf8"});return bw(r)}catch{return[]}}function bw(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 vw=E(()=>{"use strict"});function kw(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}function Yo(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2146
|
+
`,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(i){this.opts.log?.(`[dt-2] publish (exit) failed session=${e.session_id}: ${i instanceof Error?i.message:String(i)}`)}e.closed=!0,this.sessions.delete(e.session_id)}};GM={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 pw(t,e){t.post("/mailbox/terminal/launch",r=>KM(r,e)),t.post("/mailbox/terminal/end/:session_id",r=>VM(r,e)),t.get("/mailbox/terminal/sessions",r=>YM(r,e))}async function KM(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"||!mw.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let i=n.provider;if(typeof i!="string"||i==="")return t.json({error:"bad_request",message:"provider is required"},400);let o;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(o=fw(n.command_line),o===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=uw(i);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no TERMINAL_LAUNCH_DEFAULTS entry for provider "${i}"`},400);o={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=r.startSession({session_id:s,command:o.cmd,args:o.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,pid:a,command:o.cmd,args:o.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 VM(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||!mw.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 YM(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 mw,_w=E(()=>{"use strict";Hd();mw=/^[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 zM}from"node:buffer";function ej(t){try{return zM.byteLength(JSON.stringify(t),"utf8")}catch{return 256}}function hw(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 gw(t){return tj[t]}function yw(t){let e=t.trim();if(e==="")return;let r=[],n=0;for(;n<e.length;){let i=e[n];if(i===" "||i===" "){n+=1;continue}if(i==='"'){let a=n+1,l="";for(;a<e.length&&e[a]!=='"';)l+=e[a],a+=1;r.push(l),n=a+1;continue}let o=n;for(;o<e.length&&e[o]!==" "&&e[o]!==" ";)o+=1;r.push(e.slice(n,o)),n=o}if(r.length===0)return;let s=r.shift();if(!(s===void 0||s===""))return{cmd:s,args:r}}var ZM,QM,Vo,tj,Xd=E(()=>{"use strict";ZM=2e3,QM=64*1024,Vo=class{opts;sessions=new Map;pushWindowMs;pushByteCap;timers;constructor(e){this.opts=e,this.pushWindowMs=hw(e.pushWindowMs,process.env.LMCTL_PROVIDER_PUSH_WINDOW_MS,ZM),this.pushByteCap=hw(e.pushByteCap,process.env.LMCTL_PROVIDER_PUSH_BYTE_CAP,QM),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 i=await r.start(e,s);return n.child=i,this.wireChildExit(n,i),this.opts.log?.(`[dt-3] persistent session ${e.session_id} started provider=${e.provider} pid=${i.pid??"?"}`),{pid:i.pid}}catch(i){throw this.sessions.delete(e.session_id),i}}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 i=s instanceof Error?s.message:String(s);this.opts.log?.(`[dt-3] adapter.sendTurn failed session=${e.session_id}: ${i}`),this.appendEvent(r,{event_type:"error",payload:{message:`sendTurn failed: ${i}`}})}}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=ej(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(i){this.opts.log?.(`[dt-3] publish failed session=${e.session_id} reason=${r}: ${i instanceof Error?i.message:String(i)}`)}}wireChildExit(e,r){let n=e.generation;r.on("exit",(s,i)=>{n===e.generation&&(e.closed||(this.appendEvent(e,{event_type:"error",payload:{message:`provider child exited code=${s??"?"} signal=${i??""}; 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")))})}};tj={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 Ew(t,e){t.post("/mailbox/chat/launch",r=>rj(r,e)),t.post("/mailbox/chat/end/:session_id",r=>nj(r,e)),t.get("/mailbox/chat/sessions",r=>sj(r,e))}async function rj(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"||!ww.test(s))return t.json({error:"bad_request",message:"session_id must be a UUIDv7 string"},400);let i=n.provider;if(typeof i!="string"||i==="")return t.json({error:"bad_request",message:"provider is required"},400);let o;if(typeof n.command_line=="string"&&n.command_line.trim()!==""){if(o=yw(n.command_line),o===void 0)return t.json({error:"bad_request",message:"command_line could not be parsed"},400)}else{let a=gw(i);if(a===void 0)return t.json({error:"no_default_for_provider",message:`no PERSISTENT_LAUNCH_DEFAULTS entry for provider "${i}"`},400);o={cmd:a.cmd,args:[...a.args]}}try{let{pid:a}=await r.startSession({session_id:s,provider:i,command:o.cmd,args:o.args,...typeof n.cwd=="string"&&n.cwd!==""?{cwd:n.cwd}:{}});return t.json({session_id:s,provider:i,pid:a,command:o.cmd,args:o.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 nj(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||!ww.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 sj(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 ww,Tw=E(()=>{"use strict";Xd();ww=/^[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 ij}from"node:fs";function Sw(t){let e=t.artifacts.find(r=>r.kind===`${t.state_name}_transcript`);if(e?.content!==void 0&&e.content!==null)return bw(e.content);if(e?.path===void 0||e.path===null)return[];try{let r=ij(e.path,{encoding:"utf8"});return bw(r)}catch{return[]}}function bw(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 vw=E(()=>{"use strict"});function kw(t,e,r){let n=t.getRun(e);if(n===null)return{err:`run ${e}: not found`};if(r!==void 0){let l=t.findTeamMemberByAlias(n.team_id,r);return l===null?{err:`run ${e}: team has no member alias "${r}"`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let s=t.latestAgentCall(e);if(s!==null){let l=t.findTeamMemberByAlias(n.team_id,s.alias);return l===null?{err:`run ${e}: team has no member alias "${s.alias}" (latest agent_call references a member that has been removed)`}:l.sessionid===null||l.sessionid.length===0?{err:`run ${e}: member "${l.alias}" has no sessionid yet (seed first)`}:{ok:{provider:l.provider,sessionid:l.sessionid,sessiondir:l.sessiondir,alias:l.alias,...l.model!==null&&l.model!==void 0?{model:l.model}:{}}}}let o=t.listTeamMembers(n.team_id).filter(l=>l.state!=="retired"&&l.sessionid!==null&&l.sessionid.length>0);if(o.length===0)return{err:`run ${e}: cannot resolve an agent session (no agent_call yet, no seeded member)`};if(o.length>1){let l=o.map(c=>c.alias).join(", ");return{err:`run ${e}: cannot resolve an agent session (no agent_call yet; team has multiple members [${l}] \u2014 pass --alias)`}}let a=o[0];return{ok:{provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,alias:a.alias,...a.model!==null&&a.model!==void 0?{model:a.model}:{}}}}function Yo(t,e){let r=t.query(`SELECT id, kind FROM attention
|
|
2065
2147
|
WHERE run_id = ?
|
|
2066
2148
|
AND acknowledged_at IS NULL
|
|
2067
2149
|
AND requires_user = 1
|
|
2068
|
-
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var zo=E(()=>{"use strict"});function Mw(t,e){t.all("/runtime/*",r=>oj(r.req.raw,e))}async function oj(t,e){try{return Response.json(await aj(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 aj(t,e){let r=new URL(t.url),n=pj(e),s=r.pathname.split("/").filter(Boolean).map(decodeURIComponent);if(t.method==="GET"&&r.pathname==="/runtime/workspaces")return Xd(t),[{id:n.id,name:n.name}];if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="workspaces")return Zo(t,n.id,s[2]),lj(e.dal,n);if(t.method==="GET"&&s.length===5&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"){Zo(t,n.id,s[2]);let i=Nw(e.dal,s[4]);return Iw(e.dal,n,i)}if(t.method==="GET"&&r.pathname==="/runtime/lead-teams")return Xd(t),e.dal.listTeams().map(i=>mj(i));if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="chat"){let i=xw(e.dal,Aw(s[2])),o=await t.json();if(o.teamId!==`team:${i.name}`)throw new ie(400,"runtime lead chat body does not match route team");return Lw(t,n.id,o.context),Rw(i,o.context)}if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="messages"){let i=xw(e.dal,Aw(s[2])),o=await t.json();if(o.teamId!==`team:${i.name}`)throw new ie(400,"runtime lead message body does not match route team");Lw(t,n.id,o.context);let a=o.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime lead message requires draft.body");return Rw(i,o.context,a)}if(t.method==="POST"&&s.length===6&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"&&s[5]==="workflow-message"){Zo(t,n.id,s[2]);let i=Nw(e.dal,s[4]),o=await t.json();if(o.workspaceId!==n.id||o.projectId!==i.name)throw new ie(400,"runtime request body does not match route workspace/project");let a=o.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime workflow message requires draft.body");return uj(e.dal,i,a),Iw(e.dal,n,i)}if(t.method==="GET"&&r.pathname==="/runtime/templates")return As(t,n.id),e.dal.listWorkflows().map(i=>_j(i));if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="templates"){As(t,n.id);let i=gj(e.dal,s[2]);return hj(i)}if(t.method==="GET"&&r.pathname==="/runtime/runs"){As(t,n.id);let i=r.searchParams.get("project"),o=r.searchParams.get("template");if(i!==null&&o!==null)throw new ie(400,"conflicting_filters: ?project= and ?template= are mutually exclusive");return yj(e.dal,i,o).map(l=>$w(e.dal,l))}if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="runs"){As(t,n.id);let i=Ow(e.dal,s[2]);return $w(e.dal,i)}if(t.method==="GET"&&s.length===4&&s[0]==="runtime"&&s[1]==="runs"&&s[3]==="events"){As(t,n.id);let i=Ow(e.dal,s[2]),o=Ej(e.dal,i);return{runId:zd(i),events:o,...o.length>0?{cursor:o[o.length-1].id}:{}}}throw new ie(404,`unknown runtime request: ${t.method} ${r.pathname}`)}function lj(t,e){return{id:e.id,name:e.name,projects:t.listProjects().map(r=>jw(t,e,r))}}function Iw(t,e,r){let n=jw(t,e,r);return{...n,managedWorkflow:{...n.managedWorkflow,instance:cj(t,r),composerTarget:{kind:"workflow-initial",label:`Project Workflow: ${r.workflow_name}`,templateId:`template:${r.workflow_name}`,runId:n.managedWorkflow.runId}},workflowMessages:dj(t,r)}}function jw(t,e,r){let n=Dw(t,r.id),s=Kd(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 cj(t,e){let r=Dw(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:Kd(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 dj(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 uj(t,e,r){let n=fj(t,e.id);if(n!==null){let s=Yo(t,n.id);if(s?.kind==="workflow_escalation"){let i=t.resumeEscalation(s.attention_id,r);if(!i.resumed)throw new ie(409,`workflow escalation resume failed: ${i.reason}`);return}if(s?.kind==="interactive_waiting_operator"){let i=Nt(t,s.attention_id);if(i?.step_id===null||i?.step_id===void 0)throw new ie(409,"interactive resume failed: missing step");let o=t.resumeInteractive(i.step_id,r,!0);if(!o.resumed)throw new ie(409,`interactive resume failed: ${o.reason}`);return}}t.enqueueJob({project_id:e.id,source:"runtime-workflow-message",payload:JSON.stringify({prompt:r}),priority:0})}function Dw(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 fj(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 Kd(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 Nw(t,e){let r=t.findProjectByName(e);if(r===null)throw new ie(404,`project not found: ${e}`);return r}function xw(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 Aw(t){return t.startsWith("team:")?t.slice(5):t}function mj(t){return{id:`team:${t.name}`,name:t.name,teamfile:"",hasLead:!0,kind:t.name.toLowerCase().includes("manager")?"global-manager":"custom-ai-led"}}function Rw(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??Cw}`,teamId:`team:${t.name}`,title:`${t.name} Lead`,messages:s,...e===void 0?{}:{context:e}}}function pj(t){let e=t.workspaceName??Dt()??Nr.default;return{id:e,name:e}}function Xd(t){if(t.headers.get("x-lmctl-workspace-id")!==Cw)throw new ie(400,"runtime request requires global-admin workspace identity")}function Zo(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 As(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 Lw(t,e,r){if(r?.scope==="workspace"){if(r.workspaceId===void 0)throw new ie(400,"workspace manager context requires workspace identity");Zo(t,e,r.workspaceId);return}Xd(t)}function Vd(t){return`${vn}${Yd(t.name)}`}function Yd(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"item"}function zd(t){return`${Gd}${t.id}`}function _j(t){let e=Qo(t.definition);return{id:Vd(t),name:t.name,...e.description===null?{}:{description:e.description}}}function hj(t){let e=Qo(t.definition);return{id:Vd(t),name:t.name,...e.description===null?{}:{description:e.description},graph:e.graph}}function Qo(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=[],i=new Map;if(r.schema_version==="lmctl/v3"&&Array.isArray(r.steps)){let o=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&&i.set(a.name,l))}o!==null&&s.includes(o)&&s.sort((a,l)=>a===o?-1:l===o?1:0)}return{description:n,graph:e,stepIds:s,nameToId:i}}function gj(t,e){if(!e.startsWith(vn))throw new ie(404,`template not found: ${e}`);let r=e.slice(vn.length),n=t.listWorkflows().filter(s=>Yd(s.name)===r);if(n.length===0)throw new ie(404,`template not found: ${e}`);if(n.length>1){let s=n.map(i=>i.name).join(", ");throw new ie(409,`template_id_ambiguous: ${e} matches multiple workflow names [${s}]; rename to ensure unique slugs`)}return n[0]}function Ow(t,e){if(!e.startsWith(Gd))throw new ie(404,`run not found: ${e}`);let r=e.slice(Gd.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 yj(t,e,r){if(r!==null){if(!r.startsWith(vn))return[];let s=r.slice(vn.length),i=t.listWorkflows().filter(a=>Yd(a.name)===s).map(a=>a.id);if(i.length===0)return[];let o=i.map(()=>"?").join(", ");return t.query(`SELECT * FROM run WHERE workflow_id IN (${o}) ORDER BY id DESC LIMIT 200`,...i)}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 $w(t,e){let r=t.getWorkflow(e.workflow_id),n=Kd(e),s=wj(r,e);return{id:zd(e),templateId:r===null?`${vn}unknown`:Vd(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 wj(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]:[Qo(t.definition).nameToId.get(r)??r]}function Ej(t,e){let r=t.getWorkflow(e.workflow_id),n=r===null?{stepIds:[],nameToId:new Map}:Qo(r.definition),s=c=>n.nameToId.get(c)??c,i=zd(e),o=[];o.push({timestamp:e.started_at,type:"run.started",message:"Run started"});let a=t.listStepsForRun(e.id);for(let c of a){let d=s(c.state_name);if(o.push({timestamp:c.started_at,type:"step.started",stepId:d,message:`step ${c.state_name} started`}),c.ended_at!==null){let u=Tj(c);o.push({timestamp:c.ended_at,type:u,stepId:d,...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&&o.push({timestamp:e.paused_at,type:"step.paused",stepId:d})}let l=t.listSessionEvents(e.id);for(let c of l){let d=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)})(),u=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{}o.push({timestamp:u,type:"message",...d===void 0?{}:{stepId:d},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";o.push({timestamp:e.ended_at??e.started_at,type:c,message:e.terminal_state})}return o.sort((c,d)=>c.timestamp.localeCompare(d.timestamp)),o.map((c,d)=>({id:`${i}:evt:${d+1}`,runId:i,sequence:d+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 Tj(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 Cw,vn,Gd,ie,Pw=E(()=>{"use strict";We();zo();qt();Cw="global-admin";vn="template:",Gd="run:";ie=class extends Error{status;constructor(e,r){super(r),this.status=e}}});import{mkdirSync as bj,writeFileSync as Sj}from"node:fs";import{randomUUID as Fw}from"node:crypto";import{dirname as vj,resolve as ea,sep as Uw}from"node:path";async function Bw(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(!Aj(n))return t.text("missing image file",400);if(n.size>kj)return t.text("upload too large",413);let s=Buffer.from(await n.arrayBuffer()),i=Rj(s);if(i===null||!(i in Ww))return t.text("unsupported upload MIME type",415);if(n.type.length>0&&n.type!==i)return t.text("upload MIME type does not match file content",415);let o=Ij(e,r.project);if(typeof o=="string")return t.text(o,404);let a=o===null?ea(xj()):ea(o.local_path),l=ea(a,"uploads",Fw()),c=ea(l,`${Fw()}${Ww[i]}`);if(!Nj(c,a))return t.text("invalid upload path",400);bj(l,{recursive:!0});let d=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);Sj(c,d);let u={path:c,size:s.byteLength,mime:i,project:o?.name??null};return t.json(u)}function Ij(t,e){return e==null||e===""?null:typeof e!="string"?"invalid project":t.findProjectByName(e)??`project not found: ${e}`}function Nj(t,e){let r=e.endsWith(Uw)?e:`${e}${Uw}`;return t.startsWith(r)}function xj(){return vj(Z())}function Aj(t){return typeof File<"u"&&t instanceof File}function Rj(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 kj,Ww,qw=E(()=>{"use strict";We();kj=10*1024*1024,Ww={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}});import{existsSync as ta}from"node:fs";import{basename as Lj,dirname as Oj,extname as $j,isAbsolute as Cj,join as Mj,relative as jj}from"node:path";import{fileURLToPath as Dj}from"node:url";import{Hono as Pj}from"hono";import{serveStatic as At}from"@hono/node-server/serve-static";function Yw(t){let e=new Pj,r=[],n=t.localWebui!==void 0?Qd(t.localWebui.webuiDir):Fj();if(t.localWebui!==void 0&&tw(e,{s3:t.localWebui.localMailbox.s3,commands:t.localWebui.localMailbox.commands}),n!==null){let s=Uj();t.localWebui!==void 0?e.get("/config.json",s,i=>i.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,i=>i.json(t.webuiRuntimeConfig)),e.use("/dist/*",s,At({root:n})),e.use("/vendor/*",s,At({root:n})),e.use("/src/*",s,At({root:n})),e.get("/",s,At({root:n,path:"index.html"})),e.get("/admin",s,At({root:n,path:"index.html"})),e.get("/admin/*",s,At({root:n,path:"index.html"})),e.get("/terminal",s,At({root:n,path:"index.html"})),e.get("/terminal/*",s,At({root:n,path:"index.html"})),e.get("/chat",s,At({root:n,path:"index.html"})),e.get("/chat/*",s,At({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("*",Lh({disabled:t.authDisabled})),e.get("/login",s=>s.html(Re("Login",`
|
|
2150
|
+
ORDER BY id DESC LIMIT 1`,e);return r.length===0?null:{kind:r[0].kind,attention_id:r[0].id}}var zo=E(()=>{"use strict"});function Mw(t,e){t.all("/runtime/*",r=>oj(r.req.raw,e))}async function oj(t,e){try{return Response.json(await aj(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 aj(t,e){let r=new URL(t.url),n=pj(e),s=r.pathname.split("/").filter(Boolean).map(decodeURIComponent);if(t.method==="GET"&&r.pathname==="/runtime/workspaces")return Jd(t),[{id:n.id,name:n.name}];if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="workspaces")return Zo(t,n.id,s[2]),lj(e.dal,n);if(t.method==="GET"&&s.length===5&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"){Zo(t,n.id,s[2]);let i=Nw(e.dal,s[4]);return Iw(e.dal,n,i)}if(t.method==="GET"&&r.pathname==="/runtime/lead-teams")return Jd(t),e.dal.listTeams().map(i=>mj(i));if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="chat"){let i=xw(e.dal,Aw(s[2])),o=await t.json();if(o.teamId!==`team:${i.name}`)throw new ie(400,"runtime lead chat body does not match route team");return Lw(t,n.id,o.context),Rw(i,o.context)}if(t.method==="POST"&&s.length===4&&s[0]==="runtime"&&s[1]==="lead-teams"&&s[3]==="messages"){let i=xw(e.dal,Aw(s[2])),o=await t.json();if(o.teamId!==`team:${i.name}`)throw new ie(400,"runtime lead message body does not match route team");Lw(t,n.id,o.context);let a=o.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime lead message requires draft.body");return Rw(i,o.context,a)}if(t.method==="POST"&&s.length===6&&s[0]==="runtime"&&s[1]==="workspaces"&&s[3]==="projects"&&s[5]==="workflow-message"){Zo(t,n.id,s[2]);let i=Nw(e.dal,s[4]),o=await t.json();if(o.workspaceId!==n.id||o.projectId!==i.name)throw new ie(400,"runtime request body does not match route workspace/project");let a=o.draft?.body;if(typeof a!="string"||a.length===0)throw new ie(400,"runtime workflow message requires draft.body");return uj(e.dal,i,a),Iw(e.dal,n,i)}if(t.method==="GET"&&r.pathname==="/runtime/templates")return As(t,n.id),e.dal.listWorkflows().map(i=>_j(i));if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="templates"){As(t,n.id);let i=gj(e.dal,s[2]);return hj(i)}if(t.method==="GET"&&r.pathname==="/runtime/runs"){As(t,n.id);let i=r.searchParams.get("project"),o=r.searchParams.get("template");if(i!==null&&o!==null)throw new ie(400,"conflicting_filters: ?project= and ?template= are mutually exclusive");return yj(e.dal,i,o).map(l=>$w(e.dal,l))}if(t.method==="GET"&&s.length===3&&s[0]==="runtime"&&s[1]==="runs"){As(t,n.id);let i=Ow(e.dal,s[2]);return $w(e.dal,i)}if(t.method==="GET"&&s.length===4&&s[0]==="runtime"&&s[1]==="runs"&&s[3]==="events"){As(t,n.id);let i=Ow(e.dal,s[2]),o=Ej(e.dal,i);return{runId:zd(i),events:o,...o.length>0?{cursor:o[o.length-1].id}:{}}}throw new ie(404,`unknown runtime request: ${t.method} ${r.pathname}`)}function lj(t,e){return{id:e.id,name:e.name,projects:t.listProjects().map(r=>jw(t,e,r))}}function Iw(t,e,r){let n=jw(t,e,r);return{...n,managedWorkflow:{...n.managedWorkflow,instance:cj(t,r),composerTarget:{kind:"workflow-initial",label:`Project Workflow: ${r.workflow_name}`,templateId:`template:${r.workflow_name}`,runId:n.managedWorkflow.runId}},workflowMessages:dj(t,r)}}function jw(t,e,r){let n=Dw(t,r.id),s=Kd(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 cj(t,e){let r=Dw(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:Kd(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 dj(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 uj(t,e,r){let n=fj(t,e.id);if(n!==null){let s=Yo(t,n.id);if(s?.kind==="workflow_escalation"){let i=t.resumeEscalation(s.attention_id,r);if(!i.resumed)throw new ie(409,`workflow escalation resume failed: ${i.reason}`);return}if(s?.kind==="interactive_waiting_operator"){let i=Nt(t,s.attention_id);if(i?.step_id===null||i?.step_id===void 0)throw new ie(409,"interactive resume failed: missing step");let o=t.resumeInteractive(i.step_id,r,!0);if(!o.resumed)throw new ie(409,`interactive resume failed: ${o.reason}`);return}}t.enqueueJob({project_id:e.id,source:"runtime-workflow-message",payload:JSON.stringify({prompt:r}),priority:0})}function Dw(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 fj(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 Kd(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 Nw(t,e){let r=t.findProjectByName(e);if(r===null)throw new ie(404,`project not found: ${e}`);return r}function xw(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 Aw(t){return t.startsWith("team:")?t.slice(5):t}function mj(t){return{id:`team:${t.name}`,name:t.name,teamfile:"",hasLead:!0,kind:t.name.toLowerCase().includes("manager")?"global-manager":"custom-ai-led"}}function Rw(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??Cw}`,teamId:`team:${t.name}`,title:`${t.name} Lead`,messages:s,...e===void 0?{}:{context:e}}}function pj(t){let e=t.workspaceName??Dt()??Nr.default;return{id:e,name:e}}function Jd(t){if(t.headers.get("x-lmctl-workspace-id")!==Cw)throw new ie(400,"runtime request requires global-admin workspace identity")}function Zo(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 As(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 Lw(t,e,r){if(r?.scope==="workspace"){if(r.workspaceId===void 0)throw new ie(400,"workspace manager context requires workspace identity");Zo(t,e,r.workspaceId);return}Jd(t)}function Vd(t){return`${vn}${Yd(t.name)}`}function Yd(t){return t.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"item"}function zd(t){return`${Gd}${t.id}`}function _j(t){let e=Qo(t.definition);return{id:Vd(t),name:t.name,...e.description===null?{}:{description:e.description}}}function hj(t){let e=Qo(t.definition);return{id:Vd(t),name:t.name,...e.description===null?{}:{description:e.description},graph:e.graph}}function Qo(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=[],i=new Map;if(r.schema_version==="lmctl/v3"&&Array.isArray(r.steps)){let o=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&&i.set(a.name,l))}o!==null&&s.includes(o)&&s.sort((a,l)=>a===o?-1:l===o?1:0)}return{description:n,graph:e,stepIds:s,nameToId:i}}function gj(t,e){if(!e.startsWith(vn))throw new ie(404,`template not found: ${e}`);let r=e.slice(vn.length),n=t.listWorkflows().filter(s=>Yd(s.name)===r);if(n.length===0)throw new ie(404,`template not found: ${e}`);if(n.length>1){let s=n.map(i=>i.name).join(", ");throw new ie(409,`template_id_ambiguous: ${e} matches multiple workflow names [${s}]; rename to ensure unique slugs`)}return n[0]}function Ow(t,e){if(!e.startsWith(Gd))throw new ie(404,`run not found: ${e}`);let r=e.slice(Gd.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 yj(t,e,r){if(r!==null){if(!r.startsWith(vn))return[];let s=r.slice(vn.length),i=t.listWorkflows().filter(a=>Yd(a.name)===s).map(a=>a.id);if(i.length===0)return[];let o=i.map(()=>"?").join(", ");return t.query(`SELECT * FROM run WHERE workflow_id IN (${o}) ORDER BY id DESC LIMIT 200`,...i)}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 $w(t,e){let r=t.getWorkflow(e.workflow_id),n=Kd(e),s=wj(r,e);return{id:zd(e),templateId:r===null?`${vn}unknown`:Vd(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 wj(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]:[Qo(t.definition).nameToId.get(r)??r]}function Ej(t,e){let r=t.getWorkflow(e.workflow_id),n=r===null?{stepIds:[],nameToId:new Map}:Qo(r.definition),s=c=>n.nameToId.get(c)??c,i=zd(e),o=[];o.push({timestamp:e.started_at,type:"run.started",message:"Run started"});let a=t.listStepsForRun(e.id);for(let c of a){let d=s(c.state_name);if(o.push({timestamp:c.started_at,type:"step.started",stepId:d,message:`step ${c.state_name} started`}),c.ended_at!==null){let u=Tj(c);o.push({timestamp:c.ended_at,type:u,stepId:d,...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&&o.push({timestamp:e.paused_at,type:"step.paused",stepId:d})}let l=t.listSessionEvents(e.id);for(let c of l){let d=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)})(),u=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{}o.push({timestamp:u,type:"message",...d===void 0?{}:{stepId:d},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";o.push({timestamp:e.ended_at??e.started_at,type:c,message:e.terminal_state})}return o.sort((c,d)=>c.timestamp.localeCompare(d.timestamp)),o.map((c,d)=>({id:`${i}:evt:${d+1}`,runId:i,sequence:d+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 Tj(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 Cw,vn,Gd,ie,Pw=E(()=>{"use strict";We();zo();qt();Cw="global-admin";vn="template:",Gd="run:";ie=class extends Error{status;constructor(e,r){super(r),this.status=e}}});import{mkdirSync as bj,writeFileSync as Sj}from"node:fs";import{randomUUID as Fw}from"node:crypto";import{dirname as vj,resolve as ea,sep as Uw}from"node:path";async function Bw(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(!Aj(n))return t.text("missing image file",400);if(n.size>kj)return t.text("upload too large",413);let s=Buffer.from(await n.arrayBuffer()),i=Rj(s);if(i===null||!(i in Ww))return t.text("unsupported upload MIME type",415);if(n.type.length>0&&n.type!==i)return t.text("upload MIME type does not match file content",415);let o=Ij(e,r.project);if(typeof o=="string")return t.text(o,404);let a=o===null?ea(xj()):ea(o.local_path),l=ea(a,"uploads",Fw()),c=ea(l,`${Fw()}${Ww[i]}`);if(!Nj(c,a))return t.text("invalid upload path",400);bj(l,{recursive:!0});let d=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);Sj(c,d);let u={path:c,size:s.byteLength,mime:i,project:o?.name??null};return t.json(u)}function Ij(t,e){return e==null||e===""?null:typeof e!="string"?"invalid project":t.findProjectByName(e)??`project not found: ${e}`}function Nj(t,e){let r=e.endsWith(Uw)?e:`${e}${Uw}`;return t.startsWith(r)}function xj(){return vj(Z())}function Aj(t){return typeof File<"u"&&t instanceof File}function Rj(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 kj,Ww,qw=E(()=>{"use strict";We();kj=10*1024*1024,Ww={"image/png":".png","image/jpeg":".jpg","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}});import{existsSync as ta}from"node:fs";import{basename as Lj,dirname as Oj,extname as $j,isAbsolute as Cj,join as Mj,relative as jj}from"node:path";import{fileURLToPath as Dj}from"node:url";import{Hono as Pj}from"hono";import{serveStatic as At}from"@hono/node-server/serve-static";function Yw(t){let e=new Pj,r=[],n=t.localWebui!==void 0?Qd(t.localWebui.webuiDir):Fj();if(t.localWebui!==void 0&&tw(e,{s3:t.localWebui.localMailbox.s3,commands:t.localWebui.localMailbox.commands}),n!==null){let s=Uj();t.localWebui!==void 0?e.get("/config.json",s,i=>i.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,i=>i.json(t.webuiRuntimeConfig)),e.use("/dist/*",s,At({root:n})),e.use("/vendor/*",s,At({root:n})),e.use("/src/*",s,At({root:n})),e.get("/",s,At({root:n,path:"index.html"})),e.get("/admin",s,At({root:n,path:"index.html"})),e.get("/admin/*",s,At({root:n,path:"index.html"})),e.get("/terminal",s,At({root:n,path:"index.html"})),e.get("/terminal/*",s,At({root:n,path:"index.html"})),e.get("/chat",s,At({root:n,path:"index.html"})),e.get("/chat/*",s,At({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("*",Lh({disabled:t.authDisabled})),e.get("/login",s=>s.html(Re("Login",`
|
|
2069
2151
|
<h1>Login</h1>
|
|
2070
2152
|
<form method="post" action="/login">
|
|
2071
2153
|
<label>Token <input name="token" type="password"></label>
|
|
2072
2154
|
<button type="submit">Login</button>
|
|
2073
2155
|
</form>
|
|
2074
|
-
`))),e.post("/login",async s=>{let i=await s.req.parseBody(),o=typeof i.token=="string"?i.token:"";return $h(o)?(nd(s,o),s.redirect("/",302)):s.html(Re("Login","<p>Invalid token</p>"),401)}),e.post("/logout",s=>(Ch(s),s.redirect("/login",302))),Uy(e,{dal:t.dal}),Mw(e,{dal:t.dal}),nw(e,{dal:t.dal}),pw(e,{terminalSessionManager:t.terminalSessionManager}),Ew(e,{persistentSessionManager:t.persistentSessionManager}),e.post("/api/teams/:team_name/refresh",async s=>{let i=ds(s.req.param("team_name")),o=t.dal.findTeamByName(i);if(o===null)return s.notFound();let a=[],c=t.dal.db.transaction(()=>{let f=t.dal.listTeamMembers(o.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 d=[],u=[];for(let f of a)try{await Nc(t.dal,i,f.alias),t.dal.setMemberState(f.id,"idle",null),d.push(f.alias)}catch(m){let p=m instanceof Error?m.message:String(m);t.dal.setMemberState(f.id,"attention_needed",`refresh failed: ${p}`),u.push({alias:f.alias,error:p})}return P(s,{team:i,seeded:d,failed:u},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>`)}),Wh(e,{dal:t.dal}),Kh(e,{dal:t.dal}),e.get("/api/status",s=>P(s,Hi(t.dal),Gj)),e.get("/api/projects",s=>P(s,Ji(t.dal),Kj)),e.get("/api/teams",s=>P(s,L_(t.dal),zj)),e.get("/api/workflows",s=>P(s,Xi(t.dal),Zj)),e.get("/api/workflows/verify",s=>{let i=vy();return s.req.header("accept")?.includes("text/plain")?s.text(Iy(i)):s.json(i)}),e.get("/api/jobs",s=>P(s,O_(t.dal,{status:s.req.query("status")}),Qj)),e.post("/api/uploads",s=>Bw(s,t.dal)),e.get("/api/jobs/:id",s=>{let i=Gi(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/jobs",async s=>{let i;try{i=await s.req.json()}catch{return s.text("invalid JSON body",400)}let o=null;if(typeof i.project_id=="number")o=i.project_id;else if(typeof i.project=="string"){let f=t.dal.findProjectByName(i.project);if(f===null)return s.text(`project not found: ${i.project}`,404);o=f.id}else{let f=t.dal.listProjects();f.length===1&&(o=f[0].id)}if(o===null)return s.text("missing project or project_id",400);let a=typeof i.workflow_id_override=="number"?i.workflow_id_override:null;if(a===null&&typeof i.workflow=="string"){let f=t.dal.getWorkflowByName(i.workflow);if(f===null)return s.text(`workflow not found: ${i.workflow}`,404);a=f.id}let l=typeof i.source=="string"?i.source:"manual",c=i.payload,d=c==null?null:typeof c=="string"?c:JSON.stringify(c),u=t.dal.enqueueJob({project_id:o,workflow_id_override:a,source:l,source_ref:typeof i.source_ref=="string"?i.source_ref:null,payload:d,priority:typeof i.priority=="number"?i.priority:0,dedupe_key:typeof i.dedupe_key=="string"?i.dedupe_key:null});return P(s,u,ue)}),e.post("/api/jobs/:id/run",async s=>{let{runJobById:i}=await Promise.resolve().then(()=>(jo(),jy)),o=Gi(t.dal,te(s,"id"));if(o===null)return s.notFound();let a=await i({dal:t.dal,worker_id:`api-job-run-${process.pid}-${Date.now()}`,job_id:o.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 i=t.dal.getWorkflowByName(s.req.param("name"));return i===null?s.notFound():P(s,i,ue)}),e.get("/api/projects/:name/workflows",s=>{let i=t.dal.findProjectByName(s.req.param("name"));return i===null?s.notFound():P(s,t.dal.listProjectWorkflows(i.id),Vj)}),e.post("/api/projects/:name/workflows",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.text(o,400);let a=typeof o.workflow=="string"?o.workflow:null,l=typeof o.workflow_id=="number"?o.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 d=typeof o.condition=="string"&&o.condition.length>0?o.condition:null;if(d!==null)try{un(d)}catch{return s.text("invalid condition",400)}let u=qj(o.parameters_override??o.params);if(typeof u=="string"&&u.startsWith("error:"))return s.text(u.slice(6),400);let f=typeof o.priority=="number"&&Number.isInteger(o.priority)?o.priority:100,m=t.dal.insertProjectWorkflow({project_id:i.id,workflow_id:c.id,condition:d,parameters_override:u,priority:f});return P(s,m,ue)}),e.get("/api/projects/workflows/:id",s=>{let i=t.dal.getProjectWorkflow(te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.delete("/api/projects/workflows/:id",s=>t.dal.removeProjectWorkflow(te(s,"id"))?P(s,{removed:!0},ue):s.notFound()),e.post("/api/projects/workflows/:id/enable",s=>{let i=t.dal.setProjectWorkflowEnabled(te(s,"id"),!0);return i===null?s.notFound():P(s,i,ue)}),e.post("/api/projects/workflows/:id/disable",s=>{let i=t.dal.setProjectWorkflowEnabled(te(s,"id"),!1);return i===null?s.notFound():P(s,i,ue)}),e.get("/api/projects/:name/issues",s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=Jw(s.req.query("status"),Hj);if(typeof o=="string")return s.text(o,400);let a=Jw(s.req.query("severity"),Zw);return typeof a=="string"?s.text(a,400):P(s,t.dal.listIssues(i.id,{...o!==void 0?{status:o}:{},...a!==void 0?{severity:a}:{},...s.req.query("ai_test_path")!==void 0?{ai_test_path:s.req.query("ai_test_path")}:{}}),Yj)}),e.post("/api/projects/:name/issues",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.text(o,400);let a=typeof o.title=="string"&&o.title.trim().length>0?o.title:null,l=typeof o.body=="string"?o.body:null;if(a===null||l===null)return s.text("missing title or body",400);let c=Jj(o.severity);if(typeof c=="object")return s.text(c.error,400);let d=Xj(o.labels);if(typeof d=="string"&&d.startsWith("error:"))return s.text(d.slice(6),400);let u=t.dal.createIssue({project_id:i.id,title:a,body:l,...c!==void 0?{severity:c}:{},labels:d,ai_test_path:typeof o.ai_test_path=="string"?o.ai_test_path:null,source_run_id:typeof o.source_run_id=="number"?o.source_run_id:null});return P(s,u,ue)}),e.get("/api/issues/:id",s=>{let i=t.dal.getIssue(te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/issues/:id/claim",async s=>{let i=te(s,"id"),o=t.dal.getIssue(i);if(o===null)return s.notFound();let a=await kn(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(i,l);return c===null?s.json({error:`issue ${i} is not in a claimable state (status=${o.status})`},400):P(s,c,ue)}),e.post("/api/projects/:name/issues/claim-next",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.json({error:"project_not_found"},404);let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.assigned_run_id=="number"?o.assigned_run_id:null;if(a===null)return s.json({error:"missing assigned_run_id"},400);let l=t.dal.claimNextIssue(i.id,a);return l===null?s.json({status:"queue_empty"},404):P(s,l,ue)}),e.post("/api/issues/:id/close",async s=>{let i=t.dal.getIssue(te(s,"id"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.closed_run_id=="number"?o.closed_run_id:i.assigned_run_id;if(a===null)return s.json({error:"missing closed_run_id"},400);try{return P(s,t.dal.closeIssue(te(s,"id"),a,typeof o.commit_hash=="string"?o.commit_hash:null),ue)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.post("/api/issues/:id/reopen",async s=>{let i=t.dal.getIssue(te(s,"id"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.source_run_id=="number"?o.source_run_id:i.closed_run_id??i.source_run_id;if(a===null)return s.json({error:"missing source_run_id"},400);try{return P(s,t.dal.reopenIssue(te(s,"id"),a),ue)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.get("/api/projects/:name",s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=i.name.indexOf("/"),a=o>0?i.name.slice(0,o):null,l=o>0?i.name.slice(o+1):i.name;return P(s,{...i,owner:a,repo:l},ue)}),e.get("/api/runs/:run_id/artifacts",s=>{let i=te(s,"run_id"),o=s.req.query("kind"),a=Mr(t.dal,i,o);return P(s,a,ue)}),e.get("/api/runs/:run_id/artifacts/:kind",async s=>{let i=te(s,"run_id"),o=s.req.param("kind"),a=Mr(t.dal,i,o);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):P(s,l,ue);if(l.path!==null&&l.path!==void 0){if(c)try{let{readFileSync:d}=await import("node:fs"),u=Wj(l.path);if(Bj(u)){let h=d(l.path,"utf8");return s.body(h,200,{"Content-Type":u})}let f=d(l.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),p=Lj(l.path);return s.body(m,200,{"Content-Type":u,"Content-Disposition":`attachment; filename="${p}"`})}catch(d){return s.text(`failed to read artifact path: ${d.message}`,500)}return P(s,l,ue)}return P(s,l,ue)}),e.get("/api/runs",s=>P(s,cn(t.dal,{limit:Zd(s,"limit")??100}),eD)),e.get("/api/runs/:id",s=>{let i=Cr(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,tD)}),e.get("/api/runs/:id/where",s=>{let i=dn(t.dal,te(s,"id"));return i===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(Vi(i)):s.json(i)}),e.get("/api/runs/:id/timeline",s=>{let i=Yi(t.dal,te(s,"id"));return i===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(zi(i)):s.json(i)}),e.post("/api/runs/:id/resume",async s=>{let i=s.req.query("outcome");if(i===void 0||i.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&&(i=c)}}if(i===void 0||i.length===0)return s.text("missing outcome",400);let o=t.dal.resumeRun(te(s,"id"),i);return!o.resumed&&o.reason==="run_not_found"?s.notFound():o.resumed?(ra(t.daemon),P(s,o,Xw)):P(s,o,Xw,400)}),e.post("/api/interactive/:step_id/respond",async s=>{let i=te(s,"step_id"),o,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let d=await s.req.json();typeof d.input=="string"&&(o=d.input),d.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let d=await s.req.parseBody().catch(()=>({}));typeof d.input=="string"&&(o=d.input),(d.done==="true"||d.done===!0)&&(a=!0)}if(o===void 0)return s.text("missing input",400);let c=t.dal.resumeInteractive(i,o,a);return!c.resumed&&c.reason==="not_found"?s.notFound():c.resumed?(ra(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=>Hw(s,t.dal,i=>P(s,i,nD))),e.get("/api/runs/:id/steps/:step_id/transcript",s=>{let i=j_(t.dal,te(s,"id"),te(s,"step_id"));return i===null?s.notFound():zw(s)?s.html(`<pre>${S(i)}</pre>`):s.req.header("accept")?.includes("text/plain")?s.text(i):s.json({transcript:i})}),e.get("/api/runs/:id/steps/:step_id/messages",s=>Hw(s,t.dal,i=>{let o=Sw(i);return P(s,o,a=>me(["role","text"],a.map(l=>[S(l.role),S(l.text)])))})),e.get("/api/external-objects",s=>P(s,D_(t.dal,{type:s.req.query("type")}),sD)),e.get("/api/external-signals",s=>P(s,P_(t.dal,{unhandled:s.req.query("unhandled")==="true"}),iD)),e.get("/api/attentions",s=>P(s,dr(t.dal,{unacked:s.req.query("unacked")==="true"}),oD)),e.post("/api/attentions/:id/ack",s=>{let i=t.dal.acknowledgeAttention(te(s,"id"));return i===null?s.notFound():P(s,i,o=>`<p>acknowledged attention ${S(o.id)}</p>`)}),e.get("/api/escalations",s=>{let i=s.req.query("project"),o=s.req.query("all")==="true",a=s.req.query("since"),l={all:o};i!==void 0&&(l.project=i),a!==void 0&&(l.since=a);let c=Ki(t.dal,l);return P(s,c,d=>`<h1>Escalations</h1>${me(["attention_id","project","run","workflow","state","prompt"],d.map(u=>[S(u.attention_id),S(u.project),S(u.run_id),S(u.workflow_name),S(u.state_name),S((u.prompt??"").slice(0,120))]))}`)}),e.get("/api/escalations/:id",s=>{let i=Nt(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/escalations/:id/respond",async s=>{let i=te(s,"id"),o,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let m=await s.req.json();typeof m.input=="string"&&(o=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"&&(o=m.input),(m.done==="true"||m.done===!0)&&(a=!0)}if(o===void 0)return s.text("missing input",400);let c=Nt(t.dal,i);if(c===null)return s.notFound();let d=dr(t.dal).find(m=>m.id===i);if(d===void 0)return s.notFound();if(d.kind==="workflow_escalation"){let m=t.dal.resumeEscalation(i,o);if(!m.resumed)return s.json({ok:!1,reason:m.reason},400);ra(t.daemon);let p=dr(t.dal).find(h=>h.id===i);return s.json({ok:!0,attention_id:i,run_id:m.run.id,decision:o,session_status:"escalation_resumed",acknowledged_at:p?.acknowledged_at??null})}if(d.kind!=="interactive_waiting_operator")return s.json({ok:!1,reason:"wrong_kind",kind:d.kind},400);if(d.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 u=t.dal.resumeInteractive(c.step_id,o,a);if(!u.resumed)return s.json({ok:!1,reason:u.reason,step_id:c.step_id},400);let f=t.dal.acknowledgeAttention(i);return ra(t.daemon),s.json({ok:!0,attention_id:i,step_id:c.step_id,session_status:u.session.status,acknowledged_at:f?.acknowledged_at??null})}),e.get("/api/submitted-prs",s=>{let i=s.req.query("pr_url"),o=s.req.query("status"),a=$_(t.dal,{status:o,pr_url:i});return P(s,a,aD)}),e.get("/api/submitted-prs/:id",s=>{let i=te(s,"id"),o=C_(t.dal,i);return o===null?s.notFound():P(s,o,lD)}),e.get("/api/sessions",s=>P(s,t.dal.latestSessionSizes(),Gw)),e.get("/api/sessions/:team_name/:alias/history",s=>{let i=ds(s.req.param("team_name"));return P(s,t.dal.sessionSizeHistory(i,s.req.param("alias")),Gw)}),e.post("/api/sessions/:team_name/:alias/compact",async s=>{let i=ds(s.req.param("team_name"));try{let o=await v_(t.dal,i,s.req.param("alias"));return P(s,o,a=>Kw("compacted",a.row))}catch(o){if(o instanceof cs)return s.text(o.message,409);throw o}}),e.post("/api/sessions/:team_name/:alias/refresh",async s=>{let i=ds(s.req.param("team_name")),o=await Nc(t.dal,i,s.req.param("alias"));return P(s,o,a=>Kw(`refreshed ${a.sessionid}`,a.row))}),e.get("/api/intake/state",s=>P(s,r,Vw)),e.post("/api/intake/scan",async s=>(r=await po(t.dal),P(s,r,Vw))),e.get("/api/stats/run-throughput",s=>P(s,W_(t.dal),cD)),e.get("/api/daemon/state",s=>P(s,t.daemon?.state??null,dD)),e.post("/api/daemon/cycle",async s=>{if(t.daemon===void 0)return P(s,{disabled:!0},ue);let i=await t.daemon.runCycle();return P(s,{state:t.daemon.state,result:i},ue)}),e.get("/metrics/:project_id",s=>{let i=te(s,"project_id"),o=t.dal.getProject(i);if(o===null)return s.notFound();let a=Cc(t.dal,i),l=Mc(t.dal,{project_id:i});return s.html(Re(`Metrics \u2014 ${o.name}`,uD(o.name,a,l)))}),e.get("/api/metrics/reviewer/:project_id",s=>{let i=te(s,"project_id");if(t.dal.getProject(i)===null)return s.notFound();let o=Zd(s,"since_days");return s.json(Cc(t.dal,i,o))}),e.get("/api/metrics/tools/:project_id",s=>{let i=te(s,"project_id");if(t.dal.getProject(i)===null)return s.notFound();let o=Zd(s,"since_days");return s.json(Mc(t.dal,{project_id:i,since_days:o}))}),e.post("/api/drift/:id/ack",s=>{let i=t.dal.acknowledgeDriftSignal(te(s,"id"));return i===null?s.notFound():s.json({id:i.id,acknowledged_at:i.acknowledged_at})}),e}function Hw(t,e,r){let n=$c(e,te(t,"id"),te(t,"step_id"));return n===null?t.notFound():r(n)}function ra(t){t!==void 0&&t.runCycle().catch(()=>{})}function P(t,e,r,n=200){return zw(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 zw(t){let e=t.req.header("accept")??"";return e.includes("text/html")&&!e.includes("application/json")}function Fj(){let t=process.env.LMCTL_WEBUI_DIST;if(t!==void 0)return ta(`${t}/index.html`)?Qd(t):null;let e="src/serve/webui-dist";if(ta(`${e}/index.html`))return e;let r="dist/serve/webui-dist";if(ta(`${r}/index.html`))return r;let n=Mj(Oj(Dj(import.meta.url)),"webui-dist");return ta(`${n}/index.html`)?Qd(n):null}function Qd(t){if(!Cj(t))return t;let e=jj(process.cwd(),t);return e.length===0?".":e}function Uj(){return async(t,e)=>{await e(),t.header("Cache-Control","no-store")}}function te(t,e){return Number(t.req.param(e))}function Zd(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 Wj(t){switch($j(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 Bj(t){return!!(t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/xml"))}async function kn(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 qj(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 Jw(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 Jj(t){if(t!=null)return typeof t=="string"&&Zw.includes(t)?t:{error:`invalid severity: ${String(t)}`}}function Xj(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 Gj(t){return`<h1>Status</h1><div class="grid">
|
|
2156
|
+
`))),e.post("/login",async s=>{let i=await s.req.parseBody(),o=typeof i.token=="string"?i.token:"";return $h(o)?(nd(s,o),s.redirect("/",302)):s.html(Re("Login","<p>Invalid token</p>"),401)}),e.post("/logout",s=>(Ch(s),s.redirect("/login",302))),Uy(e,{dal:t.dal}),Mw(e,{dal:t.dal}),nw(e,{dal:t.dal}),pw(e,{terminalSessionManager:t.terminalSessionManager}),Ew(e,{persistentSessionManager:t.persistentSessionManager}),e.post("/api/teams/:team_name/refresh",async s=>{let i=ds(s.req.param("team_name")),o=t.dal.findTeamByName(i);if(o===null)return s.notFound();let a=[],c=t.dal.db.transaction(()=>{let f=t.dal.listTeamMembers(o.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 d=[],u=[];for(let f of a)try{await Nc(t.dal,i,f.alias),t.dal.setMemberState(f.id,"idle",null),d.push(f.alias)}catch(m){let p=m instanceof Error?m.message:String(m);t.dal.setMemberState(f.id,"attention_needed",`refresh failed: ${p}`),u.push({alias:f.alias,error:p})}return P(s,{team:i,seeded:d,failed:u},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>`)}),Wh(e,{dal:t.dal}),Kh(e,{dal:t.dal}),e.get("/api/status",s=>P(s,Hi(t.dal),Gj)),e.get("/api/projects",s=>P(s,Xi(t.dal),Kj)),e.get("/api/teams",s=>P(s,L_(t.dal),zj)),e.get("/api/workflows",s=>P(s,Ji(t.dal),Zj)),e.get("/api/workflows/verify",s=>{let i=vy();return s.req.header("accept")?.includes("text/plain")?s.text(Iy(i)):s.json(i)}),e.get("/api/jobs",s=>P(s,O_(t.dal,{status:s.req.query("status")}),Qj)),e.post("/api/uploads",s=>Bw(s,t.dal)),e.get("/api/jobs/:id",s=>{let i=Gi(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/jobs",async s=>{let i;try{i=await s.req.json()}catch{return s.text("invalid JSON body",400)}let o=null;if(typeof i.project_id=="number")o=i.project_id;else if(typeof i.project=="string"){let f=t.dal.findProjectByName(i.project);if(f===null)return s.text(`project not found: ${i.project}`,404);o=f.id}else{let f=t.dal.listProjects();f.length===1&&(o=f[0].id)}if(o===null)return s.text("missing project or project_id",400);let a=typeof i.workflow_id_override=="number"?i.workflow_id_override:null;if(a===null&&typeof i.workflow=="string"){let f=t.dal.getWorkflowByName(i.workflow);if(f===null)return s.text(`workflow not found: ${i.workflow}`,404);a=f.id}let l=typeof i.source=="string"?i.source:"manual",c=i.payload,d=c==null?null:typeof c=="string"?c:JSON.stringify(c),u=t.dal.enqueueJob({project_id:o,workflow_id_override:a,source:l,source_ref:typeof i.source_ref=="string"?i.source_ref:null,payload:d,priority:typeof i.priority=="number"?i.priority:0,dedupe_key:typeof i.dedupe_key=="string"?i.dedupe_key:null});return P(s,u,ue)}),e.post("/api/jobs/:id/run",async s=>{let{runJobById:i}=await Promise.resolve().then(()=>(jo(),jy)),o=Gi(t.dal,te(s,"id"));if(o===null)return s.notFound();let a=await i({dal:t.dal,worker_id:`api-job-run-${process.pid}-${Date.now()}`,job_id:o.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 i=t.dal.getWorkflowByName(s.req.param("name"));return i===null?s.notFound():P(s,i,ue)}),e.get("/api/projects/:name/workflows",s=>{let i=t.dal.findProjectByName(s.req.param("name"));return i===null?s.notFound():P(s,t.dal.listProjectWorkflows(i.id),Vj)}),e.post("/api/projects/:name/workflows",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.text(o,400);let a=typeof o.workflow=="string"?o.workflow:null,l=typeof o.workflow_id=="number"?o.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 d=typeof o.condition=="string"&&o.condition.length>0?o.condition:null;if(d!==null)try{un(d)}catch{return s.text("invalid condition",400)}let u=qj(o.parameters_override??o.params);if(typeof u=="string"&&u.startsWith("error:"))return s.text(u.slice(6),400);let f=typeof o.priority=="number"&&Number.isInteger(o.priority)?o.priority:100,m=t.dal.insertProjectWorkflow({project_id:i.id,workflow_id:c.id,condition:d,parameters_override:u,priority:f});return P(s,m,ue)}),e.get("/api/projects/workflows/:id",s=>{let i=t.dal.getProjectWorkflow(te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.delete("/api/projects/workflows/:id",s=>t.dal.removeProjectWorkflow(te(s,"id"))?P(s,{removed:!0},ue):s.notFound()),e.post("/api/projects/workflows/:id/enable",s=>{let i=t.dal.setProjectWorkflowEnabled(te(s,"id"),!0);return i===null?s.notFound():P(s,i,ue)}),e.post("/api/projects/workflows/:id/disable",s=>{let i=t.dal.setProjectWorkflowEnabled(te(s,"id"),!1);return i===null?s.notFound():P(s,i,ue)}),e.get("/api/projects/:name/issues",s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=Xw(s.req.query("status"),Hj);if(typeof o=="string")return s.text(o,400);let a=Xw(s.req.query("severity"),Zw);return typeof a=="string"?s.text(a,400):P(s,t.dal.listIssues(i.id,{...o!==void 0?{status:o}:{},...a!==void 0?{severity:a}:{},...s.req.query("ai_test_path")!==void 0?{ai_test_path:s.req.query("ai_test_path")}:{}}),Yj)}),e.post("/api/projects/:name/issues",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.text(o,400);let a=typeof o.title=="string"&&o.title.trim().length>0?o.title:null,l=typeof o.body=="string"?o.body:null;if(a===null||l===null)return s.text("missing title or body",400);let c=Xj(o.severity);if(typeof c=="object")return s.text(c.error,400);let d=Jj(o.labels);if(typeof d=="string"&&d.startsWith("error:"))return s.text(d.slice(6),400);let u=t.dal.createIssue({project_id:i.id,title:a,body:l,...c!==void 0?{severity:c}:{},labels:d,ai_test_path:typeof o.ai_test_path=="string"?o.ai_test_path:null,source_run_id:typeof o.source_run_id=="number"?o.source_run_id:null});return P(s,u,ue)}),e.get("/api/issues/:id",s=>{let i=t.dal.getIssue(te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/issues/:id/claim",async s=>{let i=te(s,"id"),o=t.dal.getIssue(i);if(o===null)return s.notFound();let a=await kn(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(i,l);return c===null?s.json({error:`issue ${i} is not in a claimable state (status=${o.status})`},400):P(s,c,ue)}),e.post("/api/projects/:name/issues/claim-next",async s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.json({error:"project_not_found"},404);let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.assigned_run_id=="number"?o.assigned_run_id:null;if(a===null)return s.json({error:"missing assigned_run_id"},400);let l=t.dal.claimNextIssue(i.id,a);return l===null?s.json({status:"queue_empty"},404):P(s,l,ue)}),e.post("/api/issues/:id/close",async s=>{let i=t.dal.getIssue(te(s,"id"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.closed_run_id=="number"?o.closed_run_id:i.assigned_run_id;if(a===null)return s.json({error:"missing closed_run_id"},400);try{return P(s,t.dal.closeIssue(te(s,"id"),a,typeof o.commit_hash=="string"?o.commit_hash:null),ue)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.post("/api/issues/:id/reopen",async s=>{let i=t.dal.getIssue(te(s,"id"));if(i===null)return s.notFound();let o=await kn(s);if(typeof o=="string")return s.json({error:o},400);let a=typeof o.source_run_id=="number"?o.source_run_id:i.closed_run_id??i.source_run_id;if(a===null)return s.json({error:"missing source_run_id"},400);try{return P(s,t.dal.reopenIssue(te(s,"id"),a),ue)}catch(l){return s.json({error:l instanceof Error?l.message:String(l)},400)}}),e.get("/api/projects/:name",s=>{let i=t.dal.findProjectByName(s.req.param("name"));if(i===null)return s.notFound();let o=i.name.indexOf("/"),a=o>0?i.name.slice(0,o):null,l=o>0?i.name.slice(o+1):i.name;return P(s,{...i,owner:a,repo:l},ue)}),e.get("/api/runs/:run_id/artifacts",s=>{let i=te(s,"run_id"),o=s.req.query("kind"),a=Mr(t.dal,i,o);return P(s,a,ue)}),e.get("/api/runs/:run_id/artifacts/:kind",async s=>{let i=te(s,"run_id"),o=s.req.param("kind"),a=Mr(t.dal,i,o);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):P(s,l,ue);if(l.path!==null&&l.path!==void 0){if(c)try{let{readFileSync:d}=await import("node:fs"),u=Wj(l.path);if(Bj(u)){let h=d(l.path,"utf8");return s.body(h,200,{"Content-Type":u})}let f=d(l.path),m=f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength),p=Lj(l.path);return s.body(m,200,{"Content-Type":u,"Content-Disposition":`attachment; filename="${p}"`})}catch(d){return s.text(`failed to read artifact path: ${d.message}`,500)}return P(s,l,ue)}return P(s,l,ue)}),e.get("/api/runs",s=>P(s,cn(t.dal,{limit:Zd(s,"limit")??100}),eD)),e.get("/api/runs/:id",s=>{let i=Cr(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,tD)}),e.get("/api/runs/:id/where",s=>{let i=dn(t.dal,te(s,"id"));return i===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(Vi(i)):s.json(i)}),e.get("/api/runs/:id/timeline",s=>{let i=Yi(t.dal,te(s,"id"));return i===null?s.notFound():s.req.header("accept")?.includes("text/plain")?s.text(zi(i)):s.json(i)}),e.post("/api/runs/:id/resume",async s=>{let i=s.req.query("outcome");if(i===void 0||i.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&&(i=c)}}if(i===void 0||i.length===0)return s.text("missing outcome",400);let o=t.dal.resumeRun(te(s,"id"),i);return!o.resumed&&o.reason==="run_not_found"?s.notFound():o.resumed?(ra(t.daemon),P(s,o,Jw)):P(s,o,Jw,400)}),e.post("/api/interactive/:step_id/respond",async s=>{let i=te(s,"step_id"),o,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let d=await s.req.json();typeof d.input=="string"&&(o=d.input),d.done===!0&&(a=!0)}catch{return s.text("invalid JSON body",400)}else{let d=await s.req.parseBody().catch(()=>({}));typeof d.input=="string"&&(o=d.input),(d.done==="true"||d.done===!0)&&(a=!0)}if(o===void 0)return s.text("missing input",400);let c=t.dal.resumeInteractive(i,o,a);return!c.resumed&&c.reason==="not_found"?s.notFound():c.resumed?(ra(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=>Hw(s,t.dal,i=>P(s,i,nD))),e.get("/api/runs/:id/steps/:step_id/transcript",s=>{let i=j_(t.dal,te(s,"id"),te(s,"step_id"));return i===null?s.notFound():zw(s)?s.html(`<pre>${S(i)}</pre>`):s.req.header("accept")?.includes("text/plain")?s.text(i):s.json({transcript:i})}),e.get("/api/runs/:id/steps/:step_id/messages",s=>Hw(s,t.dal,i=>{let o=Sw(i);return P(s,o,a=>me(["role","text"],a.map(l=>[S(l.role),S(l.text)])))})),e.get("/api/external-objects",s=>P(s,D_(t.dal,{type:s.req.query("type")}),sD)),e.get("/api/external-signals",s=>P(s,P_(t.dal,{unhandled:s.req.query("unhandled")==="true"}),iD)),e.get("/api/attentions",s=>P(s,dr(t.dal,{unacked:s.req.query("unacked")==="true"}),oD)),e.post("/api/attentions/:id/ack",s=>{let i=t.dal.acknowledgeAttention(te(s,"id"));return i===null?s.notFound():P(s,i,o=>`<p>acknowledged attention ${S(o.id)}</p>`)}),e.get("/api/escalations",s=>{let i=s.req.query("project"),o=s.req.query("all")==="true",a=s.req.query("since"),l={all:o};i!==void 0&&(l.project=i),a!==void 0&&(l.since=a);let c=Ki(t.dal,l);return P(s,c,d=>`<h1>Escalations</h1>${me(["attention_id","project","run","workflow","state","prompt"],d.map(u=>[S(u.attention_id),S(u.project),S(u.run_id),S(u.workflow_name),S(u.state_name),S((u.prompt??"").slice(0,120))]))}`)}),e.get("/api/escalations/:id",s=>{let i=Nt(t.dal,te(s,"id"));return i===null?s.notFound():P(s,i,ue)}),e.post("/api/escalations/:id/respond",async s=>{let i=te(s,"id"),o,a=!1;if((s.req.header("content-type")??"").includes("application/json"))try{let m=await s.req.json();typeof m.input=="string"&&(o=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"&&(o=m.input),(m.done==="true"||m.done===!0)&&(a=!0)}if(o===void 0)return s.text("missing input",400);let c=Nt(t.dal,i);if(c===null)return s.notFound();let d=dr(t.dal).find(m=>m.id===i);if(d===void 0)return s.notFound();if(d.kind==="workflow_escalation"){let m=t.dal.resumeEscalation(i,o);if(!m.resumed)return s.json({ok:!1,reason:m.reason},400);ra(t.daemon);let p=dr(t.dal).find(h=>h.id===i);return s.json({ok:!0,attention_id:i,run_id:m.run.id,decision:o,session_status:"escalation_resumed",acknowledged_at:p?.acknowledged_at??null})}if(d.kind!=="interactive_waiting_operator")return s.json({ok:!1,reason:"wrong_kind",kind:d.kind},400);if(d.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 u=t.dal.resumeInteractive(c.step_id,o,a);if(!u.resumed)return s.json({ok:!1,reason:u.reason,step_id:c.step_id},400);let f=t.dal.acknowledgeAttention(i);return ra(t.daemon),s.json({ok:!0,attention_id:i,step_id:c.step_id,session_status:u.session.status,acknowledged_at:f?.acknowledged_at??null})}),e.get("/api/submitted-prs",s=>{let i=s.req.query("pr_url"),o=s.req.query("status"),a=$_(t.dal,{status:o,pr_url:i});return P(s,a,aD)}),e.get("/api/submitted-prs/:id",s=>{let i=te(s,"id"),o=C_(t.dal,i);return o===null?s.notFound():P(s,o,lD)}),e.get("/api/sessions",s=>P(s,t.dal.latestSessionSizes(),Gw)),e.get("/api/sessions/:team_name/:alias/history",s=>{let i=ds(s.req.param("team_name"));return P(s,t.dal.sessionSizeHistory(i,s.req.param("alias")),Gw)}),e.post("/api/sessions/:team_name/:alias/compact",async s=>{let i=ds(s.req.param("team_name"));try{let o=await v_(t.dal,i,s.req.param("alias"));return P(s,o,a=>Kw("compacted",a.row))}catch(o){if(o instanceof cs)return s.text(o.message,409);throw o}}),e.post("/api/sessions/:team_name/:alias/refresh",async s=>{let i=ds(s.req.param("team_name")),o=await Nc(t.dal,i,s.req.param("alias"));return P(s,o,a=>Kw(`refreshed ${a.sessionid}`,a.row))}),e.get("/api/intake/state",s=>P(s,r,Vw)),e.post("/api/intake/scan",async s=>(r=await po(t.dal),P(s,r,Vw))),e.get("/api/stats/run-throughput",s=>P(s,W_(t.dal),cD)),e.get("/api/daemon/state",s=>P(s,t.daemon?.state??null,dD)),e.post("/api/daemon/cycle",async s=>{if(t.daemon===void 0)return P(s,{disabled:!0},ue);let i=await t.daemon.runCycle();return P(s,{state:t.daemon.state,result:i},ue)}),e.get("/metrics/:project_id",s=>{let i=te(s,"project_id"),o=t.dal.getProject(i);if(o===null)return s.notFound();let a=Cc(t.dal,i),l=Mc(t.dal,{project_id:i});return s.html(Re(`Metrics \u2014 ${o.name}`,uD(o.name,a,l)))}),e.get("/api/metrics/reviewer/:project_id",s=>{let i=te(s,"project_id");if(t.dal.getProject(i)===null)return s.notFound();let o=Zd(s,"since_days");return s.json(Cc(t.dal,i,o))}),e.get("/api/metrics/tools/:project_id",s=>{let i=te(s,"project_id");if(t.dal.getProject(i)===null)return s.notFound();let o=Zd(s,"since_days");return s.json(Mc(t.dal,{project_id:i,since_days:o}))}),e.post("/api/drift/:id/ack",s=>{let i=t.dal.acknowledgeDriftSignal(te(s,"id"));return i===null?s.notFound():s.json({id:i.id,acknowledged_at:i.acknowledged_at})}),e}function Hw(t,e,r){let n=$c(e,te(t,"id"),te(t,"step_id"));return n===null?t.notFound():r(n)}function ra(t){t!==void 0&&t.runCycle().catch(()=>{})}function P(t,e,r,n=200){return zw(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 zw(t){let e=t.req.header("accept")??"";return e.includes("text/html")&&!e.includes("application/json")}function Fj(){let t=process.env.LMCTL_WEBUI_DIST;if(t!==void 0)return ta(`${t}/index.html`)?Qd(t):null;let e="src/serve/webui-dist";if(ta(`${e}/index.html`))return e;let r="dist/serve/webui-dist";if(ta(`${r}/index.html`))return r;let n=Mj(Oj(Dj(import.meta.url)),"webui-dist");return ta(`${n}/index.html`)?Qd(n):null}function Qd(t){if(!Cj(t))return t;let e=jj(process.cwd(),t);return e.length===0?".":e}function Uj(){return async(t,e)=>{await e(),t.header("Cache-Control","no-store")}}function te(t,e){return Number(t.req.param(e))}function Zd(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 Wj(t){switch($j(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 Bj(t){return!!(t.startsWith("text/")||t.startsWith("application/json")||t.startsWith("application/xml"))}async function kn(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 qj(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 Xw(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 Xj(t){if(t!=null)return typeof t=="string"&&Zw.includes(t)?t:{error:`invalid severity: ${String(t)}`}}function Jj(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 Gj(t){return`<h1>Status</h1><div class="grid">
|
|
2075
2157
|
<div class="metric"><strong>${t.jobs.queued}</strong><br>queued jobs</div>
|
|
2076
2158
|
<div class="metric"><strong>${t.jobs.done}</strong><br>done jobs</div>
|
|
2077
2159
|
<div class="metric"><strong>${t.runs.active}</strong><br>active runs</div>
|
|
@@ -2091,7 +2173,7 @@ ${p.text}`,["approve","request_changes"],!0,s,e.writes_to_project_path===!0)));i
|
|
|
2091
2173
|
</fieldset>
|
|
2092
2174
|
</form>
|
|
2093
2175
|
<div id="pause-result" style="margin-top:0.6em;"></div>
|
|
2094
|
-
</section>`}function nD(t){return`<section><h3>${S(t.state_name)}</h3>${ue(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
|
|
2176
|
+
</section>`}function nD(t){return`<section><h3>${S(t.state_name)}</h3>${ue(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 Jw(t){return t.resumed?`<p>resumed run ${S(t.run.id)}</p>`:`<p>resume failed: ${S(t.reason)}</p>`}function sD(t){return`<h1>External Objects</h1>${me(["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 iD(t){return`<h1>External Signals</h1>${me(["id","object","kind","handled"],t.map(e=>[S(e.id),S(e.object_id),S(e.kind),S(e.handled_at)]))}`}function oD(t){let e=`<style>
|
|
2095
2177
|
@keyframes attn-flicker { 0%,100%{background:#fff8e6;} 50%{background:#ffd766;} }
|
|
2096
2178
|
tr.requires-user { animation: attn-flicker 1.4s ease-in-out infinite; font-weight:600; }
|
|
2097
2179
|
tr.requires-user td:first-child::before { content:"\u2605 "; color:#d28e00; }
|
|
@@ -2144,23 +2226,23 @@ ${i.text}`;return Yt("mailbox_delivery_attempt_stalled",r,{stalled_after_ms:i.st
|
|
|
2144
2226
|
`);if(e[0]!=="---")throw new Rt("frontmatter must start at line 1 with `---` on its own line");let r={},n=-1;for(let o=1;o<e.length;o++){let a=e[o];if(a==="---"){n=o;break}if(a.trim()==="")continue;let l=a.match(/^([a-zA-Z][a-zA-Z0-9_-]*)\s*:\s*(.*)$/);if(!l)throw new Rt(`malformed frontmatter line ${o+1}: ${JSON.stringify(a)} (expected "key: value" or "---")`);let c=l[1],d=l[2].trim();if(!RD.has(c))throw new Rt(`unknown frontmatter key "${c}" \u2014 allowed keys: ${la.join(", ")}`);r[c]=d}if(n===-1)throw new Rt("frontmatter not closed (missing trailing `---` on its own line)");for(let o of la)if(r[o]===void 0)throw new Rt(`missing required frontmatter key "${o}" \u2014 required: ${la.join(", ")}`);let s=0;for(let o=0;o<=n;o++)s+=e[o].length+1;s>t.length&&(s=t.length);let i=r.members.split(",").map(o=>o.trim()).filter(Boolean);return{title:r.title,description:r.description,members:i,bodyOffset:s}}var la,RD,Rt,SE=E(()=>{"use strict";la=["title","description","members"],RD=new Set(la),Rt=class extends Error{constructor(e){super(e),this.name="FrontmatterError"}}});import{readFileSync as LD,writeFileSync as x8,renameSync as A8,existsSync as kE}from"node:fs";import{basename as OD,resolve as In,dirname as su}from"node:path";function CD(t){let e={},r=/(\w+)=(?:"([^"]*)"|([\S]*))/g,n;for(;(n=r.exec(t))!==null;){let s=n[1],i=n[2]!==void 0?n[2]:n[3];e[s]=i}return e}function MD(t){return/^\s*_MEMBER_\s+\S/.test(t)}function jD(t){return/^\s*_SESSION_\s+\S/.test(t)}function DD(t){return/^\s*_SKILL_(?:\s|$)/.test(t)}function ca(t){let e=OD(t);return e.endsWith(".lmctl")?e.slice(0,-6):e}function Ve(t){let e=LD(t,"utf-8"),r=su(In(t)),n=ou(e,ca(t),{baseDir:r,sourcePath:In(t)});for(let s of n.members)s.sessiondir&&!s.sessiondir.startsWith("/")&&(s.sessiondir=In(r,s.sessiondir));return n}function ou(t,e,r={}){let n=[],s=[];r.sourcePath,r.baseDir;let i=t;if(i.startsWith("#teamfile:")){let l=i.indexOf(`
|
|
2145
2227
|
`);i=l>=0?i.slice(l+1):""}let o=null;if(i.startsWith("---"))try{o=bE(i)}catch(l){if(l instanceof Rt)s.push(`frontmatter: ${l.message}`);else throw l}let a=t.split(`
|
|
2146
2228
|
`);for(let l=0;l<a.length;l++){let c=a[l],d=l+1;if(jD(c))throw new Error(`line ${d}: _SESSION_ is the legacy prefix. Rename to _MEMBER_. (line: ${c.trim()})`);if(DD(c)||!MD(c))continue;let u=CD(c);for(let p of Object.keys(u))if(!vE.includes(p))throw new Error(`line ${d}: unknown key "${p}" on _MEMBER_ line: ${c.trim()}
|
|
2147
|
-
allowed keys: ${vE.join(", ")}`);if(!u.provider&&!u.teamfile){s.push(`line ${d}: member line missing provider (or teamfile): ${c.trim()}`);continue}let m={alias:u.alias||`member${n.length+1}`,provider:u.provider||"",extra:{}};u.sessionid&&(m.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(m.sessiondir=u.sessiondir),u.teamfile&&(m.teamfile=u.teamfile),u.model&&(m.model=u.model),u.effort&&(m.effort=u.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function au(t,e){let r=[];for(let i of t.parseErrors)r.push({field:"session",message:i});let n=t.members.filter(i=>i.alias.toLowerCase()===iu.toLowerCase());n.length>1&&r.push({field:iu,message:`${n.length} alias=Lead found (max 1)`});let s=new Set;for(let i of t.members){let o=i.alias.toLowerCase();if(s.has(o)&&r.push({field:i.alias,message:`Duplicate alias "${i.alias}" (case-insensitive)`}),s.add(o),i.teamfile){let a=e?In(e,i.teamfile):In(i.teamfile);if(!kE(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ve(a),c=Lt(l);c?c.session||r.push({field:i.alias,message:`Team at ${i.teamfile} lead has no session ID. Run: lmctl seed`}):r.push({field:i.alias,message:`Team at ${i.teamfile} has no lead session`})}}else $D.has(i.provider)||r.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&r.push({field:i.alias,message:"sessiondir is empty"})}return r}function Lt(t){return t.members.find(e=>e.alias.toLowerCase()===iu.toLowerCase())}function lu(t,e,r,n={}){let s=n.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let i=In(e,t.teamfile),o=r??new Set;if(o.has(i))throw new Error(`Circular team reference: ${t.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!kE(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Ve(i),l=Lt(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return lu(l,su(i),o,n);if(s&&!l.session)throw new Error(`Team at ${i} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||su(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function da(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var iu,$D,vE,zt=E(()=>{"use strict";SE();iu="Lead",$D=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","ClaudeMock"]);vE=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as PD}from"node:crypto";import{existsSync as cu,readFileSync as FD,realpathSync as UD}from"node:fs";import{basename as IE,dirname as WD,resolve as NE}from"node:path";function ve(t,e){let r=NE(t);if(cu(r))return UD(r);if(e!==void 0){let n=
|
|
2229
|
+
allowed keys: ${vE.join(", ")}`);if(!u.provider&&!u.teamfile){s.push(`line ${d}: member line missing provider (or teamfile): ${c.trim()}`);continue}let m={alias:u.alias||`member${n.length+1}`,provider:u.provider||"",extra:{}};u.sessionid&&(m.session=u.sessionid),Object.prototype.hasOwnProperty.call(u,"sessiondir")&&(m.sessiondir=u.sessiondir),u.teamfile&&(m.teamfile=u.teamfile),u.model&&(m.model=u.model),u.effort&&(m.effort=u.effort),n.push(m)}return{name:e,members:n,rawText:t,parseErrors:s,frontmatter:o}}function au(t,e){let r=[];for(let i of t.parseErrors)r.push({field:"session",message:i});let n=t.members.filter(i=>i.alias.toLowerCase()===iu.toLowerCase());n.length>1&&r.push({field:iu,message:`${n.length} alias=Lead found (max 1)`});let s=new Set;for(let i of t.members){let o=i.alias.toLowerCase();if(s.has(o)&&r.push({field:i.alias,message:`Duplicate alias "${i.alias}" (case-insensitive)`}),s.add(o),i.teamfile){let a=e?In(e,i.teamfile):In(i.teamfile);if(!kE(a))r.push({field:i.alias,message:`Teamfile not found: ${a}`});else{let l=Ve(a),c=Lt(l);c?c.session||r.push({field:i.alias,message:`Team at ${i.teamfile} lead has no session ID. Run: lmctl seed`}):r.push({field:i.alias,message:`Team at ${i.teamfile} has no lead session`})}}else $D.has(i.provider)||r.push({field:i.alias,message:`Invalid provider "${i.provider}"`});i.sessiondir!==void 0&&i.sessiondir===""&&r.push({field:i.alias,message:"sessiondir is empty"})}return r}function Lt(t){return t.members.find(e=>e.alias.toLowerCase()===iu.toLowerCase())}function lu(t,e,r,n={}){let s=n.requireSession??!0;if(!t.teamfile)throw new Error(`Member "${t.alias}" is not a team reference`);let i=In(e,t.teamfile),o=r??new Set;if(o.has(i))throw new Error(`Circular team reference: ${t.alias} \u2192 ${i} (already visited: ${[...o].join(" \u2192 ")})`);if(o.add(i),!kE(i))throw new Error(`Teamfile not found: ${i} (referenced by alias "${t.alias}")`);let a=Ve(i),l=Lt(a);if(!l)throw new Error(`Team at ${i} has no lead session`);if(l.teamfile)return lu(l,su(i),o,n);if(s&&!l.session)throw new Error(`Team at ${i} lead has no session ID. Run: lmctl seed`);return{provider:l.provider,session:l.session??"",sessiondir:l.sessiondir||su(i),alias:t.alias,resolvedFrom:i,model:l.model,effort:l.effort}}function da(t,e){return t.members.find(r=>r.alias===e)??t.members.find(r=>r.alias.toLowerCase()===e.toLowerCase())}var iu,$D,vE,zt=E(()=>{"use strict";SE();iu="Lead",$D=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","ClaudeMock"]);vE=["alias","provider","sessionid","sessiondir","teamfile","model","effort"]});import{createHash as PD}from"node:crypto";import{existsSync as cu,readFileSync as FD,realpathSync as UD}from"node:fs";import{basename as IE,dirname as WD,resolve as NE}from"node:path";function ve(t,e){let r=NE(t);if(cu(r))return UD(r);if(e!==void 0){let n=XD(t,r,e);if(n!==null)return n}return r}function qD(t,e){let r=WD(e),n=ou(t,ca(e),{baseDir:r});for(let s of n.members)s.sessiondir!==void 0&&!s.sessiondir.startsWith("/")&&(s.sessiondir=NE(r,s.sessiondir));return n}function Fe(t,e){let r=ve(t,HD(e)?e:void 0);if(cu(r)){let s=FD(r,"utf8"),i=qD(s,r);return e!==void 0&&"upsertRootTeam"in e&&e.getRootTeam(r)===null&&JD(i)&&GD(e,r,i,s),i}let n=e?.getRootTeam(r)??null;throw n!==null?new Error(`teamfile missing on disk: ${r} (registered ${n.registered_at}; the file was renamed or deleted \u2014 seed the team at its new path)`):new Error(`teamfile not found: ${t}`)}function HD(t){return typeof t=="object"&&t!==null&&"getRootTeam"in t&&"listRootTeams"in t}function XD(t,e,r){let n=r.getRootTeam(t)??r.getRootTeam(e);if(n!==null)return n.teamfile_path;let s=IE(t),i=ca(t),o=r.listRootTeams().filter(l=>(IE(l.teamfile_path)===s||l.name===i)&&cu(l.teamfile_path));if(o.length===0)return null;if(o.length===1)return o[0].teamfile_path;let a=o.map(l=>l.teamfile_path).join(", ");throw new Error(`ambiguous teamfile "${t}" in root-team registry: ${a}; pass an absolute path`)}function JD(t){return t.parseErrors.length>0?!1:t.members.every(e=>e.teamfile!==void 0?!0:e.session!==void 0&&e.session.length>=BD)}function GD(t,e,r,n){let s={teamfile_path:e,name:r.name,raw_text:n,raw_sha256:PD("sha256").update(n).digest("hex"),registered_at:new Date().toISOString(),last_seeded_at:null};t.upsertRootTeam(s)}var BD,Zt=E(()=>{"use strict";zt();BD=5});import{existsSync as KD}from"node:fs";import{dirname as xE}from"node:path";function zD(t){return VD.test(t)||YD.test(t)}function AE(t){return ua.test(t)}function Hr(t){if(!t.includes(":"))return null;let e=t.lastIndexOf(":"),r=t.slice(0,e),n=t.slice(e+1);return!r.endsWith(".lmctl")||!ua.test(n)?null:{teamfile:r,alias:n}}function $e(t,e,r){if(!t.endsWith(".lmctl"))throw new we(`lmctl: "${t}" doesn't look like a teamfile (expected .lmctl extension).`);if(!AE(e))throw new we(`lmctl: "${e}" is not a valid alias (must match ${ua.source}).`);let n=ve(t,r);if(r===void 0&&!KD(n))throw new we(`lmctl: teamfile not found: ${t}`);let s;try{s=Fe(n,r)}catch(o){throw new we(`lmctl: ${t}: ${o instanceof Error?o.message:String(o)}`)}if(s.parseErrors.length>0)throw new we(`lmctl: ${t}: ${s.parseErrors.join("; ")}`);let i=da(s,e);if(i===void 0){let o=s.members.map(a=>a.alias).join(", ")||"(none)";throw new we(`lmctl: alias "${e}" not found in ${t}.
|
|
2148
2230
|
Known aliases: ${o}`)}if(i.teamfile!==void 0){let o=lu(i,xE(n));return{teamfile:n,alias:i.alias,provider:o.provider,sessionid:o.session,sessiondir:o.sessiondir,isLead:!0,...o.model??i.model?{model:o.model??i.model}:{},...o.effort??i.effort?{effort:o.effort??i.effort}:{}}}if(i.session===void 0)throw new we(`lmctl: alias "${i.alias}" in ${t} has no session ID yet.
|
|
2149
2231
|
Run: lmctl seed ${t}`);return{teamfile:n,alias:i.alias,provider:i.provider,sessionid:i.session,sessiondir:i.sessiondir??xE(n),isLead:Lt(s)?.alias===i.alias,...i.model!==void 0?{model:i.model}:{},...i.effort!==void 0?{effort:i.effort}:{}}}function wr(t,e){let{target:r,alias:n,flags:s}=e;if(s.run!==void 0||s.project!==void 0||s.workflow!==void 0){if(r!==void 0)return{mode:"error",message:`lmctl ${t.name}: --run/--project/--workflow (managed mode) are mutually exclusive with a positional target "${r}" \u2014 pick one form.`};let o={mode:"managed"};return s.run!==void 0&&(o.run=s.run),s.project!==void 0&&(o.project=s.project),s.workflow!==void 0&&(o.workflow=s.workflow),o}if(r!==void 0){let o=Hr(r);if(o!==null)return n!==void 0&&n!==o.alias?{mode:"error",message:`lmctl ${t.name}: got "${r}" AND second positional "${n}" \u2014 pick one form.`}:{mode:"ai-team",teamfile:o.teamfile,alias:o.alias};if(r.endsWith(".lmctl"))return n!==void 0?AE(n)?{mode:"ai-team",teamfile:r,alias:n}:{mode:"error",message:`lmctl ${t.name}: "${n}" is not a valid alias (must match ${ua.source}).`}:t.allowsBareTeamfile?{mode:"ai-team",teamfile:r}:{mode:"error",message:`lmctl ${t.name}: alias required.
|
|
2150
2232
|
Use: lmctl ${t.name} ${r}:<alias> or lmctl ${t.name} ${r} <alias>`};if(zD(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.
|
|
2151
2233
|
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}".
|
|
2152
2234
|
Expected one of: <path>.lmctl, <path>.lmctl:<alias>, <sessionid>.`}}if(s.session!==void 0){if(!t.supportsRaw)return{mode:"error",message:`lmctl ${t.name}: --session (raw mode) is not supported by ${t.name}.`};let o={mode:"ai-team-raw",sessionid:s.session};return s.provider!==void 0&&(o.provider=s.provider),o}return{mode:"error",message:`lmctl ${t.name}: a target is required.
|
|
2153
2235
|
Use: <path>.lmctl[:<alias>] | <path>.lmctl <alias> | <sessionid> | --run <id>`}}var we,VD,YD,ua,ht=E(()=>{"use strict";zt();Zt();we=class extends Error{constructor(e){super(e),this.name="ChatTargetError"}},VD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,YD=/^ses_[A-Za-z0-9_-]+$/,ua=/^[A-Za-z][A-Za-z0-9_-]*$/});function fa(t){return QD.has(t)}function uu(){return du===null&&(du=bt(vt())),du}function fu(t,e,r={}){if(!fa(t))return null;try{let n=uu().getAdapter?.(t);if(n===void 0)return null;let s=n.resumeCommand(e).trim();if(s.length===0)return null;let i=s.split(/\s+/),o=t==="codex"&&r.isLead===!0?_i({warn:()=>{}}):[],a=r.model!==void 0&&r.model.trim().length>0?ZD[t]?.(r.model):void 0;return r.model!==void 0&&r.model.trim().length>0&&a===void 0&&r.onModelIgnored?.({provider:t,model:r.model,reason:`${t} terminal resume does not implement per-session model selection`}),[...i,...a??[],...o,...RE[t]??[]]}catch{return null}}function ma(t,e,r={}){let n=fu(t,e,r);return n===null?null:n.join(" ")}function Ye(t,e){return uu().getSession(t,e)}async function Nn(t){return(await uu().resolveSessions(t)).map(r=>r.provider.name)}var RE,ZD,QD,LE,du,Er=E(()=>{"use strict";It();bl();RE={claude:["--dangerously-skip-permissions"],codex:["--dangerously-bypass-approvals-and-sandbox"],gemini:["-y"],copilot:["--yolo"],opencode:[],qwen:["--approval-mode","yolo"],agy:[],lmplayer:[]},ZD={claude:t=>["--model",t],codex:t=>["--model",t],gemini:t=>["--model",t],opencode:t=>["--model",t],qwen:t=>["--model",t],agy:t=>["--model",t],lmplayer:t=>["--model",t]},QD=new Set(Object.keys(RE)),LE=/^[\w.:-]+$/;du=null});function eP(t=process.env){let e=t.LMCTL_SESSION_IDLE_TIMEOUT_MS;if(e===void 0||e.trim()==="")return OE;let r=Number(e);return!Number.isFinite(r)||r<=0?OE:r}async function tP(t,e,r){try{let n=$e(e,r,t),s=n.sessionid;if(typeof s!="string"||s.trim()===""||s===".")return null;let i;if(typeof n.provider=="string"&&n.provider.trim()!=="")i=n.provider;else{let c=await Nn(s);if(c.length!==1)return null;i=c[0]}let o=await Ye(s,i);if(o===null)return null;let a=o.modifiedAt;if(!(a instanceof Date))return null;let l=a.getTime();return Number.isFinite(l)?Date.now()-l:null}catch{return null}}async function pa(t,e,r,n,s){if(!e.busy||e.reason!=="in-flight")return!1;let i=s??eP(),o=await tP(t,r,n),a=o!==null&&o>=i;return a&&C({event:"session_idle_reclaim",receiver_teamfile:r,receiver_alias:n,idle_ms:o,idle_minutes:o===null?null:Math.round(o/6e4),threshold_ms:i,reason:"in-flight holder idle past session-idle threshold; lease will be force-reclaimed"}),a}var OE,mu=E(()=>{"use strict";de();Er();ht();OE=36e5});function rP(t=process.env){let e=t.LMCTL_DAEMON_MAILBOX_RELAY_MAX_BATCHES;if(e===void 0||e.trim()==="")return $E;let r=Number(e);return!Number.isFinite(r)||r<=0?$E:Math.max(1,Math.trunc(r))}async function ME(t){let e=t.env??process.env,r=t.maxBatches??rP(e),n=cP(t.dal),s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0};lP(t.dal,e);let i=new Set;for(;s.scanned<r;){let o=t.dal.listRelayMailboxLanes(r).find(l=>!i.has(CE(l)));if(o===void 0)break;i.add(CE(o)),s.scanned+=1;let a=await nP(t.dal,n,e,o);s.delivered+=a.delivered,s.skipped_busy+=a.skipped_busy,s.skipped_terminal+=a.skipped_terminal,s.errors+=a.errors}return s}function CE(t){return JSON.stringify([t.sender_teamfile,t.sender_alias,t.receiver_teamfile,t.receiver_alias])}async function nP(t,e,r,n){let s={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},i=Vt(t,n.receiver_teamfile,n.receiver_alias),o=!1;if(i.busy){if(!await pa(t,i,n.receiver_teamfile,n.receiver_alias))return i.reason==="terminal-held"?{...s,skipped_terminal:1}:{...s,skipped_busy:1};o=!0}let a=null;try{let l=$e(n.receiver_teamfile,n.receiver_alias,t),c=gr(t,{receiver_teamfile:n.receiver_teamfile,receiver_alias:n.receiver_alias,sender_teamfile:n.sender_teamfile,sender_alias:n.sender_alias,ttlMs:yr(),...o?{force:!0}:{}});if(!c.acquired)return{...s,skipped_busy:1};if(a=c.lease,n.message_type==="response"){let u=await mE({sender:{teamfile:n.sender_teamfile,alias:n.sender_alias},receiver:{teamfile:n.receiver_teamfile,alias:n.receiver_alias,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:e,permissionMode:"yolo",env:r});return oP(u)}let d=await ia({sender:{teamfile:n.sender_teamfile,alias:n.sender_alias},receiver:{teamfile:n.receiver_teamfile,alias:n.receiver_alias,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:e,permissionMode:"yolo",env:r,finalize:"caller"});return iP(t,d)}catch(l){return sP(t,n,`relay delivery error: ${l instanceof Error?l.message:String(l)}`)}finally{if(a!==null)try{t.releaseAgentInflight(a)}catch{}}}function sP(t,e,r){let n={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0};try{let s=e.message_type==="response"?t.listEnqueuedResponseMailFromSender(e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias):t.listEnqueuedRequestMailFromSender(e.sender_teamfile,e.sender_alias,e.receiver_teamfile,e.receiver_alias),i=e.message_type==="response"?t.markMailDelivered(s.map(o=>o.id),r,new Date().toISOString()):t.markRelayRequestDeliveredAndEnqueueResponses(s,r,new Date().toISOString()).marked;return{...n,delivered:i,errors:1}}catch{return{...n,errors:1}}}function iP(t,e){let r={scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},n=aP(e),s=new Date().toISOString(),{marked:i}=t.markRelayRequestDeliveredAndEnqueueResponses(e.queued,n,s);return{...r,delivered:i,errors:e.status==="ok"?0:1}}function oP(t){return{...{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0},delivered:t.deliveredIds.length,errors:t.status==="ok"?0:1}}function aP(t){return t.status==="ok"?t.receipt:t.status==="stalled"?`relay delivery error: provider stalled${t.stalledAfterMs!==void 0?` after ${t.stalledAfterMs}ms`:""}
|
|
2154
|
-
${t.receipt}`:`relay delivery error: ${t.error}`}function lP(t,e){t.reclaimStaleMailboxDeliveries(new Date(Date.now()-tu(e)).toISOString())}function cP(t){return{stdout:{write:()=>{}},stderr:{write:()=>{}},dal:t}}var $E,jE=E(()=>{"use strict";Br();ru();aa();ht();mu();$E=10});function Rs(){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 uP(t=process.env){let e=t.LMCTL_DAEMON_FEATURES;if(e===void 0)return new Set(["mailbox-relay"]);if(e.trim()==="")return new Set;let r=new Set;for(let n of e.split(",")){let s=n.trim();if(s!==""){if(s==="all")return new Set(DE);dP.has(s)&&r.add(s)}}return r}function PE(t){let e=t.intervalMs??Rs(),r=t.runOnceFn??Ur,n=new Set(t.features??uP()),s={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,enabled_features:[...n].sort(),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,last_mailbox_relay_scanned:0,last_mailbox_relay_delivered:0,last_mailbox_relay_errors:0},i=null,o=null,a=null,l=null,c=null;n.has("rollup-updater")&&t.startRollupUpdaterFn!==!1&&(c=(t.startRollupUpdaterFn??eE)(t.dal));let d=m=>{s.running&&(i=setTimeout(()=>{f.runCycle().finally(()=>d(e))},m))},u=m=>{s.running&&(o=setTimeout(()=>{l===null&&(l=FE(t.dal,n,t.monitorSessionActivityFn??xc,e,s).finally(()=>{l=null})),l.finally(()=>u(Ac(t.dal,e)))},m))},f={state:s,runCycle:async()=>(a!==null||(a=fP(t.dal,r,t.collectSessionSizesFn??S_,t.scanIntakeFn??po,t.monitorSessionActivityFn??xc,t.mailboxRelayFn??ME,t.worker_id??"daemon",e,n,s).finally(()=>{a=null})),a),stop:async()=>{s.running=!1,i!==null&&clearTimeout(i),o!==null&&clearTimeout(o),c?.stop(),a!==null&&await a.catch(()=>{}),l!==null&&await l.catch(()=>{})}};if(s.running){let m=t.firstDelayMs??5e3;d(m),n.has("session-monitor")&&u(m)}return f}async function fP(t,e,r,n,s,i,o,a,l,c){c.in_flight=!0,c.last_started_at=new Date().toISOString(),c.last_error=null;let d=[],u=0,f=0,m=[],p=null,h=mP();try{if(l.has("durable-memory-policies")&&Ry({dal:t}),l.has("drift-detectors")&&nE({dal:t}),l.has("intake")&&(m=await n(t)),l.has("job-worker"))for(;;){let g=await e({dal:t,worker_id:o,lease_ms:6e5});if(g===null)break;d.push(g)}if(l.has("mailbox-relay")&&(h=await i({dal:t})),l.has("session-size")){let g=await r(t);u=g.recorded,f=g.failed}l.has("session-monitor")&&(p=await FE(t,l,s,a,c))}catch(g){c.last_error=g instanceof Error?g.message:String(g);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:c.last_error})})}catch{}}finally{c.in_flight=!1,c.cycles+=1,c.last_jobs_processed=d.length,c.last_session_sizes_recorded=u,c.last_session_size_failures=f,c.last_intake_scanned=m.reduce((g,_)=>g+_.scanned,0),c.last_intake_new_jobs=m.reduce((g,_)=>g+_.new_jobs,0),c.last_intake_failures=m.filter(g=>g.error!==void 0).length,c.last_session_hung_detected=p?.hung_detected??0,c.last_mailbox_relay_scanned=h.scanned,c.last_mailbox_relay_delivered=h.delivered,c.last_mailbox_relay_errors=h.errors,c.jobs_processed+=d.length,c.last_finished_at=new Date().toISOString()}return{jobs_processed:d.length,outcomes:d,session_sizes_recorded:u,session_size_failures:f,intake:m,session_monitor:p,mailbox_relay:h}}function mP(){return{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0}}async function FE(t,e,r,n,s){if(!e.has("session-monitor"))return null;let i=Ac(t,n),o=Date.now();if(s.last_session_monitor_checked_at!==null){let a=Date.parse(s.last_session_monitor_checked_at);if(Number.isFinite(a)&&o-a<i)return null}s.last_session_monitor_checked_at=new Date(o).toISOString(),s.last_session_monitor_error=null;try{return await r({dal:t,nowMs:o})}catch(a){s.last_session_monitor_error=a instanceof Error?a.message:String(a);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:s.last_session_monitor_error})})}catch{}return null}}var DE,dP,pu=E(()=>{"use strict";Qc();jo();Rd();Ui();tE();sE();Rc();jE();DE=["durable-memory-policies","drift-detectors","intake","job-worker","mailbox-relay","session-size","session-monitor","rollup-updater"],dP=new Set(DE)});function UE(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 WE=E(()=>{"use strict"});import{mkdirSync as pP,readFileSync as _P,readdirSync as hP,statSync as gP,writeFileSync as yP}from"node:fs";import{dirname as wP,join as qE,sep as BE}from"node:path";function _a(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case HE:return EP(t,s.input);case JE:return TP(t,s.input);case XE:return bP(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:gu,GetObjectCommand:hu,PutObjectCommand:_u}}}function EP(t,e){let r=GE(t,e.Key);return pP(wP(r),{recursive:!0}),yP(r,e.Body),{}}function TP(t,e){let r=GE(t,e.Key),n;try{n=_P(r)}catch(i){throw i.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):i}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function bP(t,e){let r=e.Prefix??"";KE(r);let s=SP(t).sort((d,u)=>d.key<u.key?-1:d.key>u.key?1:0).filter(d=>d.key.startsWith(r)),i=e.ContinuationToken;i!==void 0&&i!==""&&(s=s.filter(d=>d.key>i));let o=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;o!==void 0&&s.length>o&&(a=s.slice(0,o),l=!0);let c={Contents:a.map(d=>({Key:d.key,LastModified:d.lastModified})),IsTruncated:l};return l&&(c.NextContinuationToken=a[a.length-1].key),c}function GE(t,e){return KE(e),qE(t,e)}function KE(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function SP(t){let e=[],r=(n,s)=>{let i;try{i=hP(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of i){let a=s===""?o.name:`${s}/${o.name}`,l=qE(n,o.name);if(o.isDirectory())r(l,a);else if(o.isFile()){let c=BE==="/"?a:a.split(BE).join("/");e.push({key:c,lastModified:gP(l).mtime})}}};return r(t,""),e}var HE,JE,XE,_u,hu,gu,yu=E(()=>{"use strict";HE="localfs-put",JE="localfs-get",XE="localfs-list",_u=class{input;_localfsTag=HE;constructor(e){this.input=e}},hu=class{input;_localfsTag=JE;constructor(e){this.input=e}},gu=class{input;_localfsTag=XE;constructor(e){this.input=e}}});function VE(){return{put:0,get:0,list:0}}function wu(t,e=vP){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function Eu(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var vP,ha,Tu=E(()=>{"use strict";vP={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};ha=class{counts=VE();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=VE(),e}estimateCostUsd(e){return wu(this.counts,e)}}});function YE(t){let e=t.now??Date.now,r=t.timers??kP,n=null,s=null;async function i(){let l=e(),c=Eu(l),d=t.meter.drain();(d.put>0||d.get>0||d.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:c,put:d.put,get:d.get,list:d.list,updated_at:new Date(l).toISOString()});let u=t.store.loadUsage(t.userId,t.deviceId,c),f=u?{put:u.put_count,get:u.get_count,list:u.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(c,f)}catch(h){t.log?.(`[usage] publish rollup failed: ${h instanceof Error?h.message:String(h)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(c)}catch(h){t.log?.(`[usage] read user total failed: ${h instanceof Error?h.message:String(h)}`),m=f}let p=wu(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(h){t.log?.(`[usage] onQuotaExceeded threw: ${h instanceof Error?h.message:String(h)}`)}}}function o(){return s=(s??Promise.resolve()).then(()=>i()).catch(()=>{}),s}let a=r.setInterval(()=>{o()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return o()},isOverQuota(){return n!==null&&n===Eu(e())}}}var kP,zE=E(()=>{"use strict";Tu();kP={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var bu=E(()=>{"use strict";Wo();qo();qo()});function IP(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 i=s;return typeof i.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:i}}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 NP(t){return t.reply_to!==void 0&&t.response!==void 0}function xP(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function ZE(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,Ls,QE=E(()=>{"use strict";bu();ga=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},Ls=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=Kt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let i=r?.conversationId??s,o={message_id:s,request:e};return new Promise((a,l)=>{let c=r?.abortSignal,d;if(c!==void 0){if(c.aborted){l(ZE(c));return}d=()=>{this.pending.has(s)&&(this.pending.delete(s),l(ZE(c)))},c.addEventListener("abort",d,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...d!==void 0?{abortListener:d}:{},...c!==void 0?{abortSignal:c}:{}}),this.client.putMessage({conversation_id:i,payload:o}).catch(u=>{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(u))})})}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=IP(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(NP(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??xP(e)??n.message_id,i;try{i=await this.requestHandler(n.request)}catch(l){let c=l instanceof Error?l.message:String(l),d=typeof l.code=="string"?l.code:"INTERNAL_ERROR";i={status:500,headers:{"content-type":"application/json"},body:{error:d,message:c}}}let a={message_id:Kt(this.now(),this.random),reply_to:n.message_id,response:i};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 Su(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 eT=E(()=>{"use strict"});function vu(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 tT=E(()=>{"use strict"});function Iu(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 ku,rT=E(()=>{"use strict";ku="daemon:events"});function sT(t){return{kind:"prompt",prompt_id:t.prompt_id??Kt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function Nu(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 nT,xu=E(()=>{"use strict";bu();nT="prompt:root"});function Os(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(oT(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function AP(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(oT(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function iT(t,e=60){if(typeof t!="string"||t==="")return!0;let r=AP(t);return r===null?!0:Date.now()/1e3>=r-e}function oT(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 Au=E(()=>{"use strict"});async function ya(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":RP},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 o=JSON.parse(s).AuthenticationResult,a=o?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof o?.AccessToken=="string"&&o.AccessToken!==""?{accessToken:o.AccessToken}:{},...typeof o?.ExpiresIn=="number"&&Number.isFinite(o.ExpiresIn)?{expiresAt:Date.now()+o.ExpiresIn*1e3}:{}}}var RP,Ru=E(()=>{"use strict";RP="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as aT,mkdirSync as lT,readFileSync as cT,writeFileSync as dT}from"node:fs";import{homedir as uT}from"node:os";import{dirname as fT,join as mT}from"node:path";function $s(){return process.env.LMCTL_DEVICE_AUTH_PATH??mT(uT(),".lmctl","device-auth.json")}function pT(){return process.env.LMCTL_TOKEN_PATH??mT(uT(),".lmctl","cli-tokens.json")}function Lu(t=$s()){try{let e=JSON.parse(cT(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 _T(t,e=$s()){lT(fT(e),{recursive:!0,mode:448}),dT(e,JSON.stringify(t,null,2));try{aT(e,384)}catch{}}function Ou(t,e=pT()){let r={};try{r=JSON.parse(cT(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};lT(fT(e),{recursive:!0,mode:448}),dT(e,JSON.stringify(s,null,2));try{aT(e,384)}catch{}}async function hT(t){let e=t.deviceAuthPath??$s(),r=Lu(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await ya({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return Ou({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??pT()),{idToken:n.idToken,userId:r.userId}}var $u=E(()=>{"use strict";Ru()});import{existsSync as LP,realpathSync as OP}from"node:fs";import{dirname as $P}from"node:path";function Cu(t){CP(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function CP(t){let e=t.payload.root_teamfile;try{e=OP(t.payload.root_teamfile)}catch(s){let i=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${s instanceof Error?s.message:String(s)}`;return xn({rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"root_unavailable"}),t.log?.(`[mailbox] ${i}`),{status:"error",response:null,error_detail:i}}if(t.store.getRootTeam(e)===null){let s=`prompt root is not registered: ${e}`;return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:s,reason:"root_unregistered"}),t.log?.(`[mailbox] ${s}`),{status:"error",response:null,error_detail:s}}let r=jP(e);if("error"in r)return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:r.error,reason:"root_invalid"}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=gr(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:UP(t.env??process.env)});if(!n.acquired){let s=FP(r.alias,n.current);return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:s,reason:"unavailable"}),t.log?.(`[mailbox] prompt rejected: ${s}`),{status:"error",response:null,error_detail:s}}try{let i=await(t.chat??kt)({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}:{}}),o=i.status==="stalled",a=!o&&i.text.trim()==="",l=o?`provider stalled${i.stalledAfterMs!==void 0?` after ${i.stalledAfterMs}ms`:""}`:a?"provider returned empty response":null,c=o||a?"error":"ok";return c==="ok"?await DP(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:i.text,status:c,error_detail:null,log:t.log}):xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:l??"provider failed",reason:o?"stalled":"empty_response"}),{status:c,response:c==="error"?null:i.text,error_detail:l}}catch(s){let i=s instanceof Error?s.message:String(s);return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"provider_error"}),t.log?.(`[mailbox] prompt provider error: ${i}`),{status:"error",response:null,error_detail:i}}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 xn(t){C({event:"prompt_trigger_error",reason:t.reason,prompt_id:t.promptId,root_teamfile:t.rootTeamfile,sender_teamfile:t.rootTeamfile,sender_alias:"operator",receiver_teamfile:t.receiverTeamfile,receiver_alias:t.receiverAlias,error_detail:t.detail,message_preview:MP(t.message)})}function MP(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function jP(t){if(!LP(t))return{error:`prompt root missing/unreadable: ${t}`};let e=Ve(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=Lt(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??$P(t)}}async function DP(t,e){let r=wT(e.message),n=e.response===null?null:wT(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 wT(t){return t.length<=gT?{text:t,truncated:!1}:{text:t.slice(0,gT),truncated:!0}}function PP(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function FP(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:PP(t,e)}function UP(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return yT;let r=Number(e);return!Number.isFinite(r)||r<=0?yT:r}var gT,yT,ET=E(()=>{"use strict";It();zt();de();Br();gT=256*1024,yT=30*60*1e3});import{chmodSync as IT,existsSync as WP,mkdirSync as NT,readFileSync as ba,writeFileSync as xT}from"node:fs";import{dirname as Mu,resolve as wa,join as AT}from"node:path";import{fileURLToPath as BP}from"node:url";import{homedir as RT}from"node:os";import{CognitoIdentityClient as qP,GetIdCommand as HP}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as TT}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as JP,ListObjectsV2Command as XP,PutObjectCommand as GP,S3Client as bT}from"@aws-sdk/client-s3";function Ms(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:ZP(t.selfUrl),n={},s;for(let I of r)if(WP(I)){n=zP(I),s=I;break}let i=(...I)=>{for(let x of I)if(typeof x=="string"&&x!=="")return x},o=i(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??KP,a=i(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??VP,l=i(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??YP,c=i(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",d=i(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Sa,u=[];o===void 0&&u.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&u.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&u.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:u,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(u.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,h=Ta(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=Ta(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),_=Ta(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),y=Ta(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),T=i(e.LMCTL_MAILBOX_KEY),b=i(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:o,cognitoUserPoolId:a,cognitoClientId:d,region:c,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},...h!==void 0?{readIntervalMs:h}:{},...g!==void 0?{heartbeatIdleMs:g}:{},..._!==void 0?{backoffReadIntervalMs:_}:{},...y!==void 0?{chatLogPollIntervalMs:y}:{},...T!==void 0?{mailboxKey:T}:{},...b!==void 0?{tokenPath:b}:{}},f}function zP(t){try{let e=ba(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[i,o]of Object.entries(n))o!==null&&typeof o=="object"&&typeof o.value=="string"&&(s[i]=o.value);return s}catch{return{}}}function ZP(t){let e=Mu(BP(t??import.meta.url));return[wa(e,"..","..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","infra","terraform","terraform.tfstate")]}function Ta(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function QP(t){let e=eF(t.intervalMs)??LT,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,i,o=!1,a=!1,l=()=>{try{if(s!==null){let u=s.load(s.key);if(u!==null)return i=u.last_pushed_id,!0}return i=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:i,updated_at:new Date(n()).toISOString()}),!0}catch(u){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${u instanceof Error?u.message:String(u)}`),!1}};l();let c=async()=>{if(!(a||o)){o=!0;try{if(i===void 0&&!l())return;let u=t.store.listTeamChatLogSinceId(i,r);for(let f of u){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()}),i=Math.max(i,f.id)}}catch(u){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${u instanceof Error?u.message:String(u)}`)}finally{o=!1}}},d=setInterval(()=>{c()},e);return typeof d.unref=="function"&&d.unref(),{pollNow:c,stop(){a=!0,clearInterval(d)}}}function eF(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function OT(t){let e=t.tokenPath??AT(RT(),".lmctl","cli-tokens.json"),r=vT(t.tokenPath);if(iT(r.cognito?.idToken)&&Lu()!==null)try{await hT({region:t.region,clientId:t.cognitoClientId??Sa,cliTokensPath:e}),r=vT(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(A){let ee=A instanceof Error?A.message:String(A);t.log?.(`[mx-mailbox] device-auth refresh failed: ${ee}`)}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}`,i=r.cognito.identityId,o=!1;i===void 0||i===""?i=await kT({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(o=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${i}`));let a=TT({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bT({region:t.region,credentials:a}),c={ListObjectsV2Command:XP,GetObjectCommand:JP,PutObjectCommand:GP},d=Os(n),u=d??i,f=t.deviceId,m=Tn({identityId:i,userId:d,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,h;if(p!==void 0){let A=p.loadMailboxCursor(u,m);if(A!==null)h=A.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${h??"(sentinel)"} for user_id=${u}`);else{let ee=!1,B=0;for(;!ee&&B<2;){B+=1;try{let k=Fo(m,"web"),N=0,L;do{let W=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:k,MaxKeys:1e3,...L!==void 0?{ContinuationToken:L}:{}}));for(let D of W.Contents??[]){let M=Uo(D.Key??"",m,"web");M!==void 0&&M>N&&(N=M)}L=W.IsTruncated===!0?W.NextContinuationToken:void 0}while(L!==void 0);h=N,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${N} for user_id=${u}`),ee=!0}catch(k){let N=k instanceof Error?k.message:String(k);if(o&&B===1&&nF(k)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${N}); clearing + refreshing`),rF(e),o=!1,i=await kT({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=TT({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bT({region:t.region,credentials:a}),m=Tn({identityId:i,userId:d,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${N}`);break}}p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:h??null,last_processed_at:new Date().toISOString()})}}let g=null,_=t.terminalSessionManager,y=t.persistentSessionManager,T=t.promptTriggerStore,b=new ha,I=new Wr({bucket:t.mailboxBucket,identityId:i,...d!==null?{userId:d}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:c,selfRole:"agent",onS3Op:A=>b.record(A),onMessage:async A=>{if(_!==void 0&&Su(A.payload)){_.onInbound(A.payload);return}if(y!==void 0&&vu(A.payload)){await y.onInbound(A.payload);return}if(!Iu(A.payload)){if(T!==void 0&&Nu(A.payload)){Cu({store:T,payload:A.payload,log:t.log});return}g!==null&&await g.handleIncoming(A.payload,A)}},...p!==void 0?{onCursorAdvance:A=>{p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:A,last_processed_at:new Date().toISOString()})}}:{},...h!==void 0?{cursor:h}:{},...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 Ls({client:I,...t.log!==void 0?{log:t.log}:{}}),_!==void 0&&_.setPublish(async A=>I.putMessage({conversation_id:`terminal:${A.session_id}`,payload:A})),y!==void 0&&y.setPublish(async A=>I.putMessage({conversation_id:`provider:${A.session_id}`,payload:A}));let x=A=>I.putMessage({conversation_id:ku,payload:A});I.start();let H=t.chatLogTailStore===void 0?void 0:QP({store:t.chatLogTailStore,publishDaemonEvent:x,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??LT,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let pe=t.deviceId??i,U=`${u}/usage/`,j;return j=t.usageStore===void 0?void 0:YE({meter:b,store:t.usageStore,userId:u,deviceId:pe,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:A,costUsd:ee,ceilingUsd:B})=>{t.log?.(`[usage] month ${A} cost $${ee.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),I.stop().catch(()=>{}),j?.stop()},publishOwnRollup:async(A,ee)=>{await l.send(new c.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${U}${pe}-${A}.json`,Body:JSON.stringify({...ee,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async A=>{let ee={put:0,get:0,list:0},B;do{let k=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:U,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let N of k.Contents??[]){let L=N.Key??"";if(L.endsWith(`-${A}.json`))try{let W=await l.send(new c.GetObjectCommand({Bucket:t.mailboxBucket,Key:L}));if(W.Body===void 0)continue;let D=JSON.parse(await W.Body.transformToString("utf-8"));ee.put+=D.put??0,ee.get+=D.get??0,ee.list+=D.list??0}catch{}}B=k.IsTruncated===!0?k.NextContinuationToken:void 0}while(B!==void 0);return ee},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:i,mailbox:I,fetchClient:g,publishDaemonEvent:x,async stop(){H?.stop(),j!==void 0&&(await j.flushNow().catch(()=>{}),j.stop()),await g.stop().catch(()=>{}),await I.stop().catch(()=>{})}}}async function $T(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:_a(t.rootDir),r=Tn({identityId:Cs,userId:Cs,deviceId:ST}),n=null,s=t.terminalSessionManager,i=t.persistentSessionManager,o=t.promptTriggerStore,a=new Wr({bucket:"local",identityId:Cs,userId:Cs,deviceId:ST,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async c=>{if(s!==void 0&&Su(c.payload)){s.onInbound(c.payload);return}if(i!==void 0&&vu(c.payload)){await i.onInbound(c.payload);return}if(!Iu(c.payload)){if(o!==void 0&&Nu(c.payload)){Cu({store:o,payload:c.payload,log:t.log});return}n!==null&&await n.handleIncoming(c.payload,c)}},pollIntervalMs:t.pollIntervalMs??Ea,readIntervalMs:t.readIntervalMs??Ea,heartbeatIdleMs:t.heartbeatIdleMs??Ea,backoffReadIntervalMs:t.backoffReadIntervalMs??Ea});n=new Ls({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})),i!==void 0&&i.setPublish(async c=>a.putMessage({conversation_id:`provider:${c.session_id}`,payload:c}));let l=c=>a.putMessage({conversation_id:ku,payload:c});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:Cs,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function vT(t){let e=t??AT(RT(),".lmctl","cli-tokens.json");try{let r=ba(e,"utf8");return JSON.parse(r)}catch{return{}}}function tF(t,e){if(e===void 0||e==="")return;let r={};try{let s=ba(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};NT(Mu(t),{recursive:!0,mode:448}),xT(t,JSON.stringify(n,null,2));try{IT(t,384)}catch{}}function rF(t){let e={};try{let n=ba(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,NT(Mu(t),{recursive:!0,mode:448}),xT(t,JSON.stringify(r,null,2));try{IT(t,384)}catch{}}async function kT(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new qP({region:t.region}).send(new HP({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{tF(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 nF(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 LT,Ea,Sa,KP,VP,YP,Cs,ST,ju=E(()=>{"use strict";Ho();yu();Tu();zE();QE();eT();tT();rT();xu();Wo();Au();$u();ET();LT=3e3,Ea=1e3,Sa="79u5jhkk46qofog661c9i0bdcs",KP="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",VP="us-east-1_4iUdFggDn",YP="lmctl-next-preview-mailbox-254332045686";Cs="local",ST="local"});import{spawn as Uu}from"node:child_process";import{createInterface as CT}from"node:readline";var Du,Pu,Fu,MT,jT=E(()=>{"use strict";yi();de();Du=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=Uu(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=CT({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 i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),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 i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}else{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,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,i=typeof s?.id=="string"?s.id:void 0;if(i!==void 0){let o=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),o!==void 0&&this.ctx?.turnMap.set(i,o)}}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 i=this.nextRpcId++;this.pending.set(i,{resolve:n,reject:s});let o=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:r});try{this.child.stdin.write(o+`
|
|
2236
|
+
${t.receipt}`:`relay delivery error: ${t.error}`}function lP(t,e){t.reclaimStaleMailboxDeliveries(new Date(Date.now()-tu(e)).toISOString())}function cP(t){return{stdout:{write:()=>{}},stderr:{write:()=>{}},dal:t}}var $E,jE=E(()=>{"use strict";Br();ru();aa();ht();mu();$E=10});function Rs(){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 uP(t=process.env){let e=t.LMCTL_DAEMON_FEATURES;if(e===void 0)return new Set(["mailbox-relay"]);if(e.trim()==="")return new Set;let r=new Set;for(let n of e.split(",")){let s=n.trim();if(s!==""){if(s==="all")return new Set(DE);dP.has(s)&&r.add(s)}}return r}function PE(t){let e=t.intervalMs??Rs(),r=t.runOnceFn??Ur,n=new Set(t.features??uP()),s={running:t.autoStart!==!1,in_flight:!1,interval_ms:e,enabled_features:[...n].sort(),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,last_mailbox_relay_scanned:0,last_mailbox_relay_delivered:0,last_mailbox_relay_errors:0},i=null,o=null,a=null,l=null,c=null;n.has("rollup-updater")&&t.startRollupUpdaterFn!==!1&&(c=(t.startRollupUpdaterFn??eE)(t.dal));let d=m=>{s.running&&(i=setTimeout(()=>{f.runCycle().finally(()=>d(e))},m))},u=m=>{s.running&&(o=setTimeout(()=>{l===null&&(l=FE(t.dal,n,t.monitorSessionActivityFn??xc,e,s).finally(()=>{l=null})),l.finally(()=>u(Ac(t.dal,e)))},m))},f={state:s,runCycle:async()=>(a!==null||(a=fP(t.dal,r,t.collectSessionSizesFn??S_,t.scanIntakeFn??po,t.monitorSessionActivityFn??xc,t.mailboxRelayFn??ME,t.worker_id??"daemon",e,n,s).finally(()=>{a=null})),a),stop:async()=>{s.running=!1,i!==null&&clearTimeout(i),o!==null&&clearTimeout(o),c?.stop(),a!==null&&await a.catch(()=>{}),l!==null&&await l.catch(()=>{})}};if(s.running){let m=t.firstDelayMs??5e3;d(m),n.has("session-monitor")&&u(m)}return f}async function fP(t,e,r,n,s,i,o,a,l,c){c.in_flight=!0,c.last_started_at=new Date().toISOString(),c.last_error=null;let d=[],u=0,f=0,m=[],p=null,h=mP();try{if(l.has("durable-memory-policies")&&Ry({dal:t}),l.has("drift-detectors")&&nE({dal:t}),l.has("intake")&&(m=await n(t)),l.has("job-worker"))for(;;){let g=await e({dal:t,worker_id:o,lease_ms:6e5});if(g===null)break;d.push(g)}if(l.has("mailbox-relay")&&(h=await i({dal:t})),l.has("session-size")){let g=await r(t);u=g.recorded,f=g.failed}l.has("session-monitor")&&(p=await FE(t,l,s,a,c))}catch(g){c.last_error=g instanceof Error?g.message:String(g);try{t.raiseAttention({kind:"daemon_worker_failed",severity:"error",payload:JSON.stringify({error:c.last_error})})}catch{}}finally{c.in_flight=!1,c.cycles+=1,c.last_jobs_processed=d.length,c.last_session_sizes_recorded=u,c.last_session_size_failures=f,c.last_intake_scanned=m.reduce((g,_)=>g+_.scanned,0),c.last_intake_new_jobs=m.reduce((g,_)=>g+_.new_jobs,0),c.last_intake_failures=m.filter(g=>g.error!==void 0).length,c.last_session_hung_detected=p?.hung_detected??0,c.last_mailbox_relay_scanned=h.scanned,c.last_mailbox_relay_delivered=h.delivered,c.last_mailbox_relay_errors=h.errors,c.jobs_processed+=d.length,c.last_finished_at=new Date().toISOString()}return{jobs_processed:d.length,outcomes:d,session_sizes_recorded:u,session_size_failures:f,intake:m,session_monitor:p,mailbox_relay:h}}function mP(){return{scanned:0,delivered:0,skipped_busy:0,skipped_terminal:0,errors:0}}async function FE(t,e,r,n,s){if(!e.has("session-monitor"))return null;let i=Ac(t,n),o=Date.now();if(s.last_session_monitor_checked_at!==null){let a=Date.parse(s.last_session_monitor_checked_at);if(Number.isFinite(a)&&o-a<i)return null}s.last_session_monitor_checked_at=new Date(o).toISOString(),s.last_session_monitor_error=null;try{return await r({dal:t,nowMs:o})}catch(a){s.last_session_monitor_error=a instanceof Error?a.message:String(a);try{t.raiseAttention({kind:"daemon_session_monitor_failed",severity:"error",payload:JSON.stringify({error:s.last_session_monitor_error})})}catch{}return null}}var DE,dP,pu=E(()=>{"use strict";Qc();jo();Rd();Ui();tE();sE();Rc();jE();DE=["durable-memory-policies","drift-detectors","intake","job-worker","mailbox-relay","session-size","session-monitor","rollup-updater"],dP=new Set(DE)});function UE(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 WE=E(()=>{"use strict"});import{mkdirSync as pP,readFileSync as _P,readdirSync as hP,statSync as gP,writeFileSync as yP}from"node:fs";import{dirname as wP,join as qE,sep as BE}from"node:path";function _a(t){return{s3:{async send(n){let s=n;switch(s._localfsTag){case HE:return EP(t,s.input);case XE:return TP(t,s.input);case JE:return bP(t,s.input);default:throw new Error("createLocalFsS3Client: unknown command")}}},commands:{ListObjectsV2Command:gu,GetObjectCommand:hu,PutObjectCommand:_u}}}function EP(t,e){let r=GE(t,e.Key);return pP(wP(r),{recursive:!0}),yP(r,e.Body),{}}function TP(t,e){let r=GE(t,e.Key),n;try{n=_P(r)}catch(i){throw i.code==="ENOENT"?Object.assign(new Error("NoSuchKey"),{name:"NoSuchKey"}):i}let s=n.toString("utf-8");return{Body:{transformToString:async()=>s}}}function bP(t,e){let r=e.Prefix??"";KE(r);let s=SP(t).sort((d,u)=>d.key<u.key?-1:d.key>u.key?1:0).filter(d=>d.key.startsWith(r)),i=e.ContinuationToken;i!==void 0&&i!==""&&(s=s.filter(d=>d.key>i));let o=typeof e.MaxKeys=="number"&&Number.isFinite(e.MaxKeys)&&e.MaxKeys>0?Math.floor(e.MaxKeys):void 0,a=s,l=!1;o!==void 0&&s.length>o&&(a=s.slice(0,o),l=!0);let c={Contents:a.map(d=>({Key:d.key,LastModified:d.lastModified})),IsTruncated:l};return l&&(c.NextContinuationToken=a[a.length-1].key),c}function GE(t,e){return KE(e),qE(t,e)}function KE(t){if(t.split("/").includes(".."))throw new Error(`localfs-s3-client: refusing key/prefix with '..': ${t}`)}function SP(t){let e=[],r=(n,s)=>{let i;try{i=hP(n,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return;throw o}for(let o of i){let a=s===""?o.name:`${s}/${o.name}`,l=qE(n,o.name);if(o.isDirectory())r(l,a);else if(o.isFile()){let c=BE==="/"?a:a.split(BE).join("/");e.push({key:c,lastModified:gP(l).mtime})}}};return r(t,""),e}var HE,XE,JE,_u,hu,gu,yu=E(()=>{"use strict";HE="localfs-put",XE="localfs-get",JE="localfs-list",_u=class{input;_localfsTag=HE;constructor(e){this.input=e}},hu=class{input;_localfsTag=XE;constructor(e){this.input=e}},gu=class{input;_localfsTag=JE;constructor(e){this.input=e}}});function VE(){return{put:0,get:0,list:0}}function wu(t,e=vP){return t.put*e.putUsd+t.get*e.getUsd+t.list*e.listUsd}function Eu(t){let e=new Date(t),r=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0");return`${r}-${n}`}var vP,ha,Tu=E(()=>{"use strict";vP={putUsd:5e-6,getUsd:40000000000000003e-23,listUsd:5e-6};ha=class{counts=VE();record(e,r=1){this.counts[e]+=r}peek(){return{...this.counts}}drain(){let e={...this.counts};return this.counts=VE(),e}estimateCostUsd(e){return wu(this.counts,e)}}});function YE(t){let e=t.now??Date.now,r=t.timers??kP,n=null,s=null;async function i(){let l=e(),c=Eu(l),d=t.meter.drain();(d.put>0||d.get>0||d.list>0)&&t.store.addUsage({user_id:t.userId,device_id:t.deviceId,period:c,put:d.put,get:d.get,list:d.list,updated_at:new Date(l).toISOString()});let u=t.store.loadUsage(t.userId,t.deviceId,c),f=u?{put:u.put_count,get:u.get_count,list:u.list_count}:{put:0,get:0,list:0};if(t.publishOwnRollup!==void 0)try{await t.publishOwnRollup(c,f)}catch(h){t.log?.(`[usage] publish rollup failed: ${h instanceof Error?h.message:String(h)}`)}let m=f;if(t.readUserTotal!==void 0)try{m=await t.readUserTotal(c)}catch(h){t.log?.(`[usage] read user total failed: ${h instanceof Error?h.message:String(h)}`),m=f}let p=wu(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(h){t.log?.(`[usage] onQuotaExceeded threw: ${h instanceof Error?h.message:String(h)}`)}}}function o(){return s=(s??Promise.resolve()).then(()=>i()).catch(()=>{}),s}let a=r.setInterval(()=>{o()},t.intervalMs);return{stop(){r.clearInterval(a)},flushNow(){return o()},isOverQuota(){return n!==null&&n===Eu(e())}}}var kP,zE=E(()=>{"use strict";Tu();kP={setInterval:(t,e)=>setInterval(t,e),clearInterval:t=>clearInterval(t)}});var bu=E(()=>{"use strict";Wo();qo();qo()});function IP(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 i=s;return typeof i.status!="number"?null:{message_id:e.message_id,reply_to:e.reply_to,response:i}}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 NP(t){return t.reply_to!==void 0&&t.response!==void 0}function xP(t){if(typeof t!="object"||t===null)return;let e=t.conversation_id;return typeof e=="string"?e:void 0}function ZE(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,Ls,QE=E(()=>{"use strict";bu();ga=class extends Error{name="MailboxFetchStoppedError";code="mailbox_fetch_stopped";constructor(e="MailboxFetchClient stopped before a response arrived"){super(e)}},Ls=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=Kt(this.now(),this.random);if(this.pending.has(s))throw new Error(`MailboxFetchClient.fetch: duplicate message_id=${s}`);let i=r?.conversationId??s,o={message_id:s,request:e};return new Promise((a,l)=>{let c=r?.abortSignal,d;if(c!==void 0){if(c.aborted){l(ZE(c));return}d=()=>{this.pending.has(s)&&(this.pending.delete(s),l(ZE(c)))},c.addEventListener("abort",d,{once:!0})}this.pending.set(s,{resolve:a,reject:l,...d!==void 0?{abortListener:d}:{},...c!==void 0?{abortSignal:c}:{}}),this.client.putMessage({conversation_id:i,payload:o}).catch(u=>{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(u))})})}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=IP(e);if(n===null){this.log("MailboxFetchClient: dropping non-envelope inbound payload");return}if(NP(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??xP(e)??n.message_id,i;try{i=await this.requestHandler(n.request)}catch(l){let c=l instanceof Error?l.message:String(l),d=typeof l.code=="string"?l.code:"INTERNAL_ERROR";i={status:500,headers:{"content-type":"application/json"},body:{error:d,message:c}}}let a={message_id:Kt(this.now(),this.random),reply_to:n.message_id,response:i};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 Su(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 eT=E(()=>{"use strict"});function vu(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 tT=E(()=>{"use strict"});function Iu(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 ku,rT=E(()=>{"use strict";ku="daemon:events"});function sT(t){return{kind:"prompt",prompt_id:t.prompt_id??Kt(t.now?.()??Date.now(),t.random??Math.random),root_teamfile:t.root_teamfile,text:t.text}}function Nu(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 nT,xu=E(()=>{"use strict";bu();nT="prompt:root"});function Os(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(oT(e[1]));return typeof r.sub=="string"&&r.sub!==""?r.sub:null}catch{return null}}function AP(t){let e=t.split(".");if(e.length<2||e[1]===void 0||e[1]==="")return null;try{let r=JSON.parse(oT(e[1]));return typeof r.exp=="number"&&Number.isFinite(r.exp)?r.exp:null}catch{return null}}function iT(t,e=60){if(typeof t!="string"||t==="")return!0;let r=AP(t);return r===null?!0:Date.now()/1e3>=r-e}function oT(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 Au=E(()=>{"use strict"});async function ya(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":RP},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 o=JSON.parse(s).AuthenticationResult,a=o?.IdToken;if(typeof a!="string"||a==="")throw new Error("cognito_refresh_no_id_token: InitiateAuth returned no IdToken");return{idToken:a,...typeof o?.AccessToken=="string"&&o.AccessToken!==""?{accessToken:o.AccessToken}:{},...typeof o?.ExpiresIn=="number"&&Number.isFinite(o.ExpiresIn)?{expiresAt:Date.now()+o.ExpiresIn*1e3}:{}}}var RP,Ru=E(()=>{"use strict";RP="AWSCognitoIdentityProviderService.InitiateAuth"});import{chmodSync as aT,mkdirSync as lT,readFileSync as cT,writeFileSync as dT}from"node:fs";import{homedir as uT}from"node:os";import{dirname as fT,join as mT}from"node:path";function $s(){return process.env.LMCTL_DEVICE_AUTH_PATH??mT(uT(),".lmctl","device-auth.json")}function pT(){return process.env.LMCTL_TOKEN_PATH??mT(uT(),".lmctl","cli-tokens.json")}function Lu(t=$s()){try{let e=JSON.parse(cT(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 _T(t,e=$s()){lT(fT(e),{recursive:!0,mode:448}),dT(e,JSON.stringify(t,null,2));try{aT(e,384)}catch{}}function Ou(t,e=pT()){let r={};try{r=JSON.parse(cT(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};lT(fT(e),{recursive:!0,mode:448}),dT(e,JSON.stringify(s,null,2));try{aT(e,384)}catch{}}async function hT(t){let e=t.deviceAuthPath??$s(),r=Lu(e);if(r===null)throw new Error("device_auth_not_found: no ~/.lmctl/device-auth.json; run `lmctl device login` first");let n=await ya({region:t.region,clientId:t.clientId,refreshToken:r.refreshToken,...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}});return Ou({idToken:n.idToken,...n.accessToken!==void 0?{accessToken:n.accessToken}:{},refreshToken:r.refreshToken,...n.expiresAt!==void 0?{expiresAt:n.expiresAt}:{}},t.cliTokensPath??pT()),{idToken:n.idToken,userId:r.userId}}var $u=E(()=>{"use strict";Ru()});import{existsSync as LP,realpathSync as OP}from"node:fs";import{dirname as $P}from"node:path";function Cu(t){CP(t).catch(e=>{t.log?.(`[mailbox] prompt trigger failed: ${e instanceof Error?e.message:String(e)}`)})}async function CP(t){let e=t.payload.root_teamfile;try{e=OP(t.payload.root_teamfile)}catch(s){let i=`prompt root missing/unreadable: ${t.payload.root_teamfile}: ${s instanceof Error?s.message:String(s)}`;return xn({rootTeamfile:t.payload.root_teamfile,receiverTeamfile:t.payload.root_teamfile,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"root_unavailable"}),t.log?.(`[mailbox] ${i}`),{status:"error",response:null,error_detail:i}}if(t.store.getRootTeam(e)===null){let s=`prompt root is not registered: ${e}`;return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:s,reason:"root_unregistered"}),t.log?.(`[mailbox] ${s}`),{status:"error",response:null,error_detail:s}}let r=jP(e);if("error"in r)return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:"Lead",message:t.payload.text,promptId:t.payload.prompt_id,detail:r.error,reason:"root_invalid"}),t.log?.(`[mailbox] ${r.error}`),{status:"error",response:null,error_detail:r.error};let n=gr(t.store,{receiver_teamfile:e,receiver_alias:r.alias,sender_teamfile:`prompt:${t.payload.prompt_id}`,sender_alias:"operator",ttlMs:UP(t.env??process.env)});if(!n.acquired){let s=FP(r.alias,n.current);return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:s,reason:"unavailable"}),t.log?.(`[mailbox] prompt rejected: ${s}`),{status:"error",response:null,error_detail:s}}try{let i=await(t.chat??kt)({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}:{}}),o=i.status==="stalled",a=!o&&i.text.trim()==="",l=o?`provider stalled${i.stalledAfterMs!==void 0?` after ${i.stalledAfterMs}ms`:""}`:a?"provider returned empty response":null,c=o||a?"error":"ok";return c==="ok"?await DP(t.store,{rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,response:i.text,status:c,error_detail:null,log:t.log}):xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:l??"provider failed",reason:o?"stalled":"empty_response"}),{status:c,response:c==="error"?null:i.text,error_detail:l}}catch(s){let i=s instanceof Error?s.message:String(s);return xn({rootTeamfile:e,receiverTeamfile:e,receiverAlias:r.alias,message:t.payload.text,promptId:t.payload.prompt_id,detail:i,reason:"provider_error"}),t.log?.(`[mailbox] prompt provider error: ${i}`),{status:"error",response:null,error_detail:i}}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 xn(t){C({event:"prompt_trigger_error",reason:t.reason,prompt_id:t.promptId,root_teamfile:t.rootTeamfile,sender_teamfile:t.rootTeamfile,sender_alias:"operator",receiver_teamfile:t.receiverTeamfile,receiver_alias:t.receiverAlias,error_detail:t.detail,message_preview:MP(t.message)})}function MP(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function jP(t){if(!LP(t))return{error:`prompt root missing/unreadable: ${t}`};let e=Ve(t);if(e.parseErrors.length>0)return{error:`prompt root parse error: ${e.parseErrors.join("; ")}`};let r=Lt(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??$P(t)}}async function DP(t,e){let r=wT(e.message),n=e.response===null?null:wT(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 wT(t){return t.length<=gT?{text:t,truncated:!1}:{text:t.slice(0,gT),truncated:!0}}function PP(t,e){return`${t} is servicing ${e.sender_alias} (${e.sender_teamfile}) since ${e.started_at}`}function FP(t,e){return e.sender_teamfile.startsWith("prompt:")?`${t} is busy servicing another prompt since ${e.started_at}`:PP(t,e)}function UP(t=process.env){let e=t.LMCTL_INFLIGHT_TTL_MS;if(e===void 0||e.trim()==="")return yT;let r=Number(e);return!Number.isFinite(r)||r<=0?yT:r}var gT,yT,ET=E(()=>{"use strict";It();zt();de();Br();gT=256*1024,yT=30*60*1e3});import{chmodSync as IT,existsSync as WP,mkdirSync as NT,readFileSync as ba,writeFileSync as xT}from"node:fs";import{dirname as Mu,resolve as wa,join as AT}from"node:path";import{fileURLToPath as BP}from"node:url";import{homedir as RT}from"node:os";import{CognitoIdentityClient as qP,GetIdCommand as HP}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as TT}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as XP,ListObjectsV2Command as JP,PutObjectCommand as GP,S3Client as bT}from"@aws-sdk/client-s3";function Ms(t={}){let e=t.env??process.env,r=t.tfstatePath!==void 0?[t.tfstatePath]:ZP(t.selfUrl),n={},s;for(let I of r)if(WP(I)){n=zP(I),s=I;break}let i=(...I)=>{for(let x of I)if(typeof x=="string"&&x!=="")return x},o=i(e.LMCTL_NEXT_IDENTITY_POOL_ID,n.LMCTL_NEXT_IDENTITY_POOL_ID)??KP,a=i(e.LMCTL_NEXT_COGNITO_USER_POOL_ID,n.LMCTL_NEXT_COGNITO_USER_POOL_ID)??VP,l=i(e.LMCTL_NEXT_MAILBOX_BUCKET,e.LMCTL_NEXT_POLICY_BUCKET,n.LMCTL_NEXT_MAILBOX_BUCKET,n.LMCTL_NEXT_POLICY_BUCKET)??YP,c=i(e.AWS_REGION,e.AWS_DEFAULT_REGION)??"us-east-1",d=i(e.LMCTL_NEXT_COGNITO_CLIENT_ID,n.LMCTL_NEXT_COGNITO_CLIENT_ID)??Sa,u=[];o===void 0&&u.push("LMCTL_NEXT_IDENTITY_POOL_ID"),a===void 0&&u.push("LMCTL_NEXT_COGNITO_USER_POOL_ID"),l===void 0&&u.push("LMCTL_NEXT_MAILBOX_BUCKET");let f={missing:u,tfstateCandidatesChecked:r,...s!==void 0?{tfstatePathUsed:s}:{}};if(u.length>0)return f;let m=e.LMCTL_MAILBOX_POLL_MS,p=m!==void 0&&m.length>0?Number(m):void 0,h=Ta(e.LMCTL_MAILBOX_READ_INTERVAL_SECONDS),g=Ta(e.LMCTL_MAILBOX_HEARTBEAT_IDLE_SECONDS),_=Ta(e.LMCTL_MAILBOX_BACKOFF_READ_INTERVAL_SECONDS),y=Ta(e.LMCTL_MAILBOX_CHATLOG_POLL_SECONDS),T=i(e.LMCTL_MAILBOX_KEY),b=i(e.LMCTL_TOKEN_PATH);return f.config={identityPoolId:o,cognitoUserPoolId:a,cognitoClientId:d,region:c,mailboxBucket:l,...typeof p=="number"&&Number.isFinite(p)&&p>=100?{pollIntervalMs:p}:{},...h!==void 0?{readIntervalMs:h}:{},...g!==void 0?{heartbeatIdleMs:g}:{},..._!==void 0?{backoffReadIntervalMs:_}:{},...y!==void 0?{chatLogPollIntervalMs:y}:{},...T!==void 0?{mailboxKey:T}:{},...b!==void 0?{tokenPath:b}:{}},f}function zP(t){try{let e=ba(t,"utf8"),n=JSON.parse(e).outputs??{},s={};for(let[i,o]of Object.entries(n))o!==null&&typeof o=="object"&&typeof o.value=="string"&&(s[i]=o.value);return s}catch{return{}}}function ZP(t){let e=Mu(BP(t??import.meta.url));return[wa(e,"..","..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","..","infra","terraform","terraform.tfstate"),wa(e,"..","..","infra","terraform","terraform.tfstate")]}function Ta(t){if(t===void 0||t==="")return;let e=Number(t);if(!(!Number.isFinite(e)||e<=0))return e*1e3}function QP(t){let e=eF(t.intervalMs)??LT,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,i,o=!1,a=!1,l=()=>{try{if(s!==null){let u=s.load(s.key);if(u!==null)return i=u.last_pushed_id,!0}return i=t.store.getMaxTeamChatLogId(),s!==null&&s.save({cursor_key:s.key,last_pushed_id:i,updated_at:new Date(n()).toISOString()}),!0}catch(u){return t.log?.(`[mailbox] daemon_event chat_log seed failed: ${u instanceof Error?u.message:String(u)}`),!1}};l();let c=async()=>{if(!(a||o)){o=!0;try{if(i===void 0&&!l())return;let u=t.store.listTeamChatLogSinceId(i,r);for(let f of u){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()}),i=Math.max(i,f.id)}}catch(u){t.log?.(`[mailbox] daemon_event chat_log tail failed: ${u instanceof Error?u.message:String(u)}`)}finally{o=!1}}},d=setInterval(()=>{c()},e);return typeof d.unref=="function"&&d.unref(),{pollNow:c,stop(){a=!0,clearInterval(d)}}}function eF(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}async function OT(t){let e=t.tokenPath??AT(RT(),".lmctl","cli-tokens.json"),r=vT(t.tokenPath);if(iT(r.cognito?.idToken)&&Lu()!==null)try{await hT({region:t.region,clientId:t.cognitoClientId??Sa,cliTokensPath:e}),r=vT(t.tokenPath),t.log?.("[mx-mailbox] refreshed IdToken from device-auth refresh token")}catch(A){let ee=A instanceof Error?A.message:String(A);t.log?.(`[mx-mailbox] device-auth refresh failed: ${ee}`)}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}`,i=r.cognito.identityId,o=!1;i===void 0||i===""?i=await kT({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}):(o=!0,t.log?.(`[mx-mailbox] using cached identityId from cli-tokens (skipping GetId) for ${i}`));let a=TT({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bT({region:t.region,credentials:a}),c={ListObjectsV2Command:JP,GetObjectCommand:XP,PutObjectCommand:GP},d=Os(n),u=d??i,f=t.deviceId,m=Tn({identityId:i,userId:d,deviceId:f,mailboxKey:t.mailboxKey}),p=t.cursorStore,h;if(p!==void 0){let A=p.loadMailboxCursor(u,m);if(A!==null)h=A.last_processed_seq??void 0,t.log?.(`[mx-mailbox] resumed seq cursor=${h??"(sentinel)"} for user_id=${u}`);else{let ee=!1,B=0;for(;!ee&&B<2;){B+=1;try{let k=Fo(m,"web"),N=0,L;do{let W=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:k,MaxKeys:1e3,...L!==void 0?{ContinuationToken:L}:{}}));for(let D of W.Contents??[]){let M=Uo(D.Key??"",m,"web");M!==void 0&&M>N&&(N=M)}L=W.IsTruncated===!0?W.NextContinuationToken:void 0}while(L!==void 0);h=N,t.log?.(`[mx-mailbox] cold start: seeded seq cursor=${N} for user_id=${u}`),ee=!0}catch(k){let N=k instanceof Error?k.message:String(k);if(o&&B===1&&nF(k)){t.log?.(`[mx-mailbox] cached identityId rejected by cognito (${N}); clearing + refreshing`),rF(e),o=!1,i=await kT({tokenPath:e,region:t.region,identityPoolId:t.identityPoolId,idpProvider:s,idToken:n,log:t.log}),a=TT({identityId:i,logins:{[s]:n},clientConfig:{region:t.region}}),l=new bT({region:t.region,credentials:a}),m=Tn({identityId:i,userId:d,deviceId:f,mailboxKey:t.mailboxKey});continue}t.log?.(`[mx-mailbox] cold start seq probe failed: ${N}`);break}}p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:h??null,last_processed_at:new Date().toISOString()})}}let g=null,_=t.terminalSessionManager,y=t.persistentSessionManager,T=t.promptTriggerStore,b=new ha,I=new Wr({bucket:t.mailboxBucket,identityId:i,...d!==null?{userId:d}:{},...f!==void 0?{deviceId:f}:{},...t.mailboxKey!==void 0?{mailboxKey:t.mailboxKey}:{},s3:l,commands:c,selfRole:"agent",onS3Op:A=>b.record(A),onMessage:async A=>{if(_!==void 0&&Su(A.payload)){_.onInbound(A.payload);return}if(y!==void 0&&vu(A.payload)){await y.onInbound(A.payload);return}if(!Iu(A.payload)){if(T!==void 0&&Nu(A.payload)){Cu({store:T,payload:A.payload,log:t.log});return}g!==null&&await g.handleIncoming(A.payload,A)}},...p!==void 0?{onCursorAdvance:A=>{p.saveMailboxCursor({user_id:u,mailbox_key:m,last_processed_version_id:null,last_processed_seq:A,last_processed_at:new Date().toISOString()})}}:{},...h!==void 0?{cursor:h}:{},...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 Ls({client:I,...t.log!==void 0?{log:t.log}:{}}),_!==void 0&&_.setPublish(async A=>I.putMessage({conversation_id:`terminal:${A.session_id}`,payload:A})),y!==void 0&&y.setPublish(async A=>I.putMessage({conversation_id:`provider:${A.session_id}`,payload:A}));let x=A=>I.putMessage({conversation_id:ku,payload:A});I.start();let H=t.chatLogTailStore===void 0?void 0:QP({store:t.chatLogTailStore,publishDaemonEvent:x,cursorKey:m,intervalMs:t.chatLogPollIntervalMs??t.readIntervalMs??t.pollIntervalMs??LT,log:t.log});t.log?.(`[mx-mailbox] agent polling ${m} (bucket=${t.mailboxBucket})`);let pe=t.deviceId??i,U=`${u}/usage/`,j;return j=t.usageStore===void 0?void 0:YE({meter:b,store:t.usageStore,userId:u,deviceId:pe,ceilingUsd:t.usageQuotaUsd??1/0,onQuotaExceeded:({period:A,costUsd:ee,ceilingUsd:B})=>{t.log?.(`[usage] month ${A} cost $${ee.toFixed(4)} >= ceiling $${B} \u2014 blocking mailbox`),I.stop().catch(()=>{}),j?.stop()},publishOwnRollup:async(A,ee)=>{await l.send(new c.PutObjectCommand({Bucket:t.mailboxBucket,Key:`${U}${pe}-${A}.json`,Body:JSON.stringify({...ee,updated_at:new Date().toISOString()}),ContentType:"application/json"}))},readUserTotal:async A=>{let ee={put:0,get:0,list:0},B;do{let k=await l.send(new c.ListObjectsV2Command({Bucket:t.mailboxBucket,Prefix:U,MaxKeys:1e3,...B!==void 0?{ContinuationToken:B}:{}}));for(let N of k.Contents??[]){let L=N.Key??"";if(L.endsWith(`-${A}.json`))try{let W=await l.send(new c.GetObjectCommand({Bucket:t.mailboxBucket,Key:L}));if(W.Body===void 0)continue;let D=JSON.parse(await W.Body.transformToString("utf-8"));ee.put+=D.put??0,ee.get+=D.get??0,ee.list+=D.list??0}catch{}}B=k.IsTruncated===!0?k.NextContinuationToken:void 0}while(B!==void 0);return ee},intervalMs:t.usageFlushIntervalMs??36e5,...t.log!==void 0?{log:t.log}:{}}),{identityId:i,mailbox:I,fetchClient:g,publishDaemonEvent:x,async stop(){H?.stop(),j!==void 0&&(await j.flushNow().catch(()=>{}),j.stop()),await g.stop().catch(()=>{}),await I.stop().catch(()=>{})}}}async function $T(t){let e=t.s3!==void 0&&t.commands!==void 0?{s3:t.s3,commands:t.commands}:_a(t.rootDir),r=Tn({identityId:Cs,userId:Cs,deviceId:ST}),n=null,s=t.terminalSessionManager,i=t.persistentSessionManager,o=t.promptTriggerStore,a=new Wr({bucket:"local",identityId:Cs,userId:Cs,deviceId:ST,s3:e.s3,commands:e.commands,selfRole:"agent",onMessage:async c=>{if(s!==void 0&&Su(c.payload)){s.onInbound(c.payload);return}if(i!==void 0&&vu(c.payload)){await i.onInbound(c.payload);return}if(!Iu(c.payload)){if(o!==void 0&&Nu(c.payload)){Cu({store:o,payload:c.payload,log:t.log});return}n!==null&&await n.handleIncoming(c.payload,c)}},pollIntervalMs:t.pollIntervalMs??Ea,readIntervalMs:t.readIntervalMs??Ea,heartbeatIdleMs:t.heartbeatIdleMs??Ea,backoffReadIntervalMs:t.backoffReadIntervalMs??Ea});n=new Ls({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})),i!==void 0&&i.setPublish(async c=>a.putMessage({conversation_id:`provider:${c.session_id}`,payload:c}));let l=c=>a.putMessage({conversation_id:ku,payload:c});return a.start(),t.log?.(`[local-webui] agent polling ${r} (local-fs ${t.rootDir})`),{identityId:Cs,mailbox:a,fetchClient:n,publishDaemonEvent:l,async stop(){await n.stop().catch(()=>{}),await a.stop().catch(()=>{})}}}function vT(t){let e=t??AT(RT(),".lmctl","cli-tokens.json");try{let r=ba(e,"utf8");return JSON.parse(r)}catch{return{}}}function tF(t,e){if(e===void 0||e==="")return;let r={};try{let s=ba(t,"utf8");r=JSON.parse(s)}catch{}if(r.cognito===void 0)return;let n={...r,cognito:{...r.cognito,identityId:e}};NT(Mu(t),{recursive:!0,mode:448}),xT(t,JSON.stringify(n,null,2));try{IT(t,384)}catch{}}function rF(t){let e={};try{let n=ba(t,"utf8");e=JSON.parse(n)}catch{return}if(e.cognito===void 0)return;let r={...e,cognito:{...e.cognito}};delete r.cognito.identityId,NT(Mu(t),{recursive:!0,mode:448}),xT(t,JSON.stringify(r,null,2));try{IT(t,384)}catch{}}async function kT(t){t.log?.("[mx-mailbox] cli-tokens has no identityId; calling GetId");let r=await new qP({region:t.region}).send(new HP({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId==="")throw new Error("cognito_getid_no_identity_id");try{tF(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 nF(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 LT,Ea,Sa,KP,VP,YP,Cs,ST,ju=E(()=>{"use strict";Ho();yu();Tu();zE();QE();eT();tT();rT();xu();Wo();Au();$u();ET();LT=3e3,Ea=1e3,Sa="79u5jhkk46qofog661c9i0bdcs",KP="us-east-1:69636ff0-e008-4cbc-853d-180e5526a198",VP="us-east-1_4iUdFggDn",YP="lmctl-next-preview-mailbox-254332045686";Cs="local",ST="local"});import{spawn as Uu}from"node:child_process";import{createInterface as CT}from"node:readline";var Du,Pu,Fu,MT,jT=E(()=>{"use strict";yi();de();Du=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=Uu(e.command,e.args,{cwd:e.cwd??process.cwd(),env:e.env??process.env,stdio:["pipe","pipe","pipe"]});if(this.child=n,this.rl=CT({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 i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),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 i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,resumed:!1}})}else{let i=(await this.rpc("thread/start",{cwd:e.cwd??process.cwd(),approvalPolicy:"never",sandbox:"danger-full-access"})).result?.thread,o=typeof i?.id=="string"?i.id:void 0;this.threadId=o,r.emit({event_type:"thread_started",payload:{thread_id:o,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,i=typeof s?.id=="string"?s.id:void 0;if(i!==void 0){let o=this.ctx?.turnMap.get(r);this.ctx?.turnMap.delete(r),o!==void 0&&this.ctx?.turnMap.set(i,o)}}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 i=this.nextRpcId++;this.pending.set(i,{resolve:n,reject:s});let o=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:r});try{this.child.stdin.write(o+`
|
|
2155
2237
|
`)}catch(a){this.pending.delete(i),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+`
|
|
2156
2238
|
`)}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 o=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);o.reject(new Error(`codex_rpc_error: ${l}`))}else o.resolve(r);return}let n=typeof r.method=="string"?r.method:void 0;if(n===void 0)return;let s=r.params??{},i=this.normalizeNotification(n,s);i!==void 0&&this.ctx?.emit(i)}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}}}},Pu=class{child;ctx;buffer="";sessionIdSeen;closed=!1;async start(e,r){this.ctx=r;let n=Uu(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 i=s instanceof Buffer?s.toString("utf8"):String(s);this.buffer+=i;let o=this.buffer.split(`
|
|
2157
2239
|
`);this.buffer=o.pop()??"";for(let a of o)this.handleLine(a)}),n.stderr?.on("data",s=>{if(r.generation!==r.currentGeneration())return;let i=s instanceof Buffer?s.toString("utf8"):String(s);r.emit({event_type:"notification",payload:{source:"stderr",text:i}})}),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+`
|
|
2158
2240
|
`)}catch(s){throw this.ctx?.turnMap.delete(r),s instanceof Error?s:new Error(String(s))}}async stop(){if(this.closed=!0,this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}}handleLine(e){if(e.trim()==="")return;let r;try{r=JSON.parse(e)}catch{return}let n=typeof r.type=="string"?r.type:"";if(n==="system"&&r.subtype==="init"){let s=typeof r.session_id=="string"?r.session_id:void 0;s!==void 0&&s!==this.sessionIdSeen&&(this.sessionIdSeen=s,this.ctx?.emit({event_type:"thread_started",payload:{thread_id:s,raw:r}}));return}if(n==="assistant"){let i=r.message?.content;if(Array.isArray(i))for(let o of i)o.type==="text"&&typeof o.text=="string"&&o.text!==""&&this.ctx?.emit({event_type:"assistant_message_delta",payload:{text:o.text}});return}if(n==="result"){let s=typeof r.session_id=="string"?r.session_id:void 0;for(let i of Array.from(this.ctx?.turnMap.keys()??[]))this.ctx?.turnMap.delete(i);this.ctx?.emit({event_type:"turn_complete",payload:{result:r.result,session_id:s,raw:r}});return}this.ctx?.emit({event_type:"notification",payload:{method:n,params:r}})}},Fu=class{child;ctx;rl;nextRpcId=1;pending=new Map;sessionId;closed=!1;async start(e,r){this.ctx=r;let n=e.cwd??process.cwd();if(e.provider==="opencode")try{gi(n)}catch(a){C({event:"opencode_config_install_failed",cwd:n,error_message:a instanceof Error?a.message:String(a)})}let s=Uu(e.command,e.args,{cwd:n,env:e.env??process.env,stdio:["pipe","pipe","pipe"]});this.child=s,this.rl=CT({input:s.stdout}),this.rl.on("line",a=>{r.generation===r.currentGeneration()&&this.handleLine(a)}),s.stderr?.on("data",a=>{if(r.generation!==r.currentGeneration())return;let l=a instanceof Buffer?a.toString("utf8"):String(a);r.emit({event_type:"notification",payload:{source:"stderr",text:l}})}),await this.rpc("initialize",{protocolVersion:1,clientInfo:{name:"lmctl-dt3",version:"0.1.0"},clientCapabilities:{}}),this.notify("notifications/initialized",{});let o=(await this.rpc("session/new",{cwd:e.cwd??process.cwd(),mcpServers:[]})).result;return this.sessionId=typeof o?.sessionId=="string"?o.sessionId:void 0,r.emit({event_type:"thread_started",payload:{thread_id:this.sessionId,raw:o}}),s}async sendTurn(e){if(this.closed)throw new Error("acp_session_closed");if(this.sessionId===void 0)throw new Error("acp_no_session_id");let r=`acp-${Date.now()}`;this.ctx?.turnMap.set(r,{startedAt:Date.now()});try{let s=(await this.rpc("session/prompt",{sessionId:this.sessionId,prompt:[{type:"text",text:e}]})).result;this.ctx?.emit({event_type:"turn_complete",payload:{stopReason:s?.stopReason,raw:s}})}finally{this.ctx?.turnMap.delete(r)}}async stop(){if(this.closed=!0,this.rl!==void 0&&(this.rl.close(),this.rl=void 0),this.child?.stdin?.end!==void 0)try{this.child.stdin.end()}catch{}for(let e of this.pending.values())e.reject(new Error("acp_session_stopping"));this.pending.clear()}async rpc(e,r){if(this.child?.stdin===null||this.child===void 0)throw new Error("acp_child_unavailable");return new Promise((n,s)=>{let i=this.nextRpcId++;this.pending.set(i,{resolve:n,reject:s});let o=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:r});try{this.child.stdin.write(o+`
|
|
2159
2241
|
`)}catch(a){this.pending.delete(i),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+`
|
|
2160
2242
|
`)}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 s=this.pending.get(r.id);if(this.pending.delete(r.id),r.error!==void 0){let i=r.error,o=typeof i?.message=="string"&&i.message!==""?i.message:JSON.stringify(r.error);s.reject(new Error(`acp_rpc_error: ${o}`))}else s.resolve(r);return}let n=typeof r.method=="string"?r.method:void 0;if(n!==void 0){if(typeof r.id=="number"){let s=JSON.stringify({jsonrpc:"2.0",id:r.id,error:{code:-32601,message:`Method not found: ${n} (lmctl dt-3 does not implement server-side ACP methods)`}});try{this.child?.stdin?.write(s+`
|
|
2161
|
-
`)}catch{}this.ctx?.emit({event_type:"notification",payload:{kind:"unhandled_request",method:n,id:r.id,params:r.params}});return}if(n==="session/update"){let s=r.params,i=s?.update;if((typeof i?.sessionUpdate=="string"?i.sessionUpdate:"")==="agent_message_chunk"){let a=i?.content,l=typeof a?.text=="string"?a.text:"";if(l!==""){this.ctx?.emit({event_type:"assistant_message_delta",payload:{text:l}});return}}this.ctx?.emit({event_type:"notification",payload:{method:n,params:s}});return}this.ctx?.emit({event_type:"notification",payload:{method:n,params:r.params}})}}},MT=t=>{switch(t){case"codex":return new Du;case"claude":case"qwen":return new Pu;case"gemini":case"copilot":case"opencode":return new Fu;default:throw new Error(`no_persistent_adapter_for_provider: ${t}`)}}});import{randomUUID as sF}from"node:crypto";import{existsSync as y6,mkdirSync as iF,readFileSync as oF,writeFileSync as aF}from"node:fs";import{homedir as lF}from"node:os";import{dirname as cF,join as dF}from"node:path";function va(){return process.env.LMCTL_DEVICE_FILE??dF(lF(),".lmctl","device.json")}function
|
|
2243
|
+
`)}catch{}this.ctx?.emit({event_type:"notification",payload:{kind:"unhandled_request",method:n,id:r.id,params:r.params}});return}if(n==="session/update"){let s=r.params,i=s?.update;if((typeof i?.sessionUpdate=="string"?i.sessionUpdate:"")==="agent_message_chunk"){let a=i?.content,l=typeof a?.text=="string"?a.text:"";if(l!==""){this.ctx?.emit({event_type:"assistant_message_delta",payload:{text:l}});return}}this.ctx?.emit({event_type:"notification",payload:{method:n,params:s}});return}this.ctx?.emit({event_type:"notification",payload:{method:n,params:r.params}})}}},MT=t=>{switch(t){case"codex":return new Du;case"claude":case"qwen":return new Pu;case"gemini":case"copilot":case"opencode":return new Fu;default:throw new Error(`no_persistent_adapter_for_provider: ${t}`)}}});import{randomUUID as sF}from"node:crypto";import{existsSync as y6,mkdirSync as iF,readFileSync as oF,writeFileSync as aF}from"node:fs";import{homedir as lF}from"node:os";import{dirname as cF,join as dF}from"node:path";function va(){return process.env.LMCTL_DEVICE_FILE??dF(lF(),".lmctl","device.json")}function Xr(t=va()){let e=process.env.LMCTL_DEVICE_ID;if(e!==void 0&&e!=="")return{device_id:e,created_at:"env"};try{let r=JSON.parse(oF(t,"utf8"));return typeof r.device_id!="string"||r.device_id===""?null:{device_id:r.device_id,created_at:typeof r.created_at=="string"?r.created_at:""}}catch{return null}}function Wu(t=va()){let e=Xr(t);if(e!==null&&e.created_at!=="env")return e;let r={device_id:sF(),created_at:new Date().toISOString()};return iF(cF(t),{recursive:!0}),aF(t,`${JSON.stringify(r,null,2)}
|
|
2162
2244
|
`,{encoding:"utf8",mode:384}),r}var Bu=E(()=>{"use strict"});import{mkdirSync as uF,readFileSync as DT,rmSync as fF,writeFileSync as mF}from"node:fs";import{dirname as PT,join as pF}from"node:path";function Ot(t=Z()){return pF(PT(t),"serve.pid")}function FT(t,e){let r=Ot(e);return uF(PT(r),{recursive:!0}),mF(r,`${JSON.stringify(t,null,2)}
|
|
2163
|
-
`,"utf-8"),r}function qu(t){let e=Ot(t),r;try{r=DT(e,"utf-8")}catch{return null}try{let n=JSON.parse(r);return!Number.isInteger(n.pid)||(n.pid??0)<=0?null:{pid:n.pid,startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",port:Number.isInteger(n.port)?n.port:0,bind:typeof n.bind=="string"?n.bind:"unknown",dbPath:typeof n.dbPath=="string"?n.dbPath:"unknown",startToken:typeof n.startToken=="string"?n.startToken:null}}catch{return null}}function An(t){fF(Ot(t),{force:!0})}function ka(t){let e=_F(t),r=qu(t);if(r===null)return{entry:null,running:!1,stale:!1,corrupt:e};switch(Fm(r.pid,r.startToken??null)){case"same":return{entry:r,running:!0,stale:!1,corrupt:!1};case"different":return{entry:r,running:!1,stale:!0,corrupt:!1,staleReason:"pid-reused"};case"gone":return{entry:r,running:!1,stale:!0,corrupt:!1,staleReason:"process-gone"};case"unverified":default:return{entry:r,running:!0,stale:!1,corrupt:!1,unverified:!0}}}function _F(t){let e=Ot(t),r;try{r=DT(e,"utf-8")}catch{return!1}try{let n=JSON.parse(r);return!Number.isInteger(n.pid)||(n.pid??0)<=0}catch{return!0}}function UT(){return ul(process.pid)}var WT=E(()=>{"use strict";Yn();We()});var tb={};Ee(tb,{_resetStdoutEpipeGuardForTests:()=>TF,bootstrapAgentRestMailbox:()=>YT,installStdoutEpipeGuard:()=>
|
|
2245
|
+
`,"utf-8"),r}function qu(t){let e=Ot(t),r;try{r=DT(e,"utf-8")}catch{return null}try{let n=JSON.parse(r);return!Number.isInteger(n.pid)||(n.pid??0)<=0?null:{pid:n.pid,startedAt:typeof n.startedAt=="string"?n.startedAt:"unknown",port:Number.isInteger(n.port)?n.port:0,bind:typeof n.bind=="string"?n.bind:"unknown",dbPath:typeof n.dbPath=="string"?n.dbPath:"unknown",startToken:typeof n.startToken=="string"?n.startToken:null}}catch{return null}}function An(t){fF(Ot(t),{force:!0})}function ka(t){let e=_F(t),r=qu(t);if(r===null)return{entry:null,running:!1,stale:!1,corrupt:e};switch(Fm(r.pid,r.startToken??null)){case"same":return{entry:r,running:!0,stale:!1,corrupt:!1};case"different":return{entry:r,running:!1,stale:!0,corrupt:!1,staleReason:"pid-reused"};case"gone":return{entry:r,running:!1,stale:!0,corrupt:!1,staleReason:"process-gone"};case"unverified":default:return{entry:r,running:!0,stale:!1,corrupt:!1,unverified:!0}}}function _F(t){let e=Ot(t),r;try{r=DT(e,"utf-8")}catch{return!1}try{let n=JSON.parse(r);return!Number.isInteger(n.pid)||(n.pid??0)<=0}catch{return!0}}function UT(){return ul(process.pid)}var WT=E(()=>{"use strict";Yn();We()});var tb={};Ee(tb,{_resetStdoutEpipeGuardForTests:()=>TF,bootstrapAgentRestMailbox:()=>YT,installStdoutEpipeGuard:()=>JT,publishRegisteredWorkflowsOnStart:()=>VT,resolveLocalMailboxDir:()=>QT,resolveLocalWebuiDir:()=>ZT,resolveServeConfig:()=>zT,runServe:()=>wF,runServeStatus:()=>GT,runServeStop:()=>KT,validateServeArgs:()=>eb});import{randomBytes as hF}from"node:crypto";import{existsSync as HT}from"node:fs";import{isIP as BT}from"node:net";import{homedir as gF}from"node:os";import{isAbsolute as XT,resolve as Hu}from"node:path";async function wF(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=t[0];return r==="status"?GT(t.slice(1),e):r==="stop"?KT(t.slice(1),e):r!=="start"?(e.stderr.write(r===void 0?qT:`error: unknown serve subcommand: ${r}
|
|
2164
2246
|
|
|
2165
2247
|
${qT.replace(/^error: [^\n]*\n\n/,"")}`),2):EF(t.slice(1),e)}async function EF(t,e){let r=eb(t,process.env);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
2166
2248
|
`),2;let n=ke({path:Z()}),s={portCli:RF(t)},i;try{i=zT({dal:n,cli:s,env:process.env,parsed:r,io:e})}catch(b){return n.close(),e.stderr.write(`error: ${b instanceof Error?b.message:String(b)}
|
|
@@ -2168,12 +2250,12 @@ ${qT.replace(/^error: [^\n]*\n\n/,"")}`),2):EF(t.slice(1),e)}async function EF(t
|
|
|
2168
2250
|
`)}let a=r.noDaemon?void 0:PE({dal:n,intervalMs:Rs()}),l=o!==void 0?{missing:[],tfstateCandidatesChecked:[]}:Ms({env:process.env});l.missing.length>0&&e.stderr.write(`[lmctl-next-agent] mailbox transport not configured: missing ${l.missing.join(", ")}; running without cloud sync`+(l.tfstatePathUsed===void 0?` (no terraform.tfstate found; checked ${l.tfstateCandidatesChecked.length} candidate path${l.tfstateCandidatesChecked.length===1?"":"s"})`:` (terraform.tfstate at ${l.tfstatePathUsed} did not supply the missing fields)`)+`
|
|
2169
2251
|
`);let c=await AF({log:b=>e.stderr.write(`${b}
|
|
2170
2252
|
`)}),d=new Vo({adapterFactory:MT,publish:async()=>{throw new Error("persistent_publish_not_wired: mailbox runtime has not bound the publish hook yet")},log:b=>e.stderr.write(`${b}
|
|
2171
|
-
`)}),u=
|
|
2253
|
+
`)}),u=Xr()?.device_id,f=Yw({dal:n,daemon:a,...l.config!==void 0?{webuiRuntimeConfig:NF(l.config,u)}:{},...c!==void 0?{terminalSessionManager:c}:{},persistentSessionManager:d,...o!==void 0?{localWebui:{webuiDir:o.webuiDir,localMailbox:{s3:o.s3,commands:o.commands}}}:{},authDisabled:r.insecureNoAuth}),m=process.env.LMCTL_USAGE_QUOTA_USD,p=m!==void 0&&m!==""?Number(m):NaN,h=Number.isFinite(p)&&p>0?p:void 0,g=await YT({dal:n,app:f,io:e,mailbox:l.config===void 0?void 0:{...l.config,cursorStore:n,chatLogTailStore:n,promptTriggerStore:n,usageStore:n,...h!==void 0?{usageQuotaUsd:h}:{},...u!==void 0?{deviceId:u}:{}},...o!==void 0?{localMailbox:{rootDir:o.rootDir,s3:o.s3,commands:o.commands,promptTriggerStore:n}}:{},...c!==void 0?{terminalSessionManager:c}:{},persistentSessionManager:d});await VT({dal:n,mailbox:g.mailbox,io:e});let{serve:_}=await import("@hono/node-server"),y=await new Promise((b,I)=>{let x,H=pe=>I(pe);x=_({fetch:f.fetch,port:i.port,hostname:r.bind},()=>{x.removeListener?.("error",H),b(x)}),x.once("error",H)}).catch(async b=>(a!==void 0&&await a.stop().catch(()=>{}),await g.stop().catch(()=>{}),c!==void 0&&await c.stop().catch(()=>{}),await d.stop().catch(()=>{}),n.close(),e.stderr.write(`error: could not bind ${r.bind}:${i.port}: ${b instanceof Error?b.message:String(b)}
|
|
2172
2254
|
`),null));if(y===null)return 2;e.stdout.write(`listening on ${r.bind}:${i.port}
|
|
2173
2255
|
`);let T=Z();try{let b=ka(T);b.running&&b.entry!==null&&b.entry.pid!==process.pid&&e.stderr.write(`note: replacing pidfile for a still-running daemon (pid ${b.entry.pid}, port ${b.entry.port}); \`lmctl serve stop\` will now target pid ${process.pid}
|
|
2174
2256
|
`);let I=FT({pid:process.pid,startedAt:new Date().toISOString(),port:i.port,bind:r.bind,dbPath:T,startToken:UT()},T);e.stdout.write(`pidfile ${I} (pid ${process.pid})
|
|
2175
2257
|
`)}catch(b){e.stderr.write(`warning: could not write serve pidfile: ${b instanceof Error?b.message:String(b)}; \`lmctl serve status\`/\`stop\` will not find this daemon
|
|
2176
|
-
`)}return await new Promise(b=>{let I=()=>{(async()=>{a!==void 0&&await a.stop(),y.close(),await g.stop(),c!==void 0&&await c.stop(),await d.stop(),n.close();try{let x=qu(T);x!==null&&x.pid===process.pid&&An(T)}catch{}b()})()};process.once("SIGTERM",I),process.once("SIGINT",I)}),0}function
|
|
2258
|
+
`)}return await new Promise(b=>{let I=()=>{(async()=>{a!==void 0&&await a.stop(),y.close(),await g.stop(),c!==void 0&&await c.stop(),await d.stop(),n.close();try{let x=qu(T);x!==null&&x.pid===process.pid&&An(T)}catch{}b()})()};process.once("SIGTERM",I),process.once("SIGINT",I)}),0}function JT(t){if(t.stdout!==process.stdout||Xu)return;Xu=!0;let e=r=>{throw r.code==="EPIPE"&&process.exit(0),process.stdout.off("error",e),r};process.stdout.on("error",e)}function TF(){Xu=!1}async function GT(t,e){return JT(e),bF(t,e)}async function bF(t,e){if(t.length>0)return e.stderr.write(`error: lmctl serve status takes no arguments; got: ${t.join(" ")}
|
|
2177
2259
|
`),2;let r=Z(),n=ka(r);if(n.entry===null)return e.stdout.write(`serve: not running
|
|
2178
2260
|
`),e.stdout.write(n.corrupt?` unreadable pidfile at ${Ot(r)} (could not parse)
|
|
2179
2261
|
run \`lmctl serve stop\` to clear it
|
|
@@ -2213,7 +2295,7 @@ ${qT.replace(/^error: [^\n]*\n\n/,"")}`),2):EF(t.slice(1),e)}async function EF(t
|
|
|
2213
2295
|
`)}catch(r){let n=r instanceof Error?r.message:String(r);t.io?.stderr.write(`[mailbox] WARNING: cloud mailbox auto-delivery is DISABLED; daemon continues without remote inbox relay: ${n}
|
|
2214
2296
|
`)}return{...e!==void 0?{mailbox:e}:{},async stop(){e!==void 0&&await e.stop()}}}function zT(t){let{dal:e,cli:r,env:n,parsed:s,io:i}=t,o=[],a,l=e.getConfig("api.port");if(r.portCli!==void 0)a=r.portCli;else if(l!==null){let m=Number(l);if(!Number.isInteger(m)||m<=0||m>65535)throw new Error(`invalid api.port in lmctl_config: ${l}`);a=m}else if(n.LMCTL_API_PORT!==void 0&&n.LMCTL_API_PORT.length>0){let m=Number(n.LMCTL_API_PORT);if(!Number.isInteger(m)||m<=0||m>65535)throw new Error(`invalid LMCTL_API_PORT: ${n.LMCTL_API_PORT}`);a=m,o.push("api.port")}else a=s.port;let c,d=e.getConfig("api.token");n.LMCTL_API_TOKEN!==void 0&&n.LMCTL_API_TOKEN.length>0?(c=n.LMCTL_API_TOKEN,d===null?o.push("api.token"):d!==c&&i.stderr.write(`note: LMCTL_API_TOKEN env var overrides lmctl_config api.token for this serve process.
|
|
2215
2297
|
`)):d!==null?c=d:(c=hF(32).toString("hex"),e.setConfig("api.token",c),i.stdout.write("Generated initial api.token; view via `lmctl api config get api.token`\n"));let u,f=e.getConfig("api.url");f!==null?u=f:n.LMCTL_API_URL!==void 0&&n.LMCTL_API_URL.length>0?(u=n.LMCTL_API_URL,o.push("api.url")):(u=`http://127.0.0.1:${a}`,e.setConfig("api.url",u));for(let m of o)i.stderr.write(`note: ${xF(m)} env var used as fallback for ${m}; consider \`lmctl api config set ${m} ...\` to make this DB-canonical.
|
|
2216
|
-
`);return{port:a,apiUrl:u,apiToken:c}}function xF(t){switch(t){case"api.port":return"LMCTL_API_PORT";case"api.token":return"LMCTL_API_TOKEN";case"api.url":return"LMCTL_API_URL";default:return`LMCTL_${t.replaceAll(".","_").toUpperCase()}`}}async function AF(t){let e;try{e=await import("node-pty")}catch(r){let n=r instanceof Error?r.message:String(r);t.log(`[dt-2] node-pty not available; terminal routes will return 503 (${n})`);return}return new Ko({pty:{spawn:e.spawn.bind(e)},publish:async()=>{throw new Error("terminal_publish_not_wired: mailbox runtime has not bound the publish hook yet")},log:t.log})}function ZT(t,e){let r=t!==void 0&&t!==""?t:e.LMCTL_LOCAL_WEBUI_DIR!==void 0&&e.LMCTL_LOCAL_WEBUI_DIR!==""?e.LMCTL_LOCAL_WEBUI_DIR:void 0;if(r===void 0)return null;let n=
|
|
2298
|
+
`);return{port:a,apiUrl:u,apiToken:c}}function xF(t){switch(t){case"api.port":return"LMCTL_API_PORT";case"api.token":return"LMCTL_API_TOKEN";case"api.url":return"LMCTL_API_URL";default:return`LMCTL_${t.replaceAll(".","_").toUpperCase()}`}}async function AF(t){let e;try{e=await import("node-pty")}catch(r){let n=r instanceof Error?r.message:String(r);t.log(`[dt-2] node-pty not available; terminal routes will return 503 (${n})`);return}return new Ko({pty:{spawn:e.spawn.bind(e)},publish:async()=>{throw new Error("terminal_publish_not_wired: mailbox runtime has not bound the publish hook yet")},log:t.log})}function ZT(t,e){let r=t!==void 0&&t!==""?t:e.LMCTL_LOCAL_WEBUI_DIR!==void 0&&e.LMCTL_LOCAL_WEBUI_DIR!==""?e.LMCTL_LOCAL_WEBUI_DIR:void 0;if(r===void 0)return null;let n=XT(r)?r:Hu(process.cwd(),r);return HT(`${n}/index.html`)?n:null}function QT(t){let e=t.LMCTL_LOCAL_MAILBOX_DIR;return e!==void 0&&e!==""?XT(e)?e:Hu(process.cwd(),e):Hu(gF(),".lmctl","local-mailbox")}function RF(t){for(let e=0;e<t.length;e+=1)if(t[e]==="--port"){let r=t[e+1];if(r!==void 0&&!r.startsWith("--")){let n=Number(r);if(Number.isInteger(n)&&n>0&&n<=65535)return n}}}function eb(t,e=process.env){let r=OF(t);return typeof r=="string"?r:!LF(r.bind)&&!r.insecureNoAuth&&!e.LMCTL_API_TOKEN?`auth required for non-loopback --bind ${r.bind}; set LMCTL_API_TOKEN or pass --insecure-no-auth`:r}function LF(t){let e=t.trim().toLowerCase();if(e==="localhost"||e==="::1")return!0;if(e.startsWith("::ffff:")){let r=e.slice(7);return BT(r)===4&&r.split(".")[0]==="127"}return BT(e)===4&&e.split(".")[0]==="127"}function OF(t){let e={port:8787,bind:"127.0.0.1",noDaemon:!1,insecureNoAuth:!1};for(let r=0;r<t.length;r+=1){let n=t[r];if(n==="--port"){let s=t[++r];if(s===void 0||s.startsWith("--"))return"missing value for --port";let i=Number(s);if(!Number.isInteger(i)||i<=0||i>65535)return`invalid --port: ${s}`;e.port=i;continue}if(n==="--bind"){let s=t[++r];if(s===void 0||s.startsWith("--"))return"missing value for --bind";e.bind=s;continue}if(n==="--no-daemon"){e.noDaemon=!0;continue}if(n==="--insecure-no-auth"){e.insecureNoAuth=!0;continue}if(n==="--webui"){let s=t[r+1];s!==void 0&&!s.startsWith("--")?(e.localWebui={dir:s},r+=1):e.localWebui={dir:void 0};continue}return`unknown argument: ${n}`}return e}var yF,qT,Xu,SF,kF,IF,rb=E(()=>{"use strict";Qe();Qw();pu();WE();td();ju();yu();Hd();Xd();jT();Bu();We();Yn();Dc();WT();yF=`usage: lmctl serve <start|status|stop> [options]
|
|
2217
2299
|
|
|
2218
2300
|
Manage the local lmctl daemon: HTTP API, web UI, queue daemon, terminal
|
|
2219
2301
|
manager, and agent services. A subcommand is REQUIRED \u2014 bare \`lmctl serve\`
|
|
@@ -2269,17 +2351,17 @@ unauthenticated daemon.
|
|
|
2269
2351
|
lmctl serve stop
|
|
2270
2352
|
|
|
2271
2353
|
Run 'lmctl serve --help' for details.
|
|
2272
|
-
`;
|
|
2273
|
-
`,"utf8"),st.renameSync(r,t)}catch(n){try{st.unlinkSync(r)}catch{}throw n}}function BF(t,e){st.mkdirSync(js(t),{recursive:!0});let r=gt(js(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{st.writeFileSync(r,e,"utf8"),st.renameSync(r,t)}catch(n){try{st.unlinkSync(r)}catch{}throw n}}function Tr(t,e,r){try{if(!st.existsSync(t))return;let n=JSON.parse(st.readFileSync(t,"utf8"));if(!On(n)||!On(n[e]))return;let s={...n[e]},i=[];for(let{name:o,shouldRemove:a}of r)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;n[e]=s,WF(t,n),C({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Rn(){return{name:Na,shouldRemove:zF}}function ab(){return{name:Na,shouldRemove:ZF}}function Ln(){return{name:Ia,shouldRemove:VF}}function lb(){return{name:Ia,shouldRemove:YF}}function qF(t){let e=ib??sb();switch(t){case"copilot":Tr(ob(e),"mcpServers",[Rn(),Ln()]);return;case"claude":Tr(gt(e,".claude.json"),"mcpServers",[Rn(),Ln()]);return;case"gemini":Tr(gt(e,".gemini","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"qwen":Tr(gt(e,".qwen","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"agy":Tr(gt(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"opencode":Tr(gt(e,".config","opencode","opencode.json"),"mcp",[ab(),lb()]);return;case"codex":HF(gt(e,".codex","config.toml"));return;default:return}}function HF(t){try{if(!st.existsSync(t))return;let e=st.readFileSync(t,"utf8"),r=
|
|
2274
|
-
`)),C({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function nb(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function
|
|
2354
|
+
`;Xu=!1;SF=2e3;kF=100,IF=1e4});import{existsSync as $F,mkdirSync as CF,readFileSync as MF,renameSync as jF,unlinkSync as DF,writeFileSync as PF}from"node:fs";import{homedir as sb}from"node:os";import{dirname as js,join as gt,resolve as FF}from"node:path";function $n(t,e,r){let n=js(FF(r)),s=new Set,i=new Map;for(let o of e.members){if(s.add(o.provider),o.teamfile!==void 0)continue;let a=o.sessiondir??n,l=i.get(a)??new Set;l.add(o.provider),i.set(a,l)}for(let[o,a]of i.entries())Tr(gt(o,".mcp.json"),"mcpServers",[Rn(),Ln()]),a.has("opencode")&&Tr(gt(o,".opencode","opencode.json"),"mcp",[ab(),lb()]);for(let o of s)qF(o)}function ob(t=ib??sb()){return gt(t,".copilot","mcp-config.json")}function WF(t,e){st.mkdirSync(js(t),{recursive:!0});let r=gt(js(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{st.writeFileSync(r,`${JSON.stringify(e,null,2)}
|
|
2355
|
+
`,"utf8"),st.renameSync(r,t)}catch(n){try{st.unlinkSync(r)}catch{}throw n}}function BF(t,e){st.mkdirSync(js(t),{recursive:!0});let r=gt(js(t),`.mcp-config.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`);try{st.writeFileSync(r,e,"utf8"),st.renameSync(r,t)}catch(n){try{st.unlinkSync(r)}catch{}throw n}}function Tr(t,e,r){try{if(!st.existsSync(t))return;let n=JSON.parse(st.readFileSync(t,"utf8"));if(!On(n)||!On(n[e]))return;let s={...n[e]},i=[];for(let{name:o,shouldRemove:a}of r)Object.prototype.hasOwnProperty.call(s,o)&&a(s[o])&&(delete s[o],i.push(o));if(i.length===0)return;n[e]=s,WF(t,n),C({event:"mcp_cleanup",path:t,removed:i})}catch{}}function Rn(){return{name:Na,shouldRemove:zF}}function ab(){return{name:Na,shouldRemove:ZF}}function Ln(){return{name:Ia,shouldRemove:VF}}function lb(){return{name:Ia,shouldRemove:YF}}function qF(t){let e=ib??sb();switch(t){case"copilot":Tr(ob(e),"mcpServers",[Rn(),Ln()]);return;case"claude":Tr(gt(e,".claude.json"),"mcpServers",[Rn(),Ln()]);return;case"gemini":Tr(gt(e,".gemini","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"qwen":Tr(gt(e,".qwen","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"agy":Tr(gt(e,".gemini","antigravity-cli","settings.json"),"mcpServers",[Rn(),Ln()]);return;case"opencode":Tr(gt(e,".config","opencode","opencode.json"),"mcp",[ab(),lb()]);return;case"codex":HF(gt(e,".codex","config.toml"));return;default:return}}function HF(t){try{if(!st.existsSync(t))return;let e=st.readFileSync(t,"utf8"),r=XF(e);if(r===null)return;let n=e.split(/\n/),s=[],i=new Set,o=!1,a;for(let l of n){let c=cb(l);if(c===null)return;if(c!==void 0){if(nb(c,r)){o=!0,a=c[1],i.add(a);continue}o=!1,a=void 0,s.push(l);continue}if(o){if(/^\s*(?:#.*)?$/.test(l)){s.push(l);continue}a!==void 0&&i.add(a);continue}let d=GF(l);if(d===null)return;if(d!==void 0&&nb(d,r)){i.add(d[1]);continue}s.push(l)}if(i.size===0)return;BF(t,s.join(`
|
|
2356
|
+
`)),C({event:"mcp_cleanup",path:t,removed:[...i]})}catch{}}function nb(t,e){return t.length<2||t[0]!=="mcp_servers"?!1:e.has(t[1])}function XF(t){let e=new Map,r;for(let s of t.split(/\n/)){let i=cb(s);if(i===null)return null;if(i!==void 0){r=i;continue}let o=s.indexOf("=");if(o<0)continue;let a=s.slice(0,o).trim(),l=s.slice(o+1).trim(),c=JF(a,r);if(c===null)return null;if(c===void 0||c.length!==3||c[0]!=="mcp_servers"||c[1]!==Ia&&c[1]!==Na)continue;let d=e.get(c[1])??{};if(c[2]==="command"){let u=db(l);if(u===null)return null;d.command=u}else if(c[2]==="args"){let u=KF(l);if(u===null)return null;d.args=u}e.set(c[1],d)}let n=new Set;for(let[s,i]of e.entries())s===Ia&&fb(i.command,i.args)&&n.add(s),s===Na&&mb(i.command,i.args)&&n.add(s);return n}function JF(t,e){if(t.startsWith("mcp_servers"))return xa(t);if(e===void 0||e.length<2||e[0]!=="mcp_servers")return;let r=xa(t);return r===null?null:[...e,...r]}function cb(t){if(!/^\s*\[/.test(t))return;let e=/^\s*\[([^\]\r\n]+)\]\s*(?:#.*)?$/.exec(t);return e===null?null:xa(e[1])}function GF(t){let e=t.indexOf("=");if(e<0)return;let r=t.slice(0,e).trim();if(!(r.length===0||!r.startsWith("mcp_servers")))return xa(r)}function xa(t){let e=[],r=0,n=()=>{for(;r<t.length&&/\s/.test(t[r]);)r+=1};for(;r<t.length;){if(n(),r>=t.length)return null;if(t[r]==='"'){r+=1;let s="",i=!1;for(;r<t.length;){let o=t[r];if(o==="\\"){if(r+1>=t.length)return null;s+=t[r+1],r+=2;continue}if(o==='"'){r+=1,i=!0;break}s+=o,r+=1}if(!i)return null;e.push(s)}else{let s=r;for(;r<t.length&&/[A-Za-z0-9_-]/.test(t[r]);)r+=1;if(r===s)return null;e.push(t.slice(s,r))}if(n(),r>=t.length)break;if(t[r]!==".")return null;r+=1}return e.length>0?e:null}function db(t){let e=ub(t).trim();if(e.startsWith('"'))try{let r=JSON.parse(e);return typeof r=="string"?r:null}catch{return null}return e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1):null}function KF(t){let e=ub(t).trim();if(!e.startsWith("[")||!e.endsWith("]"))return null;let r=e.slice(1,-1).trim();if(r.length===0)return[];let n=r.split(",").map(s=>db(s.trim()));return n.some(s=>s===null)?null:n}function ub(t){let e;for(let r=0;r<t.length;r+=1){let n=t[r];if(e!==void 0){if(e==='"'&&n==="\\"){r+=1;continue}n===e&&(e=void 0);continue}if(n==='"'||n==="'"){e=n;continue}if(n==="#")return t.slice(0,r)}return t}function VF(t){return On(t)?t.type==="stdio"&&typeof t.command=="string"&&fb(t.command,t.args):!1}function YF(t){return!On(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&_b(t.command[0])&&t.command[1]==="mcp"||t.command.length===3&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&typeof t.command[2]=="string"&&pb(t.command[0],[t.command[1],t.command[2]])}function zF(t){return On(t)?t.type==="stdio"&&mb(t.command,t.args):!1}function ZF(t){return!On(t)||!Array.isArray(t.command)?!1:t.command.length===2&&typeof t.command[0]=="string"&&typeof t.command[1]=="string"&&hb(t.command[0])&&t.command[1]==="mcp"}function fb(t,e){return _b(t)&&gb(e)||pb(t,e)}function mb(t,e){return hb(t)&&gb(e)}function pb(t,e){return QF(t)&&Array.isArray(e)&&e.length===2&&e1(e[0])&&e[1]==="mcp"}function _b(t){return typeof t=="string"&&Ju(t)==="lmctl"}function hb(t){return typeof t=="string"&&Ju(t)==="lmctl0"}function QF(t){if(typeof t!="string")return!1;let e=Ju(t).toLowerCase();return e==="node"||e==="node.exe"}function e1(t){if(typeof t!="string")return!1;let e=t.replace(/\\/g,"/");return e==="lmctl-cli/dist/index.js"||e.endsWith("/lmctl-cli/dist/index.js")}function Ju(t){let e=t.replace(/\\/g,"/");return e.split("/").filter(n=>n.length>0).at(-1)??e}function gb(t){return Array.isArray(t)&&t.length===1&&t[0]==="mcp"}function On(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var Ia,Na,UF,st,ib,Ds=E(()=>{"use strict";de();Ia="lmctl",Na="lmctl0",UF={existsSync:$F,mkdirSync:CF,readFileSync:MF,writeFileSync:PF,renameSync:jF,unlinkSync:DF},st=UF});function Eb(t){let e=yb(t.registry,t.fromTeamfile);if(e===void 0)return Cn(`sender team is not registered in policy graph: ${t.fromTeamfile}`);if(!wb(e,t.fromAlias))return Cn(`sender alias "${t.fromAlias}" not found in ${t.fromTeamfile}`);let r=yb(t.registry,t.toTeamfile);return r===void 0?Cn(`target team is not registered in policy graph: ${t.toTeamfile}`):wb(r,t.toAlias)?t.toTeamfile===t.fromTeamfile?{allowed:!0,outOfPolicy:!1,reason:"same team"}:e.leadAlias===null?Cn(`sender team has no Lead: ${t.fromTeamfile}`):t.fromAlias!==e.leadAlias?Cn(`cross-team sends may only originate from Lead; got "${t.fromAlias}" in ${t.fromTeamfile}`):{allowed:!0,outOfPolicy:!1,reason:"cross-team send from Lead"}:Cn(`target alias "${t.toAlias}" not found in ${t.toTeamfile}`)}function yb(t,e){return t.teams.find(r=>r.teamfile===e)}function wb(t,e){return t.aliases.some(r=>r===e)}function Cn(t){return{allowed:!1,outOfPolicy:!0,reason:t}}var Tb=E(()=>{"use strict"});import{randomUUID as t1}from"node:crypto";import{hostname as bb,networkInterfaces as r1}from"node:os";function Sb(t){let e=(t.now??new Date).toISOString();return{lock_id:t1(),teamfile:t.teamfile,alias:t.alias,holder_pid:t.pid??process.pid,holder_host:t.host??bb(),holder_ips:t.ips??a1(),started_at:e,last_heartbeat:e}}function vb(t=process.env){return kb(t.LMCTL_TERMINAL_LOCK_HEARTBEAT_MS,n1)}function i1(t=process.env){return kb(t.LMCTL_TERMINAL_LOCK_STALE_MS,s1)}function Gu(t,e={}){let r=e.now??new Date,n=e.localHost??bb(),s=e.staleMs??i1();if(t.holder_host===n)return(e.isProcessAlive??o1)(t.holder_pid)?{live:!0,reason:"local-pid-alive"}:{live:!1,reason:"dead-pid"};let i=Date.parse(t.last_heartbeat);return Number.isFinite(i)?r.getTime()-i<=s?{live:!0,reason:"remote-heartbeat-fresh"}:{live:!1,reason:"stale-heartbeat"}:{live:!1,reason:"stale-heartbeat"}}function Ku(t){return`${t.alias} is held by a terminal on ${t.holder_host} since ${t.started_at}; retry later`}function kb(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 o1(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 a1(){let t=new Set;for(let e of Object.values(r1()))for(let r of e??[])r.internal||t.add(r.address);return[...t].sort()}var n1,s1,Vu=E(()=>{"use strict";n1=15e3,s1=12e4});function l1(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is not set \u2014 it looks like you are running lmctl
|
|
2275
2357
|
manually, outside a member session that lmctl started. Running lmctl this way is
|
|
2276
2358
|
not officially supported.
|
|
2277
2359
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Ps(t){return`lmctl ${t}: LMCTL_SELF_SESSIONID is set but does not match any member of a registered team.
|
|
2278
2360
|
The session marker may be stale or the team may not be registered in this lmctl database.
|
|
2279
2361
|
Consulted ${ei(Dt(),Z())}
|
|
2280
2362
|
To experiment with it manually: https://lmctl.com/lmctl/docs/manual-invocation`}function Ib(t){return`unknown option --from
|
|
2281
|
-
${l1(t)}`}function Nb(t,e){let r=Yu(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function Yu(t,e){let r=t[ts];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=Fe(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===r&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var Aa=E(()=>{"use strict";at();We();Zt()});function
|
|
2282
|
-
`}),i=await m1(r,{receiverTeamfile:d,receiverAlias:c.alias,sender:f,rootTeamfile:m,provider:c.provider,model:c.model,sessionId:c.sessionid,cwd:c.sessiondir,prompt:t.prompt,origin:u.origin}),o=h1(r,i);try{$n(r,Ve(d),d)}catch{}n={root_teamfile:m,sender_teamfile:f?.teamfile??null,sender_alias:f?.alias??null,receiver_teamfile:d,receiver_alias:c.alias,origin:u.origin,policy:p};let h=await Lb(r,d,c.alias);if(h!==null){let I=Ku(h);if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}let g=await u1(r,d,c.alias);if(g.busy){if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}let I=await f1(r,d,c.alias);return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}if(f!==null&&f.teamfile!==d){let I=await $(r,x=>yE(x,{root:m,sender:f,receiverTeamfile:d,receiverAlias:c.alias,now:new Date}));if(I.stop){let x=EE(I.chain);return Mn(i,n,t.prompt,x,"cycle"),a=La(x,null),{status:"error",errorKind:"cycle",message:x,teamChatLogId:null}}}let _=await S1(r,{receiver_teamfile:d,receiver_alias:c.alias,sender_teamfile:f?.teamfile??d,sender_alias:f?.alias??"operator",...g.idleReclaim?{force:!0}:{}});if(!_.acquired){let I=Ob(d,c.alias,_.current);if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}s=_.lease;let y=await ia({sender:f??{teamfile:d,alias:"operator"},receiver:{teamfile:d,alias:c.alias,provider:c.provider,sessionId:c.sessionid,cwd:c.sessiondir,...c.model!==void 0?{model:c.model}:{},...c.effort!==void 0?{effort:c.effort}:{},...c.isLead!==void 0?{isLead:c.isLead}:{}},newMessage:t.prompt,newMessageFrom:f===null?"operator":`${f.teamfile}:${f.alias}`,io:r,permissionMode:t.permissionMode,env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:I=>e({kind:"delta",chunk:I}),onProgress:I=>e({kind:"progress",alias:c.alias,event:I}),onPromptBuilt:I=>{if(l=I,i!==null)return _1(r,i,I)}});l=y.prompt;let T=y.status==="stalled",b=null;if(T){let I=`provider stalled${y.stalledAfterMs!==void 0?` after ${y.stalledAfterMs}ms`:""}`;Mn(i,n,l,I,"error"),a=La(I,null,y.receipt)}else b=await k1(r,{...n,message:l,response:y.receipt,status:n.policy?.outOfPolicy===!0?"out_of_policy":"ok",error_detail:n.policy?.outOfPolicy===!0?n.policy.reason:null}),a=Ra(y.receipt,b);return{status:T?"stalled":"ok",replyText:y.receipt,wroteDelta:y.wroteDelta,teamChatLogId:b,durationMs:y.durationMs}}catch(c){let d=c instanceof Error?c.message:String(c);return Mn(i,n,l,d,"error"),a=La(d,null),{status:"error",errorKind:c instanceof we?"target":"provider",message:d,teamChatLogId:null}}finally{o!==void 0&&clearInterval(o),s!==null&&await v1(r,s),i!==null&&await p1(r,i,a??La("chat turn exited without a terminal outcome",null))}}function d1(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function u1(t,e,r){let n=await $(t,i=>Vt(i,e,r));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await $(t,i=>pa(i,n,e,r));return{busy:!s,idleReclaim:s}}async function f1(t,e,r){let n=await Lb(t,e,r);if(n!==null)return Ku(n);let s=await $(t,i=>i.getAgentInflight(e,r));return s!==null?Ob(e,r,s):`${r} is busy; wait and retry`}async function Zu(t,e){return await oa(t,t.env??process.env),await $(t,r=>r.enqueueMail({sender_teamfile:e.sender.teamfile,sender_alias:e.sender.alias,receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,payload:e.payload}))}function Qu(t,e,r,n){let s=`${r}:${n}`;return{status:"enqueued",id:t,message:`mailbox message ${t} enqueued to ${s}`,teamChatLogId:null,sender:`${e.teamfile}:${e.alias}`,receiver:s}}async function m1(t,e){try{return(await $(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:g1(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return ce()&&Oe(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function p1(t,e,r){try{await $(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){ce()&&Oe(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function _1(t,e,r){try{await $(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){ce()&&Oe(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}function h1(t,e){if(e===null)return;let r=setInterval(()=>{$(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{ce()&&Oe(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},c1);return r.unref?.(),r}function Ra(t,e){return{status:"done",result_summary:Fs(t),error:null,team_chat_log_id:e}}function ef(t,e){return{status:"busy",result_summary:Fs(t),error:t,team_chat_log_id:e}}function La(t,e,r){return{status:"error",result_summary:Fs(r===void 0?t:r),error:t,team_chat_log_id:e}}function Fs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function g1(t,e,r){return`lmctl chat ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function y1(t,e){let r=Nb(e,t);if(r.ok)return{sender:
|
|
2363
|
+
${l1(t)}`}function Nb(t,e){let r=Yu(t,e);return r.ok?{ok:!0,identity:r.identity,source:"session"}:r}function Yu(t,e){let r=t[ts];if(r===void 0||r.length===0)return{ok:!1,reason:"unset"};let n=[];for(let i of e.listRootTeams()){let o;try{o=Fe(i.teamfile_path,e)}catch{continue}for(let a of o.members)a.teamfile===void 0&&a.session===r&&n.push(`${i.teamfile_path}:${a.alias}`)}let s=[...new Set(n)];if(s.length===0)return{ok:!1,reason:"not-found"};if(s.length>1)throw new Error("LMCTL_SELF_SESSIONID matches multiple team members; the team registry is ambiguous");return{ok:!0,identity:s[0]}}var Aa=E(()=>{"use strict";at();We();Zt()});function Jr(t){let e=Hr(t);if(e===null)throw new Error(`invalid agent identity: ${t}`);return{teamfile:e.teamfile,alias:e.alias,value:t}}var zu=E(()=>{"use strict";ht()});async function Oa(t){let e=t.onEvent??(()=>{}),r=d1(t.io,e),n=null,s=null,i=null,o,a=null,l=t.prompt;try{let c=await $(r,I=>$e(t.teamfile,t.alias,I)),d=c.teamfile,u=await $(r,I=>y1(I,t.env??process.env)),f=u.sender,m=await w1(r,{explicitRoot:t.rootFlag,sender:f,receiverTeamfile:d,operatorOrigin:u.origin==="operator"}),p=f===null?null:await E1(r,{rootTeamfile:m,sender:f,receiverTeamfile:d,receiverAlias:c.alias});p!==null&&!p.allowed&&e({kind:"warning",message:`warning: out-of-policy chat send: ${p.reason}
|
|
2364
|
+
`}),i=await m1(r,{receiverTeamfile:d,receiverAlias:c.alias,sender:f,rootTeamfile:m,provider:c.provider,model:c.model,sessionId:c.sessionid,cwd:c.sessiondir,prompt:t.prompt,origin:u.origin}),o=h1(r,i);try{$n(r,Ve(d),d)}catch{}n={root_teamfile:m,sender_teamfile:f?.teamfile??null,sender_alias:f?.alias??null,receiver_teamfile:d,receiver_alias:c.alias,origin:u.origin,policy:p};let h=await Lb(r,d,c.alias);if(h!==null){let I=Ku(h);if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}let g=await u1(r,d,c.alias);if(g.busy){if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}let I=await f1(r,d,c.alias);return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}if(f!==null&&f.teamfile!==d){let I=await $(r,x=>yE(x,{root:m,sender:f,receiverTeamfile:d,receiverAlias:c.alias,now:new Date}));if(I.stop){let x=EE(I.chain);return Mn(i,n,t.prompt,x,"cycle"),a=La(x,null),{status:"error",errorKind:"cycle",message:x,teamChatLogId:null}}}let _=await S1(r,{receiver_teamfile:d,receiver_alias:c.alias,sender_teamfile:f?.teamfile??d,sender_alias:f?.alias??"operator",...g.idleReclaim?{force:!0}:{}});if(!_.acquired){let I=Ob(d,c.alias,_.current);if(f!==null){let x=await Zu(r,{sender:f,receiverTeamfile:d,receiverAlias:c.alias,rootTeamfile:m,payload:t.prompt});return a=Ra(`enqueued mailbox message ${x.id}`,null),Qu(x.id,f,d,c.alias)}return Mn(i,n,t.prompt,I,"unavailable"),a=ef(I,null),{status:"busy",message:I,teamChatLogId:null}}s=_.lease;let y=await ia({sender:f??{teamfile:d,alias:"operator"},receiver:{teamfile:d,alias:c.alias,provider:c.provider,sessionId:c.sessionid,cwd:c.sessiondir,...c.model!==void 0?{model:c.model}:{},...c.effort!==void 0?{effort:c.effort}:{},...c.isLead!==void 0?{isLead:c.isLead}:{}},newMessage:t.prompt,newMessageFrom:f===null?"operator":`${f.teamfile}:${f.alias}`,io:r,permissionMode:t.permissionMode,env:t.env??process.env,...t.idleTimeoutMs!==void 0?{idleTimeoutMs:t.idleTimeoutMs}:{},onDelta:I=>e({kind:"delta",chunk:I}),onProgress:I=>e({kind:"progress",alias:c.alias,event:I}),onPromptBuilt:I=>{if(l=I,i!==null)return _1(r,i,I)}});l=y.prompt;let T=y.status==="stalled",b=null;if(T){let I=`provider stalled${y.stalledAfterMs!==void 0?` after ${y.stalledAfterMs}ms`:""}`;Mn(i,n,l,I,"error"),a=La(I,null,y.receipt)}else b=await k1(r,{...n,message:l,response:y.receipt,status:n.policy?.outOfPolicy===!0?"out_of_policy":"ok",error_detail:n.policy?.outOfPolicy===!0?n.policy.reason:null}),a=Ra(y.receipt,b);return{status:T?"stalled":"ok",replyText:y.receipt,wroteDelta:y.wroteDelta,teamChatLogId:b,durationMs:y.durationMs}}catch(c){let d=c instanceof Error?c.message:String(c);return Mn(i,n,l,d,"error"),a=La(d,null),{status:"error",errorKind:c instanceof we?"target":"provider",message:d,teamChatLogId:null}}finally{o!==void 0&&clearInterval(o),s!==null&&await v1(r,s),i!==null&&await p1(r,i,a??La("chat turn exited without a terminal outcome",null))}}function d1(t,e){return{...t,stdout:{write:()=>{}},stderr:{write:r=>{e({kind:"warning",message:r})}}}}async function u1(t,e,r){let n=await $(t,i=>Vt(i,e,r));if(!n.busy)return{busy:!1,idleReclaim:!1};let s=await $(t,i=>pa(i,n,e,r));return{busy:!s,idleReclaim:s}}async function f1(t,e,r){let n=await Lb(t,e,r);if(n!==null)return Ku(n);let s=await $(t,i=>i.getAgentInflight(e,r));return s!==null?Ob(e,r,s):`${r} is busy; wait and retry`}async function Zu(t,e){return await oa(t,t.env??process.env),await $(t,r=>r.enqueueMail({sender_teamfile:e.sender.teamfile,sender_alias:e.sender.alias,receiver_teamfile:e.receiverTeamfile,receiver_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,payload:e.payload}))}function Qu(t,e,r,n){let s=`${r}:${n}`;return{status:"enqueued",id:t,message:`mailbox message ${t} enqueued to ${s}`,teamChatLogId:null,sender:`${e.teamfile}:${e.alias}`,receiver:s}}async function m1(t,e){try{return(await $(t,n=>n.startTrackedInvocation({kind:"chat",origin:e.origin,scope_teamfile:e.receiverTeamfile,from_identity:e.sender===null?"operator":`${e.sender.teamfile}:${e.sender.alias}`,target_teamfile:e.receiverTeamfile,target_alias:e.receiverAlias,root_teamfile:e.rootTeamfile,cwd:e.cwd??null,command:g1(e.receiverTeamfile,e.receiverAlias,e.prompt),holder_pid:process.pid,request_payload:e.prompt,meta:JSON.stringify({provider:e.provider,model:e.model??null,sessionid:e.sessionId??null})}))).id}catch(r){return ce()&&Oe(JSON.stringify({event:"tracked_invocation_start_error",error:r instanceof Error?r.message:String(r)})),null}}async function p1(t,e,r){try{await $(t,n=>{n.finishTrackedInvocation(e,r)})}catch(n){ce()&&Oe(JSON.stringify({event:"tracked_invocation_finish_error",id:e,error:n instanceof Error?n.message:String(n)}))}}async function _1(t,e,r){try{await $(t,n=>{n.updateTrackedInvocationRequestPayload(e,r)})}catch(n){ce()&&Oe(JSON.stringify({event:"tracked_invocation_request_payload_error",id:e,error:n instanceof Error?n.message:String(n)}))}}function h1(t,e){if(e===null)return;let r=setInterval(()=>{$(t,n=>n.heartbeatTrackedInvocation(e)).catch(n=>{ce()&&Oe(JSON.stringify({event:"tracked_invocation_heartbeat_error",id:e,error:n instanceof Error?n.message:String(n)}))})},c1);return r.unref?.(),r}function Ra(t,e){return{status:"done",result_summary:Fs(t),error:null,team_chat_log_id:e}}function ef(t,e){return{status:"busy",result_summary:Fs(t),error:t,team_chat_log_id:e}}function La(t,e,r){return{status:"error",result_summary:Fs(r===void 0?t:r),error:t,team_chat_log_id:e}}function Fs(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=500?e:`${e.slice(0,497)}...`}function g1(t,e,r){return`lmctl chat ${JSON.stringify(t)} ${e} ${JSON.stringify(r)}`}function y1(t,e){let r=Nb(e,t);if(r.ok)return{sender:Jr(r.identity),origin:"agent"};if(r.reason==="unset")return{sender:null,origin:"operator"};throw new Error(Ps("chat"))}async function w1(t,e){if(e.explicitRoot!==void 0)return await $(t,n=>ve(e.explicitRoot,n));if(e.operatorOrigin||e.sender===null)return e.receiverTeamfile;let r=e.sender;return await $(t,n=>wE(n,{sender:r,now:new Date})??e.receiverTeamfile)}async function E1(t,e){return await $(t,r=>Eb({rootTeamfile:e.rootTeamfile,fromTeamfile:e.sender.teamfile,fromAlias:e.sender.alias,toTeamfile:e.receiverTeamfile,toAlias:e.receiverAlias,registry:T1(r,e.sender.teamfile,e.receiverTeamfile)}))}function T1(t,e,r){return{teams:[e,r].map(s=>b1(s,t))}}function b1(t,e){let r=Fe(t,e),n=Lt(r);return{teamfile:t,aliases:r.members.map(s=>s.alias),leadAlias:n?.alias??null}}async function S1(t,e){return await $(t,r=>{let n=ce(),s=gr(r,{receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,ttlMs:yr(),...e.force===!0?{force:!0}:{}});return s.acquired?(n&&Oe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:s.reclaimReason===null?"acquired":"reclaimed",...s.reclaimReason===null?{}:{reclaim_reason:s.reclaimReason,holder:Ab(s.previous)}})),{acquired:!0,lease:s.lease}):(n&&Oe(JSON.stringify({event:"inflight_acquire",receiver:{teamfile:e.receiver_teamfile,alias:e.receiver_alias},sender:{teamfile:e.sender_teamfile,alias:e.sender_alias},result:"rejected",holder:Ab(s.current)})),{acquired:!1,current:s.current})})}async function Lb(t,e,r){return await $(t,n=>{for(let i=0;i<2;i+=1){let o=n.getTerminalLock(e,r);if(o===null)return null;if(Gu(o).live)return o;let l=n.getAgentInflight(e,r);if(n.clearTerminalLock(e,r,o.lock_id))return l!==null&&l.sender_teamfile===e&&l.sender_alias==="terminal"&&n.clearObservedTerminalAgentInflight(e,r,{sender_teamfile:l.sender_teamfile,sender_alias:l.sender_alias,started_at:l.started_at,holder_pid:l.holder_pid}),null}let s=n.getTerminalLock(e,r);return s===null?null:Gu(s).live?s:null})}function Ab(t){return t===null?null:{sender_teamfile:t.sender_teamfile,sender_alias:t.sender_alias,holder_pid:t.holder_pid,started_at:t.started_at}}async function v1(t,e){try{await $(t,r=>{r.releaseAgentInflight(e)})}catch(r){t.stderr.write(`warning: failed to release chat in-flight slot: ${r instanceof Error?r.message:String(r)}
|
|
2283
2365
|
`)}}function Ob(t,e,r){return`${e} is servicing ${r.sender_alias} (${r.sender_teamfile}) since ${r.started_at} \u2014 wait and retry, or inspect without waking it: lmctl tail "${t}" ${e}`}async function k1(t,e){let r=Rb(e.message),n=e.response===null?null:Rb(e.response);try{return await $(t,s=>s.insertTeamChatLog({root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,message:r.text,response:n?.text??null,origin:e.origin,status:e.status,error_detail:e.error_detail,truncated:r.truncated||n?.truncated?1:0,created_at:new Date().toISOString()}))}catch(s){return t.stderr.write(`warning: failed to record chat log: ${s instanceof Error?s.message:String(s)}
|
|
2284
2366
|
`),null}}function Mn(t,e,r,n,s){t!==null||e===null||C({event:"chat_attempt_error",reason:s,root_teamfile:e.root_teamfile,sender_teamfile:e.sender_teamfile,sender_alias:e.sender_alias,receiver_teamfile:e.receiver_teamfile,receiver_alias:e.receiver_alias,origin:e.origin,error_detail:n,message_preview:Fs(r)})}function Rb(t){return t.length<=xb?{text:t,truncated:!1}:{text:t.slice(0,xb),truncated:!0}}var xb,c1,tf=E(()=>{"use strict";ht();zt();Ds();Tb();Zt();aa();de();Le();Br();mu();Vu();Aa();zu();ru();xb=256*1024,c1=3e4});var Pb={};Ee(Pb,{parseIdleTimeoutMs:()=>jb,resolvePromptInput:()=>Mb,runChat:()=>x1});import{readFileSync as I1}from"node:fs";async function x1(t,e={stdout:process.stdout,stderr:process.stderr}){let r=e.env??process.env;if(t.length===0||t[0]==="--help"||t[0]==="-h")return e.stdout.write(`${Cb}
|
|
2285
2367
|
`),t.length===0?2:0;let n=A1(t);if(typeof n=="string")return e.stderr.write(`error: ${n}
|
|
@@ -2347,11 +2429,11 @@ Send a prompt to a team member or raw provider session, or answer a paused run.`
|
|
|
2347
2429
|
|
|
2348
2430
|
${nf}`);if(n.positionals.length===0)return v(e,`recover requires a <teamfile>
|
|
2349
2431
|
|
|
2350
|
-
${nf}`);if(n.positionals.length>2)return v(e,`unexpected argument: ${n.positionals[2]}`);let s=n.positionals[0],i=Hr(s),o=i?.teamfile??s,a=n.positionals[1],l=i?.alias??a;if(i!==null&&a!==void 0)return v(e,"recover alias was provided twice; use either <teamfile>:<alias> or <teamfile> <alias>");if(K(n,"--all")&&l!==void 0)return v(e,"recover --all is mutually exclusive with <alias>");let c;try{c=await q1(e,o,l)}catch(p){if(p instanceof we)return v(e,p.message);throw p}let d=r.now??new Date,u=K(n,"--dry-run"),f=[];for(let p of c)f.push(await H1(e,p,{now:d,dryRun:u}));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(K(n,"--json"))le(e,{dryRun:u,now:d.toISOString(),summary:m,members:f});else{for(let p of f)e.stdout.write(
|
|
2351
|
-
`)}return m.errors>0?1:0}async function q1(t,e,r){return await $(t,n=>{let s=ve(e,n);if(r!==void 0){let i=Fe(s,n);if(i.parseErrors.length>0)throw new we(`lmctl: ${e}: ${i.parseErrors.join("; ")}`);let o=da(i,r);return o?.teamfile!==void 0?sf(qb(Bb(s),o.teamfile),n,new Set):[$e(e,r,n)]}return sf(s,n,new Set)})}function sf(t,e,r){let n=ve(t,e);if(r.has(n))return[];r.add(n);let s=Fe(n,e);if(s.parseErrors.length>0)throw new we(`lmctl: ${n}: ${s.parseErrors.join("; ")}`);let i=[];for(let o of s.members){if(o.teamfile!==void 0){i.push(...sf(qb(Bb(n),o.teamfile),e,r));continue}o.session!==void 0&&i.push($e(n,o.alias,e))}return i}async function H1(t,e,r){let n;try{let a=await Ye(e.sessionid,e.provider);if(a===null)return $t(e,"session_not_found",null,"session detail not found");n=Us(a.messages)}catch(a){return $t(e,"load_error",null,a instanceof Error?a.message:String(a))}if(n===null)return $t(e,"not_limited",null,"no current session-limit marker");if(n.resets_at===null)return $t(e,"unknown_reset",n,"reset time could not be parsed");let s=Date.parse(n.resets_at);if(!Number.isFinite(s))return $t(e,"unknown_reset",n,"reset time could not be parsed");if(s>r.now.getTime())return $t(e,"not_due",n,`resets_at ${n.resets_at} is in the future`);let i=await $(t,a=>a.getAgentInflight(e.teamfile,e.alias));if(i!==null)return $t(e,"busy",n,`in-flight since ${i.started_at}`);if(r.dryRun)return $t(e,"would_recover",n,null);let o=await Oa({teamfile:e.teamfile,alias:e.alias,prompt:W1,permissionMode:"yolo",io:t,env:process.env});return o.status==="ok"||o.status==="stalled"?$t(e,"recovered",n,null):$t(e,o.status==="busy"?"busy":"send_error",n,o.message)}function $t(t,e,r,n){return{alias:t.alias,teamfile:t.teamfile,provider:t.provider,sessionid:t.sessionid,action:e,sessionLimit:r,reason:n}}function
|
|
2352
|
-
`}var W1,nf,
|
|
2353
|
-
`)});var Ws,B5,of=E(()=>{"use strict";Ws=[{name:"lmctl_chat",description:"Synchronous/blocking backup: send one prompt to a member of an AI-managed .lmctl team \u2014 addressed by teamfile path (team) and alias \u2014 and return the reply. This is the only MCP tool lmctl exposes. Prefer the CLI for normal delegation. For async or long-running work, use the provider or host runtime background/task surface around the blocking command.",inputSchema:{type:"object",properties:{team:{type:"string",description:"Path to .lmctl teamfile"},alias:{type:"string",description:"Target alias; omitted means Lead"},prompt:{type:"string",description:"Prompt text to send"}},required:["team","prompt"]},local:!0}],B5=Ws.length});import{spawn as
|
|
2354
|
-
`).length})),i({status:"ok",data:{text:l.trim()||"(empty response)"}});return}i({status:"error",code:d??1,message:c.trim()||`lmctl chat exited with code ${d}`})})})}function Z1(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return
|
|
2432
|
+
${nf}`);if(n.positionals.length>2)return v(e,`unexpected argument: ${n.positionals[2]}`);let s=n.positionals[0],i=Hr(s),o=i?.teamfile??s,a=n.positionals[1],l=i?.alias??a;if(i!==null&&a!==void 0)return v(e,"recover alias was provided twice; use either <teamfile>:<alias> or <teamfile> <alias>");if(K(n,"--all")&&l!==void 0)return v(e,"recover --all is mutually exclusive with <alias>");let c;try{c=await q1(e,o,l)}catch(p){if(p instanceof we)return v(e,p.message);throw p}let d=r.now??new Date,u=K(n,"--dry-run"),f=[];for(let p of c)f.push(await H1(e,p,{now:d,dryRun:u}));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(K(n,"--json"))le(e,{dryRun:u,now:d.toISOString(),summary:m,members:f});else{for(let p of f)e.stdout.write(X1(p));e.stdout.write(`Recover checked ${m.checked}: ${u?`${m.wouldRecover} would recover`:`${m.recovered} recovered`}, ${m.skipped} skipped, ${m.errors} error(s).
|
|
2433
|
+
`)}return m.errors>0?1:0}async function q1(t,e,r){return await $(t,n=>{let s=ve(e,n);if(r!==void 0){let i=Fe(s,n);if(i.parseErrors.length>0)throw new we(`lmctl: ${e}: ${i.parseErrors.join("; ")}`);let o=da(i,r);return o?.teamfile!==void 0?sf(qb(Bb(s),o.teamfile),n,new Set):[$e(e,r,n)]}return sf(s,n,new Set)})}function sf(t,e,r){let n=ve(t,e);if(r.has(n))return[];r.add(n);let s=Fe(n,e);if(s.parseErrors.length>0)throw new we(`lmctl: ${n}: ${s.parseErrors.join("; ")}`);let i=[];for(let o of s.members){if(o.teamfile!==void 0){i.push(...sf(qb(Bb(n),o.teamfile),e,r));continue}o.session!==void 0&&i.push($e(n,o.alias,e))}return i}async function H1(t,e,r){let n;try{let a=await Ye(e.sessionid,e.provider);if(a===null)return $t(e,"session_not_found",null,"session detail not found");n=Us(a.messages)}catch(a){return $t(e,"load_error",null,a instanceof Error?a.message:String(a))}if(n===null)return $t(e,"not_limited",null,"no current session-limit marker");if(n.resets_at===null)return $t(e,"unknown_reset",n,"reset time could not be parsed");let s=Date.parse(n.resets_at);if(!Number.isFinite(s))return $t(e,"unknown_reset",n,"reset time could not be parsed");if(s>r.now.getTime())return $t(e,"not_due",n,`resets_at ${n.resets_at} is in the future`);let i=await $(t,a=>a.getAgentInflight(e.teamfile,e.alias));if(i!==null)return $t(e,"busy",n,`in-flight since ${i.started_at}`);if(r.dryRun)return $t(e,"would_recover",n,null);let o=await Oa({teamfile:e.teamfile,alias:e.alias,prompt:W1,permissionMode:"yolo",io:t,env:process.env});return o.status==="ok"||o.status==="stalled"?$t(e,"recovered",n,null):$t(e,o.status==="busy"?"busy":"send_error",n,o.message)}function $t(t,e,r,n){return{alias:t.alias,teamfile:t.teamfile,provider:t.provider,sessionid:t.sessionid,action:e,sessionLimit:r,reason:n}}function X1(t){let e=t.sessionLimit?.resets_at??"unknown",r=t.reason===null?"":` (${t.reason})`;return`${t.alias}: ${t.action} resets_at=${e}${r}
|
|
2434
|
+
`}var W1,nf,Xb=E(()=>{"use strict";rf();Er();zt();Zt();ht();tf();Le();W1="Your session limit reset time has passed. Continue your work from the last actionable point.",nf=["usage: lmctl recover <teamfile> [--all|<alias>] [--dry-run] [--json]"," lmctl recover <teamfile>:<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(`
|
|
2435
|
+
`)});var Ws,B5,of=E(()=>{"use strict";Ws=[{name:"lmctl_chat",description:"Synchronous/blocking backup: send one prompt to a member of an AI-managed .lmctl team \u2014 addressed by teamfile path (team) and alias \u2014 and return the reply. This is the only MCP tool lmctl exposes. Prefer the CLI for normal delegation. For async or long-running work, use the provider or host runtime background/task surface around the blocking command.",inputSchema:{type:"object",properties:{team:{type:"string",description:"Path to .lmctl teamfile"},alias:{type:"string",description:"Target alias; omitted means Lead"},prompt:{type:"string",description:"Prompt text to send"}},required:["team","prompt"]},local:!0}],B5=Ws.length});import{spawn as J1}from"node:child_process";async function Gb(t,e,r){let n=K1.get(t);if(n===void 0)return{status:"error",code:404,message:`unknown tool: ${t}`};let s=e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{};for(let i of n.inputSchema.required??[])if(s[i]===void 0)return{status:"error",code:400,message:`missing required parameter: ${i}`};return V1(n.name,s)}function V1(t,e){return t==="lmctl_chat"?Y1(e):{status:"error",code:404,message:`unknown local tool: ${t}`}}function Y1(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 ce()&&Oe(JSON.stringify({event:"mcp_chat_spawn",team:r,alias:n})),z1(s,process.cwd())}function z1(t,e){return new Promise(r=>{let n=!1,s,i=d=>{n||(n=!0,s!==void 0&&clearTimeout(s),r(d))},o=J1("lmctl",t,{cwd:e,env:process.env,stdio:["ignore","pipe","pipe"]}),a=Z1(process.env);s=setTimeout(()=>{try{o.kill("SIGTERM")}catch{}i({status:"error",code:124,message:`lmctl chat timed out after ${a}ms`})},a),s.unref?.();let l="",c="";o.stdout?.on("data",d=>{l+=d.toString("utf8")}),o.stderr?.on("data",d=>{c+=d.toString("utf8")}),o.on("error",d=>{i({status:"error",code:1,message:`failed to spawn lmctl chat: ${d.message}`})}),o.on("exit",d=>{if(d===0){ce()&&Oe(JSON.stringify({event:"mcp_chat_payload",bytes:Buffer.byteLength(l,"utf8"),lines:l.split(`
|
|
2436
|
+
`).length})),i({status:"ok",data:{text:l.trim()||"(empty response)"}});return}i({status:"error",code:d??1,message:c.trim()||`lmctl chat exited with code ${d}`})})})}function Z1(t){let e=t.LMCTL_MCP_CHAT_TIMEOUT_MS;if(e===void 0||e.trim().length===0)return Jb;let r=Number(e);return!Number.isFinite(r)||r<=0?Jb:r}function af(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:G1),s=t.getConfig("api.token"),i=e.LMCTL_API_TOKEN!==void 0&&e.LMCTL_API_TOKEN.length>0?e.LMCTL_API_TOKEN:s;return{baseUrl:n,token:i}}var G1,Jb,K1,lf=E(()=>{"use strict";of();de();G1="http://127.0.0.1:8787",Jb=30*60*1e3,K1=new Map(Ws.map(t=>[t.name,t]))});async function rU(t,e){let r=t.id===void 0,n=t.id??null;if(t.method==="exit")return r||e.io.write(cf({jsonrpc:"2.0",id:n,result:null})),{kind:"exit"};if(t.method==="initialize")return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{protocolVersion:Q1,capabilities:{tools:{listChanged:!1}},serverInfo:{name:eU,version:tU}}}};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:Ws.map(s=>({name:s.name,description:s.description,inputSchema:s.inputSchema}))}}};if(t.method==="tools/call"){let s=t.params!==null&&typeof t.params=="object"?t.params:{},i=typeof s.name=="string"?s.name:"",o=s.arguments,a=await Gb(i,o,e.dispatch),l=i==="lmctl_chat"&&a.status==="ok"&&a.data!==null&&typeof a.data=="object"&&typeof a.data.text=="string"?a.data.text:JSON.stringify(a);return{kind:"response",message:{jsonrpc:"2.0",id:n,result:{isError:a.status==="error",content:[{type:"text",text:l}]}}}}return r?{kind:"notification"}:{kind:"response",message:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`method not found: ${t.method}`}}}}function cf(t){return`${JSON.stringify(t)}
|
|
2355
2437
|
`}async function Kb(t,e){let r=!1,n="",s=!1,i=async o=>{let a=o.trim();if(a.length===0)return;let l;try{l=JSON.parse(a)}catch(d){t.io.write(cf({jsonrpc:"2.0",id:null,error:{code:-32700,message:`parse error: ${d instanceof Error?d.message:String(d)}`}}));return}l.method==="shutdown"&&(r=!0);let c=await rU(l,t);c.kind==="response"?t.io.write(cf(c.message)):c.kind==="exit"&&(s=!0)};return new Promise(o=>{let a=Promise.resolve(),l=!1,c=u=>{l||(l=!0,o(u))},d=()=>{let u=n.indexOf(`
|
|
2356
2438
|
`);for(;u!==-1;){let f=n.slice(0,u);n=n.slice(u+1),a=a.then(()=>i(f)).then(()=>{s&&c(0)}),u=n.indexOf(`
|
|
2357
2439
|
`)}};e.setEncoding("utf8"),e.on("data",u=>{n+=u,d()}),e.on("end",()=>{n.trim().length>0&&(a=a.then(()=>i(n))),a.finally(()=>c(0))}),e.on("error",u=>{t.io.log?.(`mcp: stdin error: ${u.message}
|
|
@@ -2361,20 +2443,20 @@ ${nf}`);if(n.positionals.length>2)return v(e,`unexpected argument: ${n.positiona
|
|
|
2361
2443
|
Start the stdio MCP bridge. The bridge resolves api.url and api.token from
|
|
2362
2444
|
local config, then uses stdin/stdout for JSON-RPC frames.
|
|
2363
2445
|
`});var Qb={};Ee(Qb,{runDevice:()=>gU});import{readFileSync as aU}from"node:fs";import{homedir as lU}from"node:os";import{join as cU}from"node:path";import{CognitoIdentityClient as dU,GetIdCommand as uU}from"@aws-sdk/client-cognito-identity";import{fromCognitoIdentity as fU}from"@aws-sdk/credential-provider-cognito-identity";import{GetObjectCommand as mU,ListObjectsV2Command as pU,PutObjectCommand as _U,S3Client as hU}from"@aws-sdk/client-s3";async function gU(t,e={stdout:process.stdout,stderr:process.stderr}){let[r]=t;if(r===void 0||r==="--help"||r==="-h"||r==="help")return e.stdout.write(df),0;if(r==="init"){let n=Wu();return e.stdout.write(`${n.device_id}
|
|
2364
|
-
`),0}if(r==="id"){let n=
|
|
2446
|
+
`),0}if(r==="id"){let n=Xr();return n===null?(e.stderr.write(`error: no device id initialized at ${va()}; run 'lmctl device init'
|
|
2365
2447
|
`),1):(e.stdout.write(`${n.device_id}
|
|
2366
2448
|
`),0)}return r==="login"?await yU(t.slice(1),e):r==="prompt"?await EU(t.slice(1),e):(e.stderr.write(`usage: lmctl device <id|init|login|prompt>
|
|
2367
2449
|
`),1)}async function yU(t,e){let r=wU(t);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
2368
2450
|
${df}`),2;let n=Ms();if(n.config===void 0)return e.stderr.write(`error: mailbox is not configured; missing ${n.missing.join(", ")}
|
|
2369
2451
|
`),1;_T({userId:r.userId,refreshToken:r.accessKey});let s,i,o;try{let c=await ya({region:n.config.region,clientId:n.config.cognitoClientId??Sa,refreshToken:r.accessKey});s=c.idToken,i=c.accessToken,o=c.expiresAt}catch(c){let d=c instanceof Error?c.message:String(c);return e.stderr.write(`error: could not authenticate access key: ${d}
|
|
2370
2452
|
`),1}let a=Os(s);if(a!==null&&a!==r.userId)return e.stderr.write(`error: access key belongs to user-id ${a}, not ${r.userId}
|
|
2371
|
-
`),1;Ou({idToken:s,...i!==void 0?{accessToken:i}:{},refreshToken:r.accessKey,...o!==void 0?{expiresAt:o}:{}});let l=
|
|
2453
|
+
`),1;Ou({idToken:s,...i!==void 0?{accessToken:i}:{},refreshToken:r.accessKey,...o!==void 0?{expiresAt:o}:{}});let l=Xr()??Wu();return e.stdout.write(`logged in as ${r.userId}
|
|
2372
2454
|
device id: ${l.device_id}
|
|
2373
2455
|
mailbox prefix: ${r.userId}/${l.device_id}/
|
|
2374
2456
|
access key stored at ${$s()}
|
|
2375
2457
|
`),0}function wU(t){let e,r;for(let n=0;n<t.length;n+=1){let s=t[n];if(s==="--user-id"){let i=t[++n];if(i===void 0||i.startsWith("--"))return"missing value for --user-id";e=i;continue}if(s==="--access-key"){let i=t[++n];if(i===void 0||i.startsWith("--"))return"missing value for --access-key";r=i;continue}return`unknown argument: ${s}`}return e===void 0?"missing --user-id <sub>":r===void 0?"missing --access-key <refreshToken>":{userId:e,accessKey:r}}async function EU(t,e){let r=TU(t);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
2376
2458
|
${df}`),2;let n=Ms();if(n.config===void 0)return e.stderr.write(`error: mailbox is not configured; missing ${n.missing.join(", ")}
|
|
2377
|
-
`),1;let s=SU();if(s===null)return e.stderr.write("error: no Cognito id token found; run `webcli login` or `lmctl device login` first\n"),1;let i=s.cognito?.idToken;if(typeof i!="string"||i.length===0)return e.stderr.write("error: no Cognito id token found; run `webcli login` or `lmctl device login` first\n"),1;let o=`cognito-idp.${n.config.region}.amazonaws.com/${n.config.cognitoUserPoolId}`,a=typeof s.cognito?.identityId=="string"&&s.cognito.identityId.length>0?s.cognito.identityId:await bU({region:n.config.region,identityPoolId:n.config.identityPoolId,idpProvider:o,idToken:i}),l=fU({identityId:a,logins:{[o]:i},clientConfig:{region:n.config.region}}),c=n.config.deviceId??
|
|
2459
|
+
`),1;let s=SU();if(s===null)return e.stderr.write("error: no Cognito id token found; run `webcli login` or `lmctl device login` first\n"),1;let i=s.cognito?.idToken;if(typeof i!="string"||i.length===0)return e.stderr.write("error: no Cognito id token found; run `webcli login` or `lmctl device login` first\n"),1;let o=`cognito-idp.${n.config.region}.amazonaws.com/${n.config.cognitoUserPoolId}`,a=typeof s.cognito?.identityId=="string"&&s.cognito.identityId.length>0?s.cognito.identityId:await bU({region:n.config.region,identityPoolId:n.config.identityPoolId,idpProvider:o,idToken:i}),l=fU({identityId:a,logins:{[o]:i},clientConfig:{region:n.config.region}}),c=n.config.deviceId??Xr()?.device_id,d=Os(i)??void 0,u=new Wr({bucket:n.config.mailboxBucket,identityId:a,...d!==void 0?{userId:d}:{},...c!==void 0?{deviceId:c}:{},...n.config.mailboxKey!==void 0?{mailboxKey:n.config.mailboxKey}:{},s3:new hU({region:n.config.region,credentials:l}),commands:{ListObjectsV2Command:pU,GetObjectCommand:mU,PutObjectCommand:_U},selfRole:"browser",onMessage:async()=>{}}),f=sT({root_teamfile:r.root,text:r.text,...r.promptId!==void 0?{prompt_id:r.promptId}:{}}),m=await u.putMessage({conversation_id:nT,payload:f});return e.stdout.write(JSON.stringify({prompt_id:f.prompt_id,mailbox_key:u.getMailboxBasePrefix(),object_key:m},null,2)+`
|
|
2378
2460
|
`),0}function TU(t){let e,r,n;for(let s=0;s<t.length;s+=1){let i=t[s];if(i==="--root"){let o=t[++s];if(o===void 0||o.startsWith("--"))return"missing value for --root";e=o;continue}if(i==="--text"){let o=t[++s];if(o===void 0||o.startsWith("--"))return"missing value for --text";r=o;continue}if(i==="--prompt-id"){let o=t[++s];if(o===void 0||o.startsWith("--"))return"missing value for --prompt-id";n=o;continue}return`unknown argument: ${i}`}return e===void 0?"missing --root <teamfile>":r===void 0?"missing --text <prompt>":{root:e,text:r,...n!==void 0?{promptId:n}:{}}}async function bU(t){let r=await new dU({region:t.region}).send(new uU({IdentityPoolId:t.identityPoolId,Logins:{[t.idpProvider]:t.idToken}}));if(r.IdentityId===void 0||r.IdentityId.length===0)throw new Error("Cognito GetId returned no IdentityId");return r.IdentityId}function SU(t=process.env.LMCTL_TOKEN_PATH??cU(lU(),".lmctl","cli-tokens.json")){try{return JSON.parse(aU(t,"utf8"))}catch{return null}}var df,eS=E(()=>{"use strict";Bu();ju();Ho();xu();Au();$u();Ru();df=`usage: lmctl device <id|init|login|prompt>
|
|
2379
2461
|
lmctl device login --user-id <sub> --access-key <refreshToken>
|
|
2380
2462
|
lmctl device prompt --root <teamfile> --text <prompt> [--prompt-id <id>]
|
|
@@ -2385,7 +2467,7 @@ addressing. The id is stored in ~/.lmctl/device.json by default.
|
|
|
2385
2467
|
'lmctl device login' authenticates this machine's 'lmctl serve' daemon to the
|
|
2386
2468
|
cloud mailbox using your user-id (Cognito sub) and an access key (refresh
|
|
2387
2469
|
token). The access key is stored in ~/.lmctl/device-auth.json (chmod 600).
|
|
2388
|
-
`});import{existsSync as tS,mkdirSync as vU,readdirSync as kU,readFileSync as rS,writeFileSync as IU}from"node:fs";import{join as jn}from"node:path";import{fileURLToPath as NU}from"node:url";function AU(t){try{return xU.some(e=>tS(jn(t,e)))}catch{return!1}}function RU(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return null;let r=e[1],n=e[2].trimStart(),s=r.match(/^name:\s*(.+)$/m),i=r.match(/^type:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),a=s?.[1]?.trim(),l=i?.[1]?.trim();return!a||!l?null:{name:a,type:l,description:o?.[1]?.trim()??null,body:n}}function nS(t,e){t.durable_memory_mode!=="db"?LU(t):OU(t,e)}function sS(t){let e=AU(t),r;try{r=kU($a).filter(n=>n.endsWith(".template")).sort()}catch(n){return C({event:"bootstrap_templates_unreadable",path:$a,error_message:n instanceof Error?n.message:String(n)}),[]}return r.filter(n=>n==="skills_lmprobe.md.template"||n==="skills_lmdebug.md.template"?e:!0)}function LU(t){let e=t.local_path;if(!e){console.warn("[bootstrap] skipping: project has no local_path"),C({event:"bootstrap_skipped_no_local_path",project_id:t.id,project_name:t.name});return}let r=jn(e,"durable-memory");try{vU(r,{recursive:!0})}catch(i){console.error("[bootstrap] failed to create durable-memory directory:",i),C({event:"bootstrap_memory_dir_create_failed",project_id:t.id,path:r,error_message:i instanceof Error?i.message:String(i)});return}let n=sS(e),s=[];for(let i of n){let o=i.replace(/\.template$/,""),a=jn(r,o);if(!tS(a))try{let l=rS(jn($a,i),"utf8");IU(a,l,"utf8"),s.push(o)}catch(l){console.error(`[bootstrap] failed to copy ${i}:`,l),C({event:"bootstrap_template_copy_failed",project_id:t.id,template:i,path:a,error_message:l instanceof Error?l.message:String(l)})}}s.length>0&&console.log(`[bootstrap] filled durable-memory stubs at ${r}: ${s.join(", ")}`)}function OU(t,e){let r=t.local_path??"",n=sS(r),s=[];for(let i of n){let o=jn($a,i),a;try{a=rS(o,"utf8")}catch(c){console.error(`[bootstrap] failed to read ${i}:`,c),C({event:"bootstrap_template_read_failed",project_id:t.id,template:i,path:o,error_message:c instanceof Error?c.message:String(c)});continue}let l=RU(a);if(l===null){console.error(`[bootstrap] failed to parse frontmatter in ${i}`),C({event:"bootstrap_template_frontmatter_invalid",project_id:t.id,template:i,path:o});continue}if(e.getDurableMemoryByName(t.id,l.name)===null)try{e.upsertDurableMemory({project_id:t.id,type:l.type,name:l.name,description:l.description,body:l.body}),s.push(l.name)}catch(c){console.error(`[bootstrap] failed to upsert ${l.name}:`,c),C({event:"bootstrap_memory_upsert_failed",project_id:t.id,memory_name:l.name,template:i,error_message:c instanceof Error?c.message:String(c)})}}s.length>0&&console.log(`[bootstrap] filled durable-memory DB stubs for project ${t.name}: ${s.join(", ")}`)}var $a,xU,iS=E(()=>{"use strict";de();$a=jn(NU(import.meta.url),"../../config/durable_memory_templates"),xU=[".git","package.json","Cargo.toml","pyproject.toml","go.mod","Gemfile","pom.xml","build.gradle","composer.json","Pipfile"]});import{createHash as $U}from"node:crypto";import{existsSync as CU,mkdirSync as MU,writeFileSync as jU}from"node:fs";import{dirname as DU,join as Dn}from"node:path";function uf(t){return typeof t=="string"&&t.startsWith(oS)}function qU(t){if(!uf(t))throw new yt(`not an lmctl:// URI: ${t}`,"malformed");let e=t.slice(oS.length),r=e.indexOf("/");if(r<=0)throw new yt(`malformed lmctl:// URI (expected lmctl://<workflow|mcp|skill>/<name>): ${t}`,"malformed");let n=e.slice(0,r);if(!WU.has(n))throw new yt(`unknown lmctl:// kind '${n}' (expected workflow|mcp|skill): ${t}`,"malformed");let s=e.slice(r+1),i,o=s.indexOf("@");o>=0&&(i=s.slice(o+1).trim(),s=s.slice(0,o));let a=s.trim();if(a.length===0)throw new yt(`empty name in lmctl:// URI: ${t}`,"malformed");if(/[\\/]|\.\./.test(a))throw new yt(`invalid name in lmctl:// URI (no path separators): ${t}`,"malformed");return{kind:n,name:a,...i!==void 0&&i.length>0?{ref:i}:{}}}function HU(t,e,r){if(t==="workflow")return So(e,r);let n=t==="mcp"?Dn("templates","mcp",`${e}.json`):Dn("templates","skills",e,"SKILL.md");for(let s of md(r)){let i=Dn(s,n);if(CU(i))return i}return null}function
|
|
2470
|
+
`});import{existsSync as tS,mkdirSync as vU,readdirSync as kU,readFileSync as rS,writeFileSync as IU}from"node:fs";import{join as jn}from"node:path";import{fileURLToPath as NU}from"node:url";function AU(t){try{return xU.some(e=>tS(jn(t,e)))}catch{return!1}}function RU(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(e===null)return null;let r=e[1],n=e[2].trimStart(),s=r.match(/^name:\s*(.+)$/m),i=r.match(/^type:\s*(.+)$/m),o=r.match(/^description:\s*(.+)$/m),a=s?.[1]?.trim(),l=i?.[1]?.trim();return!a||!l?null:{name:a,type:l,description:o?.[1]?.trim()??null,body:n}}function nS(t,e){t.durable_memory_mode!=="db"?LU(t):OU(t,e)}function sS(t){let e=AU(t),r;try{r=kU($a).filter(n=>n.endsWith(".template")).sort()}catch(n){return C({event:"bootstrap_templates_unreadable",path:$a,error_message:n instanceof Error?n.message:String(n)}),[]}return r.filter(n=>n==="skills_lmprobe.md.template"||n==="skills_lmdebug.md.template"?e:!0)}function LU(t){let e=t.local_path;if(!e){console.warn("[bootstrap] skipping: project has no local_path"),C({event:"bootstrap_skipped_no_local_path",project_id:t.id,project_name:t.name});return}let r=jn(e,"durable-memory");try{vU(r,{recursive:!0})}catch(i){console.error("[bootstrap] failed to create durable-memory directory:",i),C({event:"bootstrap_memory_dir_create_failed",project_id:t.id,path:r,error_message:i instanceof Error?i.message:String(i)});return}let n=sS(e),s=[];for(let i of n){let o=i.replace(/\.template$/,""),a=jn(r,o);if(!tS(a))try{let l=rS(jn($a,i),"utf8");IU(a,l,"utf8"),s.push(o)}catch(l){console.error(`[bootstrap] failed to copy ${i}:`,l),C({event:"bootstrap_template_copy_failed",project_id:t.id,template:i,path:a,error_message:l instanceof Error?l.message:String(l)})}}s.length>0&&console.log(`[bootstrap] filled durable-memory stubs at ${r}: ${s.join(", ")}`)}function OU(t,e){let r=t.local_path??"",n=sS(r),s=[];for(let i of n){let o=jn($a,i),a;try{a=rS(o,"utf8")}catch(c){console.error(`[bootstrap] failed to read ${i}:`,c),C({event:"bootstrap_template_read_failed",project_id:t.id,template:i,path:o,error_message:c instanceof Error?c.message:String(c)});continue}let l=RU(a);if(l===null){console.error(`[bootstrap] failed to parse frontmatter in ${i}`),C({event:"bootstrap_template_frontmatter_invalid",project_id:t.id,template:i,path:o});continue}if(e.getDurableMemoryByName(t.id,l.name)===null)try{e.upsertDurableMemory({project_id:t.id,type:l.type,name:l.name,description:l.description,body:l.body}),s.push(l.name)}catch(c){console.error(`[bootstrap] failed to upsert ${l.name}:`,c),C({event:"bootstrap_memory_upsert_failed",project_id:t.id,memory_name:l.name,template:i,error_message:c instanceof Error?c.message:String(c)})}}s.length>0&&console.log(`[bootstrap] filled durable-memory DB stubs for project ${t.name}: ${s.join(", ")}`)}var $a,xU,iS=E(()=>{"use strict";de();$a=jn(NU(import.meta.url),"../../config/durable_memory_templates"),xU=[".git","package.json","Cargo.toml","pyproject.toml","go.mod","Gemfile","pom.xml","build.gradle","composer.json","Pipfile"]});import{createHash as $U}from"node:crypto";import{existsSync as CU,mkdirSync as MU,writeFileSync as jU}from"node:fs";import{dirname as DU,join as Dn}from"node:path";function uf(t){return typeof t=="string"&&t.startsWith(oS)}function qU(t){if(!uf(t))throw new yt(`not an lmctl:// URI: ${t}`,"malformed");let e=t.slice(oS.length),r=e.indexOf("/");if(r<=0)throw new yt(`malformed lmctl:// URI (expected lmctl://<workflow|mcp|skill>/<name>): ${t}`,"malformed");let n=e.slice(0,r);if(!WU.has(n))throw new yt(`unknown lmctl:// kind '${n}' (expected workflow|mcp|skill): ${t}`,"malformed");let s=e.slice(r+1),i,o=s.indexOf("@");o>=0&&(i=s.slice(o+1).trim(),s=s.slice(0,o));let a=s.trim();if(a.length===0)throw new yt(`empty name in lmctl:// URI: ${t}`,"malformed");if(/[\\/]|\.\./.test(a))throw new yt(`invalid name in lmctl:// URI (no path separators): ${t}`,"malformed");return{kind:n,name:a,...i!==void 0&&i.length>0?{ref:i}:{}}}function HU(t,e,r){if(t==="workflow")return So(e,r);let n=t==="mcp"?Dn("templates","mcp",`${e}.json`):Dn("templates","skills",e,"SKILL.md");for(let s of md(r)){let i=Dn(s,n);if(CU(i))return i}return null}function XU(t,e,r){let n=Dn(fd(r),FU,t);return t==="skill"?Dn(n,e,"SKILL.md"):Dn(n,`${e}${t==="workflow"?".compound.json":".json"}`)}function JU(t,e){if(e.trim().length===0)return!1;if(t==="skill")return!0;let r=e.trim();if(t==="mcp")try{let n=JSON.parse(r);return n!==null&&typeof n=="object"}catch{return!1}if(r.startsWith("{")||r.startsWith("["))try{return JSON.parse(r),!0}catch{return!1}return!0}async function aS(t,e){let{kind:r,name:n,ref:s}=qU(t),i=HU(r,n,e);if(i!==null)return i;let o=`${PU}${r}/${n}`,a;try{a=await fetch(o,{signal:AbortSignal.timeout(UU)})}catch(d){throw new yt(`lmctl:// '${t}' not found locally or at the remote catalog ${o} (${d instanceof Error?d.message:String(d)}). Failing closed.`,"missing")}if(!a.ok)throw new yt(`lmctl:// '${t}' not found locally or at the remote catalog ${o} (HTTP ${a.status}). Failing closed.`,"missing");let l=await a.text();if(s!==void 0){let d=BU.exec(s);if(d!==null){let u=$U("sha256").update(l).digest("hex");if(u.toLowerCase()!==d[1].toLowerCase())throw new yt(`lmctl:// '${t}' remote artifact FAILED integrity pin (expected sha256 ${d[1]}, got ${u}) \u2014 discarded, NOT cached.`,"validation-failure")}}if(!JU(r,l))throw new yt(`lmctl:// '${t}' remote artifact failed shape validation for ${r} \u2014 discarded, NOT cached.`,"validation-failure");let c=XU(r,n,e);return MU(DU(c),{recursive:!0}),jU(c,l,"utf8"),c}var oS,PU,FU,UU,WU,yt,BU,lS=E(()=>{"use strict";pd();oS="lmctl://",PU="https://lmctl.com/templates/",FU=".cache",UU=8e3,WU=new Set(["workflow","mcp","skill"]),yt=class extends Error{reason;constructor(e,r="malformed"){super(e),this.reason=r,this.name="LmctlUriError"}},BU=/^(?:sha256[:-])?([0-9a-f]{64})$/i});import{spawnSync as GU}from"node:child_process";import{cpSync as cS,existsSync as KU,mkdirSync as VU,mkdtempSync as YU,readFileSync as x9,statSync as zU,writeFileSync as dS}from"node:fs";import{homedir as ZU,tmpdir as QU}from"node:os";import{basename as uS,join as er}from"node:path";function ff(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function mf(t,e,r){if(Array.isArray(t)){for(let n of t)mf(n,e,r);return}if(ff(t)){t.alias===e&&(Array.isArray(t.mcp)&&r.mcp.push(...t.mcp),Array.isArray(t.skills)&&r.skills.push(...t.skills));for(let n of Object.values(t))mf(n,e,r)}}function nW(t,e){let r={mcp:[],skills:[]},n=new Set;for(let i of t.listProjects()){if(i.team_id!==e.team_id)continue;let o=t.getWorkflowByName(i.workflow_name);if(o===null||n.has(o.id))continue;n.add(o.id);let a;try{a=JSON.parse(o.definition)}catch{continue}if(!(!ff(a)||!Array.isArray(a.steps)))for(let l of a.steps)ff(l)&&l.members!==void 0&&mf(l.members,e.alias,r)}let s=i=>{let o=new Map;for(let a of i)o.set(rW(a),a);return[...o.values()]};return{mcp:s(r.mcp),skills:s(r.skills)}}function sW(t,e){return t.listProjects().find(r=>r.team_id===e.team_id)?.local_path}async function iW(t,e){let r;try{r=await fetch(t,{signal:AbortSignal.timeout(eW)})}catch(s){throw new br(e,`fetch ${t} failed: ${s.message}`)}if(!r.ok)throw new br(e,`fetch ${t} \u2192 HTTP ${r.status}`);let n=await r.text();if(n.length>fS)throw new br(e,`fetched ${t} exceeds ${fS} bytes`);return n}function oW(t,e,r,n){let s=GU(t,e,{cwd:r,env:sr(void 0,r),encoding:"utf8",timeout:6e4});if(s.error)throw new br(n,`spawn ${t} failed: ${s.error.message}`);if(s.status!==0)throw new br(n,`${t} ${e.slice(0,3).join(" ")} exited ${s.status}: ${(s.stderr??"").trim().slice(0,200)}`)}function aW(t){if(typeof t!="string")return t.name;let e=uS(t.replace(/\/+$/,""));return e.toLowerCase()==="skill.md"?uS(t.replace(/\/skill\.md$/i,"")):e}async function mS(t,e,r){let n=aW(t),s=er(e,n);if(VU(s,{recursive:!0}),typeof t!="string")return dS(er(s,"SKILL.md"),t.content,"utf8"),{name:n,dir:s};if(uf(t)&&(t=await aS(t)),_S.test(t))return dS(er(s,"SKILL.md"),await iW(t,r),"utf8"),{name:n,dir:s};if(!KU(t))throw new br(r,`skill path not found: ${t}`);return zU(t).isDirectory()?(cS(t,s,{recursive:!0}),{name:n,dir:s}):(cS(t,er(s,"SKILL.md")),{name:n,dir:s})}async function hS(t){let{dal:e,member:r,stderr:n}=t,s=nW(e,r);if(s.mcp.length===0&&s.skills.length===0)return;let i=Be(r),o=r.sessiondir||t.baseDir||sW(e,r)||process.cwd(),a=l=>{n.write(`[seed:${r.alias}] ${l}
|
|
2389
2471
|
`)};if(s.mcp.length>0&&a(`MCP capability install is disabled in lmctl; ${s.mcp.length} declared server(s) NOT installed. Use nomcp for MCP server access.`),s.skills.length>0)if(tW.has(i))a(`skills for ${i} are honest-BLOCKED \u2014 opencode has NO SKILL.md filesystem ingestion (no \`skill\` subcommand, no skills dir, no SKILL.md in the opencode package; \`opencode agent\` is a distinct artifact); ${s.skills.length} declared skill(s) NOT installed (operator follow-up).`);else if(i==="gemini"||i==="agy"){let l=YU(er(QU(),`lmctl-skill-${r.alias}-`));for(let c of s.skills){let d=typeof c=="string"&&!_S.test(c)?c:(await mS(c,l,r.alias)).dir;oW(i,["skills","install",d,"--scope","user","--consent"],o,r.alias)}a(`installed ${s.skills.length} skill(s) via \`${i} skills install --scope user\` (idempotent).`)}else if(pS[i]!==void 0){let l=pS[i]();for(let c of s.skills)await mS(c,l,r.alias);a(`installed ${s.skills.length} skill(s) \u2192 ${l}/<name>/SKILL.md (idempotent overwrite).`)}else a(`provider ${i} has no verified skills mechanism \u2014 ${s.skills.length} declared skill(s) NOT installed.`)}var br,_S,eW,fS,tW,rW,Ca,pS,gS=E(()=>{"use strict";Qe();lS();at();Ds();br=class extends Error{alias;constructor(e,r){super(`capability install failed for ${e}: ${r}`),this.alias=e,this.name="CapabilityInstallError"}},_S=/^https?:\/\//i,eW=8e3,fS=1e6,tW=new Set(["opencode"]),rW=t=>JSON.stringify(t),Ca=()=>process.env.HOME??ZU();pS={claude:()=>er(Ca(),".claude","skills"),qwen:()=>er(Ca(),".qwen","skills"),codex:()=>er(Ca(),".codex","skills"),copilot:()=>er(Ca(),".copilot","skills")}});var pf,yS=E(()=>{"use strict";pf=`---
|
|
2390
2472
|
|
|
2391
2473
|
# Durable memory \u2014 how to use it
|
|
@@ -2505,7 +2587,7 @@ Show provider session details, team rollups, or managed run state/token totals.`
|
|
|
2505
2587
|
[--recursive] [--all] [--format table|teamfile|json] [--json]
|
|
2506
2588
|
lmctl ls --runs [--limit N] [--format table|json] [--json]
|
|
2507
2589
|
|
|
2508
|
-
List native provider sessions in scope, or list recent managed runs with --runs.`,FW=50,FS=500});import{existsSync as qs,readFileSync as BS}from"node:fs";import{homedir as HW}from"node:os";import{dirname as qS,resolve as Pn}from"node:path";import{fileURLToPath as
|
|
2590
|
+
List native provider sessions in scope, or list recent managed runs with --runs.`,FW=50,FS=500});import{existsSync as qs,readFileSync as BS}from"node:fs";import{homedir as HW}from"node:os";import{dirname as qS,resolve as Pn}from"node:path";import{fileURLToPath as XW}from"node:url";function bf(t,e={}){let r=[],n=KW(e.modelSelectionDocPath);for(let s of t){let i=s.provider.trim().toLowerCase();if(s.effort&&i!=="opencode"&&i!=="lmplayer"&&i!=="qwen"&&r.push(`[${s.alias}] effort="${s.effort}" is ignored: effort selection is only supported for opencode and lmplayer.`),i==="qwen"&&s.effort&&r.push(`[${s.alias}] effort="${s.effort}" is not a qwen CLI flag: Qwen Code does not expose reasoning-effort selection. Use a thinking/effort model id in model= instead.`),i==="copilot"){if(!s.model)continue;r.push(`[${s.alias}] model="${s.model}" is ignored: copilot does not support lmctl model selection.`);continue}if(i==="lmplayer"&&!s.model){r.push(`[${s.alias}] provider=lmplayer has no model= \u2014 lmplayer will choose its own default model, which may not be visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.4).`);continue}if(i==="lmplayer")continue;if(i==="opencode"){if(s.effort&&!s.model&&r.push(`[${s.alias}] effort="${s.effort}" has no effect without model= on an opencode member.`),!s.model){r.push(`[${s.alias}] provider=opencode has no model= \u2014 opencode will choose its own default model, which may not be servable and isn't visible in the teamfile. Set model= explicitly (e.g. github-copilot/gpt-5.4).`);continue}let a=eB(e.opencodeConfigPath);if(!a.available){r.push(`[${s.alias}] model="${s.model}" cannot be verified for opencode: ${a.reason}.`);continue}if(a.models.includes(s.model)||/^github-copilot\/(gpt|gemini|o[0-9])/.test(s.model))continue;if(!s.model.includes("/")){let l=a.models.filter(c=>c.endsWith(`/${s.model}`));r.push(l.length>0?`[${s.alias}] model="${s.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model>. Your opencode.json declares it as ${l.join(" / ")}; set model=${l[0]}.`:`[${s.alias}] model="${s.model}" has no provider prefix \u2014 opencode model ids are <provider>/<model> (e.g. github-copilot/${s.model}). Declare it in ~/.config/opencode/opencode.json (see https://lmctl.com/examples/opencode.json).`);continue}r.push(`[${s.alias}] model="${s.model}" is not declared in your opencode.json. opencode resolves github-copilot GPT/Gemini config-free, but copilot Claude and custom providers must be declared \u2014 copy https://lmctl.com/examples/opencode.json to ~/.config/opencode/opencode.json and adjust for your account.`);continue}if(!s.model)continue;let o=n.get(i);if(!o){r.push(`[${s.alias}] model="${s.model}" cannot be verified for provider "${i}": `+(Da??"no tested models found in durable-memory/model_selection.md"));continue}o.includes(s.model)||r.push(`[${s.alias}] model="${s.model}" is not in the tested model list for provider "${i}". Valid tested models: ${rB(o)}`)}return r}function KW(t){if(!t&&Bs)return Bs;let e=new Map,r,n=t??VW();if(!qs(n))return r=`${n} not found`,t||Ef(e),t||(Bs=e),t||(Da=r),e;let s;try{s=BS(n,"utf-8")}catch(i){return r=`${n} could not be read: ${i instanceof Error?i.message:String(i)}`,t||Ef(e),t||(Bs=e),t||(Da=r),e}for(let[i,o]of Object.entries(JW)){let a=ZW(s,o),l=QW(a);l.length>0&&e.set(i,l)}return e.size===0&&(r=`${n} has no tested model rows`),!t&&e.size===0&&Ef(e),t||(Bs=e),t||(Da=r),e}function VW(){return YW(qS(XW(import.meta.url)))}function YW(t){let e=zW(t);if(e){let n=Pn(e,"durable-memory","model_selection.md");if(qs(n))return n}let r=[Pn(t,"..","..","durable-memory","model_selection.md"),Pn(t,"..","..","..","durable-memory","model_selection.md")];for(let n of r)if(qs(n))return n;return r[r.length-1]}function zW(t){let e=Pn(t);for(;;){if(qs(Pn(e,"package.json")))return e;let r=qS(e);if(r===e)return null;e=r}}function Ef(t){for(let[e,r]of Object.entries(GW))t.set(e,r)}function ZW(t,e){let n=new RegExp(`^## ${nB(e)}\\s*$`,"m").exec(t);if(!n)return"";let s=n.index+n[0].length,i=t.slice(s),o=/^##\s+/m.exec(i);return o?i.slice(0,o.index):i}function QW(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n.startsWith("| `"))continue;let s=/^\|\s*`([^`]+)`\s*\|/.exec(n);if(!s)continue;let i=s[1].trim();i&&i!=="Configured `model="&&e.add(i)}return[...e]}function eB(t){let e=t??Pn(HW(),".config","opencode","opencode.json");if(!qs(e))return{available:!0,models:[]};let r;try{r=JSON.parse(BS(e,"utf-8"))}catch(n){return{available:!1,models:[],reason:`${e} could not be parsed: ${n instanceof Error?n.message:String(n)}`}}return{available:!0,models:tB(r)}}function tB(t){if(!Tf(t))return[];let e=ja(t.provider)??ja(t.providers);if(!e)return[];let r=new Set;for(let[n,s]of Object.entries(e)){if(!Tf(s))continue;let i=ja(s.models)??ja(s.model);if(i)for(let o of Object.keys(i))r.add(o.startsWith(`${n}/`)?o:`${n}/${o}`)}return[...r].sort()}function ja(t){return Tf(t)?t:null}function Tf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rB(t){return t.length>0?t.join(", "):"(none)"}function nB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var JW,GW,Bs,Da,HS=E(()=>{"use strict";JW={claude:"Claude",codex:"Codex",gemini:"Gemini",qwen:"Qwen",agy:"Antigravity"},GW={claude:["claude-opus-4-6","claude-opus-4-7","claude-opus-4-8","claude-sonnet-4-6","claude-sonnet-5","claude-haiku-4-5","claude-fable-5"],codex:["gpt-5.2","gpt-5.4","gpt-5.5","gpt-5.6-sol","gpt-5.4-mini","gpt-5.3-codex","gpt-5.3-codex-spark"],gemini:["gemini-3.1-pro-preview","gemini-3-flash-preview","gemini-3.1-flash-lite-preview","gemini-2.5-flash","gemini-2.5-flash-lite"],qwen:["qwen3.5-plus","qwen3.6-plus"],agy:["Gemini 3.5 Flash (Medium)","Gemini 3.5 Flash (High)","Gemini 3.5 Flash (Low)","Gemini 3.1 Pro (Low)","Gemini 3.1 Pro (High)","Claude Sonnet 4.6 (Thinking)","Claude Opus 4.6 (Thinking)","GPT-OSS 120B (Medium)"]},Bs=null});import{homedir as sB}from"node:os";import{basename as iB}from"node:path";function Pa(t,e){let r=new Set;return{text:t.replace(aB,(s,i)=>{let o=i.trim(),a=oB[o];return a===void 0?(r.add(o),s):a(e)}),unknownNames:[...r].sort()}}function Fa(t){return{workdir:t.workdir,teamfile:t.teamfile,date:lB(t.date)}}function lB(t){return t.toISOString().slice(0,10)}var oB,aB,Sf=E(()=>{"use strict";oB={workdir:t=>t.workdir,teamfile:t=>t.teamfile,teamname:t=>{let e=iB(t.teamfile);return e.endsWith(".lmctl")?e.slice(0,-6):e},home:()=>sB(),date:t=>t.date},aB=/{{\s*([A-Za-z0-9_-]+)\s*}}/g});var Js={};Ee(Js,{GEMINI_PROVIDER_NOTICE:()=>KS,_setLintOpenCodeConfigProbeForTests:()=>gB,_setLintSessiondirFsOpsForTests:()=>hB,_setTeamfileSeedForTests:()=>_B,buildRootTeamRegistrationRow:()=>ev,registerRootTeam:()=>tv,runHire:()=>IB,runLint:()=>kB,runRefresh:()=>NB,runSeed:()=>ZS,sha256Text:()=>QS});import{createHash as cB}from"node:crypto";import{accessSync as dB,constants as XS,existsSync as uB,readFileSync as Ba,realpathSync as If,statSync as fB,writeFileSync as Wa}from"node:fs";import{dirname as Sr,resolve as GS}from"node:path";function _B(t){VS=t??(async e=>{let{seed:r}=await Promise.resolve().then(()=>(It(),Ec)),n=await r(e);return n.success?{sessionId:n.sessionId,warnings:n.warnings}:{error:n.error??"provider seed failed"}})}function hB(t){Gr=t===null?Nf:{...Nf,...t}}function gB(t){YS=t??Cl}async function yB(t,e,r){let n=t.filter(i=>i.teamfile===void 0&&i.provider.trim().toLowerCase()==="opencode"&&i.model!==void 0&&i.model.length>0);return(await Promise.all(n.map(async i=>({member:i,result:await YS({cwd:i.sessiondir??e,model:i.model,...i.effort!==void 0?{effort:i.effort}:{},...r!==void 0?{env:r}:{}})})))).flatMap(({member:i,result:o})=>o.status==="rejected"?[`[${i.alias}] ${o.option}="${o.value}" rejected by opencode: ${o.error}`]:[])}function wB(t,e){let r=Sr(e),n=new Set,s=[];for(let i of t){if(i.teamfile!==void 0)continue;let o=i.sessiondir??r,a=GS(o);if(n.has(a))continue;let l=EB(a);l!==void 0&&(n.add(a),s.push(`${i.alias}: sessiondir ${a} is not writable (seed would fail: ${l}) \u2014 fix permissions or set a writable sessiondir`))}return s}function EB(t){try{if(Gr.existsSync(t)){if(!Gr.statSync(t).isDirectory())return"ENOTDIR";Gr.accessSync(t,XS.W_OK);return}let e=SB(t);if(e===void 0)return;if(!Gr.statSync(e).isDirectory())return"ENOTDIR";Gr.accessSync(e,XS.W_OK);return}catch(e){return vB(e)??"permission check failed"}}function TB(t,e){let r=[];for(let n of t)n.teamfile!==void 0||n.sessiondir===void 0||zS(n.sessiondir,e)&&r.push(`${n.alias}: sessiondir equals the teamfile directory and is redundant; lmctl seed will remove it`);return r}function bB(t,e,r,n){let s=!1;for(let i of t){if(i.teamfile!==void 0||i.sessiondir===void 0||!zS(i.sessiondir,n))continue;let o=r.get(i.alias.toLowerCase());if(o===void 0)continue;let a=rv(e[o],"sessiondir");a!==e[o]&&(e[o]=a,s=!0),i.sessiondir=void 0}return s}function zS(t,e){return JS(t)===JS(e)}function JS(t){let e=GS(t);try{return If(e)}catch{return e}}function SB(t){let e=t;for(;;){try{if(Gr.existsSync(e))return e}catch{return}let r=Sr(e);if(r===e)return;e=r}}function vB(t){if(typeof t=="object"&&t!==null&&"code"in t){let e=t.code;if(typeof e=="string"&&e.length>0)return e}}async function kB(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(mB),0;if(t.length!==1)return e.stderr.write(`usage: lmctl lint <teamfile.lmctl>
|
|
2509
2591
|
`),2;let r=t[0],n;try{n=await $(e,c=>ve(r,c))}catch(c){return Ce(e,`${r}: ${c instanceof Error?c.message:String(c)}`)}let s;try{s=Ve(n)}catch(c){return Ce(e,`${r}: ${c instanceof Error?c.message:String(c)}`)}let i=au(s,Sr(n)),o=bf(s.members),a=Ba(n,"utf8"),l=Pa(a,Fa({workdir:Sr(n),teamfile:n,date:new Date})).unknownNames;l.length>0&&o.push(`unknown template placeholder${l.length===1?"":"s"}: ${l.map(c=>`{{${c}}}`).join(", ")}`),o.push(...Rl(s.members,Sr(n))),o.push(...wB(s.members,n)),o.push(...TB(s.members,Sr(n))),o.push(...await yB(s.members,Sr(n),e.env));for(let c of i)e.stderr.write(`error: ${c.field}: ${c.message}
|
|
2510
2592
|
`);for(let c of s.members)Af([c],e),c.session!==void 0&&c.session.length<Hs&&o.push(`${c.alias}: sessionid is shorter than ${Hs} chars; run lmctl seed to refresh it`);for(let c of o)e.stderr.write(`warning: ${c}
|
|
2511
2593
|
`);return i.length>0?1:(e.stdout.write(`ok
|
|
@@ -2527,11 +2609,11 @@ List native provider sessions in scope, or list recent managed runs with --runs.
|
|
|
2527
2609
|
`);let g=new Date().toISOString();return await $(e,_=>{tv(_,{teamfilePath:s,name:o.name,rawText:h,now:g})}),0}async function IB(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(Ua),0;let r=Q(t,["--provider","--sessiondir"],[]);if(r.error!==void 0)return kf(e,r.error,Ua);if(r.positionals.length!==2)return kf(e,"expected <teamfile.lmctl> and <alias>",Ua);let[n,s]=r.positionals;if(!$B(s))return Ce(e,`invalid alias "${s}"`);if(s.toLowerCase()==="lead")return Ce(e,"hire only applies to non-Lead members");let i=F(r,"--provider");if(i===void 0)return kf(e,"missing value for --provider",Ua);if(!nv(i))return Ce(e,`invalid provider "${i}"`);let o;try{o=await $(e,u=>ve(n,u))}catch(u){return Ce(e,`${n}: ${u instanceof Error?u.message:String(u)}`)}let a;try{a=Ba(o,"utf8")}catch(u){return Ce(e,`${n}: ${u instanceof Error?u.message:String(u)}`)}if(OB(a,s))return Ce(e,`${s}: alias already exists in ${o}`);let l=F(r,"--sessiondir"),c=[`_MEMBER_ alias=${xf(s)} provider=${i}`,...l===void 0?[]:[`sessiondir=${xf(l)}`]].join(" "),d=MB(a,c);return Wa(o,d,"utf8"),e.stdout.write(`Hired ${s} (${i}) -> ${o}
|
|
2528
2610
|
`),e.stdout.write(`Run: lmctl seed ${o}
|
|
2529
2611
|
`),0}async function NB(t,e={stdout:process.stdout,stderr:process.stderr}){if(t[0]==="--help"||t[0]==="-h"||t[0]==="help")return e.stdout.write(vf),0;let r,n;if(t.length===1){let u=Hr(t[0]);if(u===null)return e.stderr.write(vf),2;r=u.teamfile,n=u.alias}else if(t.length===2)[r,n]=t;else return e.stderr.write(vf),2;let s;try{s=await $(e,u=>ve(r,u))}catch(u){return Ce(e,`${r}: ${u instanceof Error?u.message:String(u)}`)}let i;try{i=Ba(s,"utf8")}catch(u){return Ce(e,`${r}: ${u instanceof Error?u.message:String(u)}`)}let o=i.split(`
|
|
2530
|
-
`),a=LB(o,n);if(a===void 0)return Ce(e,`${n}: no active _MEMBER_ entry found`);let l=o[a];if(
|
|
2612
|
+
`),a=LB(o,n);if(a===void 0)return Ce(e,`${n}: no active _MEMBER_ entry found`);let l=o[a];if(Xs(l,"teamfile")!==void 0)return Ce(e,`${n}: refresh only applies to provider-backed members, not teamfile= members`);let c=(e.env??process.env)[ts],d=Xs(l,"sessionid");return c!==void 0&&c.length>0&&d===c?Ce(e,`${n}: cannot refresh its own running session \u2014 run this refresh from a different member session or a plain operator shell.`):(o[a]=rv(l,"sessionid"),a>0&&/^\s*#CreationTime:/u.test(o[a-1])&&o.splice(a-1,1),Wa(s,o.join(`
|
|
2531
2613
|
`),"utf8"),ZS([s],e))}function QS(t){return cB("sha256").update(t).digest("hex")}function ev(t,e){return{teamfile_path:e.teamfilePath,name:e.name,raw_text:e.rawText,raw_sha256:QS(e.rawText),registered_at:t?.registered_at??e.now,last_seeded_at:e.now}}function tv(t,e){let r=ev(t.getRootTeam(e.teamfilePath),e);return t.upsertRootTeam(r),r}function xB(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(`
|
|
2532
2614
|
`):"- (no non-Lead members)",i=r.find(a=>a.alias.toLowerCase()==="lead")?.provider??"",o=AB(i,t);return["lmctl seed initial connection only. Create or pin this provider session, then stop.","Do not inspect files, run commands, infer a task, delegate, edit, or begin work.","",`Teamfile path: ${t}`,"You are alias Lead for this AI-managed .lmctl team.","","Delegating work:",`- Blocking command shape: lmctl chat "${t}" <alias> "your task here"`,"- SAFE INPUT \u2014 use for ANYTHING non-trivial. A prompt typed into the command line is expanded by YOUR shell first,"," so backticks, $(...), $VAR and quotes are executed or stripped out of the message before lmctl sees it."," If the text contains backticks, quotes, $, newlines, or ANY relayed/pasted/quoted content, do NOT put it in the command.",` Write it to a file with your file-writing tool (NOT echo/heredoc \u2014 those are shell too), then: lmctl chat "${t}" <alias> --prompt-file <path>`,"- lmctl is foreground/background agnostic. Use your provider or host runtime for async command handling when it supports that.","- For delegation, run the lmctl chat command above. If your runtime has a tracked background mode, it may wrap that same blocking command, but check the result with --json or lmctl status.","- Busy receiver ENQUEUES. lmctl chat exits 0 for BOTH delivered and enqueued, so exit code alone CANNOT tell you a reply arrived.",'- lmctl chat ... --json is machine-readable: status="ok" is a delivered reply (with replyText); status="enqueued" (plus path="enqueued") means it was queued, and carries id/sender/receiver.',"- lmctl status shows your identity, members with busy/idle, mail queued TO and FROM you, and why a receiver is busy. Run it when you are unsure whether a delegation landed.","- For arbitrary shell work, use your provider/runtime shell tools directly; lmctl does not execute shell commands.",o,"","Delegation is an ACTION, not a plan: to hand a member a task, run the lmctl chat command above. lmctl exposes no delegation tool you should use \u2014 delegate with lmctl chat.","","Team members:",s,"","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 session \u2014 run it from a different member session or a plain operator shell.`,` Optional: lmctl tail "${t}" <alias> to inspect its recent messages while troubleshooting.`,"(These health/recovery commands are shell commands. For delegation, use lmctl chat.)","","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(`
|
|
2533
|
-
`)}function AB(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: run lmctl chat as the blocking delegation primitive; use Codex-native tool/background behavior when available.";case"gemini":return"- Gemini note: run lmctl chat as the blocking delegation primitive; use Gemini-native tool/background behavior when available.";case"opencode":return"- OpenCode note: use the provider-native background/task surface when available; otherwise run one blocking lmctl chat turn and wait.";default:return"- If your provider has native background completion, use it around the blocking command; otherwise run one blocking lmctl chat turn at a time."}}function RB(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=
|
|
2534
|
-
`))if(/^\s*#?\s*_MEMBER_\s+\S/u.test(r)&&
|
|
2615
|
+
`)}function AB(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: run lmctl chat as the blocking delegation primitive; use Codex-native tool/background behavior when available.";case"gemini":return"- Gemini note: run lmctl chat as the blocking delegation primitive; use Gemini-native tool/background behavior when available.";case"opencode":return"- OpenCode note: use the provider-native background/task surface when available; otherwise run one blocking lmctl chat turn and wait.";default:return"- If your provider has native background completion, use it around the blocking command; otherwise run one blocking lmctl chat turn at a time."}}function RB(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=Xs(n,"alias");s!==void 0&&e.set(s.toLowerCase(),r)}return e}function LB(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)&&Xs(s,"alias")?.toLowerCase()===r)return n}}function OB(t,e){for(let r of t.split(`
|
|
2616
|
+
`))if(/^\s*#?\s*_MEMBER_\s+\S/u.test(r)&&Xs(r,"alias")===e)return!0;return!1}function $B(t){return/^[A-Za-z][A-Za-z0-9_-]*$/u.test(t)}function Xs(t,e){let n=new RegExp(`(?:^|\\s)${e}=(?:"([^"]*)"|(\\S*))`).exec(t);return n===null?void 0:n[1]??n[2]??""}function CB(t,e,r){let n=`${e}=${xf(r)}`,s=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return s.test(t)?t.replace(s,(i,o)=>`${o}${n}`):`${t.trimEnd()} ${n}`}function rv(t,e){let r=new RegExp(`(^|\\s)${e}=(?:"[^"]*"|\\S*)`);return t.replace(r,"").replace(/\s+/gu," ").trimEnd()}function xf(t){return/[\s"]/u.test(t)?`"${t.replace(/"/g,'\\"')}"`:t}function MB(t,e){let r=t.split(`
|
|
2535
2617
|
`),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(`
|
|
2536
2618
|
`);let s=r.length;for(;s>0&&r[s-1]==="";)s-=1;let i=r.slice(0,s).join(`
|
|
2537
2619
|
`),o=r.slice(s).join(`
|
|
@@ -2571,17 +2653,17 @@ re-seed.
|
|
|
2571
2653
|
A member cannot refresh its own running session; run the refresh from a
|
|
2572
2654
|
different member session or a plain operator shell.
|
|
2573
2655
|
`,KS='notice: member "%s" uses provider=gemini \u2014 the Gemini CLI requires an API/enterprise Google account; personal Google subscriptions should use provider=agy (Antigravity).',Nf={existsSync:uB,statSync:fB,accessSync:dB},VS=async t=>{let{seed:e}=await Promise.resolve().then(()=>(It(),Ec)),r=await e(t);return r.success?{sessionId:r.sessionId,warnings:r.warnings}:{error:r.error??"provider seed failed"}},Gr=Nf,YS=Cl});var cv={};Ee(cv,{runClone:()=>HB});import{existsSync as Rf,mkdirSync as DB,readFileSync as PB,readdirSync as FB,statSync as av,writeFileSync as UB}from"node:fs";import{basename as sv,dirname as WB,extname as BB,join as lv,resolve as iv}from"node:path";async function HB(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(qB),0;if(t.length!==2)return e.stderr.write(`usage: lmctl clone <source> <dest>
|
|
2574
|
-
`),2;let[r,n]=t,s,i=r;try{if(/^http:\/\//i.test(r))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(r))s=await
|
|
2656
|
+
`),2;let[r,n]=t,s,i=r;try{if(/^http:\/\//i.test(r))throw new Error("plaintext http:// sources are not allowed; use https://");if(/^https:\/\//i.test(r))s=await JB(r);else{let c=iv(r);if(!Rf(c))throw new Error(`source not found: ${r}`);let u=av(c).isDirectory()?GB(c):c;s=PB(u,"utf8"),i=u}}catch(c){return e.stderr.write(`error: ${c instanceof Error?c.message:String(c)}
|
|
2575
2657
|
`),1}let o=iv(n),a=KB(o,i,n);if(Rf(a))return e.stderr.write(`error: ${a} already exists.
|
|
2576
2658
|
`),1;let l=YB(VB(s));return DB(WB(a),{recursive:!0}),UB(a,l,"utf8"),e.stdout.write(`Cloned ${r} -> ${a}
|
|
2577
2659
|
`),e.stdout.write(`Edit ${a}; only _MEMBER_ lines are parsed, everything else is free-form.
|
|
2578
2660
|
`),e.stdout.write(`After editing, run: lmctl lint ${a}
|
|
2579
2661
|
`),e.stdout.write(`Then run: lmctl seed ${a}
|
|
2580
|
-
`),0}async function
|
|
2662
|
+
`),0}async function JB(t){let e=new URL(t);for(let r=0;;r+=1){if(e.protocol!=="https:")throw new Error("HTTPS clone redirects must remain https://");let n=await fetch(e.href,{redirect:"manual"});if(n.url!==""&&new URL(n.url).protocol!=="https:")throw new Error("HTTPS clone redirects must remain https://");if(!XB.has(n.status)){if(!n.ok)throw new Error(`HTTP ${n.status}`);return await n.text()}if(r>=ov)throw new Error(`too many HTTPS redirects (maximum ${ov})`);let s=n.headers.get("location");if(s===null)throw new Error(`HTTP ${n.status} redirect missing Location header`);e=new URL(s,e)}}function GB(t){let e=FB(t).filter(r=>r.endsWith(".lmctl"));if(e.length===0)throw new Error(`no .lmctl files in source directory: ${t}`);if(e.length>1)throw new Error(`multiple .lmctl files in source directory: ${t}; specify the source file explicitly`);return lv(t,e[0])}function KB(t,e,r){if(r.endsWith("/")||Rf(t)&&av(t).isDirectory()){let n=sv(e).endsWith(".lmctl")?sv(e):"team.lmctl";return lv(t,n)}return BB(t)?t:`${t}.lmctl`}function VB(t){return t.split(`
|
|
2581
2663
|
`).map(e=>/^\s*_MEMBER_\s+\S/.test(e)?e.replace(/\s+sessionid=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessionid=(?:"[^"]*"|\S+)\s+/g,"$1 "):e).join(`
|
|
2582
2664
|
`)}function YB(t){return t.split(`
|
|
2583
2665
|
`).map(e=>/^\s*_MEMBER_\s+\S/.test(e)?e.replace(/\s+sessiondir=(?:"[^"]*"|\S+)/g,"").replace(/^(\s*_MEMBER_)\s+sessiondir=(?:"[^"]*"|\S+)\s+/g,"$1 "):e).join(`
|
|
2584
|
-
`)}var qB,
|
|
2666
|
+
`)}var qB,XB,ov,dv=E(()=>{"use strict";qB=`usage: lmctl clone <source> <dest>
|
|
2585
2667
|
|
|
2586
2668
|
Copy a teamfile and strip its session ids, producing a static editable template.
|
|
2587
2669
|
<source> may be a .lmctl file, an https:// URL, or a directory containing
|
|
@@ -2591,7 +2673,7 @@ Examples:
|
|
|
2591
2673
|
lmctl clone ./backend/backend.lmctl ./backend-v2/backend-v2.lmctl
|
|
2592
2674
|
lmctl clone ./backend/ ./backend-v2/backend-v2.lmctl
|
|
2593
2675
|
lmctl clone https://example.com/backend.lmctl ./backend-v2/backend-v2.lmctl
|
|
2594
|
-
`;
|
|
2676
|
+
`;XB=new Set([301,302,303,307,308]),ov=10});var mv={};Ee(mv,{runPlan:()=>nq});import{existsSync as zB,mkdirSync as ZB,writeFileSync as QB}from"node:fs";import{basename as uv,extname as fv,join as eq,resolve as tq}from"node:path";async function nq(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(rq),0;let r=Q(t,["--team","--provider"],[]);if(r.error!==void 0)return e.stderr.write(`error: ${r.error}
|
|
2595
2677
|
`),e.stderr.write(`usage: lmctl plan [options] <directory>
|
|
2596
2678
|
`),2;if(r.positionals.length!==1)return e.stderr.write(`usage: lmctl plan [options] <directory>
|
|
2597
2679
|
`),2;let n=tq(r.positionals[0]);ZB(n,{recursive:!0});let s=F(r,"--team")??uv(n),i=F(r,"--provider")??"claude",o=eq(n,sq(s));if(zB(o))return e.stderr.write(`error: ${o} already exists.
|
|
@@ -2726,7 +2808,7 @@ delete requires --confirm; deleting default or active workspaces also requires -
|
|
|
2726
2808
|
# tail_lines=${u.tail_lines}
|
|
2727
2809
|
`;await s("intents/recent.log",`${m}${u.tail}${u.tail.length>0?`
|
|
2728
2810
|
`:""}`)}if(await s("README.md",qq(t)),t.sanitized)for(let u of n){let f=await Wq(u.absPath);try{im(u.bundlePath,f.toString("utf8"))}catch(m){throw await Pv(e,{recursive:!0,force:!0}),m instanceof xr,m}}let o=await Cv(n),a=Mv({ticketId:t.ticketId,lmctlNextVersion:t.lmctlNextVersion,nodeVersion:process.version,platform:process.platform,generatedAt:t.generatedAt??new Date,sanitized:t.sanitized,files:o});await s("manifest.json",i(a)),await Df(Fv(t.outputPath),{recursive:!0});let l=jv("tar",["-czf",t.outputPath,"-C",e,`diagnostic-${t.ticketId}`],{encoding:"utf8"});if(l.status!==0)throw new Error(`tar failed (status=${l.status}): ${l.stderr??""}`);let c=jv("stat",["-c","%s",t.outputPath],{encoding:"utf8"}),d=Number.parseInt((c.stdout??"0").trim(),10)||0;return await Pv(e,{recursive:!0,force:!0}),{outputPath:t.outputPath,manifest:a,bundleSizeBytes:d}}function qq(t){let e=Object.keys(t.data).sort().join(", ")||"(none)";return[`# Diagnostic Bundle ${t.ticketId}`,"",`Generated by lmctl ${t.lmctlNextVersion}.`,"",`Sections included: ${e}`,`Sanitized: ${t.sanitized?"yes":"NO (--no-sanitize)"}`,"","## Layout","","- `manifest.json` \u2014 file index + sha256 + lmctl version.","- `serve/` \u2014 daemon PID + sanitized log tail.","- `db/` \u2014 sqlite integrity-check, schema version, table row counts.","- `runs/` \u2014 last 50 run metadata, stale runs, paused runs.","- `jobs/` \u2014 queue snapshot (pending/running/done/failed counts + ids).","- `attentions/` \u2014 unacked operator attentions.","- `env/` \u2014 lmctl version, node, uname -a, du -sh, tracked env vars.","- `intents/` \u2014 last N entries of the rolling intent log (sanitized).","","## What this bundle does NOT contain","","- Prompt bodies or message contents.","- step_artifact contents (code/text artifacts produced by runs).","- durable_memory bodies.","- session_event payloads.","- API tokens or bearer tokens (redacted in sanitization).",""].join(`
|
|
2729
|
-
`)}var Wv=E(()=>{"use strict";jf();ti()});import{spawnSync as Hq}from"node:child_process";import{stat as
|
|
2811
|
+
`)}var Wv=E(()=>{"use strict";jf();ti()});import{spawnSync as Hq}from"node:child_process";import{stat as Xq}from"node:fs/promises";async function Bv(t){try{if(!(await Xq(t.bundlePath)).isFile())return{mode:t.mode,ok:!1,message:`bundle not a regular file: ${t.bundlePath}`}}catch(e){return{mode:t.mode,ok:!1,message:`bundle missing: ${e instanceof Error?e.message:String(e)}`}}switch(t.mode){case"local":return{mode:"local",ok:!0,message:`bundle written: ${t.bundlePath}`,destination:t.bundlePath};case"internal-s3":return Jq(t);case"hq":return Gq(t)}}function Jq(t){let r=Hq("which",["aws"],{encoding:"utf8"}).status===0,s=`${t.s3Prefix??"s3://lmctl/diagnostics/"}${t.ticketId}.tar.gz`;return r?{mode:"internal-s3",ok:!0,message:`STUB (no actual upload performed): would run \`aws s3 cp ${t.bundlePath} ${s}\``,destination:s}:{mode:"internal-s3",ok:!1,message:`aws CLI not available; would upload ${t.bundlePath} -> ${s}`,destination:s}}function Gq(t){let e=t.hqUrl??"https://lmctl.anthropic.com";return{mode:"hq",ok:!1,message:`headquarter upload not implemented in MVP; would POST to ${e}/diagnostics/init with ticket ${t.ticketId}`,destination:e}}var qv=E(()=>{"use strict"});var Xv={};Ee(Xv,{parseDiagnoseArgs:()=>Hv,runDiagnose:()=>Yq});import{tmpdir as Kq}from"node:os";import{join as Vq}from"node:path";async function Yq(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${Qq()}
|
|
2730
2812
|
`),0;let r=Hv(t);if(typeof r=="string")return e.stderr.write(`error: ${r}
|
|
2731
2813
|
`),2;if(r.noSanitize&&(r.upload||r.internalS3||r.hqUrl!==void 0))return e.stderr.write(`error: --no-sanitize is incompatible with upload modes (--upload/--internal-s3/--hq)
|
|
2732
2814
|
`),2;if(r.upload&&r.internalS3)return e.stderr.write(`error: pick one of --upload (HQ) or --internal-s3, not both
|
|
@@ -2737,7 +2819,7 @@ delete requires --confirm; deleting default or active workspaces also requires -
|
|
|
2737
2819
|
`),e.stdout.write(`upload[${c.mode}]: ${c.ok?"ok":"noop"} \u2014 ${c.message}
|
|
2738
2820
|
`)),c.ok||i==="local"?0:1})}catch(o){return e.stderr.write(`diagnose failed: ${o instanceof Error?o.message:String(o)}
|
|
2739
2821
|
`),1}}function Hv(t){let e={upload:!1,internalS3:!1,noSanitize:!1,json:!1},r=[];for(let n=0;n<t.length;n+=1){let s=t[n];if(s==="--output"){let i=t[++n];if(i===void 0||i.startsWith("--"))return"missing value for --output";e.outputPath=i;continue}if(s==="--upload"){e.upload=!0;continue}if(s==="--internal-s3"){e.internalS3=!0;continue}if(s==="--hq"){let i=t[++n];if(i===void 0||i.startsWith("--"))return"missing value for --hq";e.hqUrl=i,e.upload=!0;continue}if(s==="--include"){let i=t[++n];if(i===void 0||i.startsWith("--"))return"missing value for --include";if(!zq(i))return`unknown section: ${i} (expected one of ${ri.join(", ")})`;r.push(i);continue}if(s==="--no-sanitize"){e.noSanitize=!0;continue}if(s==="--json"){e.json=!0;continue}if(!(s==="--help"||s==="-h"))return`unknown argument: ${s}`}return r.length>0&&(e.include=r),e}function zq(t){return ri.includes(t)}function Zq(t){return Vq(Kq(),`lmctl-diag-${t}.tar.gz`)}function Qq(){return["usage: lmctl diagnose [options]","","Collect platform diagnostics into a sanitized troubleshooting bundle,","with optional upload modes for support workflows.","","options:"," --output <path> write bundle to <path> (default /tmp/lmctl-diag-<ticket>.tar.gz)"," --upload upload to headquarter (HTTP, currently stub)"," --hq <url> override headquarter base URL (implies --upload)"," --internal-s3 upload to s3://lmctl/diagnostics/ (stub; checks aws CLI)"," --include <section> restrict to one of: serve|db|runs|jobs|attentions|env|intents (repeatable)"," --no-sanitize DANGER: skip secret redaction; incompatible with upload"," --json emit JSON summary to stdout"].join(`
|
|
2740
|
-
`)}var
|
|
2822
|
+
`)}var Jv=E(()=>{"use strict";Hn();Wv();jf();ti();qv();We();Le()});var Zv={};Ee(Zv,{ATTENTION_STATES:()=>Wf,DAEMON_INTERVAL_FAST_MS:()=>Uf,REQUIRED_TEAM_ALIASES:()=>Gv,chooseDiagnoses:()=>Yv,collectEvidence:()=>Vv,diagnose:()=>Kv,renderReport:()=>zv,runDiagnosePrompt:()=>rH});function Kv(t,e){let r=Vv(t,e),n=Yv(r);return zv(r,n)}function Vv(t,e){let r=e.trim(),n={promptId:r,prompt:{exists:!1},dispatch:{sectionAvailable:!0,rowExists:!1},job:{sectionAvailable:!0,exists:!1},run:{sectionAvailable:!0,exists:!1},project:{sectionAvailable:!0,exists:!1},workflows:{sectionAvailable:!0,count:0,rows:[]},team:{sectionAvailable:!0,members:[],missingAliases:[]},daemon:{workerPid:null,intervalMs:Rs(),lastTickAt:null}},s=null;try{s=t.getPromptDispatch(r)}catch{n.dispatch.sectionAvailable=!1}if(s!=null&&(n.dispatch.rowExists=!0,n.prompt.exists=!0,n.prompt.project_id=s.project_id,n.prompt.text_preview=tH(s.text),n.prompt.created_at=s.created_at,n.prompt.completed_at=s.completed_at,n.prompt.job_id=s.job_id),n.prompt.job_id!==void 0)try{let i=t.getJob(n.prompt.job_id);if(i!==null&&(n.job.exists=!0,n.job.status=i.status,n.job.attempt_count=i.attempt_count,n.job.last_error=i.last_error,n.job.available_at=i.available_at,n.job.locked_by=i.locked_by,n.job.run_id=i.run_id,i.run_id!==null))try{let o=t.getRun(i.run_id);if(o!==null){n.run.exists=!0,n.run.id=o.id,n.run.current_state=o.current_state,n.run.terminal_state=o.terminal_state,n.run.started_at=o.started_at,n.run.ended_at=o.ended_at;let a="__paused__:";n.run.paused_step=o.current_state!==null&&o.current_state.startsWith(a)?o.current_state.slice(a.length):null,n.run.paused_at=o.paused_at}}catch{n.run.sectionAvailable=!1}}catch{n.job.sectionAvailable=!1}if(n.prompt.project_id!==void 0)try{let i=t.getProject(n.prompt.project_id);if(i!==null){n.project.exists=!0,n.project.id=i.id,n.project.name=i.name,n.project.local_path=i.local_path,n.project.test_command=i.test_command,n.project.workflow_name=i.workflow_name,n.project.team_id=i.team_id;try{n.project.workflow_name_resolves=t.getWorkflowByName(i.workflow_name)!==null}catch{n.project.workflow_name_resolves=!1}}}catch{n.project.sectionAvailable=!1}if(n.project.id!==void 0)try{let i=t.listProjectWorkflows(n.project.id);n.workflows.count=i.length;for(let o of i){let a=`workflow_id=${o.workflow_id}`,l=0,c=null;try{let u=t.listWorkflows().find(f=>f.id===o.workflow_id);u!==void 0&&(a=u.name,l=u.version,c=u.source_uri)}catch{}n.workflows.rows.push({workflow_name:a,version:l,enabled:o.enabled,source_uri:c})}}catch{n.workflows.sectionAvailable=!1}if(n.project.team_id!==void 0)try{n.team.teamId=n.project.team_id;let i=t.listTeamMembers(n.project.team_id);for(let a of i)n.team.members.push({alias:a.alias,provider:a.provider,sessionid:a.sessionid,sessiondir:a.sessiondir,state:a.state,state_reason:a.state_reason,state_updated_at:a.state_updated_at});let o=new Set(i.map(a=>a.alias));n.team.missingAliases=Gv.filter(a=>!o.has(a))}catch{n.team.sectionAvailable=!1}return n.daemon.workerPid=null,n.daemon.lastTickAt=null,n}function Yv(t){let e=[];if(t.dispatch.sectionAvailable&&!t.dispatch.rowExists)return e.push({cause:"Prompt wasn't enqueued (no prompt_dispatch row); SPA\u2192agent submitPrompt path broken",action:"Inspect mailbox-rest-router submitPrompt logs on the agent; confirm the SPA reached /mailbox/projects/:id/prompts"}),e;t.dispatch.rowExists&&t.job.exists&&(t.job.run_id===null||t.job.run_id===void 0)&&!t.run.exists&&e.push({cause:"Daemon poll didn't pick up the job (no run row); check daemon interval + worker pid",action:"Restart the agent serve process or lower LMCTL_DAEMON_INTERVAL_MS (current default 600000ms = 10min)"}),t.daemon.intervalMs>Uf&&e.push({cause:`Daemon poll interval is ${t.daemon.intervalMs}ms (${Math.round(t.daemon.intervalMs/1e3)}s); WT/dev expected <=${Uf}ms`,action:"Set LMCTL_DAEMON_INTERVAL_MS=5000 (or lower) in the agent's env before relaunching `lmctl-next-agent`"}),t.project.exists&&t.workflows.sectionAvailable&&t.workflows.count===0&&t.project.workflow_name_resolves!==!0&&e.push({cause:`Project ${t.project.name??`id=${t.project.id??"?"}`} has 0 workflows registered AND project.workflow_name does not resolve; engine can't dispatch`,action:"The workflow/project CLI surface is retired; inspect the dormant DB rows or migrate this project to a .lmctl teamfile path."}),t.team.sectionAvailable&&t.team.missingAliases.length>0&&e.push({cause:`Default team (team_id=${t.team.teamId??"?"}) missing required aliases: ${t.team.missingAliases.join(", ")} (TC2 DEFECT-E class \u2014 engine will stall with missing_agent:<alias>)`,action:"Run `lmctl team seed` against this project's team, or add the missing members via `lmctl team add-member`"});let r=t.team.sectionAvailable?t.team.members.filter(s=>Wf.has(s.state)):[];if(t.run.exists&&(t.run.paused_step??null)!==null||r.length>0){let s=t.run.paused_step??null,i=r.map(a=>a.alias).join(", "),o=s!==null&&i.length>0?`Run paused at ${s} awaiting operator escalation decision (member ${i} attention_needed)`:s!==null?`Run paused at ${s} awaiting operator escalation decision`:`Team member(s) ${i} awaiting operator attention`;e.push({cause:o,action:"Open the run in the SPA escalations panel (paused badge) or resolve via the operator-resume verb"})}return t.dispatch.rowExists&&t.job.exists&&!t.run.exists&&t.daemon.workerPid===null&&e.push({cause:"Worker pid not observable (agent serve process may not be actively daemoning)",action:"Verify `lmctl-next-agent` is running and check stderr for `[lmctl-next-agent]` lines"}),e.slice(0,3)}function zv(t,e){let r=[];if(r.push(`DIAGNOSE ${t.promptId}`),r.push(""),r.push("[PROMPT]"),t.prompt.exists?(r.push(` id: ${t.promptId}`),r.push(` project_id: ${t.prompt.project_id??"?"}`),r.push(` text: ${t.prompt.text_preview??"?"}`),r.push(` created_at: ${t.prompt.created_at??"?"}`),r.push(` completed_at: ${t.prompt.completed_at??"null"}`)):r.push(" not present in prompt_dispatch table"),r.push(""),r.push("[PROMPT_DISPATCH]"),t.dispatch.sectionAvailable?(r.push(` row exists in prompt_dispatch table: ${t.dispatch.rowExists?"YES":"NO"}`),t.dispatch.rowExists&&(r.push(` job_id: ${t.prompt.job_id??"?"}`),r.push(` dispatched_at: ${t.prompt.created_at??"?"}`),r.push(` last_seen_status: ${eH(t)}`))):r.push(" table not present (schema variation)"),r.push(""),r.push("[PROMPT_RUN]"),t.job.sectionAvailable?t.job.exists?t.run.exists?(r.push(" row exists in prompt_runs table: YES"),r.push(` run_id: ${t.run.id??"?"}`),r.push(` current_step: ${t.run.current_state??"null"}`),r.push(` status: ${t.run.terminal_state??"in_progress"}`),r.push(` started_at: ${t.run.started_at??"?"}`),r.push(` attempts: ${t.job.attempt_count??0}`)):(r.push(" row exists in prompt_runs table: NO"),r.push(` job_id: ${t.prompt.job_id??"?"} status=${t.job.status??"?"} attempts=${t.job.attempt_count??0}`),r.push(" -> job enqueued but no run; daemon poll did not consume it")):(r.push(" row exists in prompt_runs table: NO"),r.push(" -> worker never picked up the prompt (job row missing)")):r.push(" job table not accessible"),r.push(""),r.push("[PROJECT]"),t.project.sectionAvailable?t.project.exists?(r.push(` id: ${t.project.id??"?"}`),r.push(` name: ${t.project.name??"?"}`),r.push(` local_path: ${t.project.local_path??"?"}`),r.push(` test_command: ${t.project.test_command??"null"}`),r.push(` default_workflow: ${t.project.workflow_name??"null"}`)):t.prompt.project_id===void 0?r.push(" not resolvable (no project_id on prompt)"):r.push(` not present (id=${t.prompt.project_id})`):r.push(" project table not accessible"),r.push(""),r.push("[WORKFLOWS REGISTERED FOR PROJECT]"),!t.workflows.sectionAvailable)r.push(" project_workflow table not accessible");else if(t.workflows.count===0&&t.project.exists&&t.project.workflow_name_resolves===!0)r.push(` default_workflow_name: ${t.project.workflow_name??"?"} (resolved via project.workflow_name)`),r.push(" project_workflow rows: 0 (uses fallback resolution; expected)");else{r.push(` count: ${t.workflows.count}`);for(let i of t.workflows.rows)r.push(` - ${i.workflow_name} v${i.version} enabled=${i.enabled===1?"true":"false"} source=${i.source_uri??"null"}`)}if(r.push(""),r.push("[TEAM MEMBERS FOR PROJECT'S DEFAULT TEAM]"),!t.team.sectionAvailable)r.push(" team_member table not accessible");else if(t.team.teamId===void 0)r.push(" not resolvable (no team_id on project)");else{t.team.members.length===0&&r.push(" (no members)");for(let i of t.team.members)r.push(` - alias=${i.alias} provider=${i.provider} state=${i.state} sessionid=${i.sessionid??"null"} sessiondir=${i.sessiondir}`);t.team.missingAliases.length>0&&r.push(` ! missing aliases: ${t.team.missingAliases.join(", ")}`)}r.push("");let n=t.team.sectionAvailable?t.team.members.filter(i=>Wf.has(i.state)):[],s=t.run.exists?t.run.paused_step??null:null;if(s!==null||n.length>0){if(r.push("[ATTENTION/ESCALATION]"),s!==null){let i=t.run.paused_at??t.run.started_at??"?";r.push(` paused_step: ${s} (started: ${i})`)}if(n.length>0){let i=n.map(o=>`${o.alias} (state=${o.state}${o.state_updated_at?` since ${o.state_updated_at}`:""}${o.state_reason?`, reason="${o.state_reason}"`:""})`).join(", ");r.push(` members awaiting operator: ${i}`)}else r.push(" members awaiting operator: (none flagged on team)");r.push(" next action expected: operator response via /admin or webcli escalations verb"),r.push("")}if(r.push("[DAEMON STATE]"),r.push(` worker pid: ${t.daemon.workerPid===null?"not observable from CLI":String(t.daemon.workerPid)}`),r.push(` daemon poll interval (LMCTL_DAEMON_INTERVAL_MS env): ${t.daemon.intervalMs}`),r.push(` last daemon tick: ${t.daemon.lastTickAt??"not exposed"}`),r.push(""),r.push("[DIAGNOSIS]"),e.length===0)r.push(" no obvious root cause flagged by the v1 rules (see brief Part 4)");else for(let i of e)r.push(` - ${i.cause}`),r.push(` -> ${i.action}`);return r.join(`
|
|
2741
2823
|
`)+`
|
|
2742
2824
|
`}function eH(t){return t.dispatch.rowExists?t.prompt.completed_at!==null&&t.prompt.completed_at!==void 0?"done":t.job.exists?t.run.exists?t.run.terminal_state!==null&&t.run.terminal_state!==void 0?`terminal:${t.run.terminal_state}`:`running:${t.run.current_state??"?"}`:"pending (no run)":"pending (no job)":"unknown"}function tH(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:`${e.slice(0,80)}...`}async function rH(t,e={stdout:process.stdout,stderr:process.stderr}){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(`${Ff()}
|
|
2743
2825
|
`),0;let r=[];for(let s of t){if(s.startsWith("--"))return e.stderr.write(`error: unknown flag: ${s}
|
|
@@ -2747,7 +2829,7 @@ delete requires --confirm; deleting default or active workspaces also requires -
|
|
|
2747
2829
|
`),2;let n=r[0];try{return await $(e,s=>(e.stdout.write(Kv(s,n)),0))}catch(s){return e.stderr.write(`diagnose-prompt failed: ${s instanceof Error?s.message:String(s)}
|
|
2748
2830
|
`),1}}function Ff(){return["usage: lmctl diagnose-prompt <prompt_id>","",'Narrow read-only diagnostic for the WT-6 "prompt-pending-forever"',"symptom. Renders prompt + dispatch + run + project + workflows + team","state, then picks the top 1-3 likely root causes (daemon interval,","missing workflows, missing team aliases, etc).","","options:"," -h, --help show this help and exit"].join(`
|
|
2749
2831
|
`)}var Gv,Uf,Wf,Qv=E(()=>{"use strict";pu();Le();Gv=["Coder","Reviewer1","Polisher"],Uf=3e4,Wf=new Set(["attention_needed","paused","escalation"])});var bk={};Ee(bk,{appendIntent:()=>mk,resolveIntentLogPath:()=>fk,runStatus:()=>pH});import{appendFileSync as nH,existsSync as sH,mkdirSync as iH}from"node:fs";import{homedir as oH,hostname as ek}from"node:os";import{basename as aH,dirname as uk,isAbsolute as lH,join as cH,resolve as dH}from"node:path";function fk(){return process.env.LMCTL_INTENT_LOG??cH(oH(),".lmctl","recent-intents.log")}function mk(t){try{let e=fk();iH(uk(e),{recursive:!0});let r=JSON.stringify({ts:t.ts??new Date().toISOString(),cwd:t.cwd??process.cwd(),verb:t.verb,args:[...t.args]});nH(e,`${r}
|
|
2750
|
-
`)}catch{}}async function pH(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(uH),0;let r=t.find(o=>o==="--project"||o.startsWith("--project=")||o==="--web");if(r!==void 0)return v(e,`unknown option ${r}; lmctl status is team/SELF scoped now`);let n=Q(t,["--since"],["--json"]);if(n.error!==void 0)return v(e,n.error);if(n.positionals.length>0)return v(e,`unknown argument: ${n.positionals[0]}`);let s=K(n,"--json"),i=
|
|
2832
|
+
`)}catch{}}async function pH(t,e){if(t.includes("--help")||t.includes("-h"))return e.stdout.write(uH),0;let r=t.find(o=>o==="--project"||o.startsWith("--project=")||o==="--web");if(r!==void 0)return v(e,`unknown option ${r}; lmctl status is team/SELF scoped now`);let n=Q(t,["--since"],["--json"]);if(n.error!==void 0)return v(e,n.error);if(n.positionals.length>0)return v(e,`unknown argument: ${n.positionals[0]}`);let s=K(n,"--json"),i=XH(F(n,"--since"));if("error"in i)return v(e,i.error);try{let o=e.env??process.env;if(s){let a=await $(e,l=>ik(l,o));le(e,a)}else{let a=await $(e,async l=>LH(await ik(l,o),{sinceIso:i.iso}));e.stdout.write(a)}return mk({verb:"status",args:t}),0}catch(o){return v(e,o instanceof Error?o.message:String(o))}}async function ik(t,e){let r=Yu(e,t);if(!r.ok){if(r.reason==="not-found")throw new Error(Ps("status"));return await hH(t)}return await _H(t,r.identity)}async function _H(t,e){let r=Jr(e),n=t.getRootTeam(r.teamfile);if(n===null)throw new Error(Ps("status"));let s=Fe(n.teamfile_path,t),i=qf(Ja(t,{from:r.value})),o=qf(Ja(t,{target_teamfile:r.teamfile,target_alias:r.alias})),a=EH([...Bf(t,{from:r.value}),...Bf(t,{target_teamfile:r.teamfile,target_alias:r.alias})]);return{scope:"self",identity:r.value,...pk(),team:{name:s.name,teamfile:n.teamfile_path},members:s.members.map(l=>yH(t,n.teamfile_path,l)),activity:{from_me:i.map(l=>Hf(l,t)),to_me:o.map(l=>Hf(l,t))},transcript_harvest:await hk(a),mailbox:{outbound:Ga(TH(t,r.teamfile,r.alias),"outbound"),inbound_pending:Ga(bH(t,r.teamfile,r.alias),"inbound")},waiting_on:SH(t,r.teamfile,r.alias).map(l=>_k(l,t))}}function pk(){return{workspace:Dt(),db_path:Z()}}async function hH(t){let e=t.listRootTeams();return{scope:"workspace",identity:null,...pk(),teams:e.map(r=>gH(t,r)),activity:qf(Ja(t)).map(r=>Hf(r,t)),transcript_harvest:await hk(Bf(t)),mailbox:{pending_outbound:Ga(ok(t,"sender"),"outbound"),pending_inbound:Ga(ok(t,"receiver"),"inbound")},waiting_on:vH(t).map(r=>_k(r,t))}}function gH(t,e){if(!sH(e.teamfile_path))return{name:e.name,teamfile:e.teamfile_path,member_count:0,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at,missing_on_disk:!0};let r=0;try{r=Fe(e.teamfile_path,t).members.length}catch{r=0}return{name:e.name,teamfile:e.teamfile_path,member_count:r,registered_at:e.registered_at,last_seeded_at:e.last_seeded_at}}function yH(t,e,r){let n=r.teamfile===void 0?null:ve(lH(r.teamfile)?r.teamfile:dH(uk(e),r.teamfile),t),s=Vt(t,e,r.alias),i=s.busy&&s.reason==="in-flight"?wH(t,e,r.alias,s.inFlight):null;return{alias:r.alias,provider:r.provider,model:r.model??null,teamfile:e,referenced_teamfile:n,sessionid:r.session??null,sessiondir:r.sessiondir??null,state:s.busy?"busy":"idle",reason:s.busy?s.reason:null,handling:i}}function wH(t,e,r,n){let s=n.sender_alias==="operator"?"operator":`${n.sender_teamfile}:${n.sender_alias}`,o=t.db.prepare(`
|
|
2751
2833
|
SELECT * FROM tracked_invocation
|
|
2752
2834
|
WHERE kind = 'chat'
|
|
2753
2835
|
AND status = 'running'
|
|
@@ -2757,11 +2839,11 @@ delete requires --confirm; deleting default or active workspaces also requires -
|
|
|
2757
2839
|
AND holder_pid IS ?
|
|
2758
2840
|
ORDER BY started_at DESC, id DESC
|
|
2759
2841
|
LIMIT 5
|
|
2760
|
-
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:Tk(o.request_payload)}}function
|
|
2842
|
+
`).all(e,r,s,n.holder_pid).find(a=>a.request_payload!==null);return o?.request_payload===void 0||o.request_payload===null?null:{tracked_invocation_id:o.id,from_identity:o.from_identity,started_at:o.started_at,request_payload:o.request_payload,request_preview:Tk(o.request_payload)}}function Ja(t,e={}){let r=[],n=[];e.from!==void 0&&(r.push("from_identity = ?"),n.push(e.from)),e.target_teamfile!==void 0&&(r.push("target_teamfile = ?"),n.push(e.target_teamfile)),e.target_alias!==void 0&&(r.push("target_alias = ?"),n.push(e.target_alias));let s=r.length===0?"":` WHERE ${r.join(" AND ")}`;return t.db.prepare(`
|
|
2761
2843
|
SELECT * FROM tracked_invocation
|
|
2762
2844
|
${s}
|
|
2763
2845
|
ORDER BY started_at DESC, id DESC
|
|
2764
|
-
`).all(...n)}function Bf(t,e={}){return
|
|
2846
|
+
`).all(...n)}function Bf(t,e={}){return Ja(t,e).filter(n=>n.kind==="chat"&&n.status==="running"&&na(n)==="dead")}function EH(t){let e=new Set,r=[];for(let n of t)e.has(n.id)||(e.add(n.id),r.push(n));return r.sort((n,s)=>{let i=Date.parse(s.started_at)-Date.parse(n.started_at);return Number.isFinite(i)&&i!==0?i:s.id-n.id})}function TH(t,e,r){return t.db.prepare(`
|
|
2765
2847
|
SELECT * FROM agent_mailbox
|
|
2766
2848
|
WHERE sender_teamfile = ?
|
|
2767
2849
|
AND sender_alias = ?
|
|
@@ -2826,9 +2908,9 @@ delete requires --confirm; deleting default or active workspaces also requires -
|
|
|
2826
2908
|
id ASC
|
|
2827
2909
|
`).all()}function qf(t){return t.filter(e=>na(e)!=="dead")}function _k(t,e){let r=t.delivered_at!==null&&(t.receipt===null||t.receipt==="");return{id:t.id,state:r?"no reply":"queued",sender:t.sender_teamfile===null||t.sender_alias===null?null:`${t.sender_teamfile}:${t.sender_alias}`,receiver:`${t.receiver_teamfile}:${t.receiver_alias}`,message_type:t.message_type,payload:t.payload,payload_preview:Tk(t.payload),receiver_availability:kH(Vt(e,t.receiver_teamfile,t.receiver_alias)),age_basis_at:r?t.delivered_at:t.created_at,created_at:t.created_at,delivered_at:t.delivered_at}}function kH(t){if(!t.busy)return{state:"idle",reason:null,detail:"receiver idle now"};if(t.reason==="in-flight"){let s=t.inFlight.sender_alias==="operator"?"operator":`${t.inFlight.sender_teamfile}:${t.inFlight.sender_alias}`,i=t.inFlight.holder_pid===null?"":`, holder pid ${t.inFlight.holder_pid}`;return{state:"busy",reason:"in-flight",detail:`receiver busy now (in-flight: ${ze(s)} since ${t.inFlight.started_at}${i})`}}if(t.source==="terminal-lock"){let s=t.terminalLock,i=s.holder_host===ek()?"this host":s.holder_host;return{state:"busy",reason:"terminal-held",detail:`receiver busy now (terminal: holder pid ${s.holder_pid} alive on ${i})`}}let e=t.terminalInvocation,r=e.holder_host===null?"unknown host":e.holder_host===ek()?"this host":e.holder_host,n=e.holder_pid===null?"":` holder pid ${e.holder_pid}`;return{state:"busy",reason:"terminal-held",detail:`receiver busy now (terminal: invocation #${e.id}${n} alive on ${r})`}}async function hk(t){let e=[];for(let r of t)e.push(await IH(r));return e}async function IH(t){let e=t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,r={tracked_invocation_id:t.id,from_identity:t.from_identity,target:e??"(unknown)",started_at:t.started_at,tail_hint:e===null?"":`lmctl tail "${t.target_teamfile}" ${t.target_alias}`};if(e===null)return Kr(r,"missing-target",null,null);if(t.request_payload===null||t.request_payload.length===0)return Kr(r,"missing-request-payload",null,null);let n=NH(t.meta);if(n.provider===null||n.sessionid===null)return Kr(r,"missing-session-metadata",n.provider,n.sessionid);if(!xH(n.provider))return Kr(r,"unsupported-provider",n.provider,n.sessionid);let s;try{s=await Ye(n.sessionid,n.provider)}catch{return Kr(r,"read-error",n.provider,n.sessionid)}if(s===null)return Kr(r,"session-not-found",n.provider,n.sessionid);let i=AH(t.request_payload,s.messages);return i.state!=="completed"?Kr(r,i.reason,n.provider,n.sessionid):{...r,state:"completed",reason:null,provider:n.provider,session_id:n.sessionid,result_payload:i.result,result_preview:Ek(i.result),assistant_timestamp:i.assistantTimestamp,matched_user_index:i.userIndex}}function Kr(t,e,r,n){return{...t,state:"unreconciled",reason:e,provider:r,session_id:n,result_payload:null,result_preview:null,assistant_timestamp:null,matched_user_index:null}}function NH(t){if(t===null||t.trim()==="")return{provider:null,sessionid:null};try{let e=JSON.parse(t);return{provider:typeof e.provider=="string"&&e.provider.length>0?e.provider:null,sessionid:typeof e.sessionid=="string"&&e.sessionid.length>0?e.sessionid:null}}catch{return{provider:null,sessionid:null}}}function xH(t){return["claude","codex","gemini","copilot","opencode","lmplayer","qwen","agy","ClaudeMock"].includes(t)}function AH(t,e){let r=e.map((i,o)=>({message:i,index:o})).filter(({message:i})=>i.role==="user"&&i.content===t);if(r.length===0)return{state:"unreconciled",reason:"request-not-found"};if(r.length>1)return{state:"unreconciled",reason:"duplicate-request"};let n=r[0].index,s=[];for(let i of e.slice(n+1)){if(i.role==="user")break;i.role==="assistant"&&i.content.trim().length>0&&s.push(i)}return s.length===0?{state:"unreconciled",reason:"no-assistant-response"}:{state:"completed",userIndex:n,result:s.map(i=>i.content).join(`
|
|
2828
2910
|
|
|
2829
|
-
`),assistantTimestamp:RH(s[s.length-1]?.timestamp)}}function RH(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function Hf(t,e){let r={id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:na(t),mailbox_delivery:null,from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:dk(t.result_summary),error:dk(t.error)};return r.mailbox_delivery=FH(r,e),r}function Ga(t,e){let r=new Map;for(let n of t){let s=n.sender_teamfile===null||n.sender_alias===null?"operator":`${n.sender_teamfile}:${n.sender_alias}`,i=`${n.receiver_teamfile}:${n.receiver_alias}`,o=e==="outbound"?`${s}\0${i}`:`${i}\0${s}`,a=r.get(o);a===void 0?r.set(o,[n]):a.push(n)}return[...r.values()].map(n=>{let s=n[0],i=n.map(o=>o.created_at).sort();return{sender:s.sender_teamfile===null||s.sender_alias===null?null:`${s.sender_teamfile}:${s.sender_alias}`,receiver:`${s.receiver_teamfile}:${s.receiver_alias}`,message_types:[...new Set(n.map(o=>o.message_type))].sort(),pending_count:n.length,oldest_created_at:i[0],newest_created_at:i[i.length-1],ids:n.map(o=>o.id)}})}function LH(t,e){return t.scope==="self"?OH(t,e):$H(t,e)}function OH(t,e){let r=[];r.push(`identity: ${t.identity}`),r.push(`team: ${t.team.name}`),r.push(`teamfile: ${t.team.teamfile}`),r.push(""),r.push("members:"),t.members.length===0&&r.push(" none");for(let n of t.members){let s=n.model===null?"":` model=${n.model}`,i=n.sessionid===null?"":` session=${n.sessionid}`,o=n.state==="idle"?"idle":`busy (${n.reason})`,a=n.handling===null?"":` handling="${n.handling.request_preview}"`;r.push(` ${n.alias}: ${o} provider=${n.provider}${s}${i}${a}`)}return r.push(""),r.push("Waiting on:"),yk(r,t.waiting_on,"self"),r.push(""),r.push("transcript harvest:"),wk(r,t.transcript_harvest,"self"),r.push(""),r.push("activity from me:"),
|
|
2830
|
-
`)}function $H(t,e){let r=[];r.push("scope: workspace"),r.push("identity: none"),r.push(""),r.push("teams:"),t.teams.length===0&&r.push(" none");for(let n of t.teams){let s=n.name===null?"(unnamed)":n.name;r.push(` ${s}: ${n.teamfile} (${n.member_count} members)`)}return r.push(""),r.push("Waiting on:"),yk(r,t.waiting_on,"workspace"),r.push(""),r.push("transcript harvest:"),wk(r,t.transcript_harvest,"workspace"),r.push(""),r.push("recent activity:"),
|
|
2831
|
-
`)}function gk(t){return ei(t.workspace,t.db_path)}function
|
|
2911
|
+
`),assistantTimestamp:RH(s[s.length-1]?.timestamp)}}function RH(t){if(t===void 0)return null;let e=t.getTime();return Number.isFinite(e)?t.toISOString():null}function Hf(t,e){let r={id:t.id,kind:t.kind,origin:t.origin,status:t.status,holder_liveness:na(t),mailbox_delivery:null,from_identity:t.from_identity,target:t.target_teamfile===null||t.target_alias===null?null:`${t.target_teamfile}:${t.target_alias}`,started_at:t.started_at,ended_at:t.ended_at,result:dk(t.result_summary),error:dk(t.error)};return r.mailbox_delivery=FH(r,e),r}function Ga(t,e){let r=new Map;for(let n of t){let s=n.sender_teamfile===null||n.sender_alias===null?"operator":`${n.sender_teamfile}:${n.sender_alias}`,i=`${n.receiver_teamfile}:${n.receiver_alias}`,o=e==="outbound"?`${s}\0${i}`:`${i}\0${s}`,a=r.get(o);a===void 0?r.set(o,[n]):a.push(n)}return[...r.values()].map(n=>{let s=n[0],i=n.map(o=>o.created_at).sort();return{sender:s.sender_teamfile===null||s.sender_alias===null?null:`${s.sender_teamfile}:${s.sender_alias}`,receiver:`${s.receiver_teamfile}:${s.receiver_alias}`,message_types:[...new Set(n.map(o=>o.message_type))].sort(),pending_count:n.length,oldest_created_at:i[0],newest_created_at:i[i.length-1],ids:n.map(o=>o.id)}})}function LH(t,e){return t.scope==="self"?OH(t,e):$H(t,e)}function OH(t,e){let r=[];r.push(`identity: ${t.identity}`),r.push(`team: ${t.team.name}`),r.push(`teamfile: ${t.team.teamfile}`),r.push(""),r.push("members:"),t.members.length===0&&r.push(" none");for(let n of t.members){let s=n.model===null?"":` model=${n.model}`,i=n.sessionid===null?"":` session=${n.sessionid}`,o=n.state==="idle"?"idle":`busy (${n.reason})`,a=n.handling===null?"":` handling="${n.handling.request_preview}"`;r.push(` ${n.alias}: ${o} provider=${n.provider}${s}${i}${a}`)}return r.push(""),r.push("Waiting on:"),yk(r,t.waiting_on,"self"),r.push(""),r.push("transcript harvest:"),wk(r,t.transcript_harvest,"self"),r.push(""),r.push("activity from me:"),Xf(r,Jf(t.activity.from_me,e.sinceIso),"from-me"),r.push(""),r.push("activity to me:"),Xf(r,Jf(t.activity.to_me,e.sinceIso),"to-me"),r.push(""),r.push("mailbox outbound:"),Va(r,t.mailbox.outbound),r.push(""),r.push("mailbox inbound pending:"),Va(r,t.mailbox.inbound_pending),r.push(""),r.push(gk(t)),r.join(`
|
|
2912
|
+
`)}function $H(t,e){let r=[];r.push("scope: workspace"),r.push("identity: none"),r.push(""),r.push("teams:"),t.teams.length===0&&r.push(" none");for(let n of t.teams){let s=n.name===null?"(unnamed)":n.name;r.push(` ${s}: ${n.teamfile} (${n.member_count} members)`)}return r.push(""),r.push("Waiting on:"),yk(r,t.waiting_on,"workspace"),r.push(""),r.push("transcript harvest:"),wk(r,t.transcript_harvest,"workspace"),r.push(""),r.push("recent activity:"),Xf(r,Jf(t.activity,e.sinceIso),"workspace"),r.push(""),r.push("mailbox pending outbound:"),Va(r,t.mailbox.pending_outbound),r.push(""),r.push("mailbox pending inbound:"),Va(r,t.mailbox.pending_inbound),r.push(""),r.push(gk(t)),r.join(`
|
|
2913
|
+
`)}function gk(t){return ei(t.workspace,t.db_path)}function Xf(t,e,r){if(e.length===0){t.push(" none");return}let n=e.filter(ck).sort(DH),s=n.length===0?e:e.filter(i=>!ck(i));for(let i of n.slice(0,tk))lk(t,i,r);Ka(t,n.length,tk,"more open delegations");for(let i of s.slice(0,Xa))lk(t,i,r);Ka(t,s.length,Xa,"older")}function yk(t,e,r){if(e.length===0){t.push(" none");return}let n=CH(e,fH);for(let s of n){let i=r==="workspace"&&s.sender!==null?`${ze(s.sender)} -> ${ze(s.receiver)}`:ze(s.receiver);t.push(` ${i} - ${s.state} ${HH(s.age_basis_at)} (#${s.id}, ${s.message_type})`),t.push(` "${s.payload_preview}"`),t.push(` ${s.receiver_availability.detail}; lane key: sender+receiver, another sender's chat will not flush this queued mail`)}jH(t,e,n)}function wk(t,e,r){if(e.length===0){t.push(" none");return}for(let n of e.slice(0,Xa)){let s=r==="workspace"?` from ${ze(n.from_identity)} -> ${ze(n.target)}`:` -> ${ze(n.target)}`;if(n.state==="completed"){let i=n.result_preview===null?"":` "${n.result_preview}"`;t.push(` #${n.tracked_invocation_id} completed in transcript; lmctl DB not finalized${s} since ${n.started_at}${i}`)}else t.push(` #${n.tracked_invocation_id} unreconciled${s} since ${n.started_at} (${n.reason??"unknown"})`);n.tail_hint.length>0&&t.push(` inspect: ${n.tail_hint}`)}Ka(t,e.length,Xa,"more transcript harvest rows")}function CH(t,e){let r=[...t].sort(ak);if(r.length<=e)return r;let n=r.slice(0,e),s=new Set(r.map(i=>i.state));for(let i of s){if(n.some(l=>l.state===i))continue;let o=r.find(l=>l.state===i);if(o===void 0)continue;let a=MH(n);a>=0&&(n[a]=o)}return n.sort(ak)}function MH(t){let e=new Map;for(let r of t)e.set(r.state,(e.get(r.state)??0)+1);for(let r=t.length-1;r>=0;r-=1)if((e.get(t[r].state)??0)>1)return r;return-1}function jH(t,e,r){let n=new Set(r.map(l=>l.id)),s=e.filter(l=>!n.has(l.id));if(s.length===0)return;let i=s.filter(l=>l.state==="queued").length,o=s.filter(l=>l.state==="no reply").length,a=[i>0?`${i} queued`:null,o>0?`${o} no reply`:null].filter(l=>l!==null);t.push(` (+${s.length} older: ${a.join(", ")} -- use --json)`)}function ak(t,e){let r=Date.parse(t.age_basis_at),n=Date.parse(e.age_basis_at);return Number.isFinite(r)&&Number.isFinite(n)&&r!==n?r-n:Number.isFinite(r)!==Number.isFinite(n)?Number.isFinite(r)?-1:1:t.id-e.id}function Jf(t,e){let r=Date.parse(e);return Number.isFinite(r)?t.filter(n=>{let s=Date.parse(n.ended_at??n.started_at);return Number.isFinite(s)&&s>=r}):t}function lk(t,e,r){let n=qH(e,r),s=e.status==="running"?`since ${e.started_at}`:`ended ${e.ended_at??e.started_at}`,i=e.error??e.result,o=i===null?"":` "${Ek(i)}"`;t.push(` #${e.id} ${PH(e)} ${e.kind}${n} ${s}${o}`)}function ck(t){return t.mailbox_delivery?.state==="queued"||t.mailbox_delivery?.state==="delivering"}function DH(t,e){let r=Date.parse(t.started_at)-Date.parse(e.started_at);return Number.isFinite(r)&&r!==0?r:t.id-e.id}function PH(t){return t.status==="running"&&t.holder_liveness==="unknown"?"RUNNING_UNKNOWN":t.mailbox_delivery===null?t.status.toUpperCase():t.mailbox_delivery.state.toUpperCase()}function FH(t,e){let r=UH(t,e);return r===null?null:{mailbox_id:r.id,state:r.delivered_at!==null?"delivered":r.delivering_at!==null?"delivering":"queued",delivered_at:r.delivered_at,delivering_at:r.delivering_at}}function UH(t,e){if(t.kind!=="chat"||t.status!=="done"||t.target===null||t.result===null)return null;let r,n;try{r=Jr(t.from_identity),n=Jr(t.target)}catch{return null}for(let s of WH(t.result)){let i=e.getMailboxMessage(s);if(i!==null&&!(i.sender_teamfile!==r.teamfile||i.sender_alias!==r.alias)&&!(i.receiver_teamfile!==n.teamfile||i.receiver_alias!==n.alias)&&BH(i,t))return i}return null}function WH(t){let e=new Set,r=[];for(let n of t.matchAll(/\d+/g)){let s=Number(n[0]);!Number.isSafeInteger(s)||s<=0||e.has(s)||(e.add(s),r.push(s))}return r}function BH(t,e){let r=Date.parse(e.started_at),n=Date.parse(e.ended_at??e.started_at),s=Date.parse(t.created_at);return!Number.isFinite(r)||!Number.isFinite(n)||!Number.isFinite(s)?!1:s>=r&&s<=n}function qH(t,e){if(e==="from-me")return t.target===null?"":` -> ${ze(t.target)}`;if(e==="to-me")return` from ${ze(t.from_identity)}`;let r=t.target===null?"":` -> ${ze(t.target)}`;return` from ${ze(t.from_identity)}${r}`}function Ka(t,e,r,n){let s=e-r;s>0&&t.push(` (+${s} ${n} -- use --json)`)}function Va(t,e){if(e.length===0){t.push(" none");return}for(let r of e.slice(0,rk)){let n=r.sender??"operator";t.push(` ${ze(n)} -> ${ze(r.receiver)}: ${r.pending_count} pending ${r.message_types.join("+")} (oldest ${r.oldest_created_at})`)}Ka(t,e.length,rk,"more lanes")}function dk(t){return t===null||t.length===0?null:t.replace(/\s+/g," ").trim()}function Ek(t){let e=t.replace(/\s+/g," ").trim();return e.length<=nk?e:`${e.slice(0,nk-3)}...`}function Tk(t){let e=t.replace(/\s+/gu," ").trim();return e.length<=sk?e:`${e.slice(0,sk-3)}...`}function HH(t){let e=Date.parse(t);if(!Number.isFinite(e))return"unknown age";let r=Math.max(0,Math.floor((Date.now()-e)/1e3));if(r<60)return`${r}s`;let n=Math.floor(r/60);if(n<60)return`${n}m`;let s=Math.floor(n/60);return s<48?`${s}h`:`${Math.floor(s/24)}d`}function ze(t){if(t==="operator")return t;try{let e=Jr(t);return`${aH(e.teamfile)}:${e.alias}`}catch{return t}}function XH(t){if(t===void 0)return{iso:new Date(Date.now()-mH).toISOString()};let e=/^(\d+)([smhd])$/.exec(t);if(e!==null){let n=Number(e[1]),s=e[2],i=s==="s"?n:s==="m"?n*60:s==="h"?n*3600:n*86400;return{iso:new Date(Date.now()-i*1e3).toISOString()}}let r=Date.parse(t);return Number.isFinite(r)?{iso:new Date(r).toISOString()}:{error:`invalid --since value: ${t} (expected ISO8601 or duration like 24h)`}}var uH,Xa,tk,rk,fH,mH,nk,sk,Sk=E(()=>{"use strict";Br();Le();zu();We();Aa();Zt();Er();uH=`usage: lmctl status [--json] [--since <duration|ISO8601>]
|
|
2832
2914
|
|
|
2833
2915
|
Show this member's team, busy/idle roster, recent tracked activity, and mailbox
|
|
2834
2916
|
state. From a plain operator shell, show a workspace-level team/activity summary.
|
|
@@ -2836,7 +2918,7 @@ state. From a plain operator shell, show a workspace-level team/activity summary
|
|
|
2836
2918
|
Text output shows recent activity from the last 24h by default. Use --since 7d
|
|
2837
2919
|
or an ISO timestamp to widen the investigation window. --json returns complete,
|
|
2838
2920
|
uncapped data.
|
|
2839
|
-
`,
|
|
2921
|
+
`,Xa=5,tk=5,rk=5,fH=5,mH=24*60*60*1e3,nk=72,sk=80});We();Hn();de();import{pathToFileURL as JH}from"node:url";import{mkdirSync as gI,readFileSync as yI,renameSync as wI,writeFileSync as EI}from"node:fs";import{homedir as TI}from"node:os";import{dirname as bI,join as SI}from"node:path";function hm(t){try{return new URL(t).protocol==="https:"}catch{return!1}}function _I(t){return/^[A-Za-z]:[\\/]/.test(t)?!1:/^[A-Za-z][A-Za-z0-9+.-]*:/.test(t)}function hI(t,e){return!_I(t)||hm(t)?null:`${e} must use https://: ${t}`}async function gm(t,e){let r=hI(t,e.description);if(r!==null||!hm(t))throw new Error(r??`${e.description} must use https://: ${t}`);let n=e.timeoutMs??15e3,s=new AbortController,i=setTimeout(()=>s.abort(),n);try{let o;try{o=await fetch(t,{signal:s.signal,redirect:"manual"})}catch(a){throw _m(t,e.description,n,a)}if(o.type==="opaqueredirect"||o.status>=300&&o.status<400)throw new Error(`refusing to follow redirect from ${e.description} ${t} (https-only: the URL must serve the content directly, not redirect)`);if(!o.ok)throw new Error(`failed to fetch ${e.description} ${t}: HTTP ${o.status}${o.statusText?` ${o.statusText}`:""}`);try{return Buffer.from(await o.arrayBuffer())}catch(a){throw _m(t,e.description,n,a)}}finally{clearTimeout(i)}}function _m(t,e,r,n){let i=n instanceof Error&&n.name==="AbortError"?`timed out after ${r}ms`:n instanceof Error?n.message:String(n);return new Error(`failed to fetch ${e} ${t}: ${i}`)}Hn();var vI="https://registry.npmjs.org/@lmctl-ai/lmctl/latest",kI=60*60*1e3,II=1500;function NI(){let t=process.env.HOME??TI();return SI(t,".lmctl",".update-check.json")}function xI(t){return t.isTTY===!0}function AI(t,e){let r=i=>{let o=/^(\d+)\.(\d+)\.(\d+)(?:$|[-+])/.exec(i.trim());if(o===null)return null;let a=o.slice(1).map(l=>Number(l));return a.some(l=>!Number.isSafeInteger(l)||l<0)?null:a},n=r(t),s=r(e);if(n===null||s===null)return 0;for(let i=0;i<3;i+=1){if(n[i]>s[i])return 1;if(n[i]<s[i])return-1}return 0}function nl(t,e){return!!(process.env.LMCTL_NO_UPDATE_NOTIFIER==="1"||!xI(e.stderr)||t.includes("--json")||t.includes("--help")||t.includes("-h")||t[0]==="help"||t[0]==="mcp")}function RI(t,e){try{let r=JSON.parse(yI(t,"utf8"));if(typeof r.checkedAt=="number"&&Number.isFinite(r.checkedAt)&&typeof r.latest=="string"&&e-r.checkedAt<kI)return r.latest}catch{}return null}function LI(t,e){gI(bI(t),{recursive:!0});let r=`${t}.tmp-${process.pid}-${Math.random().toString(16).slice(2)}`;EI(r,`${JSON.stringify(e)}
|
|
2840
2922
|
`,"utf8"),wI(r,t)}async function OI(){let t=await gm(vI,{description:"lmctl npm metadata",timeoutMs:II}),e=JSON.parse(t.toString("utf8"));if(typeof e.version!="string"||e.version.trim()==="")throw new Error("registry response missing version");return e.version}async function ym(t,e=[],r={}){try{if(nl(e,t))return;let n=r.now?.()??Date.now(),s=r.cachePath??NI();if(RI(s,n)!==null)return;let o=await(r.fetchLatest??OI)();try{LI(s,{checkedAt:n,latest:o})}catch{return}let a=r.currentVersion?.()??Et();AI(o,a)>0&&t.stderr.write(`update available: ${a} \u2192 ${o} run: npm i -g @lmctl-ai/lmctl@latest
|
|
2841
2923
|
`)}catch{}}var Un=`usage: lmctl [--db PATH] [--workspace NAME] [--debug] <command> [args]
|
|
2842
2924
|
`,Gf=`${Un}
|
|
@@ -2892,10 +2974,10 @@ ${Un}Run 'lmctl help' for usage.
|
|
|
2892
2974
|
`),0;if(n==="--help"||n==="-h"||n===void 0)return e.stdout.write(Gf),0;if(n==="help"){let[a,...l]=r.slice(1);return a===void 0||a==="--help"||a==="-h"?(e.stdout.write(Gf),0):vk.has(a)?kk(a,[...l,"--help"],e):Ik(e,a)}Qf(Z(),e.stderr),tm(e.stderr);let[s,...i]=r;if(s===void 0)return e.stdout.write(Gf),0;let o=Date.now();Vf(s,i,{phase:"start",started_at:new Date(o).toISOString()});try{let a=await kk(s,i,e);return Vf(s,i,{phase:"finish",outcome:a===0?"ok":"error",exit_code:a,duration_ms:Date.now()-o}),vk.has(s)&&!nl(r,e)&&await ym(e,r),a}catch(a){let l=a instanceof Error?a:new Error(String(a));return Vf(s,i,{phase:"fatal",outcome:"fatal",exit_code:1,duration_ms:Date.now()-o,error_class:l.name,error_message:l.message,error_stack:l.stack??null,causes:YH(l)}),VH(a,s,i,e)}}function Vf(t,e,r){Ae({event:t,record_kind:"cli_action",command:t,argv:e,cwd:process.cwd(),db_path:Z(),workspace:process.env.LMCTL_WORKSPACE??null,lmctl_version:Et(),node_version:process.version,...r})}function VH(t,e,r,n){let s=t instanceof Error?t:new Error(String(t));return n.stderr.write(`error: ${s.message}
|
|
2893
2975
|
`),pm()?(n.stderr.write(`(debug details written to ~/.lmctl/debug-*.log)
|
|
2894
2976
|
`),1):(n.stderr.write(`(re-run with --debug for the full stack trace and context in ~/.lmctl/debug-*.log)
|
|
2895
|
-
`),1)}function YH(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 kk(t,e,r){switch(t){case"api":{let{runApi:n}=await Promise.resolve().then(()=>(Dc(),sh));return n(e,r)}case"serve":{let{runServe:n}=await Promise.resolve().then(()=>(rb(),tb));return n(e,r)}case"chat":{let{runChat:n}=await Promise.resolve().then(()=>(Fb(),Pb));return n(e,r)}case"recover":{let{runRecover:n}=await Promise.resolve().then(()=>(
|
|
2977
|
+
`),1)}function YH(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 kk(t,e,r){switch(t){case"api":{let{runApi:n}=await Promise.resolve().then(()=>(Dc(),sh));return n(e,r)}case"serve":{let{runServe:n}=await Promise.resolve().then(()=>(rb(),tb));return n(e,r)}case"chat":{let{runChat:n}=await Promise.resolve().then(()=>(Fb(),Pb));return n(e,r)}case"recover":{let{runRecover:n}=await Promise.resolve().then(()=>(Xb(),Hb));return n(e,r)}case"mcp":{let{runMcp:n}=await Promise.resolve().then(()=>(Zb(),zb));return n(e,r)}case"device":{let{runDevice:n}=await Promise.resolve().then(()=>(eS(),Qb));return n(e,r)}case"team":{let{runTeam:n}=await Promise.resolve().then(()=>(TS(),ES));return n(e,r)}case"tail":{let{runTail:n}=await Promise.resolve().then(()=>(AS(),xS));return n(e,r)}case"health":{let{runInfo:n}=await Promise.resolve().then(()=>(PS(),DS));return n(e,r)}case"ls":{let{runLs:n}=await Promise.resolve().then(()=>(WS(),US));return n(e,r)}case"lint":{let{runLint:n}=await Promise.resolve().then(()=>(Gs(),Js));return n(e,r)}case"seed":{let{runSeed:n}=await Promise.resolve().then(()=>(Gs(),Js));return n(e,r)}case"hire":{let{runHire:n}=await Promise.resolve().then(()=>(Gs(),Js));return n(e,r)}case"refresh":{let{runRefresh:n}=await Promise.resolve().then(()=>(Gs(),Js));return n(e,r)}case"clone":{let{runClone:n}=await Promise.resolve().then(()=>(dv(),cv));return n(e,r)}case"plan":{let{runPlan:n}=await Promise.resolve().then(()=>(pv(),mv));return n(e,r)}case"terminal":{let{runTerminal:n}=await Promise.resolve().then(()=>(Sv(),bv));return n(e,r)}case"workspace":{let{runWorkspace:n}=await Promise.resolve().then(()=>(Ov(),Lv));return n(e,r)}case"diagnose":{let{runDiagnose:n}=await Promise.resolve().then(()=>(Jv(),Xv));return n(e,r)}case"diagnose-prompt":{let{runDiagnosePrompt:n}=await Promise.resolve().then(()=>(Qv(),Zv));return n(e,r)}case"status":{let{runStatus:n}=await Promise.resolve().then(()=>(Sk(),bk));return n(e,r)}case"db":return zH(e,r);default:return Ik(r,t)}}function zH(t,e){let[r,...n]=t;return r==="--help"||r==="-h"||r==="help"?(e.stdout.write(`usage: lmctl db downgrade --to <version> --confirm
|
|
2896
2978
|
|
|
2897
2979
|
Database utilities. The downgrade command is currently a documented stub;
|
|
2898
2980
|
restore from backup for rollback and use normal migrations for forward changes.
|
|
2899
2981
|
`),0):r==="downgrade"?(e.stderr.write(`not yet implemented; restore from backup, or run lmctl migrate (forward-migrates ok)
|
|
2900
2982
|
`),1):(e.stderr.write(`usage: lmctl db downgrade --to <version> --confirm
|
|
2901
|
-
`),1)}if(process.argv[1]!==void 0&&import.meta.url===
|
|
2983
|
+
`),1)}if(process.argv[1]!==void 0&&import.meta.url===JH(process.argv[1]).href){let t=await GH(process.argv.slice(2));process.exitCode=t}export{GH as runCli};
|