@lmctl-ai/lmctl 0.2.185 → 0.2.186

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/lmbee.js CHANGED
@@ -1,98 +1,98 @@
1
1
  #!/usr/bin/env node
2
- var Iv=Object.create;var Ca=Object.defineProperty;var Lv=Object.getOwnPropertyDescriptor;var Cv=Object.getOwnPropertyNames;var Ov=Object.getPrototypeOf,Dv=Object.prototype.hasOwnProperty;var Pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Mv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_o=(e,t)=>{for(var r in t)Ca(e,r,{get:t[r],enumerable:!0})},Pv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Cv(t))!Dv.call(e,o)&&o!==r&&Ca(e,o,{get:()=>t[o],enumerable:!(n=Lv(t,o))||n.enumerable});return e};var Ut=(e,t,r)=>(r=e!=null?Iv(Ov(e)):{},Pv(t||!e||!e.__esModule?Ca(r,"default",{value:e,enumerable:!0}):r,e));var xt=Mv(ut=>{"use strict";function oa(e){if(!Array.isArray(e))throw new TypeError("Each row and headers must be an array of cells");return Array.from(e,t=>{let r=t==null?"":String(t);if(/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("Cells must be single-line text without terminal control characters");return r})}function NL(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError('align must be an array of "left" or "right" per column');return e.map(t=>{if(t!=="left"&&t!=="right")throw new TypeError('align entries must be "left" or "right"');return t})}function Lr(e){let t=0;for(let r of e){let n=r.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){t+=2;continue}t+=1}}return t}function Q_(e,t,r){let n=" ".repeat(Math.max(0,t-Lr(e)));return r?n+e:e+n}function IL(e){if(Array.isArray(e))return{rows:e};if(e!==null&&typeof e=="object"&&Array.isArray(e.rows))return e;throw new TypeError("each grid must be a rows array or { rows, headers }")}function LL(e){if(e===void 0)return"\u2026";if(typeof e!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(e))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return e}function CL(e,t,r="\u2026"){if(Lr(e)<=t)return e;let n=Lr(r)>t?"\u2026":r,o=Lr(n);if(t<=o)return n;let s="",i=0;for(let a of e){let c=Lr(a);if(i+c>t-o)break;s+=a,i+=c}return`${s}${n}`}function OL(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("max must be an array of per-column width caps");return e.map(t=>{if(t!=null){if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new TypeError("max entries must be positive integers, null, or undefined");return t}})}function Z_(e,{max:t}={}){if(!Array.isArray(e))throw new TypeError("grids must be an array of grids");let r=OL(t),n=[],o=(s,i)=>{n[s]=Math.max(n[s]??0,i)};for(let s of e){let i=IL(s);i.headers!==void 0&&oa(i.headers).forEach((a,c)=>{o(c,Lr(a))});for(let a of i.rows.map(oa))a.forEach((c,l)=>{o(l,Lr(c))})}return n.map((s,i)=>{let a=r[i];return a===void 0?s:Math.min(s,a)})}ut.measureColumns=Z_;function DL(e){if(e===void 0)return"";if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return" ".repeat(e);if(typeof e=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(e))return e;throw new TypeError("margin must be a number of spaces or a single-line string")}function ew(e,{widths:t,headers:r,align:n,truncate:o=!0,truncateTrailing:s=!1,margin:i,max:a,ellipsis:c}={}){if(!Array.isArray(e))throw new TypeError("rows must be an array of row arrays");if(t!==void 0&&!Array.isArray(t))throw new TypeError("widths must be an array of column widths");if(t!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let l=DL(i),u=NL(n),d=LL(c),m=t??Z_([{rows:e,headers:r}],{max:a}),f=e.map(oa);r!==void 0&&f.unshift(oa(r));let p=f.map(h=>{let w=h.length-1;for(;w>=0&&h[w]==="";)w--;return h.slice(0,w+1).map((_,E)=>{let T=m[E]||0,v=o&&T>0&&(E!==w||s)?CL(_,T,d):_;return u[E]==="right"?Q_(v,T,!0):E===w?v:Q_(v,T,!1)}).join(" ")}).join(`
2
+ var Mv=Object.create;var Ma=Object.defineProperty;var Pv=Object.getOwnPropertyDescriptor;var Uv=Object.getOwnPropertyNames;var Fv=Object.getPrototypeOf,qv=Object.prototype.hasOwnProperty;var Pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var jv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),yo=(e,t)=>{for(var r in t)Ma(e,r,{get:t[r],enumerable:!0})},Hv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Uv(t))!qv.call(e,o)&&o!==r&&Ma(e,o,{get:()=>t[o],enumerable:!(n=Pv(t,o))||n.enumerable});return e};var Ut=(e,t,r)=>(r=e!=null?Mv(Fv(e)):{},Hv(t||!e||!e.__esModule?Ma(r,"default",{value:e,enumerable:!0}):r,e));var xt=jv(ut=>{"use strict";function aa(e){if(!Array.isArray(e))throw new TypeError("Each row and headers must be an array of cells");return Array.from(e,t=>{let r=t==null?"":String(t);if(/[\x00-\x1f\x7f-\x9f]/u.test(r))throw new TypeError("Cells must be single-line text without terminal control characters");return r})}function PI(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError('align must be an array of "left" or "right" per column');return e.map(t=>{if(t!=="left"&&t!=="right")throw new TypeError('align entries must be "left" or "right"');return t})}function Ir(e){let t=0;for(let r of e){let n=r.codePointAt(0);if(!(n>=768&&n<=879||n>=6832&&n<=6911||n>=7616&&n<=7679||n>=8400&&n<=8447||n>=65024&&n<=65039||n>=65056&&n<=65071||n===8203||n>=917760&&n<=917999)){if(n>=4352&&n<=4447||n>=11904&&n<=12350||n>=12353&&n<=13311||n>=13312&&n<=19903||n>=19968&&n<=40959||n>=40960&&n<=42191||n>=44032&&n<=55203||n>=63744&&n<=64255||n>=65072&&n<=65135||n>=65280&&n<=65376||n>=65504&&n<=65510||n>=9728&&n<=10175||n>=126976&&n<=129791||n>=131072&&n<=262141){t+=2;continue}t+=1}}return t}function rw(e,t,r){let n=" ".repeat(Math.max(0,t-Ir(e)));return r?n+e:e+n}function UI(e){if(Array.isArray(e))return{rows:e};if(e!==null&&typeof e=="object"&&Array.isArray(e.rows))return e;throw new TypeError("each grid must be a rows array or { rows, headers }")}function FI(e){if(e===void 0)return"\u2026";if(typeof e!="string"||/[\x00-\x1f\x7f-\x9f]/u.test(e))throw new TypeError("ellipsis must be a single-line string without terminal control characters");return e}function qI(e,t,r="\u2026"){if(Ir(e)<=t)return e;let n=Ir(r)>t?"\u2026":r,o=Ir(n);if(t<=o)return n;let s="",i=0;for(let a of e){let c=Ir(a);if(i+c>t-o)break;s+=a,i+=c}return`${s}${n}`}function jI(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("max must be an array of per-column width caps");return e.map(t=>{if(t!=null){if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new TypeError("max entries must be positive integers, null, or undefined");return t}})}function ow(e,{max:t}={}){if(!Array.isArray(e))throw new TypeError("grids must be an array of grids");let r=jI(t),n=[],o=(s,i)=>{n[s]=Math.max(n[s]??0,i)};for(let s of e){let i=UI(s);i.headers!==void 0&&aa(i.headers).forEach((a,c)=>{o(c,Ir(a))});for(let a of i.rows.map(aa))a.forEach((c,l)=>{o(l,Ir(c))})}return n.map((s,i)=>{let a=r[i];return a===void 0?s:Math.min(s,a)})}ut.measureColumns=ow;function HI(e){if(e===void 0)return"";if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return" ".repeat(e);if(typeof e=="string"&&!/[\x00-\x1f\x7f-\x9f]/u.test(e))return e;throw new TypeError("margin must be a number of spaces or a single-line string")}function sw(e,{widths:t,headers:r,align:n,truncate:o=!0,truncateTrailing:s=!1,margin:i,max:a,ellipsis:c}={}){if(!Array.isArray(e))throw new TypeError("rows must be an array of row arrays");if(t!==void 0&&!Array.isArray(t))throw new TypeError("widths must be an array of column widths");if(t!==void 0&&a!==void 0)throw new TypeError("pass widths or max, not both (max caps a measurement)");let l=HI(i),u=PI(n),d=FI(c),m=t??ow([{rows:e,headers:r}],{max:a}),f=e.map(aa);r!==void 0&&f.unshift(aa(r));let p=f.map(h=>{let w=h.length-1;for(;w>=0&&h[w]==="";)w--;return h.slice(0,w+1).map((_,T)=>{let E=m[T]||0,v=o&&E>0&&(T!==w||s)?qI(_,E,d):_;return u[T]==="right"?rw(v,E,!0):T===w?v:rw(v,E,!1)}).join(" ")}).join(`
3
3
  `);return p===""||l===""?p:`${l}${p.split(`
4
4
  `).join(`
5
- ${l}`)}`}ut.renderGrid=ew;function tw(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a}={}){return ew(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a})}function ML(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a,stream:c=process.stdout}={}){let l=tw(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a});l&&c.write(`${l}
6
- `)}ut.formatTable=tw;ut.printTable=ML;function X_(e){return e instanceof Date?e.getTime():typeof e=="number"?e:typeof e=="string"&&e.trim()?Date.parse(e):NaN}function PL(e,{now:t=Date.now()}={}){let r=X_(t);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=X_(e);if(!Number.isFinite(n))return"unknown";let o=n-r,s=Math.floor(Math.abs(o)/1e3);if(s===0)return"now";for(let[i,a]of[["w",604800],["d",86400],["h",3600],["m",60],["s",1]])if(s>=a)return`${Math.floor(s/a)}${i}${o<0?" ago":""}`}ut.formatRelativeTime=PL;function UL(e){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let t=e<0?"-":"",r=Math.abs(e);if(r<1e3)return String(e);let n=Math.round(r/1e3);return n<1e3?`${t}${n}K`:`${t}${(r/1e6).toFixed(1)}M`}ut.formatCount=UL;var su=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function FL(e,{maxUnit:t="w",style:r="spaced"}={}){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let n=su.findIndex(([a])=>a===t);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(r!=="spaced"&&r!=="compact")throw new TypeError('style must be "spaced" or "compact"');let o=Math.floor(Math.max(0,e)/1e3);if(r==="compact"){let a=su.slice(n).filter(([d])=>d!=="s");if(a.length===0||o<60)return"<1m";let c=[],l=o,u=!1;for(let[d,m]of a){let f=Math.floor(l/m);if(l-=f*m,f>0&&!u){let p=d==="d"||d==="w"?`${f}${d}`:`${Jt(f)}${d}`;c.push({text:p,zero:!1}),u=!0}else u&&c.push({text:`${Jt(f)}${d}`,zero:f===0})}for(;c.length>0&&c[c.length-1].zero;)c.pop();return c.map(d=>d.text).join("")}let s=o,i=[];for(let[a,c]of su.slice(n))if(s>=c||a==="s"&&i.length===0){let l=Math.floor(s/c);if(s-=l*c,i.push(`${l}${a}`),i.length===2)break}return i.join(" ")}ut.formatDuration=FL;function rw(e){return e===void 0?new Date:e instanceof Date?e:typeof e=="number"||typeof e=="string"?new Date(e):new Date(NaN)}function Jt(e){return String(e).padStart(2,"0")}function nw(e){let t=rw(e);return Number.isNaN(t.getTime())?"unknown":`${Jt(t.getHours())}:${Jt(t.getMinutes())}:${Jt(t.getSeconds())}`}ut.formatClock=nw;function qL(e){let t=rw(e);return Number.isNaN(t.getTime())?"unknown":`${`${t.getFullYear()}-${Jt(t.getMonth()+1)}-${Jt(t.getDate())}`} ${nw(t)}`}ut.formatLocalTimestamp=qL;function jL(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e*100)}%`:"?%"}ut.formatPercent=jL;function HL(e,{width:t=10,fill:r="#",empty:n=" ",unknown:o="?"}={}){if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new TypeError("width must be a positive integer");for(let[i,a]of[["fill",r],["empty",n],["unknown",o]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||Lr(a)!==1)throw new TypeError(`${i} must be a single character with terminal display width 1`);if(typeof e!="number"||!Number.isFinite(e))return o.repeat(t);let s=Math.min(t,Math.max(0,Math.round(e*t)));return`${r.repeat(s)}${n.repeat(t-s)}`}ut.formatBar=HL;function BL(e){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let t=Math.floor(Math.max(0,e)/1e3),r=Math.floor(t/86400);t-=r*86400;let n=Math.floor(t/3600);t-=n*3600;let o=Math.floor(t/60);t-=o*60;let s=`${Jt(n)}:${Jt(o)}:${Jt(t)}`;return r>0?`${r}d ${s}`:s}ut.formatTimer=BL;function WL(e){return(e==null?"":String(e)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
7
- `?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}ut.escapeCell=WL});import{createHash as hM,randomBytes as CT}from"node:crypto";function OT(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||is.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||is.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||is.scope,ports:is.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||is.authUrl).replace(/\/+$/,"")}}function DT(e=CT){let t=e(32).toString("base64url"),r=hM("sha256").update(t).digest("base64url");return{verifier:t,challenge:r}}function MT(e=CT){return e(16).toString("base64url")}function PT(e){return`http://127.0.0.1:${e}/callback`}function UT(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:PT(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r.toString()}`}function FT(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function qT(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:PT(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await HT(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function jT(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await HT(n)}`);return await n.json()}async function HT(e){try{return(await e.text()).slice(0,300)}catch{return""}}var is,BT=Pt(()=>{is={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var JT={};_o(JT,{appkeyDir:()=>GT,persistCredentials:()=>VT,runLogin:()=>$M});import{createServer as gM}from"node:http";import{spawn as _M}from"node:child_process";import{hostname as wM}from"node:os";import{mkdir as yM,rename as EM,writeFile as TM}from"node:fs/promises";import{homedir as bM}from"node:os";import{join as ga}from"node:path";function GT(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||ga(bM(),".config");return ga(t,"lmctl")}async function VT(e,t,r,n=process.env){let o=GT(n);await yM(o,{recursive:!0,mode:448});let s=ga(o,"appkey.json"),i={version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at};await WT(s,JSON.stringify(i,null,2)+`
8
- `);let a=null;if(t.refresh_token){a=ga(o,"identity.json");let c={user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token};await WT(a,JSON.stringify(c,null,2)+`
9
- `)}return{appkeyPath:s,identityPath:a}}async function WT(e,t){let r=`${e}.tmp-${process.pid}`;await TM(r,t,{mode:384}),await EM(r,e)}async function SM(e){let t,r=new Promise(o=>t=o),n=gM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=FT(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body style='font-family:sans-serif'><h3>lmctl login complete.</h3><p>You can close this tab and return to the terminal.</p></body></html>"),t(i)});for(let o of e)if(await vM(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")}); is another login running?`)}function vM(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function AM(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=_M(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
5
+ ${l}`)}`}ut.renderGrid=sw;function iw(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a}={}){return sw(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a})}function BI(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a,stream:c=process.stdout}={}){let l=iw(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a});l&&c.write(`${l}
6
+ `)}ut.formatTable=iw;ut.printTable=BI;function nw(e){return e instanceof Date?e.getTime():typeof e=="number"?e:typeof e=="string"&&e.trim()?Date.parse(e):NaN}function WI(e,{now:t=Date.now()}={}){let r=nw(t);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=nw(e);if(!Number.isFinite(n))return"unknown";let o=n-r,s=Math.floor(Math.abs(o)/1e3);if(s===0)return"now";for(let[i,a]of[["w",604800],["d",86400],["h",3600],["m",60],["s",1]])if(s>=a)return`${Math.floor(s/a)}${i}${o<0?" ago":""}`}ut.formatRelativeTime=WI;function GI(e){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let t=e<0?"-":"",r=Math.abs(e);if(r<1e3)return String(e);let n=Math.round(r/1e3);return n<1e3?`${t}${n}K`:`${t}${(r/1e6).toFixed(1)}M`}ut.formatCount=GI;var cu=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function VI(e,{maxUnit:t="w",style:r="spaced"}={}){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let n=cu.findIndex(([a])=>a===t);if(n===-1)throw new TypeError('maxUnit must be one of "w", "d", "h", "m", "s"');if(r!=="spaced"&&r!=="compact")throw new TypeError('style must be "spaced" or "compact"');let o=Math.floor(Math.max(0,e)/1e3);if(r==="compact"){let a=cu.slice(n).filter(([d])=>d!=="s");if(a.length===0||o<60)return"<1m";let c=[],l=o,u=!1;for(let[d,m]of a){let f=Math.floor(l/m);if(l-=f*m,f>0&&!u){let p=d==="d"||d==="w"?`${f}${d}`:`${Jt(f)}${d}`;c.push({text:p,zero:!1}),u=!0}else u&&c.push({text:`${Jt(f)}${d}`,zero:f===0})}for(;c.length>0&&c[c.length-1].zero;)c.pop();return c.map(d=>d.text).join("")}let s=o,i=[];for(let[a,c]of cu.slice(n))if(s>=c||a==="s"&&i.length===0){let l=Math.floor(s/c);if(s-=l*c,i.push(`${l}${a}`),i.length===2)break}return i.join(" ")}ut.formatDuration=VI;function aw(e){return e===void 0?new Date:e instanceof Date?e:typeof e=="number"||typeof e=="string"?new Date(e):new Date(NaN)}function Jt(e){return String(e).padStart(2,"0")}function cw(e){let t=aw(e);return Number.isNaN(t.getTime())?"unknown":`${Jt(t.getHours())}:${Jt(t.getMinutes())}:${Jt(t.getSeconds())}`}ut.formatClock=cw;function JI(e){let t=aw(e);return Number.isNaN(t.getTime())?"unknown":`${`${t.getFullYear()}-${Jt(t.getMonth()+1)}-${Jt(t.getDate())}`} ${cw(t)}`}ut.formatLocalTimestamp=JI;function KI(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e*100)}%`:"?%"}ut.formatPercent=KI;function zI(e,{width:t=10,fill:r="#",empty:n=" ",unknown:o="?"}={}){if(typeof t!="number"||!Number.isInteger(t)||t<1)throw new TypeError("width must be a positive integer");for(let[i,a]of[["fill",r],["empty",n],["unknown",o]])if(typeof a!="string"||[...a].length!==1||/[\x00-\x1f\x7f-\x9f]/u.test(a)||Ir(a)!==1)throw new TypeError(`${i} must be a single character with terminal display width 1`);if(typeof e!="number"||!Number.isFinite(e))return o.repeat(t);let s=Math.min(t,Math.max(0,Math.round(e*t)));return`${r.repeat(s)}${n.repeat(t-s)}`}ut.formatBar=zI;function YI(e){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let t=Math.floor(Math.max(0,e)/1e3),r=Math.floor(t/86400);t-=r*86400;let n=Math.floor(t/3600);t-=n*3600;let o=Math.floor(t/60);t-=o*60;let s=`${Jt(n)}:${Jt(o)}:${Jt(t)}`;return r>0?`${r}d ${s}`:s}ut.formatTimer=YI;function QI(e){return(e==null?"":String(e)).replace(/[\x00-\x1f\x7f-\x9f]/gu,r=>r===`
7
+ `?"\\n":r===" "?"\\t":r==="\r"?"\\r":`\\x${r.codePointAt(0).toString(16).padStart(2,"0")}`)}ut.escapeCell=QI});import{createHash as bM,randomBytes as UT}from"node:crypto";function FT(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||us.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||us.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||us.scope,ports:us.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||us.authUrl).replace(/\/+$/,"")}}function qT(e=UT){let t=e(32).toString("base64url"),r=bM("sha256").update(t).digest("base64url");return{verifier:t,challenge:r}}function jT(e=UT){return e(16).toString("base64url")}function HT(e){return`http://127.0.0.1:${e}/callback`}function BT(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:HT(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r.toString()}`}function WT(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function GT(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:HT(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await JT(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function VT(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await JT(n)}`);return await n.json()}async function JT(e){try{return(await e.text()).slice(0,300)}catch{return""}}var us,KT=Pt(()=>{us={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var XT={};yo(XT,{appkeyDir:()=>YT,persistCredentials:()=>QT,runLogin:()=>CM});import{createServer as SM}from"node:http";import{spawn as vM}from"node:child_process";import{hostname as AM}from"node:os";import{mkdir as kM,rename as $M,writeFile as xM}from"node:fs/promises";import{homedir as RM}from"node:os";import{join as ya}from"node:path";function YT(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||ya(RM(),".config");return ya(t,"lmctl")}async function QT(e,t,r,n=process.env){let o=YT(n);await kM(o,{recursive:!0,mode:448});let s=ya(o,"appkey.json"),i={version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at};await zT(s,JSON.stringify(i,null,2)+`
8
+ `);let a=null;if(t.refresh_token){a=ya(o,"identity.json");let c={user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token};await zT(a,JSON.stringify(c,null,2)+`
9
+ `)}return{appkeyPath:s,identityPath:a}}async function zT(e,t){let r=`${e}.tmp-${process.pid}`;await xM(r,t,{mode:384}),await $M(r,e)}async function NM(e){let t,r=new Promise(o=>t=o),n=SM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=WT(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body style='font-family:sans-serif'><h3>lmctl login complete.</h3><p>You can close this tab and return to the terminal.</p></body></html>"),t(i)});for(let o of e)if(await LM(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")}); is another login running?`)}function LM(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function IM(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=vM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
10
10
  If your browser didn't open, visit:
11
11
  ${e}
12
12
 
13
- `)}async function $M(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env,n=OT(r),o=e.fetchImpl??fetch,s=e.openBrowserFn??AM;if((!("stdin"in process)||!process.stdin.isTTY)&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmchat login` needs an interactive browser. On a headless box, run login on a machine with a browser and copy ~/.config/lmctl/appkey.json here (or set LMCTL_APPKEY).\n"),1;let{verifier:i,challenge:a}=DT(),c=MT(),{server:l,port:u,wait:d}=await SM(n.ports);try{let m=UT(n,{port:u,state:c,challenge:a});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
14
- `),s(m,t);let f=await d;if(f.error)throw new Error(`authorization failed: ${f.error}`);if(!f.code)throw new Error("no authorization code returned");if(f.state!==c)throw new Error("state mismatch (possible CSRF); aborting");let p=await qT(n,{code:f.code,verifier:i,port:u},o),h=await jT(n,{idToken:p.id_token,label:wM()},o),{appkeyPath:w,identityPath:_}=await VT(h,p,n,r);return t.stdout.write(`
13
+ `)}async function CM(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env,n=FT(r),o=e.fetchImpl??fetch,s=e.openBrowserFn??IM;if((!("stdin"in process)||!process.stdin.isTTY)&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmchat login` needs an interactive browser. On a headless box, run login on a machine with a browser and copy ~/.config/lmctl/appkey.json here (or set LMCTL_APPKEY).\n"),1;let{verifier:i,challenge:a}=qT(),c=jT(),{server:l,port:u,wait:d}=await NM(n.ports);try{let m=BT(n,{port:u,state:c,challenge:a});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
14
+ `),s(m,t);let f=await d;if(f.error)throw new Error(`authorization failed: ${f.error}`);if(!f.code)throw new Error("no authorization code returned");if(f.state!==c)throw new Error("state mismatch (possible CSRF); aborting");let p=await GT(n,{code:f.code,verifier:i,port:u},o),h=await VT(n,{idToken:p.id_token,label:AM()},o),{appkeyPath:w,identityPath:_}=await QT(h,p,n,r);return t.stdout.write(`
15
15
  \u2713 Signed in as ${h.user_id}
16
16
  \u2713 Appkey saved to ${w} (0600)
17
17
  `+(_?`\u2713 Refresh token saved to ${_} (0600, for silent re-mint)
18
18
  `:"")+`
19
19
  All lmctl tools now use this key automatically.
20
20
  `),0}catch(m){return t.stderr.write(`error: ${m instanceof Error?m.message:String(m)}
21
- `),1}finally{l.close()}}var KT=Pt(()=>{BT()});import{createHash as JM,randomBytes as nb}from"node:crypto";function ob(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||as.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||as.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||as.scope,ports:as.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||as.authUrl).replace(/\/+$/,"")}}function sb(e=nb){let t=e(32).toString("base64url");return{verifier:t,challenge:JM("sha256").update(t).digest("base64url")}}function ib(e=nb){return e(16).toString("base64url")}function ab(e){return`http://127.0.0.1:${e}/callback`}function cb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:ab(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function lb(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function ub(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:ab(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await mb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function db(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await mb(n)}`);return n.json()}async function mb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var as,fb=Pt(()=>{as={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var _b={};_o(_b,{appkeyDir:()=>hb,persistCredentials:()=>gb,runLogin:()=>oP});import{spawn as KM}from"node:child_process";import{mkdir as zM,rename as YM,writeFile as QM}from"node:fs/promises";import{createServer as XM}from"node:http";import{homedir as ZM,hostname as eP}from"node:os";import{join as ya}from"node:path";function hb(e=process.env){return ya(e.XDG_CONFIG_HOME?.trim()||ya(ZM(),".config"),"lmctl")}async function gb(e,t,r,n=process.env){let o=hb(n);await zM(o,{recursive:!0,mode:448});let s=ya(o,"appkey.json");await pb(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
22
- `);let i=null;return t.refresh_token&&(i=ya(o,"identity.json"),await pb(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
23
- `)),{appkeyPath:s,identityPath:i}}async function pb(e,t){let r=`${e}.tmp-${process.pid}`;await QM(r,t,{mode:384}),await YM(r,e)}async function tP(e){let t,r=new Promise(o=>{t=o}),n=XM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=lb(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await rP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function rP(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function nP(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=KM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
21
+ `),1}finally{l.close()}}var ZT=Pt(()=>{KT()});import{createHash as eP,randomBytes as cb}from"node:crypto";function lb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ds.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ds.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ds.scope,ports:ds.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ds.authUrl).replace(/\/+$/,"")}}function ub(e=cb){let t=e(32).toString("base64url");return{verifier:t,challenge:eP("sha256").update(t).digest("base64url")}}function db(e=cb){return e(16).toString("base64url")}function mb(e){return`http://127.0.0.1:${e}/callback`}function fb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:mb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function pb(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function hb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:mb(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await _b(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function gb(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await _b(n)}`);return n.json()}async function _b(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ds,wb=Pt(()=>{ds={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var bb={};yo(bb,{appkeyDir:()=>Eb,persistCredentials:()=>Tb,runLogin:()=>dP});import{spawn as tP}from"node:child_process";import{mkdir as rP,rename as nP,writeFile as oP}from"node:fs/promises";import{createServer as sP}from"node:http";import{homedir as iP,hostname as aP}from"node:os";import{join as ba}from"node:path";function Eb(e=process.env){return ba(e.XDG_CONFIG_HOME?.trim()||ba(iP(),".config"),"lmctl")}async function Tb(e,t,r,n=process.env){let o=Eb(n);await rP(o,{recursive:!0,mode:448});let s=ba(o,"appkey.json");await yb(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
22
+ `);let i=null;return t.refresh_token&&(i=ba(o,"identity.json"),await yb(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
23
+ `)),{appkeyPath:s,identityPath:i}}async function yb(e,t){let r=`${e}.tmp-${process.pid}`;await oP(r,t,{mode:384}),await nP(r,e)}async function cP(e){let t,r=new Promise(o=>{t=o}),n=sP((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=pb(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await lP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function lP(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function uP(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=tP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
24
24
  If your browser didn't open, visit:
25
25
  ${e}
26
26
 
27
- `)}async function oP(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmmail login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=ob(r),{verifier:o,challenge:s}=sb(),i=ib(),{server:a,port:c,wait:l}=await tP(n.ports);try{let u=cb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
28
- `),(e.openBrowserFn??nP)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await ub(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await db(n,{idToken:m.id_token,label:eP()},e.fetchImpl??fetch),p=await gb(f,m,n,r);return t.stdout.write(`
27
+ `)}async function dP(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmmail login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=lb(r),{verifier:o,challenge:s}=ub(),i=db(),{server:a,port:c,wait:l}=await cP(n.ports);try{let u=fb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
28
+ `),(e.openBrowserFn??uP)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await hb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await gb(n,{idToken:m.id_token,label:aP()},e.fetchImpl??fetch),p=await Tb(f,m,n,r);return t.stdout.write(`
29
29
  Signed in as ${f.user_id}
30
30
  Appkey saved to ${p.appkeyPath} (0600)
31
31
  `),0}catch(u){return t.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
32
- `),1}finally{a.close()}}var wb=Pt(()=>{fb()});import{createHash as TP,randomBytes as Sb}from"node:crypto";function vb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||cs.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||cs.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||cs.scope,ports:cs.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||cs.authUrl).replace(/\/+$/,"")}}function Ab(e=Sb){let t=e(32).toString("base64url");return{verifier:t,challenge:TP("sha256").update(t).digest("base64url")}}function $b(e=Sb){return e(16).toString("base64url")}function kb(e){return`http://127.0.0.1:${e}/callback`}function xb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:kb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Rb(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function Nb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:kb(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await Lb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function Ib(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await Lb(n)}`);return n.json()}async function Lb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var cs,Cb=Pt(()=>{cs={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var Pb={};_o(Pb,{appkeyDir:()=>Db,persistCredentials:()=>Mb,runLogin:()=>LP});import{spawn as bP}from"node:child_process";import{mkdir as SP,rename as vP,writeFile as AP}from"node:fs/promises";import{createServer as $P}from"node:http";import{homedir as kP,hostname as xP}from"node:os";import{join as Ta}from"node:path";function Db(e=process.env){return Ta(e.XDG_CONFIG_HOME?.trim()||Ta(kP(),".config"),"lmctl")}async function Mb(e,t,r,n=process.env){let o=Db(n);await SP(o,{recursive:!0,mode:448});let s=Ta(o,"appkey.json");await Ob(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
33
- `);let i=null;return t.refresh_token&&(i=Ta(o,"identity.json"),await Ob(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
34
- `)),{appkeyPath:s,identityPath:i}}async function Ob(e,t){let r=`${e}.tmp-${process.pid}`;await AP(r,t,{mode:384}),await vP(r,e)}async function RP(e){let t,r=new Promise(o=>{t=o}),n=$P((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Rb(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await NP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function NP(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function IP(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=bP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
32
+ `),1}finally{a.close()}}var Sb=Pt(()=>{wb()});import{createHash as xP,randomBytes as xb}from"node:crypto";function Rb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ms.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ms.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ms.scope,ports:ms.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ms.authUrl).replace(/\/+$/,"")}}function Nb(e=xb){let t=e(32).toString("base64url");return{verifier:t,challenge:xP("sha256").update(t).digest("base64url")}}function Lb(e=xb){return e(16).toString("base64url")}function Ib(e){return`http://127.0.0.1:${e}/callback`}function Cb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:Ib(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Ob(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function Db(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Ib(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await Pb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function Mb(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await Pb(n)}`);return n.json()}async function Pb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ms,Ub=Pt(()=>{ms={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var Hb={};yo(Hb,{appkeyDir:()=>qb,persistCredentials:()=>jb,runLogin:()=>FP});import{spawn as RP}from"node:child_process";import{mkdir as NP,rename as LP,writeFile as IP}from"node:fs/promises";import{createServer as CP}from"node:http";import{homedir as OP,hostname as DP}from"node:os";import{join as va}from"node:path";function qb(e=process.env){return va(e.XDG_CONFIG_HOME?.trim()||va(OP(),".config"),"lmctl")}async function jb(e,t,r,n=process.env){let o=qb(n);await NP(o,{recursive:!0,mode:448});let s=va(o,"appkey.json");await Fb(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
33
+ `);let i=null;return t.refresh_token&&(i=va(o,"identity.json"),await Fb(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
34
+ `)),{appkeyPath:s,identityPath:i}}async function Fb(e,t){let r=`${e}.tmp-${process.pid}`;await IP(r,t,{mode:384}),await LP(r,e)}async function MP(e){let t,r=new Promise(o=>{t=o}),n=CP((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Ob(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await PP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function PP(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function UP(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=RP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
35
35
  If your browser didn't open, visit:
36
36
  ${e}
37
37
 
38
- `)}async function LP(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmnote login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=vb(r),{verifier:o,challenge:s}=Ab(),i=$b(),{server:a,port:c,wait:l}=await RP(n.ports);try{let u=xb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
39
- `),(e.openBrowserFn??IP)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await Nb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await Ib(n,{idToken:m.id_token,label:xP()},e.fetchImpl??fetch),p=await Mb(f,m,n,r);return t.stdout.write(`
38
+ `)}async function FP(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmnote login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=Rb(r),{verifier:o,challenge:s}=Nb(),i=Lb(),{server:a,port:c,wait:l}=await MP(n.ports);try{let u=Cb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
39
+ `),(e.openBrowserFn??UP)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await Db(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await Mb(n,{idToken:m.id_token,label:DP()},e.fetchImpl??fetch),p=await jb(f,m,n,r);return t.stdout.write(`
40
40
  Signed in as ${f.user_id}
41
41
  Appkey saved to ${p.appkeyPath} (0600)
42
42
  `),0}catch(u){return t.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
43
- `),1}finally{a.close()}}var Ub=Pt(()=>{Cb()});import{createHash as KP,randomBytes as jb}from"node:crypto";function Hb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ms.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ms.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ms.scope,ports:ms.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ms.authUrl).replace(/\/+$/,"")}}function Bb(e=jb){let t=e(32).toString("base64url");return{verifier:t,challenge:KP("sha256").update(t).digest("base64url")}}function Wb(e=jb){return e(16).toString("base64url")}function Gb(e){return`http://127.0.0.1:${e}/callback`}function Vb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:Gb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Jb(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function Kb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Gb(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await Yb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function zb(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await Yb(n)}`);return n.json()}async function Yb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ms,Qb=Pt(()=>{ms={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var tS={};_o(tS,{appkeyDir:()=>Zb,persistCredentials:()=>eS,runLogin:()=>sU});import{spawn as zP}from"node:child_process";import{mkdir as YP,rename as QP,writeFile as XP}from"node:fs/promises";import{createServer as ZP}from"node:http";import{homedir as eU,hostname as tU}from"node:os";import{join as ba}from"node:path";function Zb(e=process.env){return ba(e.XDG_CONFIG_HOME?.trim()||ba(eU(),".config"),"lmctl")}async function eS(e,t,r,n=process.env){let o=Zb(n);await YP(o,{recursive:!0,mode:448});let s=ba(o,"appkey.json");await Xb(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
44
- `);let i=null;return t.refresh_token&&(i=ba(o,"identity.json"),await Xb(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
45
- `)),{appkeyPath:s,identityPath:i}}async function Xb(e,t){let r=`${e}.tmp-${process.pid}`;await XP(r,t,{mode:384}),await QP(r,e)}async function rU(e){let t,r=new Promise(o=>{t=o}),n=ZP((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Jb(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await nU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function nU(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function oU(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=zP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
43
+ `),1}finally{a.close()}}var Bb=Pt(()=>{Ub()});import{createHash as tU,randomBytes as Vb}from"node:crypto";function Jb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||gs.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||gs.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||gs.scope,ports:gs.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||gs.authUrl).replace(/\/+$/,"")}}function Kb(e=Vb){let t=e(32).toString("base64url");return{verifier:t,challenge:tU("sha256").update(t).digest("base64url")}}function zb(e=Vb){return e(16).toString("base64url")}function Yb(e){return`http://127.0.0.1:${e}/callback`}function Qb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:Yb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Xb(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function Zb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Yb(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await tS(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function eS(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await tS(n)}`);return n.json()}async function tS(e){try{return(await e.text()).slice(0,300)}catch{return""}}var gs,rS=Pt(()=>{gs={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var iS={};yo(iS,{appkeyDir:()=>oS,persistCredentials:()=>sS,runLogin:()=>mU});import{spawn as rU}from"node:child_process";import{mkdir as nU,rename as oU,writeFile as sU}from"node:fs/promises";import{createServer as iU}from"node:http";import{homedir as aU,hostname as cU}from"node:os";import{join as Aa}from"node:path";function oS(e=process.env){return Aa(e.XDG_CONFIG_HOME?.trim()||Aa(aU(),".config"),"lmctl")}async function sS(e,t,r,n=process.env){let o=oS(n);await nU(o,{recursive:!0,mode:448});let s=Aa(o,"appkey.json");await nS(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
44
+ `);let i=null;return t.refresh_token&&(i=Aa(o,"identity.json"),await nS(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
45
+ `)),{appkeyPath:s,identityPath:i}}async function nS(e,t){let r=`${e}.tmp-${process.pid}`;await sU(r,t,{mode:384}),await oU(r,e)}async function lU(e){let t,r=new Promise(o=>{t=o}),n=iU((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Xb(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await uU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function uU(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function dU(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=rU(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
46
46
  If your browser didn't open, visit:
47
47
  ${e}
48
48
 
49
- `)}async function sU(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmsheet login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=Hb(r),{verifier:o,challenge:s}=Bb(),i=Wb(),{server:a,port:c,wait:l}=await rU(n.ports);try{let u=Vb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
50
- `),(e.openBrowserFn??oU)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await Kb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await zb(n,{idToken:m.id_token,label:tU()},e.fetchImpl??fetch),p=await eS(f,m,n,r);return t.stdout.write(`
49
+ `)}async function mU(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmsheet login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=Jb(r),{verifier:o,challenge:s}=Kb(),i=zb(),{server:a,port:c,wait:l}=await lU(n.ports);try{let u=Qb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
50
+ `),(e.openBrowserFn??dU)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await Zb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await eS(n,{idToken:m.id_token,label:cU()},e.fetchImpl??fetch),p=await sS(f,m,n,r);return t.stdout.write(`
51
51
  Signed in as ${f.user_id}
52
52
  Appkey saved to ${p.appkeyPath} (0600)
53
53
  `),0}catch(u){return t.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
54
- `),1}finally{a.close()}}var rS=Pt(()=>{Qb()});import{createHash as mU,randomBytes as cS}from"node:crypto";function lS(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||fs.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||fs.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||fs.scope,ports:fs.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||fs.authUrl).replace(/\/+$/,"")}}function uS(e=cS){let t=e(32).toString("base64url");return{verifier:t,challenge:mU("sha256").update(t).digest("base64url")}}function dS(e=cS){return e(16).toString("base64url")}function mS(e){return`http://127.0.0.1:${e}/callback`}function fS(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:mS(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function pS(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function hS(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:mS(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await _S(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function gS(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await _S(n)}`);return n.json()}async function _S(e){try{return(await e.text()).slice(0,300)}catch{return""}}var fs,wS=Pt(()=>{fs={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var bS={};_o(bS,{appkeyDir:()=>ES,persistCredentials:()=>TS,runLogin:()=>SU});import{spawn as fU}from"node:child_process";import{mkdir as pU,rename as hU,writeFile as gU}from"node:fs/promises";import{createServer as _U}from"node:http";import{homedir as wU,hostname as yU}from"node:os";import{join as Sa}from"node:path";function ES(e=process.env){return Sa(e.XDG_CONFIG_HOME?.trim()||Sa(wU(),".config"),"lmctl")}async function TS(e,t,r,n=process.env){let o=ES(n);await pU(o,{recursive:!0,mode:448});let s=Sa(o,"appkey.json");await yS(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
55
- `);let i=null;return t.refresh_token&&(i=Sa(o,"identity.json"),await yS(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
56
- `)),{appkeyPath:s,identityPath:i}}async function yS(e,t){let r=`${e}.tmp-${process.pid}`;await gU(r,t,{mode:384}),await hU(r,e)}async function EU(e){let t,r=new Promise(o=>{t=o}),n=_U((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=pS(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await TU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function TU(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function bU(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=fU(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
54
+ `),1}finally{a.close()}}var aS=Pt(()=>{rS()});import{createHash as yU,randomBytes as fS}from"node:crypto";function pS(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||_s.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||_s.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||_s.scope,ports:_s.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||_s.authUrl).replace(/\/+$/,"")}}function hS(e=fS){let t=e(32).toString("base64url");return{verifier:t,challenge:yU("sha256").update(t).digest("base64url")}}function gS(e=fS){return e(16).toString("base64url")}function _S(e){return`http://127.0.0.1:${e}/callback`}function wS(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:_S(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function yS(e){let t=new URL(e,"http://127.0.0.1");return{code:t.searchParams.get("code")??void 0,state:t.searchParams.get("state")??void 0,error:t.searchParams.get("error")??void 0}}async function ES(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:_S(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await bS(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function TS(e,t,r=fetch){let n=await r(`${e.authUrl}/appkeys`,{method:"POST",headers:{authorization:`Bearer ${t.idToken}`,"content-type":"application/json"},body:JSON.stringify({label:t.label})});if(!n.ok)throw new Error(`appkey mint failed: HTTP ${n.status} ${await bS(n)}`);return n.json()}async function bS(e){try{return(await e.text()).slice(0,300)}catch{return""}}var _s,SS=Pt(()=>{_s={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var $S={};yo($S,{appkeyDir:()=>AS,persistCredentials:()=>kS,runLogin:()=>NU});import{spawn as EU}from"node:child_process";import{mkdir as TU,rename as bU,writeFile as SU}from"node:fs/promises";import{createServer as vU}from"node:http";import{homedir as AU,hostname as kU}from"node:os";import{join as ka}from"node:path";function AS(e=process.env){return ka(e.XDG_CONFIG_HOME?.trim()||ka(AU(),".config"),"lmctl")}async function kS(e,t,r,n=process.env){let o=AS(n);await TU(o,{recursive:!0,mode:448});let s=ka(o,"appkey.json");await vS(s,JSON.stringify({version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at},null,2)+`
55
+ `);let i=null;return t.refresh_token&&(i=ka(o,"identity.json"),await vS(i,JSON.stringify({user_pool_id:n.COGNITO_USER_POOL_ID?.trim()||"us-east-1_UalgyPyId",client_id:r.clientId,refresh_token:t.refresh_token},null,2)+`
56
+ `)),{appkeyPath:s,identityPath:i}}async function vS(e,t){let r=`${e}.tmp-${process.pid}`;await SU(r,t,{mode:384}),await bU(r,e)}async function $U(e){let t,r=new Promise(o=>{t=o}),n=vU((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=yS(o.url);s.writeHead(200,{"content-type":"text/html"}).end("<html><body><h3>lmctl login complete.</h3><p>You can close this tab.</p></body></html>"),t(i)});for(let o of e)if(await xU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function xU(e,t){return new Promise(r=>{let n=()=>{e.removeListener("error",n),r(!1)};e.once("error",n),e.listen(t,"127.0.0.1",()=>{e.removeListener("error",n),r(!0)})})}function RU(e,t){let r=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",n=process.platform==="win32"?["/c","start","",e]:[e];try{let o=EU(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
57
57
  If your browser didn't open, visit:
58
58
  ${e}
59
59
 
60
- `)}async function SU(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmtext login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=lS(r),{verifier:o,challenge:s}=uS(),i=dS(),{server:a,port:c,wait:l}=await EU(n.ports);try{let u=fS(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
61
- `),(e.openBrowserFn??bU)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await hS(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await gS(n,{idToken:m.id_token,label:yU()},e.fetchImpl??fetch),p=await TS(f,m,n,r);return t.stdout.write(`
60
+ `)}async function NU(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env;if(!process.stdin.isTTY&&(r.LMCTL_NONINTERACTIVE||r.CI))return t.stderr.write("error: `lmtext login` needs an interactive browser. Run it on a machine with a browser and copy ~/.config/lmctl/appkey.json here.\n"),1;let n=pS(r),{verifier:o,challenge:s}=hS(),i=gS(),{server:a,port:c,wait:l}=await $U(n.ports);try{let u=wS(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
61
+ `),(e.openBrowserFn??RU)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await ES(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await TS(n,{idToken:m.id_token,label:kU()},e.fetchImpl??fetch),p=await kS(f,m,n,r);return t.stdout.write(`
62
62
  Signed in as ${f.user_id}
63
63
  Appkey saved to ${p.appkeyPath} (0600)
64
64
  `),0}catch(u){return t.stderr.write(`error: ${u instanceof Error?u.message:String(u)}
65
- `),1}finally{a.close()}}var SS=Pt(()=>{wS()});import{spawn as iq}from"node:child_process";import{openSync as aq,mkdirSync as cq,writeFileSync as lq}from"node:fs";import{homedir as uq}from"node:os";import{join as wd}from"node:path";import{mkdirSync as _q,readFileSync as Uv,renameSync as wq,writeFileSync as yq}from"node:fs";import{homedir as Fv}from"node:os";import{dirname as bq,join as Td}from"node:path";var pq=Object.freeze({free:1e6,test:1e7});var Gr=class extends Error{code="APPKEY_NOT_FOUND";constructor(t="no lmctl appkey found; run `lmchat login` on a machine with a browser, or copy ~/.config/lmctl/appkey.json here, or set LMCTL_APPKEY"){super(t),this.name="AppkeyNotFoundError"}},sr=class extends Error{code="APPKEY_VALIDATION_ERROR";status;constructor(t,r={}){super(t),this.name="AppkeyValidationError",this.status=r.status,this.cause=r.cause}},Es=class extends Error{code="APPKEY_INVALID";source;constructor(t){super(`${t} resolved an invalid lmctl appkey`),this.name="AppkeyInvalidError",this.source=t}},Ts=class extends Error{code="AUTH_API_ERROR";status;constructor(t,r={}){super(t),this.name="AuthApiError",this.status=r.status,this.cause=r.cause}};var qv="https://lmctl.ai/auth",jv=1e4;function Oa(e){return e.length>0&&!e.includes(`
66
- `)}function Se(e={}){let t=e.env??process.env,r=e.fs??{readFileSync:(c,l)=>Uv(c,l)},n=e.homedir??Fv,o=t.LMCTL_APPKEY?.trim();if(o&&Oa(o))return{appkey:o,source:"env:LMCTL_APPKEY",envelope:null};let s=t.LMCTL_APPKEY_FILE?.trim();if(s){let c=bd(r,s,"env:LMCTL_APPKEY_FILE");if(c)return c}let i=Hv(t,n),a=bd(r,i,"file:default");if(a)return a;throw new Gr}async function vd(e,t={}){let r=await Gv("/whoami",{method:"GET",headers:{authorization:`Bearer ${e}`}},t,sr);if(r.status===401)return{valid:!1};if(r.status!==200)throw new sr(`appkey validation failed with status ${r.status}`,{status:r.status});let n=await Jv(r,"validate appkey response",sr);return{valid:!0,userId:Sd(n,"user_id","validate appkey response",sr),label:Sd(n,"label","validate appkey response",sr)}}function bd(e,t,r){let n;try{n=e.readFileSync(t,"utf8")}catch{return null}let o=n.trim();if(o.length===0)return null;if(o.startsWith("{")){let s;try{s=JSON.parse(o)}catch{s=void 0}if(s&&typeof s=="object"){let i=s;return typeof i.appkey=="string"&&Oa(i.appkey.trim())?{appkey:i.appkey.trim(),source:r,envelope:i}:null}}return Oa(o)?{appkey:o,source:r,envelope:null}:null}function Hv(e,t){let r=e.XDG_CONFIG_HOME?.trim()||Td(t(),".config");return Td(r,"lmctl","appkey.json")}function Bv(e){let t=e.env??process.env;return(e.authBaseUrl?.trim()||t.LMCTL_AUTH_BASE_URL?.trim()||qv).replace(/\/+$/,"")}function Wv(e,t){if(e.fetchImpl)return e.fetchImpl;if(typeof globalThis.fetch=="function")return(r,n)=>globalThis.fetch(r,n);throw new t("global fetch is unavailable; pass fetchImpl explicitly")}async function Gv(e,t,r,n){return await Vv(e,t,r,n,r.timeoutMs)}async function Vv(e,t,r,n,o,s){let i=Wv(r,n),a=`${Bv(r)}${e}`,c=o??jv,l={...t},u=new AbortController;l.signal=u.signal;let d=setTimeout(()=>{u.abort()},c);try{return await i(a,l)}catch(m){throw u.signal.aborted?s?s():new n(`auth request timed out for ${e} after ${c}ms`,{cause:m}):m instanceof n?m:new n(`auth request failed for ${e}`,{cause:m})}finally{clearTimeout(d)}}async function Jv(e,t,r){let n;try{n=await e.json()}catch(o){throw new r(`${t} was not valid JSON`,{cause:o,status:e.status})}if(!n||typeof n!="object"||Array.isArray(n))throw new r(`${t} must be a JSON object`,{status:e.status});return n}function Sd(e,t,r,n){let o=e[t];if(typeof o!="string"||o.length===0)throw new n(`${r} missing string field ${t}`);return o}function Je(e){return async(...t)=>{throw new Error(`lmmail-client fake: ${e} not stubbed`)}}var Aq={listMailboxes:Je("listMailboxes"),createMailbox:Je("createMailbox"),deleteMailbox:Je("deleteMailbox"),sendMessage:Je("sendMessage"),listMessages:Je("listMessages"),getRecentMessages:Je("getRecentMessages"),getMessage:Je("getMessage"),getMessageMetadata:Je("getMessageMetadata"),getThread:Je("getThread"),download:Je("download"),deleteMessage:Je("deleteMessage"),registerSite:Je("registerSite"),resolveSite:Je("resolveSite"),listSites:Je("listSites"),setSiteName:Je("setSiteName"),deleteSiteName:Je("deleteSiteName"),deleteSite:Je("deleteSite")};var Ft=class extends Error{status;code;responseBody;constructor(t,r,n,o){super(`${t}: HTTP ${r}${o?` ${o}`:n?` ${n}`:""}`),this.name="LmmailHttpError",this.status=r,this.code=o,this.responseBody=n}};function pt(e){let t=e.apiUrl.replace(/\/+$/,"");if(!t)throw new Error("lmmail API URL is required");if(!e.appkey)throw new Error("lmmail appkey is required");let r=e.fetch??fetch,n={authorization:`Bearer ${e.appkey}`};async function o(x={}){return(await S(`${t}/mailboxes${x.withCounts?"?with_counts=1":""}`,{headers:n},"list mailboxes failed")).mailboxes}async function s(x,I={}){let k=await r(`${t}/mailboxes`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({mailbox_name:x})});if(k.status===409){let B=await k.text().catch(()=>"");if(I.tolerate409!==!1&&xd(B)==="mailbox_exists")return;throw kd("create mailbox failed",k.status,B)}await N(k,"create mailbox failed")}async function i(x){return S(`${t}/mailboxes/${encodeURIComponent(x)}`,{method:"DELETE",headers:n},"delete mailbox failed")}async function a(x){let I=x.attachments??[],k=await S(`${t}/mailboxes/${encodeURIComponent(x.mailbox)}/messages`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({...x.subject===void 0?{}:{subject:x.subject},body:Ad(x.body),attachments:I.map(Ad)})},"allocate message failed"),B=[{target:k.body,bytes:x.body.bytes},...k.attachments.map((C,g)=>({target:C,bytes:I[g].bytes}))];for(let{target:C,bytes:g}of B){let y=new FormData;for(let[P,J]of Object.entries(C.fields))y.append(P,J);y.append("file",new Blob([new Uint8Array(g)],{type:C.content_type}),C.name);let R=await r(C.upload_url,{method:"POST",body:y});await N(R,`upload failed for ${C.name}`)}return await S(Kv(t,k.finalize_url),{method:"POST",headers:n},"finalize message failed"),k.seq}async function c(x,I={}){let k=new URLSearchParams;if(I.status&&k.set("status",I.status),I.after!==void 0&&k.set("after",String(I.after)),I.wait_s!==void 0){if(!Number.isInteger(I.wait_s)||I.wait_s<0||I.wait_s>20)throw new Error("wait_s must be an integer from 0 through 20");k.set("wait_s",String(I.wait_s))}let B=k.size>0?`?${k.toString()}`:"",C=await S(`${t}/mailboxes/${encodeURIComponent(x)}/messages${B}`,{headers:n},"list messages failed");return{messages:C.messages,next_after:C.next_after}}async function l(x={}){let I=new URLSearchParams;if(x.limit!==void 0){if(!Number.isInteger(x.limit)||x.limit<1||x.limit>50)throw new Error("limit must be an integer from 1 through 50");I.set("limit",String(x.limit))}let k=I.size>0?`?${I.toString()}`:"";return S(`${t}/messages/recent${k}`,{headers:n},"get recent messages failed")}async function u(x,I){return S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${I}`,{headers:n},"get message failed")}async function d(x,I){let k=await u(x,I);return{...k,body:$d(k.body),attachments:k.attachments.map($d)}}async function m(x,I){return S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${I}/thread`,{headers:n},"get thread failed")}async function f(x){let I=await r(x);return await N(I,"download failed"),new Uint8Array(await I.arrayBuffer())}async function p(x,I){await S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${I}`,{method:"DELETE",headers:n},"delete message failed")}async function h(x,I,k){return await S(`${t}/sites`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site_name:x,site_uuid:I,mailbox:k})},"register site failed")}async function w(x){return await S(`${t}/sites/${encodeURIComponent(x)}`,{headers:n},"resolve site failed")}async function _(x={}){let I=new URLSearchParams;if(x.cursor!==void 0&&I.set("cursor",x.cursor),x.limit!==void 0){if(!Number.isInteger(x.limit)||x.limit<1||x.limit>50)throw new Error("limit must be an integer from 1 through 50");I.set("limit",String(x.limit))}let k=I.size>0?`?${I.toString()}`:"";return S(`${t}/sites${k}`,{headers:n},"list sites failed")}async function E(x,I){return S(`${t}/sites/name`,{method:"PUT",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site:x,name:I})},"set site name failed")}async function T(x){return S(`${t}/sites/name`,{method:"DELETE",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site:x})},"delete site name failed")}async function v(x){await S(`${t}/sites/${encodeURIComponent(x)}`,{method:"DELETE",headers:n},"delete site failed")}async function S(x,I,k){let B=await r(x,I);await N(B,k);try{return await B.json()}catch(C){throw new Error(`${k}: invalid JSON response: ${zv(C)}`)}}async function N(x,I){if(x.ok)return;let k=await x.text().catch(()=>"");throw kd(I,x.status,k)}return{listMailboxes:o,createMailbox:s,deleteMailbox:i,sendMessage:a,listMessages:c,getRecentMessages:l,getMessage:u,getMessageMetadata:d,getThread:m,download:f,deleteMessage:p,registerSite:h,resolveSite:w,listSites:_,setSiteName:E,deleteSiteName:T,deleteSite:v}}function Ad(e){return{name:e.name,size:e.bytes.byteLength,content_type:e.contentType}}function $d(e){return{name:e.name,size:e.size,content_type:e.content_type}}function kd(e,t,r){return new Ft(e,t,r,xd(r))}function xd(e){try{let t=JSON.parse(e);return typeof t.error=="string"?t.error:void 0}catch{return}}function Kv(e,t){return/^https?:\/\//i.test(t)?t:`${e}${t.startsWith("/")?"":"/"}${t}`}function zv(e){return e instanceof Error?e.message:String(e)}import{execFile as vA}from"node:child_process";import{existsSync as AA}from"node:fs";import{join as $A}from"node:path";import{promisify as kA}from"node:util";import{existsSync as Rd}from"node:fs";import{createRequire as Yv}from"node:module";import{dirname as Qv}from"node:path";var Da=null;function Xv(){return Da===null&&(Da=Yv(import.meta.url)("node:sqlite").DatabaseSync),Da}var Zv={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"},eA={261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB",264:"SQLITE_READONLY_RECOVERY",520:"SQLITE_READONLY_CANTLOCK",776:"SQLITE_READONLY_ROLLBACK",1032:"SQLITE_READONLY_DBMOVED",1288:"SQLITE_READONLY_CANTINIT",1544:"SQLITE_READONLY_DIRECTORY",270:"SQLITE_CANTOPEN_NOTEMPDIR",526:"SQLITE_CANTOPEN_ISDIR",782:"SQLITE_CANTOPEN_FULLPATH",1038:"SQLITE_CANTOPEN_CONVPATH",1294:"SQLITE_CANTOPEN_DIRTYWAL",1550:"SQLITE_CANTOPEN_SYMLINK",275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE"};function tA(e){return eA[e]??Zv[e&255]??`SQLITE_UNKNOWN_${e}`}var rA="SQLite3 can only bind numbers, strings, bigints, buffers, and null";function qt(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.errcode=="number")throw t.code=tA(t.errcode),e;if(t.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(t.message)))throw new TypeError(rA);if(t.code==="ERR_INVALID_STATE"&&/database is not open/.test(String(t.message)))throw new TypeError("The database connection is not open")}throw e}function nA(){let e="unable to open database file";return Object.assign(new Error(e),{code:"SQLITE_CANTOPEN",errcode:14,errstr:e})}function Nd(e){return e instanceof Uint8Array&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function oA(e){if(e==null)return e;if(Array.isArray(e))return e.map(Nd);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=Nd(n);return t}return e}function sA(e){if(e===null||typeof e!="object"||Array.isArray(e)||e instanceof Uint8Array)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bs(e){return e.map((t,r)=>{if(t===void 0)return null;if(r===0&&sA(t)){let n={};for(let[o,s]of Object.entries(t))n[o]=s===void 0?null:s;return n}return t})}var Ma=class{handle;pluckMode=!1;arrayMode=!1;constructor(t){this.handle=t,this.handle.setAllowBareNamedParameters(!0),this.handle.setAllowUnknownNamedParameters(!0)}get source(){return this.handle.sourceSQL}run(...t){try{let r=this.handle.run(...bs(t));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){qt(r)}}get(...t){try{return this.project(this.handle.get(...bs(t)))}catch(r){qt(r)}}all(...t){try{return this.handle.all(...bs(t)).map(r=>this.project(r))}catch(r){qt(r)}}*iterate(...t){let r;try{r=this.handle.iterate(...bs(t))}catch(n){qt(n)}for(;;){let n;try{n=r.next()}catch(o){qt(o)}if(n.done)return;yield this.project(n.value)}}raw(t=!0){return this.arrayMode=t,this.handle.setReturnArrays(t||this.pluckMode),this}pluck(t=!0){return this.pluckMode=t,this.handle.setReturnArrays(t||this.arrayMode),this}project(t){let r=oA(t);return this.pluckMode&&Array.isArray(r)?r[0]:r}},Pa=class{name;memory;readonly;handle;savepointId=0;constructor(t,r={}){let n=t===":memory:"||t==="";if(r.readonly===!0&&n)throw new TypeError("In-memory/temporary databases cannot be readonly");if(!n&&!Rd(Qv(t)))throw new TypeError("Cannot open database because the directory does not exist");if(r.fileMustExist===!0&&!n&&!Rd(t))throw nA();this.name=t,this.memory=n,this.readonly=r.readonly===!0;try{this.handle=new(Xv())(t,{readOnly:this.readonly,timeout:r.timeout??5e3,enableForeignKeyConstraints:r.foreignKeys??!0})}catch(o){qt(o)}}get open(){return this.handle.isOpen}get inTransaction(){return this.handle.isTransaction}prepare(t){try{return new Ma(this.handle.prepare(t))}catch(r){qt(r)}}exec(t){try{return this.handle.exec(t),this}catch(r){qt(r)}}pragma(t,r){let n=this.prepare(`PRAGMA ${t}`);return r?.simple===!0?n.pluck().get():n.all()}transaction(t){let r=o=>(...s)=>this.runTransaction(o,t,s),n=r("BEGIN");return n.default=r("BEGIN"),n.deferred=r("BEGIN DEFERRED"),n.immediate=r("BEGIN IMMEDIATE"),n.exclusive=r("BEGIN EXCLUSIVE"),n}serialize(){try{let t=this.handle.serialize();return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}catch(t){qt(t)}}close(){if(!this.handle.isOpen)return this;try{return this.handle.close(),this}catch(t){qt(t)}}runTransaction(t,r,n){if(!this.inTransaction){this.exec(t);try{let s=r(...n);return this.exec("COMMIT"),s}catch(s){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(i){if(!iA(i))throw i}throw s}}let o=`lmbee_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${o}`);try{let s=r(...n);return this.exec(`RELEASE ${o}`),s}catch(s){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${o}`),this.exec(`RELEASE ${o}`)}catch(i){if(!aA(i))throw i}throw s}}};function iA(e){return e instanceof Error&&/cannot rollback - no transaction is active/i.test(e.message)}function aA(e){return e instanceof Error&&/no such savepoint:/i.test(e.message)}var ht=Pa;import{existsSync as Fa,lstatSync as cA,mkdirSync as lA,readFileSync as Dd,realpathSync as Id}from"node:fs";import{basename as uA,dirname as qa,isAbsolute as dA,join as mA,relative as fA,resolve as Ld}from"node:path";import{fileURLToPath as pA}from"node:url";var Md=mA(qa(pA(import.meta.url)),"schema.sql");function wo(e){if(e!==void 0&&e!=="")return e;let t=process.env.LMBEE_DB;if(t)return t;throw new Error("No lmbee database selected: pass an explicit database path or set LMBEE_DB to the intended existing database. The retired ~/.lmbee/state.db default is no longer used.")}function hA(e){if(e.startsWith("~"))throw new Error(`Refusing to open the lmbee database at "${e}": lmbee does not expand "~" in database paths, so this would be created as a literal directory named "~" under the current working directory. Use an absolute path instead (for example ~/.lmbee/state.db). Note for systemd units: Environment= expands neither "~" nor "$HOME", so write the absolute path literally there too.`)}function gA(e,t){if(!(e===":memory:"||Fa(e)))throw new Error(`Refusing to create the lmbee database at "${e}": ${t} points at non-existent "${e}", and a typo is indistinguishable from a fresh install. To provision a new database here, \`touch "${e}"\` first, then retry, or point ${t} at an existing database.`)}function _A(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(queue)").all();if(r.length===0)return;let n=new Set(r.map(s=>s.name));n.has("subject_id")||e.exec("ALTER TABLE queue ADD COLUMN subject_id TEXT"),n.has("dedupe_key")||e.exec("ALTER TABLE queue ADD COLUMN dedupe_key TEXT"),e.prepare(`SELECT name FROM pragma_index_list('queue') WHERE "unique" = 1 AND partial = 0`).all().some(s=>{let i=e.prepare("SELECT name FROM pragma_index_info(?) ORDER BY seqno").all(s.name);return i.length===1&&i[0].name==="dedupe_key"})||e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe_key ON queue(dedupe_key)"),n.has("delivered_via_escalation")||e.exec("ALTER TABLE queue ADD COLUMN delivered_via_escalation INTEGER NOT NULL DEFAULT 0"),n.has("escalation_claimed_ts")||e.exec("ALTER TABLE queue ADD COLUMN escalation_claimed_ts TEXT"),n.has("escalation_claim_token")||e.exec("ALTER TABLE queue ADD COLUMN escalation_claim_token TEXT"),n.has("escalation_only")||e.exec("ALTER TABLE queue ADD COLUMN escalation_only INTEGER NOT NULL DEFAULT 0"),n.has("admission_fingerprint")||e.exec("ALTER TABLE queue ADD COLUMN admission_fingerprint TEXT"),n.has("expects_response")||e.exec("ALTER TABLE queue ADD COLUMN expects_response INTEGER NOT NULL DEFAULT 0"),n.has("to_alias")||e.exec("ALTER TABLE queue ADD COLUMN to_alias TEXT"),n.has("retracted_ts")||e.exec("ALTER TABLE queue ADD COLUMN retracted_ts TEXT"),n.has("retracted_reason")||e.exec("ALTER TABLE queue ADD COLUMN retracted_reason TEXT"),n.has("retraction_notice")||e.exec("ALTER TABLE queue ADD COLUMN retraction_notice INTEGER NOT NULL DEFAULT 0"),n.has("in_reply_to")||e.exec("ALTER TABLE queue ADD COLUMN in_reply_to INTEGER"),n.has("operator_priority")||e.exec("ALTER TABLE queue ADD COLUMN operator_priority INTEGER NOT NULL DEFAULT 0"),n.has("merged_into_id")||e.exec("ALTER TABLE queue ADD COLUMN merged_into_id INTEGER")}).immediate()}function wA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(team_progress)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("last_miniplayer_reply_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN last_miniplayer_reply_hash TEXT"),n.has("blocked_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN blocked_surfaced_ts TEXT"),n.has("last_escalation_attempt_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN last_escalation_attempt_ts TEXT"),n.has("escalation_attempt_count")||e.exec("ALTER TABLE team_progress ADD COLUMN escalation_attempt_count INTEGER NOT NULL DEFAULT 0"),n.has("fault_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN fault_surfaced_ts TEXT"),n.has("epic_closed_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN epic_closed_surfaced_ts TEXT"),n.has("quota_exhausted_last_seen_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN quota_exhausted_last_seen_ts TEXT"),n.has("quota_exhausted_message")||e.exec("ALTER TABLE team_progress ADD COLUMN quota_exhausted_message TEXT"),n.has("miniplayer_verdict_label")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_label TEXT"),n.has("miniplayer_verdict_reason")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_reason TEXT"),n.has("miniplayer_verdict_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_ts TEXT"),n.has("miniplayer_verdict_input_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_input_hash TEXT"),n.has("miniplayer_verdict_structural_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_structural_hash TEXT"),n.has("holder_watch_pid")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_pid INTEGER"),n.has("holder_watch_started_at")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_started_at TEXT"),n.has("holder_watch_cpu_ticks")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_cpu_ticks INTEGER"),n.has("holder_watch_observed_at")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_observed_at TEXT"),n.has("holder_watch_low_cpu_streak")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_low_cpu_streak INTEGER"),n.has("hung_holder_flagged_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN hung_holder_flagged_ts TEXT"),n.has("hung_holder_reason")||e.exec("ALTER TABLE team_progress ADD COLUMN hung_holder_reason TEXT"),n.has("last_cli_activity_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN last_cli_activity_ts TEXT")}).immediate()}function yA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(cron_jobs)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("last_fire_error")||e.exec("ALTER TABLE cron_jobs ADD COLUMN last_fire_error TEXT"),n.has("running_systemd_unit")||e.exec("ALTER TABLE cron_jobs ADD COLUMN running_systemd_unit TEXT"),n.has("timezone")||e.exec("ALTER TABLE cron_jobs ADD COLUMN timezone TEXT"),n.has("provider")||e.exec("ALTER TABLE cron_jobs ADD COLUMN provider TEXT"),n.has("model")||e.exec("ALTER TABLE cron_jobs ADD COLUMN model TEXT"),n.has("working_directory")||e.exec("ALTER TABLE cron_jobs ADD COLUMN working_directory TEXT"),n.has("escalation_owner")||e.exec("ALTER TABLE cron_jobs ADD COLUMN escalation_owner TEXT"),n.has("session_teamfile")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_teamfile TEXT"),n.has("session_alias")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_alias TEXT"),n.has("session_seeded_at")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_seeded_at TEXT"),n.has("session_generation")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_generation INTEGER NOT NULL DEFAULT 0")}).immediate()}function EA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(entities)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("delivered_ts")||e.exec("ALTER TABLE entities ADD COLUMN delivered_ts TEXT"),n.has("review_time")||e.exec("ALTER TABLE entities ADD COLUMN review_time TEXT"),n.has("needs_review")||e.exec("ALTER TABLE entities ADD COLUMN needs_review INTEGER NOT NULL DEFAULT 0 CHECK(needs_review IN (0,1))"),n.has("review_reason")||e.exec("ALTER TABLE entities ADD COLUMN review_reason TEXT"),n.has("review_input_hash")||e.exec("ALTER TABLE entities ADD COLUMN review_input_hash TEXT"),n.has("hold_until")||e.exec("ALTER TABLE entities ADD COLUMN hold_until TEXT"),n.has("hold_reason")||e.exec("ALTER TABLE entities ADD COLUMN hold_reason TEXT"),n.has("blocked_on")||e.exec("ALTER TABLE entities ADD COLUMN blocked_on TEXT")}).immediate()}function TA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(mail_ledger)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("ack_sent_ts")||e.exec("ALTER TABLE mail_ledger ADD COLUMN ack_sent_ts TEXT"),n.has("delivery_error")||e.exec("ALTER TABLE mail_ledger ADD COLUMN delivery_error TEXT"),n.has("delivery_error_ts")||e.exec("ALTER TABLE mail_ledger ADD COLUMN delivery_error_ts TEXT")}).immediate()}function ja(e){let t=process.env.LMBEE_TEST_DB_ROOT;if(!t||e===":memory:")return;let r=[],n=Ld(e);for(;cA(n,{throwIfNoEntry:!1})===void 0;){r.unshift(uA(n));let i=qa(n);if(i===n)throw new Error("Cannot resolve test database path");n=i}let o=Ld(Id(n),...r),s=fA(Id(t),o);if(s===".."||s.startsWith("../")||s.startsWith("..\\")||dA(s))throw new Error(`Database path is outside the test database root: ${e}`)}function Cd(e){let t=o=>e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(o)!==void 0,r=o=>e.prepare(`PRAGMA table_info(${o})`).all(),n;for(let o of["queue_responses","chat_tasks","chat_messages","chat_message_task_reassignments"])if(t(o)){n=`legacy table '${o}'`;break}if(n===void 0&&t("answers")){let o=new Set(r("answers").map(s=>s.name));o.has("request_queue_id")?n="legacy column 'answers.request_queue_id'":o.has("superseded_at")||(n="legacy 'answers' shape: missing column 'superseded_at'")}if(n===void 0&&t("queue")){let o=r("queue"),s=new Set(o.map(i=>i.name));s.has("team")?n="legacy column 'queue.team'":s.has("to_id")?o.some(i=>i.name==="from_id"&&i.notnull!==1)?n="legacy 'queue' shape: from_id is still nullable":s.has("restart_nudge_sent_ts")&&(n="legacy column 'queue.restart_nudge_sent_ts'"):n="legacy 'queue' shape: missing column 'to_id'"}if(n===void 0&&t("cron_jobs")){let o=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'cron_jobs'").get();(o===void 0||!o.sql.includes("'miniplayer'"))&&(n="legacy 'cron_jobs' CHECK constraint predates 'miniplayer'")}if(n===void 0&&t("cron_jobs")){let o=e.prepare("SELECT id, action_payload FROM cron_jobs WHERE action_kind = 'enqueue'").all();for(let s of o){let i;try{i=JSON.parse(s.action_payload)}catch{i=void 0}let a=typeof i=="object"&&i!==null?i.prompt:void 0;if(typeof a!="string"||a.trim().length===0){n=`legacy 'cron_jobs' enqueue payload (id ${s.id}) predates the 'prompt' vocabulary`;break}}}if(n===void 0&&t("team_progress")&&new Set(r("team_progress").map(s=>s.name)).has("last_scan_head")&&(n="legacy column 'team_progress.last_scan_head'"),n===void 0&&t("cron_runs")&&(new Set(r("cron_runs").map(s=>s.name)).has("execution_state")||(n="legacy 'cron_runs' shape: missing column 'execution_state'")),n===void 0&&t("rate_limit_policy_log")){let o=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'rate_limit_policy_log'").get();(o===void 0||!o.sql.includes("'confirmed_would_fire_policy_disabled'"))&&(n="legacy 'rate_limit_policy_log' CHECK constraint predates 'confirmed_would_fire_policy_disabled'")}if(n===void 0&&t("rate_limit_policy_arm")&&(new Set(r("rate_limit_policy_arm").map(s=>s.name)).has("armed_used_fraction")||(n="legacy 'rate_limit_policy_arm' shape: missing column 'armed_used_fraction'")),n!==void 0)throw new Error(`Refusing to open this lmbee state.db: abandoned pre-v14 lmbee schema shape (${n}). Per the operator's 2026-10-01 shared-database decision, lmbee now shares lmctl's state.db and every pre-existing lmbee-only database is abandoned -- there is no data migration, ever. Do not remove a shared lmctl database. Check LMBEE_DB and the database ownership; point lmbee at the intended compatible database. Preserve this file for operator review.`)}var Ss=62;function Od(e){let t=e.pragma("user_version",{simple:!0});if(t<=Ss)return;let r;if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_meta'").get()!==void 0){let o=new Set(e.prepare("PRAGMA table_info(schema_meta)").all().map(s=>s.name));if(o.has("key")&&o.has("value")){let s=e.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();typeof s?.value=="string"&&(r=s.value)}}let n;if(r===void 0)n="schema_meta.min_reader_version is absent";else if(!/^[1-9]\d*$/.test(r))n=`schema_meta.min_reader_version=${JSON.stringify(r)} is malformed (not a canonical decimal integer)`;else if(Number(r)>Ss)n=`schema_meta.min_reader_version=${r} declares a breaking floor above ${Ss}`;else return;throw new Error(`Refusing to open the shared state.db: it was migrated by a newer lmctl with breaking changes (user_version=${t} exceeds the newest lmctl schema version this lmbee build understands, ${Ss}, and ${n}). Upgrade lmbee to a build that understands the newer lmctl schema before opening this database again. lmbee never writes user_version or schema_meta, so the file is untouched.`)}var Ua;function bA(){return Ua===void 0&&(Ua=[...Dd(Md,"utf8").matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/gi)].map(t=>t[1])),Ua}function SA(e,t){let r=new Set(e.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(o=>o.name)),n=bA().filter(o=>!r.has(o));if(n.length!==0)throw new Error(`Refusing a read-only open of "${t}": required lmbee schema is missing (no table${n.length===1?"":"s"}: ${n.join(", ")}), and a read-only handle cannot create it. Run any writable lmbee command (or start the daemon) once against this database to provision it, then retry.`)}function vs(e,t={}){let r=wo(e);hA(r);let n=!e&&typeof process.env.LMBEE_DB=="string"&&process.env.LMBEE_DB!=="";if(n&&gA(r,"LMBEE_DB"),ja(r),t.readOnly&&r===":memory:")throw new Error("Refusing a read-only open of ':memory:': an in-memory database starts empty on every open, so the required lmbee schema can never be present and a read-only handle cannot create it.");if(t.readOnly&&r!==":memory:"){if(!Fa(r))throw new Error(`Refusing a read-only open of "${r}": the file does not exist, so the required lmbee schema is missing. Run any writable lmbee command (or start the daemon) once against this database to provision it, then retry.`);let a=new ht(r,{readonly:!0,fileMustExist:!0});try{Cd(a),Od(a),a.pragma("busy_timeout = 5000"),SA(a,r)}catch(c){throw a.close(),c}return{path:r,db:a,close:()=>a.close()}}if(r!==":memory:"){let a=qa(r);Fa(a)||lA(a,{recursive:!0})}let o=new ht(r,n?{fileMustExist:!0}:void 0);try{Cd(o),Od(o)}catch(a){throw o.close(),a}o.pragma("journal_mode = WAL"),o.pragma("busy_timeout = 5000");let s=Dd(Md,"utf8"),i=o.transaction(()=>{_A(o),wA(o),TA(o),EA(o),yA(o),o.exec(s)});try{i.immediate()}catch(a){throw o.close(),a}return{path:r,db:o,close:()=>o.close()}}function Ue(e,t){return e.prepare("SELECT * FROM team_state WHERE team = ?").get(t)??null}function Pd(e,t){let r=Ue(e,t);return r===null?{kind:"never-observed"}:{kind:"observed",value:r,observedAt:r.last_ts,changedAt:r.changed_ts}}function ir(e,t,r,n){let o=new Date(n).toISOString(),s=Ue(e,t),i=s&&s.status===r?s.changed_ts:o;e.prepare(`INSERT INTO team_state(team, status, changed_ts, last_ts) VALUES (?, ?, ?, ?)
67
- ON CONFLICT(team) DO UPDATE SET status = excluded.status, changed_ts = excluded.changed_ts, last_ts = excluded.last_ts`).run(t,r,i,o)}function tt(e,t,r,n,o={}){e.prepare("INSERT INTO events(ts, scan, team, status, note) VALUES (?, ?, ?, ?, ?)").run(new Date(n).toISOString(),o.scan??null,t,r,o.note??null)}function As(e,t,r,n){return e.prepare("SELECT * FROM events WHERE status = ? AND ts >= ? ORDER BY id DESC LIMIT ?").all(t,r,n)}function ie(e,t){return e.prepare("SELECT * FROM team_progress WHERE team = ?").get(t)??null}function Ud(e,t,r,n,o=n){let s=ie(e,t),i=s&&s.progress_status===r?s.progress_changed_ts:o;e.prepare(`INSERT INTO team_progress(team, progress_status, progress_changed_ts, last_scan_ts)
65
+ `),1}finally{a.close()}}var xS=Pt(()=>{SS()});import{spawn as fq}from"node:child_process";import{openSync as pq,mkdirSync as hq,writeFileSync as gq}from"node:fs";import{homedir as _q}from"node:os";import{join as Td}from"node:path";import{mkdirSync as vq,readFileSync as Bv,renameSync as Aq,writeFileSync as kq}from"node:fs";import{homedir as Wv}from"node:os";import{dirname as Rq,join as vd}from"node:path";var Tq=Object.freeze({free:1e6,test:1e7});var Gr=class extends Error{code="APPKEY_NOT_FOUND";constructor(t="no lmctl appkey found; run `lmchat login` on a machine with a browser, or copy ~/.config/lmctl/appkey.json here, or set LMCTL_APPKEY"){super(t),this.name="AppkeyNotFoundError"}},sr=class extends Error{code="APPKEY_VALIDATION_ERROR";status;constructor(t,r={}){super(t),this.name="AppkeyValidationError",this.status=r.status,this.cause=r.cause}},vs=class extends Error{code="APPKEY_INVALID";source;constructor(t){super(`${t} resolved an invalid lmctl appkey`),this.name="AppkeyInvalidError",this.source=t}},As=class extends Error{code="AUTH_API_ERROR";status;constructor(t,r={}){super(t),this.name="AuthApiError",this.status=r.status,this.cause=r.cause}};var Gv="https://lmctl.ai/auth",Vv=1e4;function Pa(e){return e.length>0&&!e.includes(`
66
+ `)}function Se(e={}){let t=e.env??process.env,r=e.fs??{readFileSync:(c,l)=>Bv(c,l)},n=e.homedir??Wv,o=t.LMCTL_APPKEY?.trim();if(o&&Pa(o))return{appkey:o,source:"env:LMCTL_APPKEY",envelope:null};let s=t.LMCTL_APPKEY_FILE?.trim();if(s){let c=Ad(r,s,"env:LMCTL_APPKEY_FILE");if(c)return c}let i=Jv(t,n),a=Ad(r,i,"file:default");if(a)return a;throw new Gr}async function $d(e,t={}){let r=await Yv("/whoami",{method:"GET",headers:{authorization:`Bearer ${e}`}},t,sr);if(r.status===401)return{valid:!1};if(r.status!==200)throw new sr(`appkey validation failed with status ${r.status}`,{status:r.status});let n=await Xv(r,"validate appkey response",sr);return{valid:!0,userId:kd(n,"user_id","validate appkey response",sr),label:kd(n,"label","validate appkey response",sr)}}function Ad(e,t,r){let n;try{n=e.readFileSync(t,"utf8")}catch{return null}let o=n.trim();if(o.length===0)return null;if(o.startsWith("{")){let s;try{s=JSON.parse(o)}catch{s=void 0}if(s&&typeof s=="object"){let i=s;return typeof i.appkey=="string"&&Pa(i.appkey.trim())?{appkey:i.appkey.trim(),source:r,envelope:i}:null}}return Pa(o)?{appkey:o,source:r,envelope:null}:null}function Jv(e,t){let r=e.XDG_CONFIG_HOME?.trim()||vd(t(),".config");return vd(r,"lmctl","appkey.json")}function Kv(e){let t=e.env??process.env;return(e.authBaseUrl?.trim()||t.LMCTL_AUTH_BASE_URL?.trim()||Gv).replace(/\/+$/,"")}function zv(e,t){if(e.fetchImpl)return e.fetchImpl;if(typeof globalThis.fetch=="function")return(r,n)=>globalThis.fetch(r,n);throw new t("global fetch is unavailable; pass fetchImpl explicitly")}async function Yv(e,t,r,n){return await Qv(e,t,r,n,r.timeoutMs)}async function Qv(e,t,r,n,o,s){let i=zv(r,n),a=`${Kv(r)}${e}`,c=o??Vv,l={...t},u=new AbortController;l.signal=u.signal;let d=setTimeout(()=>{u.abort()},c);try{return await i(a,l)}catch(m){throw u.signal.aborted?s?s():new n(`auth request timed out for ${e} after ${c}ms`,{cause:m}):m instanceof n?m:new n(`auth request failed for ${e}`,{cause:m})}finally{clearTimeout(d)}}async function Xv(e,t,r){let n;try{n=await e.json()}catch(o){throw new r(`${t} was not valid JSON`,{cause:o,status:e.status})}if(!n||typeof n!="object"||Array.isArray(n))throw new r(`${t} must be a JSON object`,{status:e.status});return n}function kd(e,t,r,n){let o=e[t];if(typeof o!="string"||o.length===0)throw new n(`${r} missing string field ${t}`);return o}function Je(e){return async(...t)=>{throw new Error(`lmmail-client fake: ${e} not stubbed`)}}var Iq={listMailboxes:Je("listMailboxes"),createMailbox:Je("createMailbox"),deleteMailbox:Je("deleteMailbox"),sendMessage:Je("sendMessage"),listMessages:Je("listMessages"),getRecentMessages:Je("getRecentMessages"),getMessage:Je("getMessage"),getMessageMetadata:Je("getMessageMetadata"),getThread:Je("getThread"),download:Je("download"),deleteMessage:Je("deleteMessage"),registerSite:Je("registerSite"),resolveSite:Je("resolveSite"),listSites:Je("listSites"),setSiteName:Je("setSiteName"),deleteSiteName:Je("deleteSiteName"),deleteSite:Je("deleteSite")};var Ft=class extends Error{status;code;responseBody;constructor(t,r,n,o){super(`${t}: HTTP ${r}${o?` ${o}`:n?` ${n}`:""}`),this.name="LmmailHttpError",this.status=r,this.code=o,this.responseBody=n}};function pt(e){let t=e.apiUrl.replace(/\/+$/,"");if(!t)throw new Error("lmmail API URL is required");if(!e.appkey)throw new Error("lmmail appkey is required");let r=e.fetch??fetch,n={authorization:`Bearer ${e.appkey}`};async function o($={}){return(await S(`${t}/mailboxes${$.withCounts?"?with_counts=1":""}`,{headers:n},"list mailboxes failed")).mailboxes}async function s($,L={}){let R=await r(`${t}/mailboxes`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({mailbox_name:$})});if(R.status===409){let H=await R.text().catch(()=>"");if(L.tolerate409!==!1&&Ld(H)==="mailbox_exists")return;throw Nd("create mailbox failed",R.status,H)}await N(R,"create mailbox failed")}async function i($){return S(`${t}/mailboxes/${encodeURIComponent($)}`,{method:"DELETE",headers:n},"delete mailbox failed")}async function a($){let L=$.attachments??[],R=await S(`${t}/mailboxes/${encodeURIComponent($.mailbox)}/messages`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({...$.subject===void 0?{}:{subject:$.subject},body:xd($.body),attachments:L.map(xd)})},"allocate message failed"),H=[{target:R.body,bytes:$.body.bytes},...R.attachments.map((C,g)=>({target:C,bytes:L[g].bytes}))];for(let{target:C,bytes:g}of H){let y=new FormData;for(let[P,J]of Object.entries(C.fields))y.append(P,J);y.append("file",new Blob([new Uint8Array(g)],{type:C.content_type}),C.name);let x=await r(C.upload_url,{method:"POST",body:y});await N(x,`upload failed for ${C.name}`)}return await S(Zv(t,R.finalize_url),{method:"POST",headers:n},"finalize message failed"),R.seq}async function c($,L={}){let R=new URLSearchParams;if(L.status&&R.set("status",L.status),L.after!==void 0&&R.set("after",String(L.after)),L.wait_s!==void 0){if(!Number.isInteger(L.wait_s)||L.wait_s<0||L.wait_s>20)throw new Error("wait_s must be an integer from 0 through 20");R.set("wait_s",String(L.wait_s))}let H=R.size>0?`?${R.toString()}`:"",C=await S(`${t}/mailboxes/${encodeURIComponent($)}/messages${H}`,{headers:n},"list messages failed");return{messages:C.messages,next_after:C.next_after}}async function l($={}){let L=new URLSearchParams;if($.limit!==void 0){if(!Number.isInteger($.limit)||$.limit<1||$.limit>50)throw new Error("limit must be an integer from 1 through 50");L.set("limit",String($.limit))}let R=L.size>0?`?${L.toString()}`:"";return S(`${t}/messages/recent${R}`,{headers:n},"get recent messages failed")}async function u($,L){return S(`${t}/mailboxes/${encodeURIComponent($)}/messages/${L}`,{headers:n},"get message failed")}async function d($,L){let R=await u($,L);return{...R,body:Rd(R.body),attachments:R.attachments.map(Rd)}}async function m($,L){return S(`${t}/mailboxes/${encodeURIComponent($)}/messages/${L}/thread`,{headers:n},"get thread failed")}async function f($){let L=await r($);return await N(L,"download failed"),new Uint8Array(await L.arrayBuffer())}async function p($,L){await S(`${t}/mailboxes/${encodeURIComponent($)}/messages/${L}`,{method:"DELETE",headers:n},"delete message failed")}async function h($,L,R){return await S(`${t}/sites`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site_name:$,site_uuid:L,mailbox:R})},"register site failed")}async function w($){return await S(`${t}/sites/${encodeURIComponent($)}`,{headers:n},"resolve site failed")}async function _($={}){let L=new URLSearchParams;if($.cursor!==void 0&&L.set("cursor",$.cursor),$.limit!==void 0){if(!Number.isInteger($.limit)||$.limit<1||$.limit>50)throw new Error("limit must be an integer from 1 through 50");L.set("limit",String($.limit))}let R=L.size>0?`?${L.toString()}`:"";return S(`${t}/sites${R}`,{headers:n},"list sites failed")}async function T($,L){return S(`${t}/sites/name`,{method:"PUT",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site:$,name:L})},"set site name failed")}async function E($){return S(`${t}/sites/name`,{method:"DELETE",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site:$})},"delete site name failed")}async function v($){await S(`${t}/sites/${encodeURIComponent($)}`,{method:"DELETE",headers:n},"delete site failed")}async function S($,L,R){let H=await r($,L);await N(H,R);try{return await H.json()}catch(C){throw new Error(`${R}: invalid JSON response: ${eA(C)}`)}}async function N($,L){if($.ok)return;let R=await $.text().catch(()=>"");throw Nd(L,$.status,R)}return{listMailboxes:o,createMailbox:s,deleteMailbox:i,sendMessage:a,listMessages:c,getRecentMessages:l,getMessage:u,getMessageMetadata:d,getThread:m,download:f,deleteMessage:p,registerSite:h,resolveSite:w,listSites:_,setSiteName:T,deleteSiteName:E,deleteSite:v}}function xd(e){return{name:e.name,size:e.bytes.byteLength,content_type:e.contentType}}function Rd(e){return{name:e.name,size:e.size,content_type:e.content_type}}function Nd(e,t,r){return new Ft(e,t,r,Ld(r))}function Ld(e){try{let t=JSON.parse(e);return typeof t.error=="string"?t.error:void 0}catch{return}}function Zv(e,t){return/^https?:\/\//i.test(t)?t:`${e}${t.startsWith("/")?"":"/"}${t}`}function eA(e){return e instanceof Error?e.message:String(e)}import{execFile as RA}from"node:child_process";import{existsSync as NA}from"node:fs";import{join as LA}from"node:path";import{promisify as IA}from"node:util";import{existsSync as Id}from"node:fs";import{createRequire as tA}from"node:module";import{dirname as rA}from"node:path";var Ua=null;function nA(){return Ua===null&&(Ua=tA(import.meta.url)("node:sqlite").DatabaseSync),Ua}var oA={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"},sA={261:"SQLITE_BUSY_RECOVERY",517:"SQLITE_BUSY_SNAPSHOT",773:"SQLITE_BUSY_TIMEOUT",262:"SQLITE_LOCKED_SHAREDCACHE",518:"SQLITE_LOCKED_VTAB",264:"SQLITE_READONLY_RECOVERY",520:"SQLITE_READONLY_CANTLOCK",776:"SQLITE_READONLY_ROLLBACK",1032:"SQLITE_READONLY_DBMOVED",1288:"SQLITE_READONLY_CANTINIT",1544:"SQLITE_READONLY_DIRECTORY",270:"SQLITE_CANTOPEN_NOTEMPDIR",526:"SQLITE_CANTOPEN_ISDIR",782:"SQLITE_CANTOPEN_FULLPATH",1038:"SQLITE_CANTOPEN_CONVPATH",1294:"SQLITE_CANTOPEN_DIRTYWAL",1550:"SQLITE_CANTOPEN_SYMLINK",275:"SQLITE_CONSTRAINT_CHECK",531:"SQLITE_CONSTRAINT_COMMITHOOK",787:"SQLITE_CONSTRAINT_FOREIGNKEY",1043:"SQLITE_CONSTRAINT_FUNCTION",1299:"SQLITE_CONSTRAINT_NOTNULL",1555:"SQLITE_CONSTRAINT_PRIMARYKEY",1811:"SQLITE_CONSTRAINT_TRIGGER",2067:"SQLITE_CONSTRAINT_UNIQUE",2323:"SQLITE_CONSTRAINT_VTAB",2579:"SQLITE_CONSTRAINT_ROWID",2835:"SQLITE_CONSTRAINT_PINNED",3091:"SQLITE_CONSTRAINT_DATATYPE"};function iA(e){return sA[e]??oA[e&255]??`SQLITE_UNKNOWN_${e}`}var aA="SQLite3 can only bind numbers, strings, bigints, buffers, and null";function qt(e){if(e!==null&&typeof e=="object"){let t=e;if(typeof t.errcode=="number")throw t.code=iA(t.errcode),e;if(t.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(t.message)))throw new TypeError(aA);if(t.code==="ERR_INVALID_STATE"&&/database is not open/.test(String(t.message)))throw new TypeError("The database connection is not open")}throw e}function cA(){let e="unable to open database file";return Object.assign(new Error(e),{code:"SQLITE_CANTOPEN",errcode:14,errstr:e})}function Cd(e){return e instanceof Uint8Array&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function lA(e){if(e==null)return e;if(Array.isArray(e))return e.map(Cd);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=Cd(n);return t}return e}function uA(e){if(e===null||typeof e!="object"||Array.isArray(e)||e instanceof Uint8Array)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ks(e){return e.map((t,r)=>{if(t===void 0)return null;if(r===0&&uA(t)){let n={};for(let[o,s]of Object.entries(t))n[o]=s===void 0?null:s;return n}return t})}var Fa=class{handle;pluckMode=!1;arrayMode=!1;constructor(t){this.handle=t,this.handle.setAllowBareNamedParameters(!0),this.handle.setAllowUnknownNamedParameters(!0)}get source(){return this.handle.sourceSQL}run(...t){try{let r=this.handle.run(...ks(t));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){qt(r)}}get(...t){try{return this.project(this.handle.get(...ks(t)))}catch(r){qt(r)}}all(...t){try{return this.handle.all(...ks(t)).map(r=>this.project(r))}catch(r){qt(r)}}*iterate(...t){let r;try{r=this.handle.iterate(...ks(t))}catch(n){qt(n)}for(;;){let n;try{n=r.next()}catch(o){qt(o)}if(n.done)return;yield this.project(n.value)}}raw(t=!0){return this.arrayMode=t,this.handle.setReturnArrays(t||this.pluckMode),this}pluck(t=!0){return this.pluckMode=t,this.handle.setReturnArrays(t||this.arrayMode),this}project(t){let r=lA(t);return this.pluckMode&&Array.isArray(r)?r[0]:r}},qa=class{name;memory;readonly;handle;savepointId=0;constructor(t,r={}){let n=t===":memory:"||t==="";if(r.readonly===!0&&n)throw new TypeError("In-memory/temporary databases cannot be readonly");if(!n&&!Id(rA(t)))throw new TypeError("Cannot open database because the directory does not exist");if(r.fileMustExist===!0&&!n&&!Id(t))throw cA();this.name=t,this.memory=n,this.readonly=r.readonly===!0;try{this.handle=new(nA())(t,{readOnly:this.readonly,timeout:r.timeout??5e3,enableForeignKeyConstraints:r.foreignKeys??!0})}catch(o){qt(o)}}get open(){return this.handle.isOpen}get inTransaction(){return this.handle.isTransaction}prepare(t){try{return new Fa(this.handle.prepare(t))}catch(r){qt(r)}}exec(t){try{return this.handle.exec(t),this}catch(r){qt(r)}}pragma(t,r){let n=this.prepare(`PRAGMA ${t}`);return r?.simple===!0?n.pluck().get():n.all()}transaction(t){let r=o=>(...s)=>this.runTransaction(o,t,s),n=r("BEGIN");return n.default=r("BEGIN"),n.deferred=r("BEGIN DEFERRED"),n.immediate=r("BEGIN IMMEDIATE"),n.exclusive=r("BEGIN EXCLUSIVE"),n}serialize(){try{let t=this.handle.serialize();return Buffer.from(t.buffer,t.byteOffset,t.byteLength)}catch(t){qt(t)}}close(){if(!this.handle.isOpen)return this;try{return this.handle.close(),this}catch(t){qt(t)}}runTransaction(t,r,n){if(!this.inTransaction){this.exec(t);try{let s=r(...n);return this.exec("COMMIT"),s}catch(s){if(this.inTransaction)try{this.exec("ROLLBACK")}catch(i){if(!dA(i))throw i}throw s}}let o=`lmbee_sp_${this.savepointId+=1}`;this.exec(`SAVEPOINT ${o}`);try{let s=r(...n);return this.exec(`RELEASE ${o}`),s}catch(s){if(this.inTransaction)try{this.exec(`ROLLBACK TO ${o}`),this.exec(`RELEASE ${o}`)}catch(i){if(!mA(i))throw i}throw s}}};function dA(e){return e instanceof Error&&/cannot rollback - no transaction is active/i.test(e.message)}function mA(e){return e instanceof Error&&/no such savepoint:/i.test(e.message)}var ht=qa;import{existsSync as Ha,lstatSync as fA,mkdirSync as pA,readFileSync as Ud,realpathSync as Od}from"node:fs";import{basename as hA,dirname as Ba,isAbsolute as gA,join as _A,relative as wA,resolve as Dd}from"node:path";import{fileURLToPath as yA}from"node:url";var Fd=_A(Ba(yA(import.meta.url)),"schema.sql");function Eo(e){if(e!==void 0&&e!=="")return e;let t=process.env.LMBEE_DB;if(t)return t;throw new Error("No lmbee database selected: pass an explicit database path or set LMBEE_DB to the intended existing database. The retired ~/.lmbee/state.db default is no longer used.")}function EA(e){if(e.startsWith("~"))throw new Error(`Refusing to open the lmbee database at "${e}": lmbee does not expand "~" in database paths, so this would be created as a literal directory named "~" under the current working directory. Use an absolute path instead (for example ~/.lmbee/state.db). Note for systemd units: Environment= expands neither "~" nor "$HOME", so write the absolute path literally there too.`)}function TA(e,t){if(!(e===":memory:"||Ha(e)))throw new Error(`Refusing to create the lmbee database at "${e}": ${t} points at non-existent "${e}", and a typo is indistinguishable from a fresh install. To provision a new database here, \`touch "${e}"\` first, then retry, or point ${t} at an existing database.`)}function bA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(queue)").all();if(r.length===0)return;let n=new Set(r.map(s=>s.name));n.has("subject_id")||e.exec("ALTER TABLE queue ADD COLUMN subject_id TEXT"),n.has("dedupe_key")||e.exec("ALTER TABLE queue ADD COLUMN dedupe_key TEXT"),e.prepare(`SELECT name FROM pragma_index_list('queue') WHERE "unique" = 1 AND partial = 0`).all().some(s=>{let i=e.prepare("SELECT name FROM pragma_index_info(?) ORDER BY seqno").all(s.name);return i.length===1&&i[0].name==="dedupe_key"})||e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_queue_dedupe_key ON queue(dedupe_key)"),n.has("delivered_via_escalation")||e.exec("ALTER TABLE queue ADD COLUMN delivered_via_escalation INTEGER NOT NULL DEFAULT 0"),n.has("escalation_claimed_ts")||e.exec("ALTER TABLE queue ADD COLUMN escalation_claimed_ts TEXT"),n.has("escalation_claim_token")||e.exec("ALTER TABLE queue ADD COLUMN escalation_claim_token TEXT"),n.has("escalation_only")||e.exec("ALTER TABLE queue ADD COLUMN escalation_only INTEGER NOT NULL DEFAULT 0"),n.has("admission_fingerprint")||e.exec("ALTER TABLE queue ADD COLUMN admission_fingerprint TEXT"),n.has("expects_response")||e.exec("ALTER TABLE queue ADD COLUMN expects_response INTEGER NOT NULL DEFAULT 0"),n.has("to_alias")||e.exec("ALTER TABLE queue ADD COLUMN to_alias TEXT"),n.has("retracted_ts")||e.exec("ALTER TABLE queue ADD COLUMN retracted_ts TEXT"),n.has("retracted_reason")||e.exec("ALTER TABLE queue ADD COLUMN retracted_reason TEXT"),n.has("retraction_notice")||e.exec("ALTER TABLE queue ADD COLUMN retraction_notice INTEGER NOT NULL DEFAULT 0"),n.has("in_reply_to")||e.exec("ALTER TABLE queue ADD COLUMN in_reply_to INTEGER"),n.has("operator_priority")||e.exec("ALTER TABLE queue ADD COLUMN operator_priority INTEGER NOT NULL DEFAULT 0"),n.has("merged_into_id")||e.exec("ALTER TABLE queue ADD COLUMN merged_into_id INTEGER")}).immediate()}function SA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(team_progress)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("last_miniplayer_reply_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN last_miniplayer_reply_hash TEXT"),n.has("blocked_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN blocked_surfaced_ts TEXT"),n.has("last_escalation_attempt_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN last_escalation_attempt_ts TEXT"),n.has("escalation_attempt_count")||e.exec("ALTER TABLE team_progress ADD COLUMN escalation_attempt_count INTEGER NOT NULL DEFAULT 0"),n.has("fault_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN fault_surfaced_ts TEXT"),n.has("epic_closed_surfaced_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN epic_closed_surfaced_ts TEXT"),n.has("quota_exhausted_last_seen_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN quota_exhausted_last_seen_ts TEXT"),n.has("quota_exhausted_message")||e.exec("ALTER TABLE team_progress ADD COLUMN quota_exhausted_message TEXT"),n.has("miniplayer_verdict_label")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_label TEXT"),n.has("miniplayer_verdict_reason")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_reason TEXT"),n.has("miniplayer_verdict_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_ts TEXT"),n.has("miniplayer_verdict_input_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_input_hash TEXT"),n.has("miniplayer_verdict_structural_hash")||e.exec("ALTER TABLE team_progress ADD COLUMN miniplayer_verdict_structural_hash TEXT"),n.has("holder_watch_pid")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_pid INTEGER"),n.has("holder_watch_started_at")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_started_at TEXT"),n.has("holder_watch_cpu_ticks")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_cpu_ticks INTEGER"),n.has("holder_watch_observed_at")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_observed_at TEXT"),n.has("holder_watch_low_cpu_streak")||e.exec("ALTER TABLE team_progress ADD COLUMN holder_watch_low_cpu_streak INTEGER"),n.has("hung_holder_flagged_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN hung_holder_flagged_ts TEXT"),n.has("hung_holder_reason")||e.exec("ALTER TABLE team_progress ADD COLUMN hung_holder_reason TEXT"),n.has("last_cli_activity_ts")||e.exec("ALTER TABLE team_progress ADD COLUMN last_cli_activity_ts TEXT")}).immediate()}function vA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(cron_jobs)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("last_fire_error")||e.exec("ALTER TABLE cron_jobs ADD COLUMN last_fire_error TEXT"),n.has("running_systemd_unit")||e.exec("ALTER TABLE cron_jobs ADD COLUMN running_systemd_unit TEXT"),n.has("timezone")||e.exec("ALTER TABLE cron_jobs ADD COLUMN timezone TEXT"),n.has("provider")||e.exec("ALTER TABLE cron_jobs ADD COLUMN provider TEXT"),n.has("model")||e.exec("ALTER TABLE cron_jobs ADD COLUMN model TEXT"),n.has("working_directory")||e.exec("ALTER TABLE cron_jobs ADD COLUMN working_directory TEXT"),n.has("escalation_owner")||e.exec("ALTER TABLE cron_jobs ADD COLUMN escalation_owner TEXT"),n.has("session_teamfile")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_teamfile TEXT"),n.has("session_alias")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_alias TEXT"),n.has("session_seeded_at")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_seeded_at TEXT"),n.has("session_generation")||e.exec("ALTER TABLE cron_jobs ADD COLUMN session_generation INTEGER NOT NULL DEFAULT 0")}).immediate()}function AA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(entities)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("delivered_ts")||e.exec("ALTER TABLE entities ADD COLUMN delivered_ts TEXT"),n.has("review_time")||e.exec("ALTER TABLE entities ADD COLUMN review_time TEXT"),n.has("needs_review")||e.exec("ALTER TABLE entities ADD COLUMN needs_review INTEGER NOT NULL DEFAULT 0 CHECK(needs_review IN (0,1))"),n.has("review_reason")||e.exec("ALTER TABLE entities ADD COLUMN review_reason TEXT"),n.has("review_input_hash")||e.exec("ALTER TABLE entities ADD COLUMN review_input_hash TEXT"),n.has("hold_until")||e.exec("ALTER TABLE entities ADD COLUMN hold_until TEXT"),n.has("hold_reason")||e.exec("ALTER TABLE entities ADD COLUMN hold_reason TEXT"),n.has("blocked_on")||e.exec("ALTER TABLE entities ADD COLUMN blocked_on TEXT")}).immediate()}function kA(e){e.transaction(()=>{let r=e.prepare("PRAGMA table_info(mail_ledger)").all();if(r.length===0)return;let n=new Set(r.map(o=>o.name));n.has("ack_sent_ts")||e.exec("ALTER TABLE mail_ledger ADD COLUMN ack_sent_ts TEXT"),n.has("delivery_error")||e.exec("ALTER TABLE mail_ledger ADD COLUMN delivery_error TEXT"),n.has("delivery_error_ts")||e.exec("ALTER TABLE mail_ledger ADD COLUMN delivery_error_ts TEXT")}).immediate()}function Wa(e){let t=process.env.LMBEE_TEST_DB_ROOT;if(!t||e===":memory:")return;let r=[],n=Dd(e);for(;fA(n,{throwIfNoEntry:!1})===void 0;){r.unshift(hA(n));let i=Ba(n);if(i===n)throw new Error("Cannot resolve test database path");n=i}let o=Dd(Od(n),...r),s=wA(Od(t),o);if(s===".."||s.startsWith("../")||s.startsWith("..\\")||gA(s))throw new Error(`Database path is outside the test database root: ${e}`)}function Md(e){let t=o=>e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(o)!==void 0,r=o=>e.prepare(`PRAGMA table_info(${o})`).all(),n;for(let o of["queue_responses","chat_tasks","chat_messages","chat_message_task_reassignments"])if(t(o)){n=`legacy table '${o}'`;break}if(n===void 0&&t("answers")){let o=new Set(r("answers").map(s=>s.name));o.has("request_queue_id")?n="legacy column 'answers.request_queue_id'":o.has("superseded_at")||(n="legacy 'answers' shape: missing column 'superseded_at'")}if(n===void 0&&t("queue")){let o=r("queue"),s=new Set(o.map(i=>i.name));s.has("team")?n="legacy column 'queue.team'":s.has("to_id")?o.some(i=>i.name==="from_id"&&i.notnull!==1)?n="legacy 'queue' shape: from_id is still nullable":s.has("restart_nudge_sent_ts")&&(n="legacy column 'queue.restart_nudge_sent_ts'"):n="legacy 'queue' shape: missing column 'to_id'"}if(n===void 0&&t("cron_jobs")){let o=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'cron_jobs'").get();(o===void 0||!o.sql.includes("'miniplayer'"))&&(n="legacy 'cron_jobs' CHECK constraint predates 'miniplayer'")}if(n===void 0&&t("cron_jobs")){let o=e.prepare("SELECT id, action_payload FROM cron_jobs WHERE action_kind = 'enqueue'").all();for(let s of o){let i;try{i=JSON.parse(s.action_payload)}catch{i=void 0}let a=typeof i=="object"&&i!==null?i.prompt:void 0;if(typeof a!="string"||a.trim().length===0){n=`legacy 'cron_jobs' enqueue payload (id ${s.id}) predates the 'prompt' vocabulary`;break}}}if(n===void 0&&t("team_progress")&&new Set(r("team_progress").map(s=>s.name)).has("last_scan_head")&&(n="legacy column 'team_progress.last_scan_head'"),n===void 0&&t("cron_runs")&&(new Set(r("cron_runs").map(s=>s.name)).has("execution_state")||(n="legacy 'cron_runs' shape: missing column 'execution_state'")),n===void 0&&t("rate_limit_policy_log")){let o=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'rate_limit_policy_log'").get();(o===void 0||!o.sql.includes("'confirmed_would_fire_policy_disabled'"))&&(n="legacy 'rate_limit_policy_log' CHECK constraint predates 'confirmed_would_fire_policy_disabled'")}if(n===void 0&&t("rate_limit_policy_arm")&&(new Set(r("rate_limit_policy_arm").map(s=>s.name)).has("armed_used_fraction")||(n="legacy 'rate_limit_policy_arm' shape: missing column 'armed_used_fraction'")),n!==void 0)throw new Error(`Refusing to open this lmbee state.db: abandoned pre-v14 lmbee schema shape (${n}). Per the operator's 2026-10-01 shared-database decision, lmbee now shares lmctl's state.db and every pre-existing lmbee-only database is abandoned -- there is no data migration, ever. Do not remove a shared lmctl database. Check LMBEE_DB and the database ownership; point lmbee at the intended compatible database. Preserve this file for operator review.`)}var $s=62;function Pd(e){let t=e.pragma("user_version",{simple:!0});if(t<=$s)return;let r;if(e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_meta'").get()!==void 0){let o=new Set(e.prepare("PRAGMA table_info(schema_meta)").all().map(s=>s.name));if(o.has("key")&&o.has("value")){let s=e.prepare("SELECT value FROM schema_meta WHERE key = 'min_reader_version'").get();typeof s?.value=="string"&&(r=s.value)}}let n;if(r===void 0)n="schema_meta.min_reader_version is absent";else if(!/^[1-9]\d*$/.test(r))n=`schema_meta.min_reader_version=${JSON.stringify(r)} is malformed (not a canonical decimal integer)`;else if(Number(r)>$s)n=`schema_meta.min_reader_version=${r} declares a breaking floor above ${$s}`;else return;throw new Error(`Refusing to open the shared state.db: it was migrated by a newer lmctl with breaking changes (user_version=${t} exceeds the newest lmctl schema version this lmbee build understands, ${$s}, and ${n}). Upgrade lmbee to a build that understands the newer lmctl schema before opening this database again. lmbee never writes user_version or schema_meta, so the file is untouched.`)}var ja;function $A(){return ja===void 0&&(ja=[...Ud(Fd,"utf8").matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/gi)].map(t=>t[1])),ja}function xA(e,t){let r=new Set(e.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(o=>o.name)),n=$A().filter(o=>!r.has(o));if(n.length!==0)throw new Error(`Refusing a read-only open of "${t}": required lmbee schema is missing (no table${n.length===1?"":"s"}: ${n.join(", ")}), and a read-only handle cannot create it. Run any writable lmbee command (or start the daemon) once against this database to provision it, then retry.`)}function xs(e,t={}){let r=Eo(e);EA(r);let n=!e&&typeof process.env.LMBEE_DB=="string"&&process.env.LMBEE_DB!=="";if(n&&TA(r,"LMBEE_DB"),Wa(r),t.readOnly&&r===":memory:")throw new Error("Refusing a read-only open of ':memory:': an in-memory database starts empty on every open, so the required lmbee schema can never be present and a read-only handle cannot create it.");if(t.readOnly&&r!==":memory:"){if(!Ha(r))throw new Error(`Refusing a read-only open of "${r}": the file does not exist, so the required lmbee schema is missing. Run any writable lmbee command (or start the daemon) once against this database to provision it, then retry.`);let a=new ht(r,{readonly:!0,fileMustExist:!0});try{Md(a),Pd(a),a.pragma("busy_timeout = 5000"),xA(a,r)}catch(c){throw a.close(),c}return{path:r,db:a,close:()=>a.close()}}if(r!==":memory:"){let a=Ba(r);Ha(a)||pA(a,{recursive:!0})}let o=new ht(r,n?{fileMustExist:!0}:void 0);try{Md(o),Pd(o)}catch(a){throw o.close(),a}o.pragma("journal_mode = WAL"),o.pragma("busy_timeout = 5000");let s=Ud(Fd,"utf8"),i=o.transaction(()=>{bA(o),SA(o),kA(o),AA(o),vA(o),o.exec(s)});try{i.immediate()}catch(a){throw o.close(),a}return{path:r,db:o,close:()=>o.close()}}function Ue(e,t){return e.prepare("SELECT * FROM team_state WHERE team = ?").get(t)??null}function qd(e,t){let r=Ue(e,t);return r===null?{kind:"never-observed"}:{kind:"observed",value:r,observedAt:r.last_ts,changedAt:r.changed_ts}}function ir(e,t,r,n){let o=new Date(n).toISOString(),s=Ue(e,t),i=s&&s.status===r?s.changed_ts:o;e.prepare(`INSERT INTO team_state(team, status, changed_ts, last_ts) VALUES (?, ?, ?, ?)
67
+ ON CONFLICT(team) DO UPDATE SET status = excluded.status, changed_ts = excluded.changed_ts, last_ts = excluded.last_ts`).run(t,r,i,o)}function tt(e,t,r,n,o={}){e.prepare("INSERT INTO events(ts, scan, team, status, note) VALUES (?, ?, ?, ?, ?)").run(new Date(n).toISOString(),o.scan??null,t,r,o.note??null)}function Rs(e,t,r,n){return e.prepare("SELECT * FROM events WHERE status = ? AND ts >= ? ORDER BY id DESC LIMIT ?").all(t,r,n)}function ie(e,t){return e.prepare("SELECT * FROM team_progress WHERE team = ?").get(t)??null}function jd(e,t,r,n,o=n){let s=ie(e,t),i=s&&s.progress_status===r?s.progress_changed_ts:o;e.prepare(`INSERT INTO team_progress(team, progress_status, progress_changed_ts, last_scan_ts)
68
68
  VALUES (?, ?, ?, ?)
69
69
  ON CONFLICT(team) DO UPDATE SET
70
70
  progress_status = excluded.progress_status,
71
71
  progress_changed_ts = excluded.progress_changed_ts,
72
- last_scan_ts = excluded.last_scan_ts`).run(t,r,i,n)}function Ha(e,t,r){e.prepare(`INSERT INTO team_progress(team, confirmed_done_ts) VALUES (?, ?)
73
- ON CONFLICT(team) DO UPDATE SET confirmed_done_ts = excluded.confirmed_done_ts`).run(t,r)}function Fd(e,t,r){e.prepare(`INSERT INTO team_progress(team, surfaced_ts) VALUES (?, ?)
74
- ON CONFLICT(team) DO UPDATE SET surfaced_ts = excluded.surfaced_ts`).run(t,r)}function qd(e,t,r){e.prepare(`INSERT INTO team_progress(team, blocked_surfaced_ts) VALUES (?, ?)
75
- ON CONFLICT(team) DO UPDATE SET blocked_surfaced_ts = excluded.blocked_surfaced_ts`).run(t,r)}function jd(e,t,r){e.prepare(`INSERT INTO team_progress(team, fault_surfaced_ts) VALUES (?, ?)
76
- ON CONFLICT(team) DO UPDATE SET fault_surfaced_ts = excluded.fault_surfaced_ts`).run(t,r)}function Hd(e,t,r){e.prepare(`INSERT INTO team_progress(team, epic_closed_surfaced_ts) VALUES (?, ?)
77
- ON CONFLICT(team) DO UPDATE SET epic_closed_surfaced_ts = excluded.epic_closed_surfaced_ts`).run(t,r)}function Bd(e,t,r,n,o,s,i){e.prepare(`INSERT INTO team_progress(team, miniplayer_verdict_label, miniplayer_verdict_reason, miniplayer_verdict_ts, miniplayer_verdict_input_hash, miniplayer_verdict_structural_hash)
72
+ last_scan_ts = excluded.last_scan_ts`).run(t,r,i,n)}function Ga(e,t,r){e.prepare(`INSERT INTO team_progress(team, confirmed_done_ts) VALUES (?, ?)
73
+ ON CONFLICT(team) DO UPDATE SET confirmed_done_ts = excluded.confirmed_done_ts`).run(t,r)}function Hd(e,t,r){e.prepare(`INSERT INTO team_progress(team, surfaced_ts) VALUES (?, ?)
74
+ ON CONFLICT(team) DO UPDATE SET surfaced_ts = excluded.surfaced_ts`).run(t,r)}function Bd(e,t,r){e.prepare(`INSERT INTO team_progress(team, blocked_surfaced_ts) VALUES (?, ?)
75
+ ON CONFLICT(team) DO UPDATE SET blocked_surfaced_ts = excluded.blocked_surfaced_ts`).run(t,r)}function Wd(e,t,r){e.prepare(`INSERT INTO team_progress(team, fault_surfaced_ts) VALUES (?, ?)
76
+ ON CONFLICT(team) DO UPDATE SET fault_surfaced_ts = excluded.fault_surfaced_ts`).run(t,r)}function Gd(e,t,r){e.prepare(`INSERT INTO team_progress(team, epic_closed_surfaced_ts) VALUES (?, ?)
77
+ ON CONFLICT(team) DO UPDATE SET epic_closed_surfaced_ts = excluded.epic_closed_surfaced_ts`).run(t,r)}function Vd(e,t,r,n,o,s,i){e.prepare(`INSERT INTO team_progress(team, miniplayer_verdict_label, miniplayer_verdict_reason, miniplayer_verdict_ts, miniplayer_verdict_input_hash, miniplayer_verdict_structural_hash)
78
78
  VALUES (?, ?, ?, ?, ?, ?)
79
79
  ON CONFLICT(team) DO UPDATE SET
80
80
  miniplayer_verdict_label = excluded.miniplayer_verdict_label,
81
81
  miniplayer_verdict_reason = excluded.miniplayer_verdict_reason,
82
82
  miniplayer_verdict_ts = excluded.miniplayer_verdict_ts,
83
83
  miniplayer_verdict_input_hash = excluded.miniplayer_verdict_input_hash,
84
- miniplayer_verdict_structural_hash = excluded.miniplayer_verdict_structural_hash`).run(t,r,n,o,s,i)}function Wd(e,t){e.prepare("UPDATE team_progress SET miniplayer_verdict_label = NULL, miniplayer_verdict_reason = NULL, miniplayer_verdict_ts = NULL, miniplayer_verdict_input_hash = NULL, miniplayer_verdict_structural_hash = NULL WHERE team = ?").run(t)}function Ba(e,t,r,n,o,s,i){e.prepare(`INSERT INTO team_progress(team, holder_watch_pid, holder_watch_started_at, holder_watch_cpu_ticks, holder_watch_observed_at, holder_watch_low_cpu_streak)
84
+ miniplayer_verdict_structural_hash = excluded.miniplayer_verdict_structural_hash`).run(t,r,n,o,s,i)}function Jd(e,t){e.prepare("UPDATE team_progress SET miniplayer_verdict_label = NULL, miniplayer_verdict_reason = NULL, miniplayer_verdict_ts = NULL, miniplayer_verdict_input_hash = NULL, miniplayer_verdict_structural_hash = NULL WHERE team = ?").run(t)}function Va(e,t,r,n,o,s,i){e.prepare(`INSERT INTO team_progress(team, holder_watch_pid, holder_watch_started_at, holder_watch_cpu_ticks, holder_watch_observed_at, holder_watch_low_cpu_streak)
85
85
  VALUES (?, ?, ?, ?, ?, ?)
86
86
  ON CONFLICT(team) DO UPDATE SET
87
87
  holder_watch_pid = excluded.holder_watch_pid,
88
88
  holder_watch_started_at = excluded.holder_watch_started_at,
89
89
  holder_watch_cpu_ticks = excluded.holder_watch_cpu_ticks,
90
90
  holder_watch_observed_at = excluded.holder_watch_observed_at,
91
- holder_watch_low_cpu_streak = excluded.holder_watch_low_cpu_streak`).run(t,r,n,o,s,i)}function Wa(e,t,r,n){e.prepare(`INSERT INTO team_progress(team, hung_holder_flagged_ts, hung_holder_reason)
91
+ holder_watch_low_cpu_streak = excluded.holder_watch_low_cpu_streak`).run(t,r,n,o,s,i)}function Ja(e,t,r,n){e.prepare(`INSERT INTO team_progress(team, hung_holder_flagged_ts, hung_holder_reason)
92
92
  VALUES (?, ?, ?)
93
93
  ON CONFLICT(team) DO UPDATE SET
94
94
  hung_holder_flagged_ts = excluded.hung_holder_flagged_ts,
95
- hung_holder_reason = excluded.hung_holder_reason`).run(t,n,r)}function Ga(e,t){e.prepare(`INSERT INTO team_progress(team, holder_watch_pid, holder_watch_started_at, holder_watch_cpu_ticks, holder_watch_observed_at, holder_watch_low_cpu_streak, hung_holder_flagged_ts, hung_holder_reason)
95
+ hung_holder_reason = excluded.hung_holder_reason`).run(t,n,r)}function Ka(e,t){e.prepare(`INSERT INTO team_progress(team, holder_watch_pid, holder_watch_started_at, holder_watch_cpu_ticks, holder_watch_observed_at, holder_watch_low_cpu_streak, hung_holder_flagged_ts, hung_holder_reason)
96
96
  VALUES (?, NULL, NULL, NULL, NULL, NULL, NULL, NULL)
97
97
  ON CONFLICT(team) DO UPDATE SET
98
98
  holder_watch_pid = NULL,
@@ -101,103 +101,103 @@ Appkey saved to ${p.appkeyPath} (0600)
101
101
  holder_watch_observed_at = NULL,
102
102
  holder_watch_low_cpu_streak = NULL,
103
103
  hung_holder_flagged_ts = NULL,
104
- hung_holder_reason = NULL`).run(t)}function Gd(e,t,r,n,o){e.prepare(`INSERT INTO auto_nudge_suspended(team, reason, detail, suspended_at) VALUES (?, ?, ?, ?)
105
- ON CONFLICT(team) DO UPDATE SET reason = excluded.reason, detail = excluded.detail, suspended_at = excluded.suspended_at`).run(t,r,n,o)}function Vd(e,t){e.prepare("DELETE FROM auto_nudge_suspended WHERE team = ?").run(t)}function Jd(e){return e.prepare("SELECT * FROM auto_nudge_suspended ORDER BY team").all()}function Kd(e,t,r){e.prepare(`INSERT INTO unresolvable_teamfile_watch(team, first_observed_ts) VALUES (?, ?)
106
- ON CONFLICT(team) DO NOTHING`).run(t,r)}function zd(e,t){e.prepare("DELETE FROM unresolvable_teamfile_watch WHERE team = ?").run(t)}function Yd(e,t){return e.prepare("SELECT * FROM unresolvable_teamfile_watch WHERE team = ?").get(t)??null}function Qd(e,t,r){e.prepare("UPDATE unresolvable_teamfile_watch SET surfaced_ts = ? WHERE team = ?").run(r,t)}function Xd(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_cli_activity_ts)
104
+ hung_holder_reason = NULL`).run(t)}function Kd(e,t,r,n,o){e.prepare(`INSERT INTO auto_nudge_suspended(team, reason, detail, suspended_at) VALUES (?, ?, ?, ?)
105
+ ON CONFLICT(team) DO UPDATE SET reason = excluded.reason, detail = excluded.detail, suspended_at = excluded.suspended_at`).run(t,r,n,o)}function zd(e,t){e.prepare("DELETE FROM auto_nudge_suspended WHERE team = ?").run(t)}function Yd(e){return e.prepare("SELECT * FROM auto_nudge_suspended ORDER BY team").all()}function Qd(e,t,r){e.prepare(`INSERT INTO unresolvable_teamfile_watch(team, first_observed_ts) VALUES (?, ?)
106
+ ON CONFLICT(team) DO NOTHING`).run(t,r)}function Xd(e,t){e.prepare("DELETE FROM unresolvable_teamfile_watch WHERE team = ?").run(t)}function Zd(e,t){return e.prepare("SELECT * FROM unresolvable_teamfile_watch WHERE team = ?").get(t)??null}function em(e,t,r){e.prepare("UPDATE unresolvable_teamfile_watch SET surfaced_ts = ? WHERE team = ?").run(r,t)}function tm(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_cli_activity_ts)
107
107
  VALUES (?, ?)
108
- ON CONFLICT(team) DO UPDATE SET last_cli_activity_ts = excluded.last_cli_activity_ts`).run(t,r)}function Zd(e,t,r,n){return e.prepare("SELECT * FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?").get(t,r,n)??null}function Va(e,t,r,n,o,s,i){e.prepare(`INSERT INTO orphan_watch(target, started_at_ms, pid, cpu_ticks, low_cpu_streak, observed_at)
108
+ ON CONFLICT(team) DO UPDATE SET last_cli_activity_ts = excluded.last_cli_activity_ts`).run(t,r)}function rm(e,t,r,n){return e.prepare("SELECT * FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?").get(t,r,n)??null}function za(e,t,r,n,o,s,i){e.prepare(`INSERT INTO orphan_watch(target, started_at_ms, pid, cpu_ticks, low_cpu_streak, observed_at)
109
109
  VALUES (?, ?, ?, ?, ?, ?)
110
110
  ON CONFLICT(target, started_at_ms, pid) DO UPDATE SET
111
111
  cpu_ticks = excluded.cpu_ticks,
112
112
  low_cpu_streak = excluded.low_cpu_streak,
113
- observed_at = excluded.observed_at`).run(t,r,n,o,i,s)}function Ja(e,t,r,n){e.prepare("DELETE FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?").run(t,r,n)}function em(e,t){let r=e.prepare("SELECT target, started_at_ms, pid FROM orphan_watch").all(),n=new Set(t.map(s=>JSON.stringify([s.target,s.startedAtMs,s.pid]))),o=e.prepare("DELETE FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?");for(let s of r)n.has(JSON.stringify([s.target,s.started_at_ms,s.pid]))||o.run(s.target,s.started_at_ms,s.pid)}function tm(e,t,r,n,o,s,i){e.prepare(`INSERT INTO hang_probe_observation(target, started_at_ms, pid, observed_at, cpu_ticks, io_bytes)
113
+ observed_at = excluded.observed_at`).run(t,r,n,o,i,s)}function Ya(e,t,r,n){e.prepare("DELETE FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?").run(t,r,n)}function nm(e,t){let r=e.prepare("SELECT target, started_at_ms, pid FROM orphan_watch").all(),n=new Set(t.map(s=>JSON.stringify([s.target,s.startedAtMs,s.pid]))),o=e.prepare("DELETE FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?");for(let s of r)n.has(JSON.stringify([s.target,s.started_at_ms,s.pid]))||o.run(s.target,s.started_at_ms,s.pid)}function om(e,t,r,n,o,s,i){e.prepare(`INSERT INTO hang_probe_observation(target, started_at_ms, pid, observed_at, cpu_ticks, io_bytes)
114
114
  VALUES (?, ?, ?, ?, ?, ?)
115
- ON CONFLICT(target, started_at_ms, pid, observed_at) DO NOTHING`).run(t,r,n,o,s,i)}function rm(e,t){e.prepare("DELETE FROM hang_probe_observation WHERE observed_at < ?").run(t)}function nm(e,t,r,n,o,s){e.prepare(`INSERT INTO hang_probe_outcome(target, started_at_ms, pid, outcome, recorded_at)
115
+ ON CONFLICT(target, started_at_ms, pid, observed_at) DO NOTHING`).run(t,r,n,o,s,i)}function sm(e,t){e.prepare("DELETE FROM hang_probe_observation WHERE observed_at < ?").run(t)}function im(e,t,r,n,o,s){e.prepare(`INSERT INTO hang_probe_outcome(target, started_at_ms, pid, outcome, recorded_at)
116
116
  VALUES (?, ?, ?, ?, ?)
117
- ON CONFLICT(target, started_at_ms, pid) DO NOTHING`).run(t,r,n,o,s)}function om(e,t,r,n){e.prepare(`INSERT INTO team_progress(team, quota_exhausted_last_seen_ts, quota_exhausted_message) VALUES (?, ?, ?)
117
+ ON CONFLICT(target, started_at_ms, pid) DO NOTHING`).run(t,r,n,o,s)}function am(e,t,r,n){e.prepare(`INSERT INTO team_progress(team, quota_exhausted_last_seen_ts, quota_exhausted_message) VALUES (?, ?, ?)
118
118
  ON CONFLICT(team) DO UPDATE SET
119
119
  quota_exhausted_last_seen_ts = excluded.quota_exhausted_last_seen_ts,
120
- quota_exhausted_message = excluded.quota_exhausted_message`).run(t,r,n)}function sm(e,t){e.prepare("UPDATE team_progress SET quota_exhausted_last_seen_ts = NULL, quota_exhausted_message = NULL WHERE team = ?").run(t)}function im(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_escalation_attempt_ts, escalation_attempt_count) VALUES (?, ?, 1)
120
+ quota_exhausted_message = excluded.quota_exhausted_message`).run(t,r,n)}function cm(e,t){e.prepare("UPDATE team_progress SET quota_exhausted_last_seen_ts = NULL, quota_exhausted_message = NULL WHERE team = ?").run(t)}function lm(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_escalation_attempt_ts, escalation_attempt_count) VALUES (?, ?, 1)
121
121
  ON CONFLICT(team) DO UPDATE SET
122
122
  last_escalation_attempt_ts = excluded.last_escalation_attempt_ts,
123
- escalation_attempt_count = team_progress.escalation_attempt_count + 1`).run(t,r)}var xA=kA(vA);function RA(e){return AA($A(e,".git"))}async function Ka(e,t){try{let r=t.replace(/\.\d{3}Z$/,"Z"),{stdout:n}=await xA("find",[e,"(","-name",".git","-o","-name","node_modules",")","-prune","-o","-type","f","-newermt",r,"-print","-quit"],{timeout:15e3});return n.trim().length>0}catch{return!1}}async function NA(e,t){if(t===null)return"ACTIVE";for(let r of e)if(await Ka(r,t))return"ACTIVE";return e.every(r=>!RA(r))?"NOT_A_REPO":"UNKNOWN"}async function za(e,t,r,n=Date.now()){let o=t.folders&&t.folders.length>0?t.folders:[t.repoPath],s=ie(e,r),i=await NA(o,s?.last_scan_ts??null);return Ud(e,r,i,new Date(n).toISOString(),new Date().toISOString()),ie(e,r)}import{existsSync as tc,readFileSync as gm,realpathSync as GA,statSync as VA}from"node:fs";import{join as pm,resolve as Rs}from"node:path";var IA=/^[a-z0-9-]+$/;function Ya(e){if(e.length>128||!IA.test(e))throw new Error("site-id must match [a-z0-9-]+");return e}function am(e){let t=e.split(":");if(t.length!==3)throw new Error("logical address must be site-id:team-id:alias");let[r,n,o]=t;return Ya(r),pn(n,"team-id"),pn(o,"alias"),{site:r,team:n,alias:o}}function pn(e,t,r=!1){if(!r&&!e||e.length>128||e!==e.trim()||LA(e))throw new Error(`${t} must ${r?"":"be non-empty and "}contain no colons or control characters`);return e}function LA(e){if(e.includes(":"))return!0;for(let t of e){let r=t.charCodeAt(0);if(r<=31||r===127)return!0}return!1}import{link as DA,mkdir as MA,readFile as PA,rename as UA,unlink as FA,writeFile as qA}from"node:fs/promises";import{randomUUID as jA}from"node:crypto";import{homedir as CA}from"node:os";import{dirname as OA,join as cm}from"node:path";function Qa(e=process.env){let t=e.LMAUTO_DB?.trim();return t?OA(t):cm(e.HOME?.trim()||CA(),".lmauto")}function $s(e=process.env){return cm(Qa(e),"site-uuid")}var lm=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,HA={readText:e=>PA(e,"utf8"),mkdir:async e=>{await MA(e,{recursive:!0})},writePrivate:(e,t)=>qA(e,t,{flag:"wx",mode:384}),link:DA,rename:UA,remove:FA};async function um(e={}){let t=e.env??process.env,r=e.io??HA,n=$s(t),o=await xs(r,n);if(o.value)return o.value;await r.mkdir(Qa(t));let s={io:r,randomUuid:e.randomUuid??jA,pid:e.pid??process.pid,sleep:e.sleep??(i=>new Promise(a=>setTimeout(a,i)))};return o.exists?WA(s,n):BA(s,n)}async function BA(e,t){let r=await dm(e,t);try{try{return await e.io.link(r.temporary,t),r.candidate}catch(n){if(n.code!=="EEXIST")throw n;return Xa(e,t)}}finally{await ks(e.io,r.temporary)}}async function WA(e,t){let r=`${t}.repair.lock`;try{await e.io.writePrivate(r,Buffer.from(`${e.pid}
124
- `))}catch(i){if(i.code!=="EEXIST")throw i;return Xa(e,t)}let n,o,s=!1;try{n=await dm(e,t),o=`${t}.${e.pid}.${n.candidate}.corrupt`;let i=await xs(e.io,t);if(i.value)return i.value;if(i.exists)try{await e.io.rename(t,o),s=!0}catch(a){if(a.code!=="ENOENT")throw a}try{return await e.io.link(n.temporary,t),n.candidate}catch(a){if(a.code==="EEXIST")return Xa(e,t);let c=await xs(e.io,t);throw s&&!c.exists&&(await e.io.rename(o,t),s=!1),a}}finally{n&&await ks(e.io,n.temporary),s&&o&&await ks(e.io,o),await ks(e.io,r)}}async function dm(e,t){let r=e.randomUuid().toLowerCase();if(!lm.test(r))throw new Error("random UUID generator returned an invalid site identity");let n=`${t}.${e.pid}.${r}.tmp`;return await e.io.writePrivate(n,Buffer.from(`${r}
125
- `)),{candidate:r,temporary:n}}async function Xa(e,t){for(let r=0;r<100;r+=1){let n=await xs(e.io,t);if(n.value)return n.value;await e.sleep(10)}throw new Error(`timed out waiting for site identity winner at ${t}`)}async function xs(e,t){try{let r=(await e.readText(t)).trim();return lm.test(r)?{exists:!0,value:r.toLowerCase()}:{exists:!0}}catch(r){if(r.code==="ENOENT")return{exists:!1};throw r}}async function ks(e,t){try{await e.remove(t)}catch(r){if(r.code!=="ENOENT")throw r}}function Za(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}if(!t||typeof t!="object"||Array.isArray(t))return;let r=t;if(typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.ownerLabel!="string"||typeof r.startedAt!="string")return;let n=typeof r.pidStartTicks=="number"&&Number.isFinite(r.pidStartTicks)?r.pidStartTicks:null,o=ec(r.bootId)?r.bootId:null;return{pid:r.pid,ownerLabel:r.ownerLabel,startedAt:r.startedAt,pidStartTicks:n,bootId:o}}function ec(e){return typeof e=="string"&&/^[0-9a-f-]{36}$/i.test(e)}function hn(e){return`lmauto-site-${e}`}function mm(e){return`${hn(e)}-exec`}function fm(e,t){let r=hn(e);if(t!==r)throw new Error(`peer mailbox mismatch for ${e}: registered ${t}, expected ${r}`);return r}function H(e){return e.channel==="local"}function Ns(e,t){let r=e.find(n=>n.name===t);return r?H(r)?{key:t,kind:"local",name:r.name,repoPath:r.repoPath,leadAlias:r.leadAlias,channel:r.channel,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"remote",name:r.name,channel:r.channel,peerSite:r.peerSite,alias:r.alias,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"unresolved",currentSession:null,historicalCoverage:"unavailable"}}function yo(e){let t=[];for(let r of e.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.split(/\t+/).map(h=>h.trim());if(o.length<3)continue;let[s,i,a,c,l,u,d]=o,m=c||"default",f=u?u.split(",").map(h=>h.trim()).filter(h=>h.length>0):[],p=f.length>0?_m(i,f):[Rs(i)];t.push({channel:"local",name:s,repoPath:i,leadAlias:a,promptName:m,description:l??"",autoNudge:m!=="on-demand",folders:p,coordinator:d==="true"})}return t}function _m(e,t){let r=new Set,n=[];for(let o of t){let s=Rs(e,o);r.has(s)||(r.add(s),n.push(s))}return n}var JA=/^_TEAM_(\s|$)/,KA=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function zA(e){let t={};for(let m of e.matchAll(KA)){let f=m[1];f in t||(t[f]=m[2]!==void 0?m[2]:m[3])}if(t.channel==="lmmail")return YA(t,e);let{name:r,repo:n,lead:o,prompt:s,desc:i,folders:a,coordinator:c}=t;if(!r||!n||!o)return process.stderr.write(`teams-conf: skipping malformed _TEAM_ line (missing name/repo/lead): ${e}
126
- `),null;let l=s||"default",u=a?a.split(",").map(m=>m.trim()).filter(m=>m.length>0):[],d=u.length>0?_m(n,u):[Rs(n)];return{channel:"local",name:r,repoPath:n,leadAlias:o,promptName:l,description:i??"",autoNudge:l!=="on-demand",folders:d,coordinator:c==="true"}}function YA(e,t){let{peer_site:r,team:n,alias:o}=e;if(!r||!n||!o)return process.stderr.write(`teams-conf: skipping malformed remote _TEAM_ line (missing peer_site/team/alias): ${t}
123
+ escalation_attempt_count = team_progress.escalation_attempt_count + 1`).run(t,r)}var CA=IA(RA);function OA(e){return NA(LA(e,".git"))}async function Qa(e,t){try{let r=t.replace(/\.\d{3}Z$/,"Z"),{stdout:n}=await CA("find",[e,"(","-name",".git","-o","-name","node_modules",")","-prune","-o","-type","f","-newermt",r,"-print","-quit"],{timeout:15e3});return n.trim().length>0}catch{return!1}}async function DA(e,t){if(t===null)return"ACTIVE";for(let r of e)if(await Qa(r,t))return"ACTIVE";return e.every(r=>!OA(r))?"NOT_A_REPO":"UNKNOWN"}async function Xa(e,t,r,n=Date.now()){let o=t.folders&&t.folders.length>0?t.folders:[t.repoPath],s=ie(e,r),i=await DA(o,s?.last_scan_ts??null);return jd(e,r,i,new Date(n).toISOString(),new Date().toISOString()),ie(e,r)}import{existsSync as oc,readFileSync as ym,realpathSync as YA,statSync as QA}from"node:fs";import{join as _m,resolve as Cs}from"node:path";var MA=/^[a-z0-9-]+$/;function Za(e){if(e.length>128||!MA.test(e))throw new Error("site-id must match [a-z0-9-]+");return e}function um(e){let t=e.split(":");if(t.length!==3)throw new Error("logical address must be site-id:team-id:alias");let[r,n,o]=t;return Za(r),pn(n,"team-id"),pn(o,"alias"),{site:r,team:n,alias:o}}function pn(e,t,r=!1){if(!r&&!e||e.length>128||e!==e.trim()||PA(e))throw new Error(`${t} must ${r?"":"be non-empty and "}contain no colons or control characters`);return e}function PA(e){if(e.includes(":"))return!0;for(let t of e){let r=t.charCodeAt(0);if(r<=31||r===127)return!0}return!1}import{link as qA,mkdir as jA,readFile as HA,rename as BA,unlink as WA,writeFile as GA}from"node:fs/promises";import{randomUUID as VA}from"node:crypto";import{homedir as UA}from"node:os";import{dirname as FA,join as dm}from"node:path";function ec(e=process.env){let t=e.LMAUTO_DB?.trim();return t?FA(t):dm(e.HOME?.trim()||UA(),".lmauto")}function Ns(e=process.env){return dm(ec(e),"site-uuid")}var mm=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,JA={readText:e=>HA(e,"utf8"),mkdir:async e=>{await jA(e,{recursive:!0})},writePrivate:(e,t)=>GA(e,t,{flag:"wx",mode:384}),link:qA,rename:BA,remove:WA};async function fm(e={}){let t=e.env??process.env,r=e.io??JA,n=Ns(t),o=await Is(r,n);if(o.value)return o.value;await r.mkdir(ec(t));let s={io:r,randomUuid:e.randomUuid??VA,pid:e.pid??process.pid,sleep:e.sleep??(i=>new Promise(a=>setTimeout(a,i)))};return o.exists?zA(s,n):KA(s,n)}async function KA(e,t){let r=await pm(e,t);try{try{return await e.io.link(r.temporary,t),r.candidate}catch(n){if(n.code!=="EEXIST")throw n;return tc(e,t)}}finally{await Ls(e.io,r.temporary)}}async function zA(e,t){let r=`${t}.repair.lock`;try{await e.io.writePrivate(r,Buffer.from(`${e.pid}
124
+ `))}catch(i){if(i.code!=="EEXIST")throw i;return tc(e,t)}let n,o,s=!1;try{n=await pm(e,t),o=`${t}.${e.pid}.${n.candidate}.corrupt`;let i=await Is(e.io,t);if(i.value)return i.value;if(i.exists)try{await e.io.rename(t,o),s=!0}catch(a){if(a.code!=="ENOENT")throw a}try{return await e.io.link(n.temporary,t),n.candidate}catch(a){if(a.code==="EEXIST")return tc(e,t);let c=await Is(e.io,t);throw s&&!c.exists&&(await e.io.rename(o,t),s=!1),a}}finally{n&&await Ls(e.io,n.temporary),s&&o&&await Ls(e.io,o),await Ls(e.io,r)}}async function pm(e,t){let r=e.randomUuid().toLowerCase();if(!mm.test(r))throw new Error("random UUID generator returned an invalid site identity");let n=`${t}.${e.pid}.${r}.tmp`;return await e.io.writePrivate(n,Buffer.from(`${r}
125
+ `)),{candidate:r,temporary:n}}async function tc(e,t){for(let r=0;r<100;r+=1){let n=await Is(e.io,t);if(n.value)return n.value;await e.sleep(10)}throw new Error(`timed out waiting for site identity winner at ${t}`)}async function Is(e,t){try{let r=(await e.readText(t)).trim();return mm.test(r)?{exists:!0,value:r.toLowerCase()}:{exists:!0}}catch(r){if(r.code==="ENOENT")return{exists:!1};throw r}}async function Ls(e,t){try{await e.remove(t)}catch(r){if(r.code!=="ENOENT")throw r}}function rc(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return}if(!t||typeof t!="object"||Array.isArray(t))return;let r=t;if(typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.ownerLabel!="string"||typeof r.startedAt!="string")return;let n=typeof r.pidStartTicks=="number"&&Number.isFinite(r.pidStartTicks)?r.pidStartTicks:null,o=nc(r.bootId)?r.bootId:null;return{pid:r.pid,ownerLabel:r.ownerLabel,startedAt:r.startedAt,pidStartTicks:n,bootId:o}}function nc(e){return typeof e=="string"&&/^[0-9a-f-]{36}$/i.test(e)}function hn(e){return`lmauto-site-${e}`}function hm(e){return`${hn(e)}-exec`}function gm(e,t){let r=hn(e);if(t!==r)throw new Error(`peer mailbox mismatch for ${e}: registered ${t}, expected ${r}`);return r}function B(e){return e.channel==="local"}function Os(e,t){let r=e.find(n=>n.name===t);return r?B(r)?{key:t,kind:"local",name:r.name,repoPath:r.repoPath,leadAlias:r.leadAlias,channel:r.channel,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"remote",name:r.name,channel:r.channel,peerSite:r.peerSite,alias:r.alias,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"unresolved",currentSession:null,historicalCoverage:"unavailable"}}function To(e){let t=[];for(let r of e.split(/\r?\n/)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.split(/\t+/).map(h=>h.trim());if(o.length<3)continue;let[s,i,a,c,l,u,d]=o,m=c||"default",f=u?u.split(",").map(h=>h.trim()).filter(h=>h.length>0):[],p=f.length>0?Em(i,f):[Cs(i)];t.push({channel:"local",name:s,repoPath:i,leadAlias:a,promptName:m,description:l??"",autoNudge:m!=="on-demand",folders:p,coordinator:d==="true"})}return t}function Em(e,t){let r=new Set,n=[];for(let o of t){let s=Cs(e,o);r.has(s)||(r.add(s),n.push(s))}return n}var XA=/^_TEAM_(\s|$)/,ZA=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function ek(e){let t={};for(let m of e.matchAll(ZA)){let f=m[1];f in t||(t[f]=m[2]!==void 0?m[2]:m[3])}if(t.channel==="lmmail")return tk(t,e);let{name:r,repo:n,lead:o,prompt:s,desc:i,folders:a,coordinator:c}=t;if(!r||!n||!o)return process.stderr.write(`teams-conf: skipping malformed _TEAM_ line (missing name/repo/lead): ${e}
126
+ `),null;let l=s||"default",u=a?a.split(",").map(m=>m.trim()).filter(m=>m.length>0):[],d=u.length>0?Em(n,u):[Cs(n)];return{channel:"local",name:r,repoPath:n,leadAlias:o,promptName:l,description:i??"",autoNudge:l!=="on-demand",folders:d,coordinator:c==="true"}}function tk(e,t){let{peer_site:r,team:n,alias:o}=e;if(!r||!n||!o)return process.stderr.write(`teams-conf: skipping malformed remote _TEAM_ line (missing peer_site/team/alias): ${t}
127
127
  `),null;for(let[s,i]of[["peer_site",r],["team",n],["alias",o]])try{pn(i,s)}catch(a){return process.stderr.write(`teams-conf: skipping remote _TEAM_ line -- ${a instanceof Error?a.message:String(a)}: ${t}
128
- `),null}return{channel:"lmmail",name:n,peerSite:r,alias:o}}var QA=/^(`{3,}|~{3,})/;function rc(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let o=n.trim(),s=QA.exec(o);if(s){let a=s[1];r===null?r={char:a[0],len:a.length}:a[0]===r.char&&a.length>=r.len&&o.slice(a.length).trim()===""&&(r=null);continue}if(r!==null||!JA.test(o))continue;let i=zA(o);i&&t.push(i)}return t}function hm(e){return e.toLowerCase().endsWith(".md")}function XA(e,t){let r=new Set,n=[];for(let o of[e,...t])if(!(!o||r.has(o))&&(r.add(o),!!tc(o))){try{if(!VA(o).isFile())continue}catch{continue}n.push(o)}return n}function ZA(e,t=[]){let r=XA(e,t),n=new Map,o=s=>{try{return gm(s,"utf8")}catch{return null}};for(let s of r){if(!hm(s))continue;let i=o(s);if(i!==null)for(let a of rc(i))n.has(a.name)||n.set(a.name,a)}for(let s of r){if(hm(s))continue;let i=o(s);if(i!==null)for(let a of yo(i))n.has(a.name)||n.set(a.name,a)}return[...n.values()]}function Is(e,t,r){e.prepare(`INSERT INTO sources(path, label, added_ts) VALUES (?, ?, ?)
129
- ON CONFLICT(path) DO UPDATE SET label = excluded.label`).run(t,r,new Date().toISOString())}function nc(e){return e.prepare("SELECT * FROM sources ORDER BY id").all()}function Ls(e,t){e.prepare("DELETE FROM sources WHERE path = ?").run(t)}function e$(e){let t=Rs(e);return tc(t)?GA(t):null}function Q(e){let t=e$(pm(e.repoPath,`${e.name}.lmctl`));if(t)return t;throw tc(e.repoPath)?new Error(`resolveTeamfilePath: cannot resolve a teamfile for team "${e.name}" -- expected "${pm(e.repoPath,`${e.name}.lmctl`)}" to exist. teams.conf has no explicit teamfile-path column -- fix by naming the teamfile "<name>.lmctl" under repo_path.`):new Error(`resolveTeamfilePath: repo_path "${e.repoPath}" for team "${e.name}" does not exist`)}var t$=/^_MEMBER_(\s|$)/,r$=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function jt(e,t){return sc(e).find(r=>r.alias===t)?.provider??null}function oc(e){return sc(e).filter(t=>t.sessionid!==void 0&&t.sessionid.length>0).length}function Vr(e){return sc(e).filter(t=>t.alias!==void 0).map(t=>({alias:t.alias,provider:t.provider??null}))}function sc(e){let t;try{t=gm(Q(e),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
130
- `)){if(!t$.test(n.trim()))continue;let o={};for(let s of n.matchAll(r$)){let i=s[1];o[i]=s[2]!==void 0?s[2]:s[3]}r.push({alias:o.alias,provider:o.provider,sessionid:o.sessionid})}return r}function Jr(e,t){let r=nc(e).map(n=>n.path);return ZA(t,r)}function gn(e){if(typeof e!="string")return null;let t=e.lastIndexOf(":");if(t===-1)return null;let r=e.slice(0,t),n=e.slice(t+1);return!r||!n?null:{teamfilePath:r,alias:n}}function _n(e,t){let r=gn(t);if(r===null||r.alias!==e.leadAlias)return!1;let n;try{n=Q(e)}catch{return!1}return n===r.teamfilePath}function Fe(e,t){return t.running.some(r=>_n(e,r.target))}function wm(e,t,r){return r.running.some(n=>{let o=gn(n.target);return o!==null&&o.alias===t&&o.teamfilePath===e})}function n$(e,t,r){let n=new Set(e.filter(u=>Fe(u,t)).map(u=>u.name)),o=new Set(r??[]),s=r===null,i=[...o].filter(u=>!n.has(u)).sort(),a=[...n].filter(u=>!o.has(u)).sort(),c=s||i.length>0,l=s?"first-run":i.length>0?`active->other: ${i.join(", ")}`:"nochange";return{first:s,active:[...n].sort(),wentIdle:i,newlyActive:a,wake:c,why:l}}function Cs(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get("active");return t?JSON.parse(t.v):null}function o$(e,t){e.prepare("INSERT INTO kv(k, v) VALUES ('active', ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(JSON.stringify(t))}function Os(e,t,r){let n=n$(t,r,Cs(e));return o$(e,n.active),n}import{randomUUID as of}from"node:crypto";import{existsSync as sf,mkdirSync as b$,readFileSync as Bs,rmSync as S$,writeFileSync as af}from"node:fs";import{homedir as v$}from"node:os";import{join as cf,resolve as nf,sep as A$}from"node:path";var gj=64*1024;import{readFileSync as Ds,writeFileSync as i$}from"node:fs";function a$(e,t){return e.prepare("UPDATE queue SET status = 'sent', sent_ts = ? WHERE id = ? AND status = 'pending'").run(new Date().toISOString(),t).changes>0}function ym(e,t){let r=[],n=new Map;for(let s of t){if(s.dedupe_key!==null){r.push(s);continue}let i=JSON.stringify([s.from_id,s.to_id,s.escalation_only,s.to_alias]),a=n.get(i);a?a.push(s):n.set(i,[s])}let o=[...r];for(let s of n.values()){if(s.length===1){o.push(s[0]);continue}let[i,...a]=s,c;try{c=Ds(i.prompt_file,"utf8")}catch{o.push(...s);continue}let l=[],u=!0;for(let d of a)try{l.push(`
128
+ `),null}return{channel:"lmmail",name:n,peerSite:r,alias:o}}var rk=/^(`{3,}|~{3,})/;function sc(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let o=n.trim(),s=rk.exec(o);if(s){let a=s[1];r===null?r={char:a[0],len:a.length}:a[0]===r.char&&a.length>=r.len&&o.slice(a.length).trim()===""&&(r=null);continue}if(r!==null||!XA.test(o))continue;let i=ek(o);i&&t.push(i)}return t}function wm(e){return e.toLowerCase().endsWith(".md")}function nk(e,t){let r=new Set,n=[];for(let o of[e,...t])if(!(!o||r.has(o))&&(r.add(o),!!oc(o))){try{if(!QA(o).isFile())continue}catch{continue}n.push(o)}return n}function ok(e,t=[]){let r=nk(e,t),n=new Map,o=s=>{try{return ym(s,"utf8")}catch{return null}};for(let s of r){if(!wm(s))continue;let i=o(s);if(i!==null)for(let a of sc(i))n.has(a.name)||n.set(a.name,a)}for(let s of r){if(wm(s))continue;let i=o(s);if(i!==null)for(let a of To(i))n.has(a.name)||n.set(a.name,a)}return[...n.values()]}function Ds(e,t,r){e.prepare(`INSERT INTO sources(path, label, added_ts) VALUES (?, ?, ?)
129
+ ON CONFLICT(path) DO UPDATE SET label = excluded.label`).run(t,r,new Date().toISOString())}function ic(e){return e.prepare("SELECT * FROM sources ORDER BY id").all()}function Ms(e,t){e.prepare("DELETE FROM sources WHERE path = ?").run(t)}function sk(e){let t=Cs(e);return oc(t)?YA(t):null}function Q(e){let t=sk(_m(e.repoPath,`${e.name}.lmctl`));if(t)return t;throw oc(e.repoPath)?new Error(`resolveTeamfilePath: cannot resolve a teamfile for team "${e.name}" -- expected "${_m(e.repoPath,`${e.name}.lmctl`)}" to exist. teams.conf has no explicit teamfile-path column -- fix by naming the teamfile "<name>.lmctl" under repo_path.`):new Error(`resolveTeamfilePath: repo_path "${e.repoPath}" for team "${e.name}" does not exist`)}var ik=/^_MEMBER_(\s|$)/,ak=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function jt(e,t){return cc(e).find(r=>r.alias===t)?.provider??null}function ac(e){return cc(e).filter(t=>t.sessionid!==void 0&&t.sessionid.length>0).length}function Vr(e){return cc(e).filter(t=>t.alias!==void 0).map(t=>({alias:t.alias,provider:t.provider??null}))}function cc(e){let t;try{t=ym(Q(e),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
130
+ `)){if(!ik.test(n.trim()))continue;let o={};for(let s of n.matchAll(ak)){let i=s[1];o[i]=s[2]!==void 0?s[2]:s[3]}r.push({alias:o.alias,provider:o.provider,sessionid:o.sessionid})}return r}function Jr(e,t){let r=ic(e).map(n=>n.path);return ok(t,r)}function gn(e){if(typeof e!="string")return null;let t=e.lastIndexOf(":");if(t===-1)return null;let r=e.slice(0,t),n=e.slice(t+1);return!r||!n?null:{teamfilePath:r,alias:n}}function _n(e,t){let r=gn(t);if(r===null||r.alias!==e.leadAlias)return!1;let n;try{n=Q(e)}catch{return!1}return n===r.teamfilePath}function Fe(e,t){return t.running.some(r=>_n(e,r.target))}function Tm(e,t,r){return r.running.some(n=>{let o=gn(n.target);return o!==null&&o.alias===t&&o.teamfilePath===e})}function ck(e,t,r){let n=new Set(e.filter(u=>Fe(u,t)).map(u=>u.name)),o=new Set(r??[]),s=r===null,i=[...o].filter(u=>!n.has(u)).sort(),a=[...n].filter(u=>!o.has(u)).sort(),c=s||i.length>0,l=s?"first-run":i.length>0?`active->other: ${i.join(", ")}`:"nochange";return{first:s,active:[...n].sort(),wentIdle:i,newlyActive:a,wake:c,why:l}}function Ps(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get("active");return t?JSON.parse(t.v):null}function lk(e,t){e.prepare("INSERT INTO kv(k, v) VALUES ('active', ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(JSON.stringify(t))}function Us(e,t,r){let n=ck(t,r,Ps(e));return lk(e,n.active),n}import{randomUUID as cf}from"node:crypto";import{existsSync as lf,mkdirSync as $k,readFileSync as Js,rmSync as xk,writeFileSync as uf}from"node:fs";import{homedir as Rk}from"node:os";import{join as df,resolve as af,sep as Nk}from"node:path";var Sj=64*1024;import{readFileSync as Fs,writeFileSync as dk}from"node:fs";function mk(e,t){return e.prepare("UPDATE queue SET status = 'sent', sent_ts = ? WHERE id = ? AND status = 'pending'").run(new Date().toISOString(),t).changes>0}function bm(e,t){let r=[],n=new Map;for(let s of t){if(s.dedupe_key!==null){r.push(s);continue}let i=JSON.stringify([s.from_id,s.to_id,s.escalation_only,s.to_alias]),a=n.get(i);a?a.push(s):n.set(i,[s])}let o=[...r];for(let s of n.values()){if(s.length===1){o.push(s[0]);continue}let[i,...a]=s,c;try{c=Fs(i.prompt_file,"utf8")}catch{o.push(...s);continue}let l=[],u=!0;for(let d of a)try{l.push(`
131
131
 
132
132
  --- addendum, ${d.created_ts} ---
133
- ${Ds(d.prompt_file,"utf8")}`)}catch{u=!1;break}if(!u){o.push(...s);continue}if(l.length>0){i$(i.prompt_file,c+l.join(""));let d=e.prepare("UPDATE queue SET status = 'merged' WHERE id = ? AND status = 'pending'");for(let m of a)d.run(m.id)}o.push(i)}return o}function ac(e,t,r){let n=new Map(t.map(c=>[c.name,c])),o=r.teamName?e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 AND to_id = ? ORDER BY id").all(r.teamName):e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 ORDER BY id").all(),s=ym(e,o),i=new Set,a=0;for(let c of s){let l=c.to_alias===null?c.to_id:`${c.to_id}:${c.to_alias}`;if(i.has(l))continue;i.add(l);let u=n.get(c.to_id);if(!u||r.isTeamBusy(u))continue;if(r.minMemoryPercent!==void 0){let p=r.memoryCheck;if(p&&!p(r.minMemoryPercent))continue}try{Ds(c.prompt_file,"utf8")}catch{continue}if(!a$(e,c.id))continue;let d;try{d=Ds(c.prompt_file,"utf8")}catch(p){process.stderr.write(`[lmqueue] row #${c.id} claimed 'sent' but its prompt file became unreadable before dispatch -- nothing was actually sent: ${p instanceof Error?p.message:String(p)}
134
- `),a++;continue}let m=c.to_alias??u.leadAlias,f={teamfilePath:u.teamfilePath,alias:m};a++,!r.onDispatch?.({row:c,team:u,target:f,promptText:d})&&r.send(f,d)}return a}import{randomUUID as Tm}from"node:crypto";import{mkdtempSync as bm,rmSync as Sm,writeFileSync as vm}from"node:fs";import{tmpdir as Am}from"node:os";import{join as Ms}from"node:path";import{spawn as $m}from"node:child_process";var km=50*6e4,xm=5e3,Kr=["systemd-run","--user","--scope","--collect","--quiet","--","lmctl"];async function Ht(e,t,r={}){let n=r.timeoutMs??km,o=r.sigkillGraceMs??xm,s=bm(Ms(Am(),"lmauto-send-")),i=Ms(s,`${Tm()}.md`);vm(i,t,{mode:384});let c=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",i,"--json"],[l,...u]=c;return new Promise(d=>{let m=$m(l,u,{detached:!0,stdio:["ignore","pipe","pipe"]});m.unref();let f="",p="",h=!1,w=setTimeout(()=>{if(!h){if(m.pid!==void 0){let T=m.pid;try{process.kill(-T,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-T,0)}catch{return}try{process.kill(-T,"SIGKILL")}catch{}},o).unref()}E({kind:"timeout"})}},n);function _(){clearTimeout(w);try{Sm(s,{recursive:!0,force:!0})}catch{}}function E(T){h||(h=!0,_(),d(T))}m.stdout?.on("data",T=>{let v=T.toString("utf8");p+=v,f+=v;let S=f.split(`
135
- `);f=S.pop()??"";for(let N of S){let x=Em(N);x&&E(x)}}),m.stderr?.on("data",T=>{p+=T.toString("utf8")}),m.on("error",T=>{E({kind:"error",message:T.message})}),m.on("close",(T,v)=>{if(!h){if(f.trim()){let S=Em(f);if(S){E(S);return}}if(T!==0||v!==null){E({kind:"error",message:`lctl exited ${v?`via signal ${v}`:`with code ${T}`} without a recognized status line: ${p.trim().slice(-2e3)}`});return}E({kind:"no-signal",rawOutput:p.trim()})}})})}function Em(e){let t=e.trim();if(!t)return null;let r;try{r=JSON.parse(t)}catch{return null}if(typeof r!="object"||r===null)return null;let n=r;switch(n.status){case"accepted":return null;case"ok":case"stalled":return{kind:n.status==="stalled"?"stalled":"ok",replyText:typeof n.replyText=="string"?n.replyText:"",messageId:typeof n.message_id=="string"?n.message_id:null,teamChatLogId:typeof n.teamChatLogId=="number"?n.teamChatLogId:null};case"busy":return{kind:"busy",message:typeof n.message=="string"?n.message:"busy"};case"error":case"failed":return{kind:"error",message:typeof n.message=="string"?n.message:"error"};default:return null}}function Rm(e,t,r={}){let n=bm(Ms(Am(),"lmauto-send-")),o=Ms(n,`${Tm()}.md`);vm(o,t,{mode:384});let i=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",o,"--json"],[a,...c]=i,l=$m(a,c,{detached:!0,stdio:"ignore"});l.unref();function u(){try{Sm(n,{recursive:!0,force:!0})}catch{}}let d=!1;l.on("exit",()=>{d=!0,clearTimeout(m),u()});let m=setTimeout(()=>{if(d||l.pid===void 0)return;let f=l.pid;try{process.kill(-f,"SIGTERM")}catch{return}setTimeout(()=>{if(!d){try{process.kill(-f,0)}catch{return}try{process.kill(-f,"SIGKILL")}catch{}}},r.sigkillGraceMs??xm).unref()},r.timeoutMs??km);m.unref(),l.on("error",f=>{u(),process.stderr.write(`[send] sendPromptDetached: failed to spawn dispatch to ${e.teamfilePath}:${e.alias}: ${f.message} -- the queue row is already marked sent and will NOT be retried
136
- `)})}var wn="queue_delivery_paused:";function Nm(e,t){return e.prepare("SELECT 1 FROM kv WHERE k = ?").get(wn+t)!==void 0}function Im(e,t){try{let r=JSON.parse(t);return{team:e,pausedAt:typeof r.pausedAt=="string"?r.pausedAt:new Date(0).toISOString(),reason:typeof r.reason=="string"?r.reason:null}}catch{return{team:e,pausedAt:new Date(0).toISOString(),reason:null}}}function Lm(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(wn+t);return r===void 0?null:Im(t,r.v)}function Cm(e){return e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${wn}%`).map(r=>Im(r.k.slice(wn.length),r.v))}function Om(e,t,r,n){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(wn+t,JSON.stringify({pausedAt:n,reason:r}))}function Dm(e,t){return e.prepare("DELETE FROM kv WHERE k = ?").run(wn+t).changes>0}function c$(e){return{team:e.team,alias:e.alias,holderPid:e.holder_pid,reservedAt:e.reserved_at,leaseUntil:e.lease_until,reason:e.reason}}function Mm(e,t,r,n,o,s,i=6e4){let a=new Date(Date.parse(o)+i).toISOString();return e.prepare(`INSERT INTO session_reservation(team, alias, holder_pid, reserved_at, lease_until, reason)
133
+ ${Fs(d.prompt_file,"utf8")}`)}catch{u=!1;break}if(!u){o.push(...s);continue}if(l.length>0){dk(i.prompt_file,c+l.join(""));let d=e.prepare("UPDATE queue SET status = 'merged' WHERE id = ? AND status = 'pending'");for(let m of a)d.run(m.id)}o.push(i)}return o}function uc(e,t,r){let n=new Map(t.map(c=>[c.name,c])),o=r.teamName?e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 AND to_id = ? ORDER BY id").all(r.teamName):e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 ORDER BY id").all(),s=bm(e,o),i=new Set,a=0;for(let c of s){let l=c.to_alias===null?c.to_id:`${c.to_id}:${c.to_alias}`;if(i.has(l))continue;i.add(l);let u=n.get(c.to_id);if(!u||r.isTeamBusy(u))continue;if(r.minMemoryPercent!==void 0){let p=r.memoryCheck;if(p&&!p(r.minMemoryPercent))continue}try{Fs(c.prompt_file,"utf8")}catch{continue}if(!mk(e,c.id))continue;let d;try{d=Fs(c.prompt_file,"utf8")}catch(p){process.stderr.write(`[lmqueue] row #${c.id} claimed 'sent' but its prompt file became unreadable before dispatch -- nothing was actually sent: ${p instanceof Error?p.message:String(p)}
134
+ `),a++;continue}let m=c.to_alias??u.leadAlias,f={teamfilePath:u.teamfilePath,alias:m};a++,!r.onDispatch?.({row:c,team:u,target:f,promptText:d})&&r.send(f,d)}return a}import{randomUUID as vm}from"node:crypto";import{mkdtempSync as Am,rmSync as km,writeFileSync as $m}from"node:fs";import{tmpdir as xm}from"node:os";import{join as qs}from"node:path";import{spawn as Rm}from"node:child_process";var Nm=50*6e4,Lm=5e3,Kr=["systemd-run","--user","--scope","--collect","--quiet","--","lmctl"];async function Ht(e,t,r={}){let n=r.timeoutMs??Nm,o=r.sigkillGraceMs??Lm,s=Am(qs(xm(),"lmauto-send-")),i=qs(s,`${vm()}.md`);$m(i,t,{mode:384});let c=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",i,"--json"],[l,...u]=c;return new Promise(d=>{let m=Rm(l,u,{detached:!0,stdio:["ignore","pipe","pipe"]});m.unref();let f="",p="",h=!1,w=setTimeout(()=>{if(!h){if(m.pid!==void 0){let E=m.pid;try{process.kill(-E,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-E,0)}catch{return}try{process.kill(-E,"SIGKILL")}catch{}},o).unref()}T({kind:"timeout"})}},n);function _(){clearTimeout(w);try{km(s,{recursive:!0,force:!0})}catch{}}function T(E){h||(h=!0,_(),d(E))}m.stdout?.on("data",E=>{let v=E.toString("utf8");p+=v,f+=v;let S=f.split(`
135
+ `);f=S.pop()??"";for(let N of S){let $=Sm(N);$&&T($)}}),m.stderr?.on("data",E=>{p+=E.toString("utf8")}),m.on("error",E=>{T({kind:"error",message:E.message})}),m.on("close",(E,v)=>{if(!h){if(f.trim()){let S=Sm(f);if(S){T(S);return}}if(E!==0||v!==null){T({kind:"error",message:`lctl exited ${v?`via signal ${v}`:`with code ${E}`} without a recognized status line: ${p.trim().slice(-2e3)}`});return}T({kind:"no-signal",rawOutput:p.trim()})}})})}function Sm(e){let t=e.trim();if(!t)return null;let r;try{r=JSON.parse(t)}catch{return null}if(typeof r!="object"||r===null)return null;let n=r;switch(n.status){case"accepted":return null;case"ok":case"stalled":return{kind:n.status==="stalled"?"stalled":"ok",replyText:typeof n.replyText=="string"?n.replyText:"",messageId:typeof n.message_id=="string"?n.message_id:null,teamChatLogId:typeof n.teamChatLogId=="number"?n.teamChatLogId:null};case"busy":return{kind:"busy",message:typeof n.message=="string"?n.message:"busy"};case"error":case"failed":return{kind:"error",message:typeof n.message=="string"?n.message:"error"};default:return null}}function Im(e,t,r={}){let n=Am(qs(xm(),"lmauto-send-")),o=qs(n,`${vm()}.md`);$m(o,t,{mode:384});let i=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",o,"--json"],[a,...c]=i,l=Rm(a,c,{detached:!0,stdio:"ignore"});l.unref();function u(){try{km(n,{recursive:!0,force:!0})}catch{}}let d=!1;l.on("exit",()=>{d=!0,clearTimeout(m),u()});let m=setTimeout(()=>{if(d||l.pid===void 0)return;let f=l.pid;try{process.kill(-f,"SIGTERM")}catch{return}setTimeout(()=>{if(!d){try{process.kill(-f,0)}catch{return}try{process.kill(-f,"SIGKILL")}catch{}}},r.sigkillGraceMs??Lm).unref()},r.timeoutMs??Nm);m.unref(),l.on("error",f=>{u(),process.stderr.write(`[send] sendPromptDetached: failed to spawn dispatch to ${e.teamfilePath}:${e.alias}: ${f.message} -- the queue row is already marked sent and will NOT be retried
136
+ `)})}var wn="queue_delivery_paused:";function Cm(e,t){return e.prepare("SELECT 1 FROM kv WHERE k = ?").get(wn+t)!==void 0}function Om(e,t){try{let r=JSON.parse(t);return{team:e,pausedAt:typeof r.pausedAt=="string"?r.pausedAt:new Date(0).toISOString(),reason:typeof r.reason=="string"?r.reason:null}}catch{return{team:e,pausedAt:new Date(0).toISOString(),reason:null}}}function Dm(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(wn+t);return r===void 0?null:Om(t,r.v)}function Mm(e){return e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${wn}%`).map(r=>Om(r.k.slice(wn.length),r.v))}function Pm(e,t,r,n){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(wn+t,JSON.stringify({pausedAt:n,reason:r}))}function Um(e,t){return e.prepare("DELETE FROM kv WHERE k = ?").run(wn+t).changes>0}function fk(e){return{team:e.team,alias:e.alias,holderPid:e.holder_pid,reservedAt:e.reserved_at,leaseUntil:e.lease_until,reason:e.reason}}function Fm(e,t,r,n,o,s,i=6e4){let a=new Date(Date.parse(o)+i).toISOString();return e.prepare(`INSERT INTO session_reservation(team, alias, holder_pid, reserved_at, lease_until, reason)
137
137
  VALUES (?, ?, ?, ?, ?, ?)
138
138
  ON CONFLICT(team, alias) DO UPDATE SET
139
139
  holder_pid = excluded.holder_pid,
140
140
  reserved_at = excluded.reserved_at,
141
141
  lease_until = excluded.lease_until,
142
142
  reason = excluded.reason
143
- WHERE session_reservation.lease_until <= ?`).run(t,r,n,o,a,s,o).changes===0?null:{team:t,alias:r,holderPid:n,reservedAt:o,leaseUntil:a,reason:s}}function cc(e,t,r,n=Date.now()){let o=e.prepare("SELECT * FROM session_reservation WHERE team = ? AND alias = ?").get(t,r);return o===void 0?null:Date.parse(o.lease_until)>n?c$(o):null}function Ps(e,t,r,n=Date.now()){return cc(e,t,r,n)!==null}function Pm(e,t,r=Date.now()){return e.prepare("SELECT lease_until FROM session_reservation WHERE team = ?").all(t).some(o=>Date.parse(o.lease_until)>r)}function Um(e,t,r,n){return e.prepare("DELETE FROM session_reservation WHERE team = ? AND alias = ? AND holder_pid = ?").run(t,r,n).changes>0}import{homedir as l$}from"node:os";import{readFileSync as u$}from"node:fs";import{join as d$}from"node:path";function Fm(e){return{LMAUTO_DB:e}}function ar(){return process.env.LMAUTO_DB??d$(l$(),".lmbee","state.db")}function m$(e){return $s(Fm(e))}function zr(e){return hn(e)}function yn(e){return mm(e)}async function Us(e){return um({env:Fm(e)})}var f$="lmbee.site_uuid",p$=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function h$(e){let t=m$(e),r=u$(t,"utf8").trim();if(!p$.test(r))throw new Error(`Invalid site identity at "${t}"; refusing to repair it during startup`);return r.toLowerCase()}function En(e,t=ar(),r){let n=h$(t),o=e.prepare("SELECT v FROM kv WHERE k = ?").get(f$);if(!o)throw new Error("Database has no lmbee site identity binding; explicit provisioning is required before mail or configured daemon startup");if(o.v!==n||r!==void 0&&r.toLowerCase()!==n)throw new Error("Database site identity does not match the retained site-uuid or configured LMBEE_SITE_UUID");return n}function g$(e){return{v:e.v,msg_id:e.msgId,to:e.to,from:e.from,sent_at:e.sentAt,payload:e.payload,...e.inReplyTo!==void 0?{in_reply_to:e.inReplyTo}:{}}}function _$(e){return{v:e.v,msgId:e.msg_id,to:e.to,from:e.from,sentAt:e.sent_at,payload:e.payload,...e.in_reply_to!==void 0?{inReplyTo:e.in_reply_to}:{}}}var qm=64*1024;function Eo(e){return JSON.stringify(g$(e))}function Hm(e){if(Buffer.byteLength(e,"utf8")>qm)throw new Error(`envelope body exceeds ${qm} bytes`);let t;try{t=JSON.parse(e)}catch(u){throw new Error(`envelope is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("envelope must be a JSON object");let r=t;if(r.v!==1)throw new Error(`unsupported envelope version: ${JSON.stringify(r.v)}`);let n=Fs(r,"msg_id"),o=Fs(r,"sent_at"),s=Fs(r,"payload"),i=jm(r,"to"),a=jm(r,"from"),c=r.in_reply_to===void 0||r.in_reply_to===null?void 0:Fs(r,"in_reply_to"),l={v:1,msg_id:n,to:i,from:a,sent_at:o,payload:s,...c!==void 0?{in_reply_to:c}:{}};return _$(l)}function Fs(e,t){let r=t.split(".").pop(),n=e[r];if(typeof n!="string"||n.length===0)throw new Error(`envelope.${t} must be a non-empty string, got ${JSON.stringify(n)}`);return n}function lc(e,t,r){let n=t.split(".").pop(),o=e[n];if(typeof o!="string"){let s=r?"a string":"a non-empty string";throw new Error(`envelope.${t} must be ${s}, got ${JSON.stringify(o)}`)}try{pn(o,t,r)}catch(s){throw new Error(`envelope.${s instanceof Error?s.message:String(s)}`)}return o}function jm(e,t){let r=t.split(".").pop(),n=e[r];if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`envelope.${t} must be an object, got ${JSON.stringify(n)}`);let o=n;return{site:lc(o,`${t}.site`,!1),team:lc(o,`${t}.team`,!0),alias:lc(o,`${t}.alias`,!1)}}function Bm(e,t,r){if(e.prepare(`INSERT INTO mail_ledger(
143
+ WHERE session_reservation.lease_until <= ?`).run(t,r,n,o,a,s,o).changes===0?null:{team:t,alias:r,holderPid:n,reservedAt:o,leaseUntil:a,reason:s}}function dc(e,t,r,n=Date.now()){let o=e.prepare("SELECT * FROM session_reservation WHERE team = ? AND alias = ?").get(t,r);return o===void 0?null:Date.parse(o.lease_until)>n?fk(o):null}function js(e,t,r,n=Date.now()){return dc(e,t,r,n)!==null}function qm(e,t,r=Date.now()){return e.prepare("SELECT lease_until FROM session_reservation WHERE team = ?").all(t).some(o=>Date.parse(o.lease_until)>r)}function jm(e,t,r,n){return e.prepare("DELETE FROM session_reservation WHERE team = ? AND alias = ? AND holder_pid = ?").run(t,r,n).changes>0}import{homedir as pk}from"node:os";import{readFileSync as hk}from"node:fs";import{join as gk}from"node:path";function Hm(e){return{LMAUTO_DB:e}}function ar(){return process.env.LMAUTO_DB??gk(pk(),".lmbee","state.db")}function _k(e){return Ns(Hm(e))}function zr(e){return hn(e)}function yn(e){return hm(e)}async function Hs(e){return fm({env:Hm(e)})}var wk="lmbee.site_uuid",yk=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Ek(e){let t=_k(e),r=hk(t,"utf8").trim();if(!yk.test(r))throw new Error(`Invalid site identity at "${t}"; refusing to repair it during startup`);return r.toLowerCase()}function En(e,t=ar(),r){let n=Ek(t),o=e.prepare("SELECT v FROM kv WHERE k = ?").get(wk);if(!o)throw new Error("Database has no lmbee site identity binding; explicit provisioning is required before mail or configured daemon startup");if(o.v!==n||r!==void 0&&r.toLowerCase()!==n)throw new Error("Database site identity does not match the retained site-uuid or configured LMBEE_SITE_UUID");return n}function Tk(e){return{v:e.v,msg_id:e.msgId,to:e.to,from:e.from,sent_at:e.sentAt,payload:e.payload,...e.inReplyTo!==void 0?{in_reply_to:e.inReplyTo}:{}}}function bk(e){return{v:e.v,msgId:e.msg_id,to:e.to,from:e.from,sentAt:e.sent_at,payload:e.payload,...e.in_reply_to!==void 0?{inReplyTo:e.in_reply_to}:{}}}var Bm=64*1024;function bo(e){return JSON.stringify(Tk(e))}function Gm(e){if(Buffer.byteLength(e,"utf8")>Bm)throw new Error(`envelope body exceeds ${Bm} bytes`);let t;try{t=JSON.parse(e)}catch(u){throw new Error(`envelope is not valid JSON: ${u instanceof Error?u.message:String(u)}`)}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("envelope must be a JSON object");let r=t;if(r.v!==1)throw new Error(`unsupported envelope version: ${JSON.stringify(r.v)}`);let n=Bs(r,"msg_id"),o=Bs(r,"sent_at"),s=Bs(r,"payload"),i=Wm(r,"to"),a=Wm(r,"from"),c=r.in_reply_to===void 0||r.in_reply_to===null?void 0:Bs(r,"in_reply_to"),l={v:1,msg_id:n,to:i,from:a,sent_at:o,payload:s,...c!==void 0?{in_reply_to:c}:{}};return bk(l)}function Bs(e,t){let r=t.split(".").pop(),n=e[r];if(typeof n!="string"||n.length===0)throw new Error(`envelope.${t} must be a non-empty string, got ${JSON.stringify(n)}`);return n}function mc(e,t,r){let n=t.split(".").pop(),o=e[n];if(typeof o!="string"){let s=r?"a string":"a non-empty string";throw new Error(`envelope.${t} must be ${s}, got ${JSON.stringify(o)}`)}try{pn(o,t,r)}catch(s){throw new Error(`envelope.${s instanceof Error?s.message:String(s)}`)}return o}function Wm(e,t){let r=t.split(".").pop(),n=e[r];if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`envelope.${t} must be an object, got ${JSON.stringify(n)}`);let o=n;return{site:mc(o,`${t}.site`,!1),team:mc(o,`${t}.team`,!0),alias:mc(o,`${t}.alias`,!1)}}function Vm(e,t,r){if(e.prepare(`INSERT INTO mail_ledger(
144
144
  msg_id, seq, state, to_site, to_team, to_alias, from_site, from_team, from_alias,
145
145
  sender_user_id, sent_at, payload, received_ts
146
146
  ) VALUES (?, ?, 'persisted', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
147
- ON CONFLICT(msg_id) DO NOTHING`).run(t.msgId,t.seq,t.to.site,t.to.team,t.to.alias,t.from.site,t.from.team,t.from.alias,t.senderUserId,t.sentAt,t.payload,r).changes>0)return"inserted";let o=uc(e,t.msgId);return o===null?"inserted":o.seq===t.seq&&o.to_site===t.to.site&&o.to_team===t.to.team&&o.to_alias===t.to.alias&&o.from_site===t.from.site&&o.from_team===t.from.team&&o.from_alias===t.from.alias&&o.sender_user_id===t.senderUserId&&o.sent_at===t.sentAt&&o.payload===t.payload?"duplicate":"conflict"}function Wm(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'persisted' ORDER BY seq").all()}function uc(e,t){return e.prepare("SELECT * FROM mail_ledger WHERE msg_id = ?").get(t)??null}function Gm(e){return e.prepare("SELECT MAX(seq) as maxSeq FROM mail_ledger").get().maxSeq}function Vm(e,t,r){return e.prepare("UPDATE mail_ledger SET state = 'dispatched', dispatched_ts = ? WHERE msg_id = ? AND state = 'persisted'").run(r,t).changes>0}function Jm(e,t,r){return e.prepare("UPDATE mail_ledger SET state = 'replied', replied_ts = ? WHERE msg_id = ? AND state = 'dispatched'").run(r,t).changes>0}function Tn(e,t,r,n){return e.prepare(`UPDATE mail_ledger
147
+ ON CONFLICT(msg_id) DO NOTHING`).run(t.msgId,t.seq,t.to.site,t.to.team,t.to.alias,t.from.site,t.from.team,t.from.alias,t.senderUserId,t.sentAt,t.payload,r).changes>0)return"inserted";let o=fc(e,t.msgId);return o===null?"inserted":o.seq===t.seq&&o.to_site===t.to.site&&o.to_team===t.to.team&&o.to_alias===t.to.alias&&o.from_site===t.from.site&&o.from_team===t.from.team&&o.from_alias===t.from.alias&&o.sender_user_id===t.senderUserId&&o.sent_at===t.sentAt&&o.payload===t.payload?"duplicate":"conflict"}function Jm(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'persisted' ORDER BY seq").all()}function fc(e,t){return e.prepare("SELECT * FROM mail_ledger WHERE msg_id = ?").get(t)??null}function Km(e){return e.prepare("SELECT MAX(seq) as maxSeq FROM mail_ledger").get().maxSeq}function zm(e,t,r){return e.prepare("UPDATE mail_ledger SET state = 'dispatched', dispatched_ts = ? WHERE msg_id = ? AND state = 'persisted'").run(r,t).changes>0}function Ym(e,t,r){return e.prepare("UPDATE mail_ledger SET state = 'replied', replied_ts = ? WHERE msg_id = ? AND state = 'dispatched'").run(r,t).changes>0}function Tn(e,t,r,n){return e.prepare(`UPDATE mail_ledger
148
148
  SET state = 'failed', failed_ts = ?, failure_reason = ?, retry_count = retry_count + 1
149
- WHERE msg_id = ? AND state IN ('persisted', 'dispatched')`).run(n,r,t).changes>0}var dc={baseMs:6e4,maxMs:30*6e4};function w$(e,t){let r=Math.max(0,e-1);return Math.min(t.baseMs*2**r,t.maxMs)}var Yr="PERMANENT: ";function mc(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'failed' AND failed_ts IS NOT NULL ORDER BY seq").all()}function qs(e,t,r=dc){let n=Date.parse(t);return mc(e).filter(o=>{if(o.failure_reason?.startsWith(Yr))return!1;let s=Date.parse(o.failed_ts);return Number.isFinite(s)?n-s>=w$(o.retry_count,r):!1})}function Km(e){let t=e.prepare("SELECT state, COUNT(*) as n FROM mail_ledger GROUP BY state").all(),r={persisted:0,dispatched:0,replied:0,failed:0};for(let n of t)r[n.state]=n.n;return r}function zm(e,t){return e.prepare("UPDATE mail_ledger SET state = 'persisted' WHERE msg_id = ? AND state = 'failed'").run(t).changes>0}function Ym(e,t,r){return e.prepare("UPDATE mail_ledger SET ack_sent_ts = ? WHERE msg_id = ? AND ack_sent_ts IS NULL").run(r,t).changes>0}function Qm(e,t,r,n){return e.prepare("UPDATE mail_ledger SET delivery_error = ?, delivery_error_ts = ? WHERE msg_id = ?").run(r,n,t).changes>0}function Xm(e){return e.prepare("SELECT COUNT(*) as n FROM mail_ledger WHERE delivery_error IS NOT NULL").get().n}function fc(e,t,r){e.prepare(`INSERT INTO mail_outbound_ledger(
149
+ WHERE msg_id = ? AND state IN ('persisted', 'dispatched')`).run(n,r,t).changes>0}var pc={baseMs:6e4,maxMs:30*6e4};function Sk(e,t){let r=Math.max(0,e-1);return Math.min(t.baseMs*2**r,t.maxMs)}var Yr="PERMANENT: ";function hc(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'failed' AND failed_ts IS NOT NULL ORDER BY seq").all()}function Ws(e,t,r=pc){let n=Date.parse(t);return hc(e).filter(o=>{if(o.failure_reason?.startsWith(Yr))return!1;let s=Date.parse(o.failed_ts);return Number.isFinite(s)?n-s>=Sk(o.retry_count,r):!1})}function Qm(e){let t=e.prepare("SELECT state, COUNT(*) as n FROM mail_ledger GROUP BY state").all(),r={persisted:0,dispatched:0,replied:0,failed:0};for(let n of t)r[n.state]=n.n;return r}function Xm(e,t){return e.prepare("UPDATE mail_ledger SET state = 'persisted' WHERE msg_id = ? AND state = 'failed'").run(t).changes>0}function Zm(e,t,r){return e.prepare("UPDATE mail_ledger SET ack_sent_ts = ? WHERE msg_id = ? AND ack_sent_ts IS NULL").run(r,t).changes>0}function ef(e,t,r,n){return e.prepare("UPDATE mail_ledger SET delivery_error = ?, delivery_error_ts = ? WHERE msg_id = ?").run(r,n,t).changes>0}function tf(e){return e.prepare("SELECT COUNT(*) as n FROM mail_ledger WHERE delivery_error IS NOT NULL").get().n}function gc(e,t,r){e.prepare(`INSERT INTO mail_outbound_ledger(
150
150
  msg_id, to_site, to_team, to_alias, from_site, from_team, from_alias, state, sent_ts, queue_id
151
151
  ) VALUES (?, ?, ?, ?, ?, ?, ?, 'sent', ?, ?)
152
- ON CONFLICT(msg_id) DO NOTHING`).run(t.msgId,t.to.site,t.to.team,t.to.alias,t.from.site,t.from.team,t.from.alias,r,t.queueId)}function Zm(e,t){return e.prepare("SELECT * FROM mail_outbound_ledger WHERE msg_id = ?").get(t)??null}function ef(e,t,r){return e.prepare("UPDATE mail_outbound_ledger SET state = 'acked', acked_ts = ? WHERE msg_id = ? AND state = 'sent'").run(r,t).changes>0}function tf(e,t,r){return e.prepare("UPDATE mail_outbound_ledger SET state = 'replied', replied_ts = ? WHERE msg_id = ? AND state IN ('sent', 'acked')").run(r,t).changes>0}function js(e,t){return e.prepare(`SELECT * FROM mail_outbound_ledger
152
+ ON CONFLICT(msg_id) DO NOTHING`).run(t.msgId,t.to.site,t.to.team,t.to.alias,t.from.site,t.from.team,t.from.alias,r,t.queueId)}function rf(e,t){return e.prepare("SELECT * FROM mail_outbound_ledger WHERE msg_id = ?").get(t)??null}function nf(e,t,r){return e.prepare("UPDATE mail_outbound_ledger SET state = 'acked', acked_ts = ? WHERE msg_id = ? AND state = 'sent'").run(r,t).changes>0}function of(e,t,r){return e.prepare("UPDATE mail_outbound_ledger SET state = 'replied', replied_ts = ? WHERE msg_id = ? AND state IN ('sent', 'acked')").run(r,t).changes>0}function Gs(e,t){return e.prepare(`SELECT * FROM mail_outbound_ledger
153
153
  WHERE to_site = ? AND to_team = ? AND to_alias = ?
154
- ORDER BY id DESC LIMIT 1`).get(t.site,t.team,t.alias)??null}import{readFileSync as y$}from"node:fs";var E$=/^MemTotal:\s+(\d+)\s*kB/m,T$=/^MemAvailable:\s+(\d+)\s*kB/m;function Hs(e){return e===null?null:`memory headroom: ${e.percentAvailable.toFixed(1)}% available (context only, not a wake trigger)`}function To(e="/proc/meminfo"){let t;try{t=y$(e,"utf8")}catch{return null}let r=E$.exec(t),n=T$.exec(t);if(!r||!n)return null;let o=Number(r[1]),s=Number(n[1]);return!Number.isFinite(o)||o<=0||!Number.isFinite(s)||s<0?null:{totalKb:o,availableKb:s,percentAvailable:s/o*100}}var pc=10;function rf(e=pc,t=To){if(e<=0)return!0;let r=t();return r===null?(process.stderr.write(`[memory] could not read /proc/meminfo -- deferring dispatch conservatively (set --min-memory-percent 0 to disable this gate)
155
- `),!1):r.percentAvailable>=e}var L=class extends Error{code;exitCode;constructor(t,r,n=2){super(r),this.code=t,this.exitCode=n}};function Ws(){return process.env.LMBEE_QUEUE_DIR?process.env.LMBEE_QUEUE_DIR:cf(v$(),".lmbee","queue")}function $$(e,t,r){sf(r)||b$(r,{recursive:!0});let n=cf(r,`${e}.md`);return af(n,t),n}function Qr(e){if(e==="operator")return{baseId:e,alias:null};let t=e.indexOf(":");return t===-1?{baseId:e,alias:null}:{baseId:e.slice(0,t),alias:e.slice(t+1)}}function _e(e,t,r,n,o){if(!o.from)throw new Error("enqueue: options.from is required ('autopilot', 'operator', or a maintainer team name)");let{baseId:s,alias:i}=Qr(r);if(s==="math"&&o.from==="autopilot"&&o.subject!==void 0&&t.some(d=>d.name==="triage")&&(s="triage",i=null),s!=="operator"&&!t.some(d=>d.name===s))throw new Error(`enqueue: unknown team "${s}"`);let a=new Date().toISOString(),c=o.dedupeKey??null,l=o.expectsResponse??(o.from==="operator"||s==="operator");return e.transaction(()=>{let d=e.prepare(`INSERT INTO queue(from_id, to_id, prompt_file, status, created_ts, subject_id, dedupe_key, escalation_only, expects_response, to_alias, retraction_notice, in_reply_to, operator_priority)
154
+ ORDER BY id DESC LIMIT 1`).get(t.site,t.team,t.alias)??null}import{readFileSync as vk}from"node:fs";var Ak=/^MemTotal:\s+(\d+)\s*kB/m,kk=/^MemAvailable:\s+(\d+)\s*kB/m;function Vs(e){return e===null?null:`memory headroom: ${e.percentAvailable.toFixed(1)}% available (context only, not a wake trigger)`}function So(e="/proc/meminfo"){let t;try{t=vk(e,"utf8")}catch{return null}let r=Ak.exec(t),n=kk.exec(t);if(!r||!n)return null;let o=Number(r[1]),s=Number(n[1]);return!Number.isFinite(o)||o<=0||!Number.isFinite(s)||s<0?null:{totalKb:o,availableKb:s,percentAvailable:s/o*100}}var _c=10;function sf(e=_c,t=So){if(e<=0)return!0;let r=t();return r===null?(process.stderr.write(`[memory] could not read /proc/meminfo -- deferring dispatch conservatively (set --min-memory-percent 0 to disable this gate)
155
+ `),!1):r.percentAvailable>=e}var I=class extends Error{code;exitCode;constructor(t,r,n=2){super(r),this.code=t,this.exitCode=n}};function Ks(){return process.env.LMBEE_QUEUE_DIR?process.env.LMBEE_QUEUE_DIR:df(Rk(),".lmbee","queue")}function Lk(e,t,r){lf(r)||$k(r,{recursive:!0});let n=df(r,`${e}.md`);return uf(n,t),n}function Qr(e){if(e==="operator")return{baseId:e,alias:null};let t=e.indexOf(":");return t===-1?{baseId:e,alias:null}:{baseId:e.slice(0,t),alias:e.slice(t+1)}}function _e(e,t,r,n,o){if(!o.from)throw new Error("enqueue: options.from is required ('autopilot', 'operator', or a maintainer team name)");let{baseId:s,alias:i}=Qr(r);if(s==="math"&&o.from==="autopilot"&&o.subject!==void 0&&t.some(d=>d.name==="triage")&&(s="triage",i=null),s!=="operator"&&!t.some(d=>d.name===s))throw new Error(`enqueue: unknown team "${s}"`);let a=new Date().toISOString(),c=o.dedupeKey??null,l=o.expectsResponse??(o.from==="operator"||s==="operator");return e.transaction(()=>{let d=e.prepare(`INSERT INTO queue(from_id, to_id, prompt_file, status, created_ts, subject_id, dedupe_key, escalation_only, expects_response, to_alias, retraction_notice, in_reply_to, operator_priority)
156
156
  VALUES (?, ?, '', 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?)
157
- ON CONFLICT(dedupe_key) DO NOTHING`).run(o.from,s,a,o.subject??null,c,o.escalationOnly?1:0,l?1:0,i,o.retractionNotice?1:0,o.inReplyTo??null,o.operatorPriority?1:0);if(d.changes===0){let p=e.prepare("SELECT id FROM queue WHERE dedupe_key = ?").get(c);if(!p)throw new Error(`enqueue: dedupe conflict on "${c}" but the existing row is already gone`);return p.id}let m=Number(d.lastInsertRowid),f=$$(m,n,o.queueDir??Ws());return e.prepare("UPDATE queue SET prompt_file = ? WHERE id = ?").run(f,m),m}).immediate()}function hc(e,t,r=30){return t?e.prepare("SELECT * FROM queue WHERE to_id = ? ORDER BY id DESC LIMIT ?").all(t,r):e.prepare("SELECT * FROM queue ORDER BY id DESC LIMIT ?").all(r)}function lf(e,t,r={}){return r.fromAutopilot?e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' AND from_id = 'autopilot' AND subject_id IS NULL ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(t)}function qe(e,t,r={}){return r.fromAutopilot?e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating') AND from_id = 'autopilot' AND subject_id IS NULL ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating') ORDER BY id").all(t)}function Gs(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(t),n=[];for(let o of r){let s=[o.from_id,o.to_id,o.escalation_only,o.to_alias],a=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...s,o.id).id??Number.MAX_SAFE_INTEGER,c=e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ? AND retracted_ts IS NULL").all(...s,o.id,a);n.push(...c)}return n.sort((o,s)=>o.id-s.id),n}function yr(e,t){return e.prepare("SELECT * FROM queue WHERE id = ?").get(t)??null}function uf(e,t){return e.prepare(`SELECT (
157
+ ON CONFLICT(dedupe_key) DO NOTHING`).run(o.from,s,a,o.subject??null,c,o.escalationOnly?1:0,l?1:0,i,o.retractionNotice?1:0,o.inReplyTo??null,o.operatorPriority?1:0);if(d.changes===0){let p=e.prepare("SELECT id FROM queue WHERE dedupe_key = ?").get(c);if(!p)throw new Error(`enqueue: dedupe conflict on "${c}" but the existing row is already gone`);return p.id}let m=Number(d.lastInsertRowid),f=Lk(m,n,o.queueDir??Ks());return e.prepare("UPDATE queue SET prompt_file = ? WHERE id = ?").run(f,m),m}).immediate()}function wc(e,t,r=30){return t?e.prepare("SELECT * FROM queue WHERE to_id = ? ORDER BY id DESC LIMIT ?").all(t,r):e.prepare("SELECT * FROM queue ORDER BY id DESC LIMIT ?").all(r)}function mf(e,t,r={}){return r.fromAutopilot?e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' AND from_id = 'autopilot' AND subject_id IS NULL ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(t)}function qe(e,t,r={}){return r.fromAutopilot?e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating') AND from_id = 'autopilot' AND subject_id IS NULL ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating') ORDER BY id").all(t)}function zs(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(t),n=[];for(let o of r){let s=[o.from_id,o.to_id,o.escalation_only,o.to_alias],a=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...s,o.id).id??Number.MAX_SAFE_INTEGER,c=e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ? AND retracted_ts IS NULL").all(...s,o.id,a);n.push(...c)}return n.sort((o,s)=>o.id-s.id),n}function Er(e,t){return e.prepare("SELECT * FROM queue WHERE id = ?").get(t)??null}function ff(e,t){return e.prepare(`SELECT (
158
158
  EXISTS(SELECT 1 FROM queue WHERE to_id = ? AND sent_ts IS NOT NULL)
159
159
  OR EXISTS(SELECT 1 FROM queue WHERE from_id = ?)
160
- ) AS found`).get(t,t).found===1}var gc=["pending","sent","retrieved","escalating","merged"];function k$(e){let{escalation_claim_token:t,prompt_file:r,admission_fingerprint:n,...o}=e;return o}var x$=50,bo=200;function _c(e,t={}){let r=t.limit??x$;if(!Number.isSafeInteger(r)||r<1||r>bo)throw new L("INVALID_ARGUMENT",`limit must be a positive integer <= ${bo}`);let n=[],o=[];t.fromId!==void 0&&(n.push("from_id = ?"),o.push(t.fromId)),t.toId!==void 0&&(n.push("to_id = ?"),o.push(t.toId)),t.status!==void 0&&(n.push("status = ?"),o.push(t.status)),t.since!==void 0&&(n.push("created_ts >= ?"),o.push(t.since)),t.until!==void 0&&(n.push("created_ts < ?"),o.push(t.until)),t.after!==void 0&&(n.push("id < ?"),o.push(t.after));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",i=e.prepare(`SELECT * FROM queue ${s} ORDER BY id DESC LIMIT ?`).all(...o,r+1).map(k$),a=i.length>r,c=a?i.slice(0,r):i;return{rows:c,meta:{next_cursor:a?c[c.length-1].id:null}}}function R$(e,t){return e.prepare("UPDATE queue SET status = 'sent', sent_ts = ? WHERE id = ? AND status = 'pending'").run(new Date().toISOString(),t).changes>0}function N$(e){return`'${e.replaceAll("'","'\\''")}'`}function I$(e,t,r){return`${e}
160
+ ) AS found`).get(t,t).found===1}var yc=["pending","sent","retrieved","escalating","merged"];function Ik(e){let{escalation_claim_token:t,prompt_file:r,admission_fingerprint:n,...o}=e;return o}var Ck=50,vo=200;function Ec(e,t={}){let r=t.limit??Ck;if(!Number.isSafeInteger(r)||r<1||r>vo)throw new I("INVALID_ARGUMENT",`limit must be a positive integer <= ${vo}`);let n=[],o=[];t.fromId!==void 0&&(n.push("from_id = ?"),o.push(t.fromId)),t.toId!==void 0&&(n.push("to_id = ?"),o.push(t.toId)),t.status!==void 0&&(n.push("status = ?"),o.push(t.status)),t.since!==void 0&&(n.push("created_ts >= ?"),o.push(t.since)),t.until!==void 0&&(n.push("created_ts < ?"),o.push(t.until)),t.after!==void 0&&(n.push("id < ?"),o.push(t.after));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",i=e.prepare(`SELECT * FROM queue ${s} ORDER BY id DESC LIMIT ?`).all(...o,r+1).map(Ik),a=i.length>r,c=a?i.slice(0,r):i;return{rows:c,meta:{next_cursor:a?c[c.length-1].id:null}}}function Ok(e,t){return e.prepare("UPDATE queue SET status = 'sent', sent_ts = ? WHERE id = ? AND status = 'pending'").run(new Date().toISOString(),t).changes>0}function Dk(e){return`'${e.replaceAll("'","'\\''")}'`}function Mk(e,t,r){return`${e}
161
161
 
162
- [Delivery receipt: after reading this prompt, run \`lmbee queue retrieve ${N$(t)} --id ${r}\` to record that you received queue#${r}.]`}function L$(e,t,r,n,o){let i=(t.now??(()=>new Date().toISOString()))(),a={v:1,msgId:of(),to:{site:r.peerSite,team:r.name,alias:r.alias},from:{site:t.localSiteId,team:"",alias:n.from_id},sentAt:i,payload:o};fc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:n.id},i);let c=zr(r.peerSite),l=new TextEncoder().encode(Eo(a));t.client.sendMessage({mailbox:c,subject:`lmauto delivery ${a.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:l}}).catch(u=>{process.stderr.write(`[deliver] failed to send remote envelope to mailbox ${c} (team ${r.name}): ${u instanceof Error?u.message:String(u)}
163
- `)})}function C$(e,t,r,n,o,s=n.leadAlias){let i=t.now??(()=>new Date().toISOString()),a={v:1,msgId:of(),to:{site:r.from_site,team:r.from_team,alias:r.from_alias},from:{site:t.localSiteId,team:n.name,alias:s},sentAt:i(),payload:o,inReplyTo:r.msg_id},c=zr(r.from_site),l=new TextEncoder().encode(Eo(a));return t.client.sendMessage({mailbox:c,subject:`lmauto reply ${a.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:l}}).then(()=>{let u=i();fc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:null},u),Jm(e,r.msg_id,u)}).catch(u=>{let d=u instanceof Error?u.message:String(u);process.stderr.write(`[deliver] failed to send reply envelope to mailbox ${c} (in_reply_to ${r.msg_id}): ${d}
164
- `),Tn(e,r.msg_id,`${Yr}reply-send failed: ${d}`,i())})}function O$(e,t,r,n){if(!t.remoteMail)return!1;try{Bs(n.prompt_file,"utf8")}catch{return!1}if(!R$(e,n.id))return!1;let o;try{o=Bs(n.prompt_file,"utf8")}catch(s){return process.stderr.write(`[deliver] queue row #${n.id} claimed 'sent' but its prompt file became unreadable before dispatch -- nothing was actually sent: ${s instanceof Error?s.message:String(s)}
165
- `),!0}return L$(e,t.remoteMail,r,n,o),!0}function D$(e){let t=new Map,r=[];for(let n of e){if(!H(n))continue;let o;try{o=Q(n)}catch{continue}t.set(n.name,n),r.push({name:n.name,teamfilePath:o,leadAlias:n.leadAlias})}return{refs:r,byName:t}}function wc(e){let t=e.expects_response?" (expects a response)":"";return`--- addendum from ${e.from_id}, ${e.created_ts}${t} ---`}function M$(e,t){let r=new Map;for(let n of t){if(n.dedupe_key!==null)continue;let o=JSON.stringify([n.to_id,n.escalation_only,n.to_alias]),s=r.get(o);s?s.push(n):r.set(o,[n])}for(let n of r.values()){if(n.length<2)continue;let[o,...s]=n;if(e.prepare("UPDATE queue SET status = 'pending' WHERE id = ? AND status = 'pending'").run(o.id).changes===0)continue;let a;try{a=Bs(o.prompt_file,"utf8")}catch{continue}let c=[],l=!0;for(let d of s)try{c.push(`
162
+ [Delivery receipt: after reading this prompt, run \`lmbee queue retrieve ${Dk(t)} --id ${r}\` to record that you received queue#${r}.]`}function Pk(e,t,r,n,o){let i=(t.now??(()=>new Date().toISOString()))(),a={v:1,msgId:cf(),to:{site:r.peerSite,team:r.name,alias:r.alias},from:{site:t.localSiteId,team:"",alias:n.from_id},sentAt:i,payload:o};gc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:n.id},i);let c=zr(r.peerSite),l=new TextEncoder().encode(bo(a));t.client.sendMessage({mailbox:c,subject:`lmauto delivery ${a.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:l}}).catch(u=>{process.stderr.write(`[deliver] failed to send remote envelope to mailbox ${c} (team ${r.name}): ${u instanceof Error?u.message:String(u)}
163
+ `)})}function Uk(e,t,r,n,o,s=n.leadAlias){let i=t.now??(()=>new Date().toISOString()),a={v:1,msgId:cf(),to:{site:r.from_site,team:r.from_team,alias:r.from_alias},from:{site:t.localSiteId,team:n.name,alias:s},sentAt:i(),payload:o,inReplyTo:r.msg_id},c=zr(r.from_site),l=new TextEncoder().encode(bo(a));return t.client.sendMessage({mailbox:c,subject:`lmauto reply ${a.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:l}}).then(()=>{let u=i();gc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:null},u),Ym(e,r.msg_id,u)}).catch(u=>{let d=u instanceof Error?u.message:String(u);process.stderr.write(`[deliver] failed to send reply envelope to mailbox ${c} (in_reply_to ${r.msg_id}): ${d}
164
+ `),Tn(e,r.msg_id,`${Yr}reply-send failed: ${d}`,i())})}function Fk(e,t,r,n){if(!t.remoteMail)return!1;try{Js(n.prompt_file,"utf8")}catch{return!1}if(!Ok(e,n.id))return!1;let o;try{o=Js(n.prompt_file,"utf8")}catch(s){return process.stderr.write(`[deliver] queue row #${n.id} claimed 'sent' but its prompt file became unreadable before dispatch -- nothing was actually sent: ${s instanceof Error?s.message:String(s)}
165
+ `),!0}return Pk(e,t.remoteMail,r,n,o),!0}function qk(e){let t=new Map,r=[];for(let n of e){if(!B(n))continue;let o;try{o=Q(n)}catch{continue}t.set(n.name,n),r.push({name:n.name,teamfilePath:o,leadAlias:n.leadAlias})}return{refs:r,byName:t}}function Tc(e){let t=e.expects_response?" (expects a response)":"";return`--- addendum from ${e.from_id}, ${e.created_ts}${t} ---`}function jk(e,t){let r=new Map;for(let n of t){if(n.dedupe_key!==null)continue;let o=JSON.stringify([n.to_id,n.escalation_only,n.to_alias]),s=r.get(o);s?s.push(n):r.set(o,[n])}for(let n of r.values()){if(n.length<2)continue;let[o,...s]=n;if(e.prepare("UPDATE queue SET status = 'pending' WHERE id = ? AND status = 'pending'").run(o.id).changes===0)continue;let a;try{a=Js(o.prompt_file,"utf8")}catch{continue}let c=[],l=!0;for(let d of s)try{c.push(`
166
166
 
167
- ${wc(d)}
168
- ${Bs(d.prompt_file,"utf8")}`)}catch{l=!1;break}if(!l||c.length===0)continue;af(o.prompt_file,a+c.join(""));let u=e.prepare("UPDATE queue SET status = 'merged', merged_into_id = ? WHERE id = ? AND status = 'pending'");for(let d of s)u.run(o.id,d.id);n.some(d=>d.expects_response)&&!o.expects_response&&e.prepare("UPDATE queue SET expects_response = 1 WHERE id = ?").run(o.id)}}function Er(e,t){let r=t.send??Rm,n=t.sendAwaited??Ht,o=t.memoryCheck??rf,{refs:s,byName:i}=D$(t.teams),a=(t.teamName?e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 AND to_id = ? ORDER BY id").all(t.teamName):e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 ORDER BY id").all()).filter(d=>i.has(d.to_id));M$(e,a);let c=ac(e,s,{teamName:t.teamName,isTeamBusy:d=>Fe(i.get(d.name),t.report)||Nm(e,d.name)||Pm(e,d.name),minMemoryPercent:t.minMemoryPercent,memoryCheck:o,send:(d,m)=>r(d,m),onDispatch:({row:d,team:m,target:f,promptText:p})=>{let h=d.dedupe_key!==null&&t.remoteMail?uc(e,d.dedupe_key):null,w=I$(p,m.name,d.id);if(!h||!t.remoteMail)return r(f,w),!0;let _=t.remoteMail,E=i.get(m.name);return n(f,w).then(T=>{T.kind==="ok"||T.kind==="stalled"?C$(e,_,h,E,T.replyText,f.alias):(process.stderr.write(`[deliver] mail-originated dispatch to ${m.name} (in_reply_to ${h.msg_id}) produced no reply to mail back: ${T.kind}
169
- `),T.kind==="error"&&Qm(e,h.msg_id,T.message,(_.now??(()=>new Date().toISOString()))()))}).catch(T=>{process.stderr.write(`[deliver] failed to capture reply for mail-originated dispatch to ${m.name} (in_reply_to ${h.msg_id}): ${T instanceof Error?T.message:String(T)}
167
+ ${Tc(d)}
168
+ ${Js(d.prompt_file,"utf8")}`)}catch{l=!1;break}if(!l||c.length===0)continue;uf(o.prompt_file,a+c.join(""));let u=e.prepare("UPDATE queue SET status = 'merged', merged_into_id = ? WHERE id = ? AND status = 'pending'");for(let d of s)u.run(o.id,d.id);n.some(d=>d.expects_response)&&!o.expects_response&&e.prepare("UPDATE queue SET expects_response = 1 WHERE id = ?").run(o.id)}}function Tr(e,t){let r=t.send??Im,n=t.sendAwaited??Ht,o=t.memoryCheck??sf,{refs:s,byName:i}=qk(t.teams),a=(t.teamName?e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 AND to_id = ? ORDER BY id").all(t.teamName):e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 ORDER BY id").all()).filter(d=>i.has(d.to_id));jk(e,a);let c=uc(e,s,{teamName:t.teamName,isTeamBusy:d=>Fe(i.get(d.name),t.report)||Cm(e,d.name)||qm(e,d.name),minMemoryPercent:t.minMemoryPercent,memoryCheck:o,send:(d,m)=>r(d,m),onDispatch:({row:d,team:m,target:f,promptText:p})=>{let h=d.dedupe_key!==null&&t.remoteMail?fc(e,d.dedupe_key):null,w=Mk(p,m.name,d.id);if(!h||!t.remoteMail)return r(f,w),!0;let _=t.remoteMail,T=i.get(m.name);return n(f,w).then(E=>{E.kind==="ok"||E.kind==="stalled"?Uk(e,_,h,T,E.replyText,f.alias):(process.stderr.write(`[deliver] mail-originated dispatch to ${m.name} (in_reply_to ${h.msg_id}) produced no reply to mail back: ${E.kind}
169
+ `),E.kind==="error"&&ef(e,h.msg_id,E.message,(_.now??(()=>new Date().toISOString()))()))}).catch(E=>{process.stderr.write(`[deliver] failed to capture reply for mail-originated dispatch to ${m.name} (in_reply_to ${h.msg_id}): ${E instanceof Error?E.message:String(E)}
170
170
  `)}),!0}}),l=t.teamName?e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 AND to_id = ? ORDER BY id").all(t.teamName):e.prepare("SELECT * FROM queue WHERE status = 'pending' AND escalation_only = 0 ORDER BY id").all(),u=new Set;for(let d of l){let m=d.to_alias===null?d.to_id:`${d.to_id}:${d.to_alias}`;if(u.has(m)||(u.add(m),d.to_id==="operator"))continue;let f=t.teams.find(p=>p.name===d.to_id);if(!f){process.stderr.write(`[deliver] queue row #${d.id} addressed to unregistered team "${d.to_id}" -- left pending
171
- `);continue}H(f)||O$(e,t,f,d)&&c++}return c}function Vs(e,t,r){return r!==void 0?P$(e,t,r):e.transaction(o=>{let s=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(o);if(s.length===0)return s;let i=new Date().toISOString(),a=e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = ? WHERE id = ? AND status = 'pending'"),c=[];for(let l of s)a.run(i,l.id).changes!==0&&(l.status="retrieved",l.retrieved_ts=i,c.push(l));return c})(t)}function P$(e,t,r){if(!Number.isSafeInteger(r)||r<=0)throw new L("INVALID_ARGUMENT",`Queue prompt id must be a positive integer: ${r}`,2);return e.transaction((o,s)=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(s);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${s} was not found`,2);if(i.to_id!==o)throw new L("INVALID_ARGUMENT",`Queue prompt ${s} is addressed to "${i.to_id}", not "${o}"`,2);if(i.retracted_ts!==null)throw new L("CONFLICT",`Queue prompt ${s} was retracted: ${i.retracted_reason??"(no reason recorded)"}`,4);if(i.status==="merged"||i.merged_into_id!==null)throw new L("CONFLICT",`Queue prompt ${s} was merged into ${i.merged_into_id??"another prompt"}`,4);if(i.status!=="pending"&&i.status!=="sent"&&i.status!=="retrieved")throw new L("CONFLICT",`Queue prompt ${s} is not eligible for receipt (status: ${i.status})`,4);if(i.status!=="retrieved"){let c=new Date().toISOString();e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ? AND status IN ('pending', 'sent')").run(c,s)}let a=e.prepare("SELECT * FROM queue WHERE id = ?").get(s);if(a.status==="retrieved"){let c=a.retrieved_ts??new Date().toISOString();e.prepare(`WITH RECURSIVE descendants(id) AS (
171
+ `);continue}B(f)||Fk(e,t,f,d)&&c++}return c}function Ys(e,t,r){return r!==void 0?Hk(e,t,r):e.transaction(o=>{let s=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'pending' ORDER BY id").all(o);if(s.length===0)return s;let i=new Date().toISOString(),a=e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = ? WHERE id = ? AND status = 'pending'"),c=[];for(let l of s)a.run(i,l.id).changes!==0&&(l.status="retrieved",l.retrieved_ts=i,c.push(l));return c})(t)}function Hk(e,t,r){if(!Number.isSafeInteger(r)||r<=0)throw new I("INVALID_ARGUMENT",`Queue prompt id must be a positive integer: ${r}`,2);return e.transaction((o,s)=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(s);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${s} was not found`,2);if(i.to_id!==o)throw new I("INVALID_ARGUMENT",`Queue prompt ${s} is addressed to "${i.to_id}", not "${o}"`,2);if(i.retracted_ts!==null)throw new I("CONFLICT",`Queue prompt ${s} was retracted: ${i.retracted_reason??"(no reason recorded)"}`,4);if(i.status==="merged"||i.merged_into_id!==null)throw new I("CONFLICT",`Queue prompt ${s} was merged into ${i.merged_into_id??"another prompt"}`,4);if(i.status!=="pending"&&i.status!=="sent"&&i.status!=="retrieved")throw new I("CONFLICT",`Queue prompt ${s} is not eligible for receipt (status: ${i.status})`,4);if(i.status!=="retrieved"){let c=new Date().toISOString();e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ? AND status IN ('pending', 'sent')").run(c,s)}let a=e.prepare("SELECT * FROM queue WHERE id = ?").get(s);if(a.status==="retrieved"){let c=a.retrieved_ts??new Date().toISOString();e.prepare(`WITH RECURSIVE descendants(id) AS (
172
172
  SELECT id FROM queue WHERE merged_into_id = ? AND to_id = ?
173
173
  UNION ALL
174
174
  SELECT q.id FROM queue q JOIN descendants d ON q.merged_into_id = d.id WHERE q.to_id = ?
175
175
  )
176
- UPDATE queue SET retrieved_ts = COALESCE(retrieved_ts, ?) WHERE status = 'merged' AND id IN (SELECT id FROM descendants)`).run(s,o,o,c)}return[e.prepare("SELECT * FROM queue WHERE id = ?").get(s)]}).immediate(t,r)}function df(e,t={}){let r=nf(t.queueDir??Ws()),n=t.retentionMs??7*24*60*6e4,o=t.nowMs??Date.now(),s=new Date(o-n).toISOString(),i=e.prepare(`SELECT id, prompt_file FROM queue
176
+ UPDATE queue SET retrieved_ts = COALESCE(retrieved_ts, ?) WHERE status = 'merged' AND id IN (SELECT id FROM descendants)`).run(s,o,o,c)}return[e.prepare("SELECT * FROM queue WHERE id = ?").get(s)]}).immediate(t,r)}function pf(e,t={}){let r=af(t.queueDir??Ks()),n=t.retentionMs??7*24*60*6e4,o=t.nowMs??Date.now(),s=new Date(o-n).toISOString(),i=e.prepare(`SELECT id, prompt_file FROM queue
177
177
  WHERE (status = 'sent' AND sent_ts IS NOT NULL AND sent_ts < ?)
178
178
  OR (status = 'retrieved' AND retrieved_ts IS NOT NULL AND retrieved_ts < ?)
179
- OR (status = 'merged' AND created_ts < ?)`).all(s,s,s),a=0;for(let c of i){let l=nf(c.prompt_file);if(!(l!==r&&!l.startsWith(r+A$))&&sf(l))try{S$(l,{force:!0}),a++}catch{}}return a}import{spawn as W$}from"node:child_process";import{lstatSync as U$,readlinkSync as F$,realpathSync as q$}from"node:fs";import{homedir as j$}from"node:os";import{basename as H$,dirname as mf,isAbsolute as pf,join as B$,resolve as yc}from"node:path";var Tr="_lmauto_status_transition";function de(){return`${new Date().toISOString().replace("Z","000Z")}`}function ye(e,t){if(!e.trim())throw new L("INVALID_ARGUMENT",`${t} must not be blank`);return e}function Ec(e){let t;try{t=U$(e)}catch{let r=mf(e);return r===e?e:B$(Ec(r),H$(e))}if(t.isSymbolicLink()){let r=F$(e),n=pf(r)?r:yc(mf(e),r);return Ec(n)}return q$(e)}function At(e){let t=e==="~"||e.startsWith("~/")?e.replace(/^~/,j$()):e,r=pf(t)?yc(t):yc(process.cwd(),t);return Ec(r)}function bn(e){let t=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;if(t!==void 0&&(t.startsWith("SQLITE_BUSY")||t.startsWith("SQLITE_LOCKED")))throw new L("DB_BUSY","Database busy; retry after the current writer completes",5);let r=e instanceof Error?e.message:String(e);if(t!==void 0&&t.startsWith("SQLITE_CONSTRAINT")){let n={MISSING_PARENT:"NOT_FOUND",INVALID_PARENT_KIND:"INVALID_PARENT_KIND",PROJECT_MISMATCH:"PROJECT_MISMATCH",DEPENDENCY_CYCLE:"DEPENDENCY_CYCLE",IMMUTABLE_FIELD:"IMMUTABLE_FIELD",IMMUTABLE_EDGE:"IMMUTABLE_EDGE"};for(let[o,s]of Object.entries(n))if(r.includes(o))throw new L(s,r,s==="NOT_FOUND"?3:2);throw new L("STRUCTURAL_ERROR",r,2)}throw new L("STORAGE_ERROR",r,1)}function Et(e){try{return e()}catch(t){if(t instanceof L)throw t;return bn(t)}}function at(e,t){return Et(()=>e.prepare("SELECT * FROM entities WHERE id = ?").get(t)??null)}function Le(e,t){let r=at(e,t);if(r===null)throw new L("NOT_FOUND",`Entity ${t} does not exist`,3);return r}function hf(e,t,r,n){let o=n!==null?Le(e,n):null,s={epic:null,task:"epic",subtask:"task"};if(t==="epic"&&o!==null)throw new L("INVALID_PARENT_KIND","An epic cannot have a parent");if(t==="subtask"&&o===null)throw new L("INVALID_PARENT_KIND","A subtask requires a parent task");if(t==="task"&&o!==null&&o.kind!==s.task)throw new L("INVALID_PARENT_KIND","A task's parent must be an epic");if(t==="subtask"&&o!==null&&o.kind!==s.subtask)throw new L("INVALID_PARENT_KIND","A subtask's parent must be a task");if(o!==null&&o.project!==r)throw new L("PROJECT_MISMATCH","Parent and child projects must match");return o}function Js(e,t){e.prepare("UPDATE entities SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}var Ne=1e4;function gf(e,t,r,n){if(!Number.isSafeInteger(n)||n<1||n>Ne)throw new L("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return Et(()=>{let o=e.prepare(`${t} ORDER BY id LIMIT ?`).all(...r,n+1),s=o.length>n,i=s?o.slice(0,n):o;return{rows:i,meta:{next_cursor:s?i[i.length-1].id:null}}})}function ct(e,t,r){return Et(()=>{let n={},o=[["outgoing","entity_id","depends_on_id"],["incoming","depends_on_id","entity_id"]];for(let[s,i,a]of o)(r===s||r==="both")&&(n[s]=e.prepare(`SELECT e.id, e.title, e.kind, e.project, e.status FROM dependencies d JOIN entities e ON e.id = d.${a} WHERE d.${i} = ? ORDER BY e.id`).all(t));return n})}function _f(e,t){let r=e.transaction(()=>{let n=t.parentId!==void 0?Le(e,t.parentId):null,o=ye(t.project??n?.project??"default","project");if(t.owner!==void 0&&t.unassigned)throw new L("INVALID_ARGUMENT","Explicit owner and --unassigned are exclusive");try{hf(e,t.kind,o,t.parentId??null)}catch(u){if(u instanceof L)throw u;bn(u)}let s=null,i=null;t.owner!==void 0?(s=At(ye(t.owner.team,"owner team")),i=ye(t.owner.alias,"owner alias")):n!==null&&!t.unassigned&&(s=n.owner_team_path,i=n.owner_alias);let a=de(),c={kind:t.kind,project:o,parent_id:t.parentId??null,title:ye(t.title,"title"),description:t.description??"",requirements:t.requirements??"",acceptance_criteria:t.acceptanceCriteria??"",status:ye((t.status??"todo").trim(),"status"),owner_team_path:s,owner_alias:i,blocked_on:t.blockedOn??null,created_at:a,updated_at:a},l=Object.keys(c);try{let u=e.prepare(`INSERT INTO entities(${l.join(",")}) VALUES (${l.map(()=>"?").join(",")})`).run(...l.map(d=>c[d]));return Le(e,Number(u.lastInsertRowid))}catch(u){if(u instanceof L)throw u;return bn(u)}});return Et(r)}function br(e,t){if(t.owner!==void 0&&t.unassigned)throw new L("INVALID_ARGUMENT","Owner and --unassigned are exclusive");let r=["id > ?"],n=[t.after??0];return t.project!==void 0&&(r.push("project = ?"),n.push(t.project)),t.kind!==void 0&&(r.push("kind = ?"),n.push(t.kind)),t.status!==void 0&&(r.push("status = ?"),n.push(ye(t.status.trim(),"status"))),t.parentId!==void 0&&(r.push("parent_id = ?"),n.push(t.parentId)),t.owner!==void 0&&(r.push("owner_team_path = ?","owner_alias = ?"),n.push(At(t.owner.team),t.owner.alias)),t.unassigned&&r.push("owner_team_path IS NULL"),gf(e,`SELECT * FROM entities WHERE ${r.join(" AND ")}`,n,t.limit??100)}function Sr(e,t){let r=Le(e,t),n=Et(()=>e.prepare("SELECT id FROM entities WHERE parent_id = ? ORDER BY id").all(t).map(s=>s.id)),o=ct(e,t,"both");return{...r,children:n,dependencies:{outgoing:o.outgoing??[],incoming:o.incoming??[]}}}function wf(e,t){return Le(e,t),Et(()=>e.prepare(`WITH RECURSIVE subtree(id) AS (
179
+ OR (status = 'merged' AND created_ts < ?)`).all(s,s,s),a=0;for(let c of i){let l=af(c.prompt_file);if(!(l!==r&&!l.startsWith(r+Nk))&&lf(l))try{xk(l,{force:!0}),a++}catch{}}return a}import{spawn as zk}from"node:child_process";import{lstatSync as Bk,readlinkSync as Wk,realpathSync as Gk}from"node:fs";import{homedir as Vk}from"node:os";import{basename as Jk,dirname as hf,isAbsolute as _f,join as Kk,resolve as bc}from"node:path";var br="_lmauto_status_transition";function de(){return`${new Date().toISOString().replace("Z","000Z")}`}function ye(e,t){if(!e.trim())throw new I("INVALID_ARGUMENT",`${t} must not be blank`);return e}function Sc(e){let t;try{t=Bk(e)}catch{let r=hf(e);return r===e?e:Kk(Sc(r),Jk(e))}if(t.isSymbolicLink()){let r=Wk(e),n=_f(r)?r:bc(hf(e),r);return Sc(n)}return Gk(e)}function At(e){let t=e==="~"||e.startsWith("~/")?e.replace(/^~/,Vk()):e,r=_f(t)?bc(t):bc(process.cwd(),t);return Sc(r)}function bn(e){let t=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;if(t!==void 0&&(t.startsWith("SQLITE_BUSY")||t.startsWith("SQLITE_LOCKED")))throw new I("DB_BUSY","Database busy; retry after the current writer completes",5);let r=e instanceof Error?e.message:String(e);if(t!==void 0&&t.startsWith("SQLITE_CONSTRAINT")){let n={MISSING_PARENT:"NOT_FOUND",INVALID_PARENT_KIND:"INVALID_PARENT_KIND",PROJECT_MISMATCH:"PROJECT_MISMATCH",DEPENDENCY_CYCLE:"DEPENDENCY_CYCLE",IMMUTABLE_FIELD:"IMMUTABLE_FIELD",IMMUTABLE_EDGE:"IMMUTABLE_EDGE"};for(let[o,s]of Object.entries(n))if(r.includes(o))throw new I(s,r,s==="NOT_FOUND"?3:2);throw new I("STRUCTURAL_ERROR",r,2)}throw new I("STORAGE_ERROR",r,1)}function Tt(e){try{return e()}catch(t){if(t instanceof I)throw t;return bn(t)}}function at(e,t){return Tt(()=>e.prepare("SELECT * FROM entities WHERE id = ?").get(t)??null)}function Ie(e,t){let r=at(e,t);if(r===null)throw new I("NOT_FOUND",`Entity ${t} does not exist`,3);return r}function wf(e,t,r,n){let o=n!==null?Ie(e,n):null,s={epic:null,task:"epic",subtask:"task"};if(t==="epic"&&o!==null)throw new I("INVALID_PARENT_KIND","An epic cannot have a parent");if(t==="subtask"&&o===null)throw new I("INVALID_PARENT_KIND","A subtask requires a parent task");if(t==="task"&&o!==null&&o.kind!==s.task)throw new I("INVALID_PARENT_KIND","A task's parent must be an epic");if(t==="subtask"&&o!==null&&o.kind!==s.subtask)throw new I("INVALID_PARENT_KIND","A subtask's parent must be a task");if(o!==null&&o.project!==r)throw new I("PROJECT_MISMATCH","Parent and child projects must match");return o}function Qs(e,t){e.prepare("UPDATE entities SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}var Ne=1e4;function yf(e,t,r,n){if(!Number.isSafeInteger(n)||n<1||n>Ne)throw new I("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return Tt(()=>{let o=e.prepare(`${t} ORDER BY id LIMIT ?`).all(...r,n+1),s=o.length>n,i=s?o.slice(0,n):o;return{rows:i,meta:{next_cursor:s?i[i.length-1].id:null}}})}function ct(e,t,r){return Tt(()=>{let n={},o=[["outgoing","entity_id","depends_on_id"],["incoming","depends_on_id","entity_id"]];for(let[s,i,a]of o)(r===s||r==="both")&&(n[s]=e.prepare(`SELECT e.id, e.title, e.kind, e.project, e.status FROM dependencies d JOIN entities e ON e.id = d.${a} WHERE d.${i} = ? ORDER BY e.id`).all(t));return n})}function Ef(e,t){let r=e.transaction(()=>{let n=t.parentId!==void 0?Ie(e,t.parentId):null,o=ye(t.project??n?.project??"default","project");if(t.owner!==void 0&&t.unassigned)throw new I("INVALID_ARGUMENT","Explicit owner and --unassigned are exclusive");try{wf(e,t.kind,o,t.parentId??null)}catch(u){if(u instanceof I)throw u;bn(u)}let s=null,i=null;t.owner!==void 0?(s=At(ye(t.owner.team,"owner team")),i=ye(t.owner.alias,"owner alias")):n!==null&&!t.unassigned&&(s=n.owner_team_path,i=n.owner_alias);let a=de(),c={kind:t.kind,project:o,parent_id:t.parentId??null,title:ye(t.title,"title"),description:t.description??"",requirements:t.requirements??"",acceptance_criteria:t.acceptanceCriteria??"",status:ye((t.status??"todo").trim(),"status"),owner_team_path:s,owner_alias:i,blocked_on:t.blockedOn??null,created_at:a,updated_at:a},l=Object.keys(c);try{let u=e.prepare(`INSERT INTO entities(${l.join(",")}) VALUES (${l.map(()=>"?").join(",")})`).run(...l.map(d=>c[d]));return Ie(e,Number(u.lastInsertRowid))}catch(u){if(u instanceof I)throw u;return bn(u)}});return Tt(r)}function Sr(e,t){if(t.owner!==void 0&&t.unassigned)throw new I("INVALID_ARGUMENT","Owner and --unassigned are exclusive");let r=["id > ?"],n=[t.after??0];return t.project!==void 0&&(r.push("project = ?"),n.push(t.project)),t.kind!==void 0&&(r.push("kind = ?"),n.push(t.kind)),t.status!==void 0&&(r.push("status = ?"),n.push(ye(t.status.trim(),"status"))),t.parentId!==void 0&&(r.push("parent_id = ?"),n.push(t.parentId)),t.owner!==void 0&&(r.push("owner_team_path = ?","owner_alias = ?"),n.push(At(t.owner.team),t.owner.alias)),t.unassigned&&r.push("owner_team_path IS NULL"),yf(e,`SELECT * FROM entities WHERE ${r.join(" AND ")}`,n,t.limit??100)}function vr(e,t){let r=Ie(e,t),n=Tt(()=>e.prepare("SELECT id FROM entities WHERE parent_id = ? ORDER BY id").all(t).map(s=>s.id)),o=ct(e,t,"both");return{...r,children:n,dependencies:{outgoing:o.outgoing??[],incoming:o.incoming??[]}}}function Tf(e,t){return Ie(e,t),Tt(()=>e.prepare(`WITH RECURSIVE subtree(id) AS (
180
180
  SELECT ? UNION ALL SELECT e.id FROM entities e JOIN subtree s ON e.parent_id = s.id
181
181
  )
182
- SELECT e.* FROM entities e JOIN subtree s ON e.id = s.id ORDER BY e.id`).all(t))}function vr(e,t){let r=wf(e,t),n=new Map(r.map(o=>[o.id,{...o,children:[]}]));for(let o of r)o.id!==t&&o.parent_id!==null&&n.get(o.parent_id).children.push(n.get(o.id));return n.get(t)}function ff(e){let t={total:e.length,by_status:{},by_kind:{},by_delivery:{delivered:0,undelivered:0}};for(let r of e)t.by_status[r.status]=(t.by_status[r.status]??0)+1,t.by_kind[r.kind]=(t.by_kind[r.kind]??0)+1,r.kind!=="epic"&&(r.delivered_ts!=null?t.by_delivery.delivered+=1:t.by_delivery.undelivered+=1);return t}function Ar(e,t={}){if(t.id!==void 0&&t.project!==void 0)throw new L("INVALID_ARGUMENT","summary ID and --project are exclusive");if(t.id!==void 0)return ff(wf(e,t.id));let r=Et(()=>t.project!==void 0?e.prepare("SELECT * FROM entities WHERE project = ?").all(t.project):e.prepare("SELECT * FROM entities").all());return ff(r)}function Ks(e,t,r){let n=e.transaction(()=>{let o=Le(e,t);if(r.ifRevision!==void 0&&o.revision!==r.ifRevision)throw new L("REVISION_CONFLICT",`Expected revision ${r.ifRevision}; current is ${o.revision}`,4);let s={};r.title!==void 0&&(s.title=ye(r.title,"title")),r.status!==void 0&&(s.status=ye(r.status.trim(),"status"));for(let[a,c]of[["description",r.description],["requirements",r.requirements],["acceptance_criteria",r.acceptanceCriteria]])c!==void 0&&(s[a]=c);if(r.owner!==void 0&&r.clearOwner)throw new L("INVALID_ARGUMENT","Explicit owner and --clear-owner are exclusive");if(r.parentId!==void 0||r.clearParent){let a=r.clearParent?null:r.parentId;try{hf(e,o.kind,o.project,a)}catch(c){if(c instanceof L)throw c;bn(c)}s.parent_id=a}r.owner!==void 0?(s.owner_team_path=At(ye(r.owner.team,"owner team")),s.owner_alias=ye(r.owner.alias,"owner alias")):r.clearOwner&&(s.owner_team_path=null,s.owner_alias=null);let i=r.holdUntil!==void 0||r.holdReason!==void 0;if(i&&r.clearHold)throw new L("INVALID_ARGUMENT","A hold (holdUntil/holdReason) and clearHold are exclusive");if(i){if(r.holdUntil===void 0||r.holdReason===void 0)throw new L("INVALID_ARGUMENT","holdUntil and holdReason must be given together");let a=ye(r.holdUntil,"holdUntil");if(Number.isNaN(Date.parse(a)))throw new L("INVALID_ARGUMENT",`holdUntil "${a}" is not a parseable timestamp`,2);s.hold_until=a,s.hold_reason=ye(r.holdReason,"holdReason")}else r.clearHold&&(s.hold_until=null,s.hold_reason=null);if(r.blockedOn!==void 0&&r.clearBlockedOn)throw new L("INVALID_ARGUMENT","blockedOn and clearBlockedOn are exclusive");if(r.blockedOn!==void 0?s.blocked_on=ye(r.blockedOn,"blockedOn"):r.clearBlockedOn&&(s.blocked_on=null),Object.keys(s).length===0)throw new L("INVALID_ARGUMENT","Update requires at least one field");try{e.prepare(`UPDATE entities SET ${Object.keys(s).map(a=>`${a} = ?`).join(",")} WHERE id = ?`).run(...Object.values(s),t)}catch(a){bn(a)}return s.status!==void 0&&s.status!==o.status&&e.prepare("INSERT INTO notes(entity_id, body, author_team_path, author_alias, created_at) VALUES (?,?,?,?,?)").run(t,JSON.stringify({[Tr]:!0,from:o.status,to:s.status}),null,null,de()),Js(e,t),Le(e,t)});return Et(n)}function yf(e,t,r){e.prepare("UPDATE entities SET delivered_ts = ? WHERE id = ? AND delivered_ts IS NULL").run(r,t)}function Ef(e,t,r,n,o){o.needsReview?e.prepare("UPDATE entities SET review_time = ?, needs_review = 1, review_reason = ?, review_input_hash = ? WHERE id = ?").run(r,o.reason,n,t):e.prepare("UPDATE entities SET review_time = ?, needs_review = 0, review_reason = NULL, review_input_hash = ? WHERE id = ?").run(r,n,t)}function Bt(e,t,r){let n=e.transaction(()=>{Le(e,t);let o=r.author!==void 0?At(ye(r.author.team,"author team")):null,s=r.author!==void 0?ye(r.author.alias,"author alias"):null,i=e.prepare("INSERT INTO notes(entity_id, body, author_team_path, author_alias, created_at) VALUES (?,?,?,?,?)").run(t,ye(r.body,"body"),o,s,de());return Js(e,t),{note:e.prepare("SELECT * FROM notes WHERE id = ?").get(i.lastInsertRowid),revision:Le(e,t).revision}});return Et(n)}function Tc(e,t,r={}){return Le(e,t),gf(e,"SELECT * FROM notes WHERE entity_id = ? AND id > ?",[t,r.after??0],r.limit??100)}function Wt(e){try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function zs(e,t){let r=e.prepare("SELECT body, created_at FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t);for(let n of r){let o=Wt(n.body);if(o!==null&&o[Tr]===!0)return n.created_at}return null}function Sn(e,t){return Et(()=>e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t).find(n=>Wt(n.body)===null)??null)}function Tf(e,t,r={}){let{rows:n,meta:o}=Tc(e,t,r);return{rows:n.map(s=>({...s,noteType:Wt(s.body)===null?"authored":"system"})),meta:o}}function bf(e,t,r){if(Le(e,t),Le(e,r),t===r)throw new L("SELF_DEPENDENCY","An entity cannot depend on itself")}function Sf(e,t,r){let n=e.transaction(()=>{bf(e,t,r);let o;try{o=e.prepare("INSERT OR IGNORE INTO dependencies(entity_id, depends_on_id, created_at) VALUES (?,?,?)").run(t,r,de()).changes>0}catch(s){return bn(s)}return o&&Js(e,t),{entity_id:t,depends_on_id:r,changed:o,revision:Le(e,t).revision}});return Et(n)}function vf(e,t,r){let n=e.transaction(()=>{bf(e,t,r);let s=e.prepare("DELETE FROM dependencies WHERE entity_id = ? AND depends_on_id = ?").run(t,r).changes>0;return s&&Js(e,t),{entity_id:t,depends_on_id:r,changed:s,revision:Le(e,t).revision}});return Et(n)}var G$=new Set(["todo","in-progress"]),vn=new Set(["task","subtask"]),Gt="on-hold";function le(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}var Xs="blocked",An=new Set(["done","closed"]);function gt(e){return An.has(le(e))}function ti(e){return e.kind==="epic"&&!gt(e.status)&&le(e.status)!==Gt}var Zs=new Set(["rate-limited","error"]);function xe(e,t,r){let n=e.prepare("SELECT * FROM entities WHERE owner_team_path = ? AND owner_alias = ? ORDER BY id").all(At(t),r);return n.length===0?null:{entities:n}}function ei(e,t){return(ct(e,t.id,"outgoing").outgoing??[]).some(n=>le(n.status)!=="done")}var V$=45*6e4;function Af(e,t={}){let r=t.nowMs??Date.now(),n=t.staleInProgressThresholdMs??V$,o=t.project!==void 0?e.prepare("SELECT * FROM entities WHERE project = ? ORDER BY id LIMIT ?").all(t.project,Ne):e.prepare("SELECT * FROM entities ORDER BY id LIMIT ?").all(Ne),s=[];for(let i of o){if(!vn.has(i.kind))continue;let a=le(i.status);if(a===Xs){s.push({...i,attentionReason:"blocked"});continue}if(a==="in-progress"){r-new Date(i.updated_at).getTime()>=n&&s.push({...i,attentionReason:"stale_in_progress"});continue}a==="todo"&&(ct(e,i.id,"outgoing").outgoing??[]).length>0&&!ei(e,i)&&s.push({...i,attentionReason:"dependency_ready"})}return s}function vc(e){let t=le(e);return t==="done"||t===Gt}function Qs(e,t){return e.prepare("SELECT * FROM entities WHERE parent_id = ?").all(t).some(n=>!vc(n.status))}function Sc(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=null,i=null,a=null;for(let c of o){let l=Wt(c.body);if(l!==null){if(l[Tr]===!0){i=c.id,a=c.created_at;break}s===null&&(s=l)}}return{id:n.id,title:n.title,status:n.status,attrs:s,epochId:i,epochTs:a,createdAt:n.created_at,ownerTeamPath:n.owner_team_path,ownerAlias:n.owner_alias}})()}function So(e,t,r,n=Date.now(),o){let s=o!==void 0?new Map:new Map(t.entities.map(u=>[u.id,u])),a=t.entities.filter(u=>vn.has(u.kind)&&!Vt(e,u,s)).filter(u=>Zs.has(le(u.status))),c=o!==void 0?At(o.team):null,l=[];for(let u of a){let d=Sc(e,u.id);if(d===null||!Zs.has(le(d.status))||o!==void 0&&(d.ownerTeamPath!==c||d.ownerAlias!==o.alias))continue;let m=typeof d.attrs?.expected_reset_ts=="string"?Date.parse(d.attrs.expected_reset_ts):NaN;if(Number.isNaN(m)){let f=Date.parse(d.epochTs??d.createdAt);if(!Number.isNaN(f)&&n-f<r)continue}else if(m>n)continue;l.push({id:d.id,title:d.title,status:d.status})}return l}function J$(e,t){return e.prepare("SELECT * FROM notes WHERE entity_id = ?").all(t).some(n=>Wt(n.body)===null)}function Vt(e,t,r){let n=t,o=new Set;for(;n!==null&&n.parent_id!==null&&!o.has(n.id);){o.add(n.id);let s=r.get(n.parent_id)??at(e,n.parent_id);if(s===null)return!1;if(s.kind==="epic")return gt(s.status)||le(s.status)===Gt;n=s}return!1}function $n(e,t){let r=new Map(t.entities.map(n=>[n.id,n]));return t.entities.filter(n=>vn.has(n.kind)&&le(n.status)===Xs&&!Vt(e,n,r))}var Ac=24*60*6e4,K$="DESIGN-FIRST:";function $f(e,t,r=Ac,n=Date.now()){let o=new Map(t.entities.map(s=>[s.id,s]));return t.entities.filter(s=>vn.has(s.kind)&&le(s.status)==="todo"&&s.title.startsWith(K$)&&n-Date.parse(s.updated_at)>=r&&!Vt(e,s,o)&&!ei(e,s)).map(s=>({id:s.id,title:s.title,updatedAt:s.updated_at}))}function kf(e,t,r=Date.now()){let n=new Map(t.entities.map(o=>[o.id,o]));return t.entities.filter(o=>vn.has(o.kind)&&o.hold_until!==null&&Date.parse(o.hold_until)<=r&&!Vt(e,o,n)).map(o=>({id:o.id,title:o.title,holdUntil:o.hold_until,holdReason:o.hold_reason}))}function z$(e,t){return e.prepare("SELECT 1 FROM entities WHERE parent_id = ? LIMIT 1").get(t)!==void 0}function Y$(e,t){return t.entities.filter(n=>n.kind==="epic"&&!gt(n.status)&&le(n.status)!==Gt).filter(n=>z$(e,n.id)&&!Qs(e,n.id))}function Ys(e){return`'${e.replace(/'/g,"'\\''")}'`}var Q$=3e4;function bc(e,t={}){let r=t.timeoutMs??Q$,o=[...t.spawnPrefix??["miniplayer"],"run",...t.model!==void 0?["-m",t.model]:[]],[s,...i]=o;return new Promise(a=>{let c=!1,l="",u="",d=W$(s,i,{stdio:["pipe","pipe","pipe"]});function m(h){c||(c=!0,clearTimeout(p),process.stderr.write(`[lmtasks-nudge] miniplayer run failed (${h}), falling back to the generic nudge: ${u.trim().slice(-500)}
183
- `),a(null))}function f(h){c||(c=!0,clearTimeout(p),a(h))}let p=setTimeout(()=>{try{d.kill("SIGTERM")}catch{}setTimeout(()=>{if(d.exitCode===null&&d.signalCode===null)try{d.kill("SIGKILL")}catch{}},2e3).unref(),m("timeout")},r);d.stdout.on("data",h=>{l+=h.toString("utf8")}),d.stderr.on("data",h=>{u+=h.toString("utf8")}),d.on("error",h=>m(h.message)),d.on("close",h=>{if(c)return;if(h!==0){m(`exit code ${h}`);return}let w=l.trim();if(!w){m("empty output");return}f(w)}),d.stdin.write(e),d.stdin.end()})}var X$="ollama/qwen2.5:14b",Z$=5e3,ek="deepseek/deepseek-flash";async function ri(e,t={}){if(t.model!==void 0)return bc(e,t);let r=await bc(e,{...t,model:X$,timeoutMs:t.timeoutMs??Z$});return r!==null?r:bc(e,{...t,model:ek})}var tk=15*6e4;function rk(e){let t=e.filter(r=>r.kind==="epic"&&!gt(r.status)&&le(r.status)!==Gt);return t.length===1?t[0]:null}async function xf(e,t,r={}){let n=r.backoffMs??tk,o=t.entities[0];o?.owner_team_path!==void 0&&o.owner_team_path!==null&&o.owner_alias!==null&&(t=xe(e,o.owner_team_path,o.owner_alias)??{entities:[]});let s=new Map(t.entities.map(k=>[k.id,k])),i=t.entities.filter(k=>vn.has(k.kind)&&!Vt(e,k,s)),a=i.filter(k=>Zs.has(le(k.status))),c=null,l=!1;for(let k of a){let B=Sc(e,k.id);if(B===null||!Zs.has(le(B.status)))continue;l=!0;let C=Date.now(),g=typeof B.attrs?.expected_reset_ts=="string"?Date.parse(B.attrs.expected_reset_ts):NaN;if(!Number.isNaN(g)&&g>C)continue;let y=typeof B.attrs?.last_renudge_ts=="string"?Date.parse(B.attrs.last_renudge_ts):NaN;if(!(!Number.isNaN(y)&&C-y<n)){c=B;break}}if(l){if(c===null)return null;let k=c.id,B=c.epochId;return{message:`Task #${c.id} ("${c.title}") is marked ${c.status} -- not nudging further; report status if this persists.`,onSent:()=>{e.transaction(()=>{let R=Sc(e,k);R===null||R.epochId!==B||Bt(e,k,{body:JSON.stringify({...R.attrs??{},last_renudge_ts:new Date().toISOString()})})}).immediate()}}}let u=$n(e,t),d=u.length>0?`
182
+ SELECT e.* FROM entities e JOIN subtree s ON e.id = s.id ORDER BY e.id`).all(t))}function Ar(e,t){let r=Tf(e,t),n=new Map(r.map(o=>[o.id,{...o,children:[]}]));for(let o of r)o.id!==t&&o.parent_id!==null&&n.get(o.parent_id).children.push(n.get(o.id));return n.get(t)}function gf(e){let t={total:e.length,by_status:{},by_kind:{},by_delivery:{delivered:0,undelivered:0}};for(let r of e)t.by_status[r.status]=(t.by_status[r.status]??0)+1,t.by_kind[r.kind]=(t.by_kind[r.kind]??0)+1,r.kind!=="epic"&&(r.delivered_ts!=null?t.by_delivery.delivered+=1:t.by_delivery.undelivered+=1);return t}function kr(e,t={}){if(t.id!==void 0&&t.project!==void 0)throw new I("INVALID_ARGUMENT","summary ID and --project are exclusive");if(t.id!==void 0)return gf(Tf(e,t.id));let r=Tt(()=>t.project!==void 0?e.prepare("SELECT * FROM entities WHERE project = ?").all(t.project):e.prepare("SELECT * FROM entities").all());return gf(r)}function Xs(e,t,r){let n=e.transaction(()=>{let o=Ie(e,t);if(r.ifRevision!==void 0&&o.revision!==r.ifRevision)throw new I("REVISION_CONFLICT",`Expected revision ${r.ifRevision}; current is ${o.revision}`,4);let s={};r.title!==void 0&&(s.title=ye(r.title,"title")),r.status!==void 0&&(s.status=ye(r.status.trim(),"status"));for(let[a,c]of[["description",r.description],["requirements",r.requirements],["acceptance_criteria",r.acceptanceCriteria]])c!==void 0&&(s[a]=c);if(r.owner!==void 0&&r.clearOwner)throw new I("INVALID_ARGUMENT","Explicit owner and --clear-owner are exclusive");if(r.parentId!==void 0||r.clearParent){let a=r.clearParent?null:r.parentId;try{wf(e,o.kind,o.project,a)}catch(c){if(c instanceof I)throw c;bn(c)}s.parent_id=a}r.owner!==void 0?(s.owner_team_path=At(ye(r.owner.team,"owner team")),s.owner_alias=ye(r.owner.alias,"owner alias")):r.clearOwner&&(s.owner_team_path=null,s.owner_alias=null);let i=r.holdUntil!==void 0||r.holdReason!==void 0;if(i&&r.clearHold)throw new I("INVALID_ARGUMENT","A hold (holdUntil/holdReason) and clearHold are exclusive");if(i){if(r.holdUntil===void 0||r.holdReason===void 0)throw new I("INVALID_ARGUMENT","holdUntil and holdReason must be given together");let a=ye(r.holdUntil,"holdUntil");if(Number.isNaN(Date.parse(a)))throw new I("INVALID_ARGUMENT",`holdUntil "${a}" is not a parseable timestamp`,2);s.hold_until=a,s.hold_reason=ye(r.holdReason,"holdReason")}else r.clearHold&&(s.hold_until=null,s.hold_reason=null);if(r.blockedOn!==void 0&&r.clearBlockedOn)throw new I("INVALID_ARGUMENT","blockedOn and clearBlockedOn are exclusive");if(r.blockedOn!==void 0?s.blocked_on=ye(r.blockedOn,"blockedOn"):r.clearBlockedOn&&(s.blocked_on=null),Object.keys(s).length===0)throw new I("INVALID_ARGUMENT","Update requires at least one field");try{e.prepare(`UPDATE entities SET ${Object.keys(s).map(a=>`${a} = ?`).join(",")} WHERE id = ?`).run(...Object.values(s),t)}catch(a){bn(a)}return s.status!==void 0&&s.status!==o.status&&e.prepare("INSERT INTO notes(entity_id, body, author_team_path, author_alias, created_at) VALUES (?,?,?,?,?)").run(t,JSON.stringify({[br]:!0,from:o.status,to:s.status}),null,null,de()),Qs(e,t),Ie(e,t)});return Tt(n)}function bf(e,t,r){e.prepare("UPDATE entities SET delivered_ts = ? WHERE id = ? AND delivered_ts IS NULL").run(r,t)}function Sf(e,t,r,n,o){o.needsReview?e.prepare("UPDATE entities SET review_time = ?, needs_review = 1, review_reason = ?, review_input_hash = ? WHERE id = ?").run(r,o.reason,n,t):e.prepare("UPDATE entities SET review_time = ?, needs_review = 0, review_reason = NULL, review_input_hash = ? WHERE id = ?").run(r,n,t)}function Bt(e,t,r){let n=e.transaction(()=>{Ie(e,t);let o=r.author!==void 0?At(ye(r.author.team,"author team")):null,s=r.author!==void 0?ye(r.author.alias,"author alias"):null,i=e.prepare("INSERT INTO notes(entity_id, body, author_team_path, author_alias, created_at) VALUES (?,?,?,?,?)").run(t,ye(r.body,"body"),o,s,de());return Qs(e,t),{note:e.prepare("SELECT * FROM notes WHERE id = ?").get(i.lastInsertRowid),revision:Ie(e,t).revision}});return Tt(n)}function vc(e,t,r={}){return Ie(e,t),yf(e,"SELECT * FROM notes WHERE entity_id = ? AND id > ?",[t,r.after??0],r.limit??100)}function Wt(e){try{let t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Zs(e,t){let r=e.prepare("SELECT body, created_at FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t);for(let n of r){let o=Wt(n.body);if(o!==null&&o[br]===!0)return n.created_at}return null}function Sn(e,t){return Tt(()=>e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t).find(n=>Wt(n.body)===null)??null)}function vf(e,t,r={}){let{rows:n,meta:o}=vc(e,t,r);return{rows:n.map(s=>({...s,noteType:Wt(s.body)===null?"authored":"system"})),meta:o}}function Af(e,t,r){if(Ie(e,t),Ie(e,r),t===r)throw new I("SELF_DEPENDENCY","An entity cannot depend on itself")}function kf(e,t,r){let n=e.transaction(()=>{Af(e,t,r);let o;try{o=e.prepare("INSERT OR IGNORE INTO dependencies(entity_id, depends_on_id, created_at) VALUES (?,?,?)").run(t,r,de()).changes>0}catch(s){return bn(s)}return o&&Qs(e,t),{entity_id:t,depends_on_id:r,changed:o,revision:Ie(e,t).revision}});return Tt(n)}function $f(e,t,r){let n=e.transaction(()=>{Af(e,t,r);let s=e.prepare("DELETE FROM dependencies WHERE entity_id = ? AND depends_on_id = ?").run(t,r).changes>0;return s&&Qs(e,t),{entity_id:t,depends_on_id:r,changed:s,revision:Ie(e,t).revision}});return Tt(n)}var Yk=new Set(["todo","in-progress"]),vn=new Set(["task","subtask"]),Gt="on-hold";function le(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}var ri="blocked",An=new Set(["done","closed"]);function gt(e){return An.has(le(e))}function si(e){return e.kind==="epic"&&!gt(e.status)&&le(e.status)!==Gt}var ni=new Set(["rate-limited","error"]);function xe(e,t,r){let n=e.prepare("SELECT * FROM entities WHERE owner_team_path = ? AND owner_alias = ? ORDER BY id").all(At(t),r);return n.length===0?null:{entities:n}}function oi(e,t){return(ct(e,t.id,"outgoing").outgoing??[]).some(n=>le(n.status)!=="done")}var Qk=45*6e4;function xf(e,t={}){let r=t.nowMs??Date.now(),n=t.staleInProgressThresholdMs??Qk,o=t.project!==void 0?e.prepare("SELECT * FROM entities WHERE project = ? ORDER BY id LIMIT ?").all(t.project,Ne):e.prepare("SELECT * FROM entities ORDER BY id LIMIT ?").all(Ne),s=[];for(let i of o){if(!vn.has(i.kind))continue;let a=le(i.status);if(a===ri){s.push({...i,attentionReason:"blocked"});continue}if(a==="in-progress"){r-new Date(i.updated_at).getTime()>=n&&s.push({...i,attentionReason:"stale_in_progress"});continue}a==="todo"&&(ct(e,i.id,"outgoing").outgoing??[]).length>0&&!oi(e,i)&&s.push({...i,attentionReason:"dependency_ready"})}return s}function $c(e){let t=le(e);return t==="done"||t===Gt}function ti(e,t){return e.prepare("SELECT * FROM entities WHERE parent_id = ?").all(t).some(n=>!$c(n.status))}function kc(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=null,i=null,a=null;for(let c of o){let l=Wt(c.body);if(l!==null){if(l[br]===!0){i=c.id,a=c.created_at;break}s===null&&(s=l)}}return{id:n.id,title:n.title,status:n.status,attrs:s,epochId:i,epochTs:a,createdAt:n.created_at,ownerTeamPath:n.owner_team_path,ownerAlias:n.owner_alias}})()}function Ao(e,t,r,n=Date.now(),o){let s=o!==void 0?new Map:new Map(t.entities.map(u=>[u.id,u])),a=t.entities.filter(u=>vn.has(u.kind)&&!Vt(e,u,s)).filter(u=>ni.has(le(u.status))),c=o!==void 0?At(o.team):null,l=[];for(let u of a){let d=kc(e,u.id);if(d===null||!ni.has(le(d.status))||o!==void 0&&(d.ownerTeamPath!==c||d.ownerAlias!==o.alias))continue;let m=typeof d.attrs?.expected_reset_ts=="string"?Date.parse(d.attrs.expected_reset_ts):NaN;if(Number.isNaN(m)){let f=Date.parse(d.epochTs??d.createdAt);if(!Number.isNaN(f)&&n-f<r)continue}else if(m>n)continue;l.push({id:d.id,title:d.title,status:d.status})}return l}function Xk(e,t){return e.prepare("SELECT * FROM notes WHERE entity_id = ?").all(t).some(n=>Wt(n.body)===null)}function Vt(e,t,r){let n=t,o=new Set;for(;n!==null&&n.parent_id!==null&&!o.has(n.id);){o.add(n.id);let s=r.get(n.parent_id)??at(e,n.parent_id);if(s===null)return!1;if(s.kind==="epic")return gt(s.status)||le(s.status)===Gt;n=s}return!1}function kn(e,t){let r=new Map(t.entities.map(n=>[n.id,n]));return t.entities.filter(n=>vn.has(n.kind)&&le(n.status)===ri&&!Vt(e,n,r))}var xc=24*60*6e4,Zk="DESIGN-FIRST:";function Rf(e,t,r=xc,n=Date.now()){let o=new Map(t.entities.map(s=>[s.id,s]));return t.entities.filter(s=>vn.has(s.kind)&&le(s.status)==="todo"&&s.title.startsWith(Zk)&&n-Date.parse(s.updated_at)>=r&&!Vt(e,s,o)&&!oi(e,s)).map(s=>({id:s.id,title:s.title,updatedAt:s.updated_at}))}function Nf(e,t,r=Date.now()){let n=new Map(t.entities.map(o=>[o.id,o]));return t.entities.filter(o=>vn.has(o.kind)&&o.hold_until!==null&&Date.parse(o.hold_until)<=r&&!Vt(e,o,n)).map(o=>({id:o.id,title:o.title,holdUntil:o.hold_until,holdReason:o.hold_reason}))}function e$(e,t){return e.prepare("SELECT 1 FROM entities WHERE parent_id = ? LIMIT 1").get(t)!==void 0}function t$(e,t){return t.entities.filter(n=>n.kind==="epic"&&!gt(n.status)&&le(n.status)!==Gt).filter(n=>e$(e,n.id)&&!ti(e,n.id))}function ei(e){return`'${e.replace(/'/g,"'\\''")}'`}var r$=3e4;function Ac(e,t={}){let r=t.timeoutMs??r$,o=[...t.spawnPrefix??["miniplayer"],"run",...t.model!==void 0?["-m",t.model]:[]],[s,...i]=o;return new Promise(a=>{let c=!1,l="",u="",d=zk(s,i,{stdio:["pipe","pipe","pipe"]});function m(h){c||(c=!0,clearTimeout(p),process.stderr.write(`[lmtasks-nudge] miniplayer run failed (${h}), falling back to the generic nudge: ${u.trim().slice(-500)}
183
+ `),a(null))}function f(h){c||(c=!0,clearTimeout(p),a(h))}let p=setTimeout(()=>{try{d.kill("SIGTERM")}catch{}setTimeout(()=>{if(d.exitCode===null&&d.signalCode===null)try{d.kill("SIGKILL")}catch{}},2e3).unref(),m("timeout")},r);d.stdout.on("data",h=>{l+=h.toString("utf8")}),d.stderr.on("data",h=>{u+=h.toString("utf8")}),d.on("error",h=>m(h.message)),d.on("close",h=>{if(c)return;if(h!==0){m(`exit code ${h}`);return}let w=l.trim();if(!w){m("empty output");return}f(w)}),d.stdin.write(e),d.stdin.end()})}var n$="ollama/qwen2.5:14b",o$=5e3,s$="deepseek/deepseek-flash";async function ii(e,t={}){if(t.model!==void 0)return Ac(e,t);let r=await Ac(e,{...t,model:n$,timeoutMs:t.timeoutMs??o$});return r!==null?r:Ac(e,{...t,model:s$})}var i$=15*6e4;function a$(e){let t=e.filter(r=>r.kind==="epic"&&!gt(r.status)&&le(r.status)!==Gt);return t.length===1?t[0]:null}async function Lf(e,t,r={}){let n=r.backoffMs??i$,o=t.entities[0];o?.owner_team_path!==void 0&&o.owner_team_path!==null&&o.owner_alias!==null&&(t=xe(e,o.owner_team_path,o.owner_alias)??{entities:[]});let s=new Map(t.entities.map(R=>[R.id,R])),i=t.entities.filter(R=>vn.has(R.kind)&&!Vt(e,R,s)),a=i.filter(R=>ni.has(le(R.status))),c=null,l=!1;for(let R of a){let H=kc(e,R.id);if(H===null||!ni.has(le(H.status)))continue;l=!0;let C=Date.now(),g=typeof H.attrs?.expected_reset_ts=="string"?Date.parse(H.attrs.expected_reset_ts):NaN;if(!Number.isNaN(g)&&g>C)continue;let y=typeof H.attrs?.last_renudge_ts=="string"?Date.parse(H.attrs.last_renudge_ts):NaN;if(!(!Number.isNaN(y)&&C-y<n)){c=H;break}}if(l){if(c===null)return null;let R=c.id,H=c.epochId;return{message:`Task #${c.id} ("${c.title}") is marked ${c.status} -- not nudging further; report status if this persists.`,onSent:()=>{e.transaction(()=>{let x=kc(e,R);x===null||x.epochId!==H||Bt(e,R,{body:JSON.stringify({...x.attrs??{},last_renudge_ts:new Date().toISOString()})})}).immediate()}}}let u=kn(e,t),d=u.length>0?`
184
184
 
185
- (Also: ${u.length} task(s) marked blocked, including #${u[0].id} ("${u[0].title}") -- pending meta-lead review, no action needed from you on ${u.length===1?"it":"these"} right now.)`:"",m=Y$(e,t),f=t.entities[0],p=f?.owner_team_path!==null&&f?.owner_team_path!==void 0&&f?.owner_alias!==null&&f?.owner_alias!==void 0?` --owner-team ${Ys(f.owner_team_path)} --owner-alias ${Ys(f.owner_alias)}`:"",h=k=>`#${k.id} ("${k.title}") -- \`lmauto tasks create task --parent ${k.id} --title "..."${p}\` to add the next one, or \`lmauto tasks update ${k.id} --status done\` if it's genuinely complete`,w=m.length>0?`
185
+ (Also: ${u.length} task(s) marked blocked, including #${u[0].id} ("${u[0].title}") -- pending meta-lead review, no action needed from you on ${u.length===1?"it":"these"} right now.)`:"",m=t$(e,t),f=t.entities[0],p=f?.owner_team_path!==null&&f?.owner_team_path!==void 0&&f?.owner_alias!==null&&f?.owner_alias!==void 0?` --owner-team ${ei(f.owner_team_path)} --owner-alias ${ei(f.owner_alias)}`:"",h=R=>`#${R.id} ("${R.title}") -- \`lmauto tasks create task --parent ${R.id} --title "..."${p}\` to add the next one, or \`lmauto tasks update ${R.id} --status done\` if it's genuinely complete`,w=m.length>0?`
186
186
 
187
- (Also: ${m.length} epic(s) have all tasks done: ${m.map(h).join("; ")}.)`:"",_=i.filter(k=>le(k.status)==="done").map(k=>{let B=[];return ei(e,k)&&B.push("still has an unmet dependency"),Qs(e,k.id)&&B.push("still has an incomplete subtask"),{entity:k,reasons:B}}).filter(k=>k.reasons.length>0);if(_.length>0){let{entity:k,reasons:B}=_[0];return{message:`${k.kind==="subtask"?"Subtask":"Task"} #${k.id} ("${k.title}") is marked done but ${B.join(" and ")} -- please double-check and resolve the contradiction (confirm it's genuinely finished, or reopen it if something was missed).`}}let E=i.filter(k=>le(k.status)==="done"&&!J$(e,k.id));if(E.length>0){let k=E[0];return{message:`Task #${k.id} ("${k.title}") is marked done -- close it out (commit/publish/report as appropriate), then \`lmauto tasks note add ${k.id} --body "<what you did>"\` to confirm, or update its status if it needs to be reopened.`+d+w}}let T=i.filter(k=>G$.has(le(k.status))&&le(k.status)!==Gt&&!Qs(e,k.id));if(T.length===0){let k=i.filter(A=>{let q=le(A.status);return q!==Xs&&q!==Gt&&Qs(e,A.id)});if(k.length>0){let A=k[0];return{message:`${A.kind==="subtask"?"Subtask":"Task"} #${A.id} ("${A.title}") has an incomplete subtask -- check \`lmauto tasks show ${A.id}\` for what's left.`+d+w}}let B=i.filter(A=>le(A.status)===Gt),C=i.filter(A=>le(A.status)!==Gt&&le(A.status)!==Xs),g=t.entities.some(A=>A.kind==="epic"&&!gt(A.status)&&le(A.status)!==Gt);if(C.length===0&&!g)return null;if(m.length>1)return{message:`${m.length} of your open epics have all tasks done: ${m.map(h).join("; ")}.`};let y=rk(t.entities),R=t.entities[0],P=R?.owner_team_path,J=R?.owner_alias,ee=P!=null&&J!==null&&J!==void 0?` --owner-team ${Ys(P)} --owner-alias ${Ys(J)}`:"",oe=y!==null?String(y.id):"<epic-id>",V=y!==null?`lmauto tasks update ${y.id} --status done`:"<lmauto tasks update EPIC_ID --status done>",se=B.length>0&&u.length>0?"All your non-blocked/non-held tracked tasks are done.":B.length>0?"All your non-held tracked tasks are done.":u.length>0?"All your non-blocked tracked tasks are done.":"All your tracked tasks are done.",$=[];B.length>0&&$.push(`${B.length} other task(s) remain on_hold -- not done, just parked`),u.length>0&&$.push(`${u.length} task(s) remain blocked, pending meta-lead review`);let O=$.length>0?` (${$.join("; ")}; resolve those before treating the epic as complete.)`:"";return y===null&&!g?{message:`${se}${O}`}:{message:`${se}${O} Either \`lmauto tasks create task --parent ${oe} --title "..."${ee}\` to add the next one, or if the epic is genuinely complete, \`${V}\`.`}}let v=T.filter(k=>!ei(e,k));if(v.length===0){let k=T[0];return{message:`All ${T.length} of your tracked todo/in-progress task(s) are blocked on an unmet dependency, including #${k.id} ("${k.title}") -- check \`lmauto tasks show ${k.id}\` and report if you're stuck.`+d+w}}let S=v.filter(k=>le(k.status)==="in-progress"||k.delivered_ts!=null),N=S.length>0?S[0]:v[0],x=N.delivered_ts==null?()=>yf(e,N.id,new Date().toISOString()):void 0;if(v.length===1){let k=N.description.trim();return{message:`Continue task #${N.id}: "${N.title}" (status: ${N.status}).${k?`
187
+ (Also: ${m.length} epic(s) have all tasks done: ${m.map(h).join("; ")}.)`:"",_=i.filter(R=>le(R.status)==="done").map(R=>{let H=[];return oi(e,R)&&H.push("still has an unmet dependency"),ti(e,R.id)&&H.push("still has an incomplete subtask"),{entity:R,reasons:H}}).filter(R=>R.reasons.length>0);if(_.length>0){let{entity:R,reasons:H}=_[0];return{message:`${R.kind==="subtask"?"Subtask":"Task"} #${R.id} ("${R.title}") is marked done but ${H.join(" and ")} -- please double-check and resolve the contradiction (confirm it's genuinely finished, or reopen it if something was missed).`}}let T=i.filter(R=>le(R.status)==="done"&&!Xk(e,R.id));if(T.length>0){let R=T[0];return{message:`Task #${R.id} ("${R.title}") is marked done -- close it out (commit/publish/report as appropriate), then \`lmauto tasks note add ${R.id} --body "<what you did>"\` to confirm, or update its status if it needs to be reopened.`+d+w}}let E=i.filter(R=>Yk.has(le(R.status))&&le(R.status)!==Gt&&!ti(e,R.id));if(E.length===0){let R=i.filter(A=>{let q=le(A.status);return q!==ri&&q!==Gt&&ti(e,A.id)});if(R.length>0){let A=R[0];return{message:`${A.kind==="subtask"?"Subtask":"Task"} #${A.id} ("${A.title}") has an incomplete subtask -- check \`lmauto tasks show ${A.id}\` for what's left.`+d+w}}let H=i.filter(A=>le(A.status)===Gt),C=i.filter(A=>le(A.status)!==Gt&&le(A.status)!==ri),g=t.entities.some(A=>A.kind==="epic"&&!gt(A.status)&&le(A.status)!==Gt);if(C.length===0&&!g)return null;if(m.length>1)return{message:`${m.length} of your open epics have all tasks done: ${m.map(h).join("; ")}.`};let y=a$(t.entities),x=t.entities[0],P=x?.owner_team_path,J=x?.owner_alias,ee=P!=null&&J!==null&&J!==void 0?` --owner-team ${ei(P)} --owner-alias ${ei(J)}`:"",oe=y!==null?String(y.id):"<epic-id>",V=y!==null?`lmauto tasks update ${y.id} --status done`:"<lmauto tasks update EPIC_ID --status done>",se=H.length>0&&u.length>0?"All your non-blocked/non-held tracked tasks are done.":H.length>0?"All your non-held tracked tasks are done.":u.length>0?"All your non-blocked tracked tasks are done.":"All your tracked tasks are done.",k=[];H.length>0&&k.push(`${H.length} other task(s) remain on_hold -- not done, just parked`),u.length>0&&k.push(`${u.length} task(s) remain blocked, pending meta-lead review`);let O=k.length>0?` (${k.join("; ")}; resolve those before treating the epic as complete.)`:"";return y===null&&!g?{message:`${se}${O}`}:{message:`${se}${O} Either \`lmauto tasks create task --parent ${oe} --title "..."${ee}\` to add the next one, or if the epic is genuinely complete, \`${V}\`.`}}let v=E.filter(R=>!oi(e,R));if(v.length===0){let R=E[0];return{message:`All ${E.length} of your tracked todo/in-progress task(s) are blocked on an unmet dependency, including #${R.id} ("${R.title}") -- check \`lmauto tasks show ${R.id}\` and report if you're stuck.`+d+w}}let S=v.filter(R=>le(R.status)==="in-progress"||R.delivered_ts!=null),N=S.length>0?S[0]:v[0],$=N.delivered_ts==null?()=>bf(e,N.id,new Date().toISOString()):void 0;if(v.length===1){let R=N.description.trim();return{message:`Continue task #${N.id}: "${N.title}" (status: ${N.status}).${R?`
188
188
 
189
- ${k}`:""}${d}${w}`,onSent:x}}let I=N.description.trim();return{message:`Continue task #${N.id}: "${N.title}" (status: ${N.status}).${I?`
189
+ ${R}`:""}${d}${w}`,onSent:$}}let L=N.description.trim();return{message:`Continue task #${N.id}: "${N.title}" (status: ${N.status}).${L?`
190
190
 
191
- ${I}`:""}
191
+ ${L}`:""}
192
192
 
193
- (${v.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+w,onSent:x}}var pe={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function nk(e,t){return t.running.some(r=>_n(e,r.from_identity))}function Xr(e,t){return t.dead.some(r=>_n(e,r.target))&&!Fe(e,t)}function $c(e){if(e.isCurrentlyActive)return!1;let t=!e.hasInFlightWorker,r=e.timeSinceLastNudgeMs===null||e.timeSinceLastNudgeMs>e.config.cooldownMs;if(e.isDeadReclaimable)return t&&r;let n=!e.isCoordinator&&e.progressStatus==="UNKNOWN"&&(e.progressAgeMs===null||e.progressAgeMs>=e.config.idleThresholdMs),o=!e.heavyLockMayBeHeldByThisTeam&&e.hasStalePersistentInProgressWork;return t&&r&&(e.neverDispatched||n||o)}function kc(e,t,r,n){let o;try{o=Q(t)}catch{return!1}let s=xe(e,o,t.leadAlias);if(s===null)return!1;let i=new Map(s.entities.map(a=>[a.id,a]));return s.entities.some(a=>(a.kind==="task"||a.kind==="subtask")&&le(a.status)==="in-progress"&&!Vt(e,a,i)&&n-Date.parse(a.updated_at)>=r&&!xc(a,n))}function xc(e,t){return e.hold_until!==null&&Date.parse(e.hold_until)>t}function Rc(e,t){if(Ue(e,t.name)!==null||uf(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return xe(e,r,t.leadAlias)===null}function ok(e){return $c({...e,config:{...e.config,idleThresholdMs:0}})}function Rf(e){return`last_nudged:${e}`}function Nc(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(Rf(t))?.v??null}function vo(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Rf(t),r)}function Nf(e,t,r,n,o,s,i){if(Ue(e,t.name)?.status==="BLOCKED")return null;let c=Rc(e,t),l=s?.progress_changed_ts==null?null:o-Date.parse(s.progress_changed_ts),u=Nc(e,t.name),d=u===null?null:o-Date.parse(u);return{isCurrentlyActive:Fe(t,r),hasInFlightWorker:nk(t,r),neverDispatched:c,progressStatus:s?.progress_status??null,progressAgeMs:l,isDeadReclaimable:Xr(t,r),hasStalePersistentInProgressWork:kc(e,t,n.idleThresholdMs,o),timeSinceLastNudgeMs:d,config:n,isCoordinator:t.coordinator===!0,heavyLockMayBeHeldByThisTeam:i.held&&(i.holder===null||i.holder.holder===t.name)}}function If(e,t,r,n,o,s,i){let a=Nf(e,t,r,o,s,i,n);return a!==null&&$c(a)}async function Ic(e,t,r,n,o=pe,s=Date.now()){let i=await za(e,t,t.name,s);return If(e,t,r,n,o,s,i)}function Lc(e,t,r,n,o=pe,s=Date.now()){return If(e,t,r,n,o,s,ie(e,t.name))}async function kn(e,t,r,n,o=pe,s=Date.now(),i={}){let a=[];for(let c of t){if(!c.autoNudge||ie(e,c.name)?.confirmed_done_ts)continue;(i.readOnly?Lc(e,c,r,n,o,s):await Ic(e,c,r,n,o,s))&&!ie(e,c.name)?.confirmed_done_ts&&a.push(c.name)}return a}async function Lf(e,t,r,n,o=pe,s=Date.now()){let i=[],a=[];for(let c of t){if(!c.autoNudge||ie(e,c.name)?.confirmed_done_ts)continue;let l=await za(e,c,c.name,s);if(ie(e,c.name)?.confirmed_done_ts)continue;let u=Nf(e,c,r,o,s,l,n);u!==null&&($c(u)&&i.push(c.name),ok(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as Cf,readFileSync as Of}from"node:fs";import{dirname as Oc,join as Df}from"node:path";import{fileURLToPath as Mf}from"node:url";var Cc={sha:"unknown",dirty:!0,builtAt:"unknown"};function sk(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha=="string"&&typeof t.dirty=="boolean"&&typeof t.builtAt=="string"}function Pf(){let e=Oc(Mf(import.meta.url));for(let t=0;t<5;t+=1){let r=Df(e,"package.json");if(Cf(r))try{let n=JSON.parse(Of(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=Oc(e)}return"unknown"}function Dc(){let e=Df(Oc(Mf(import.meta.url)),"..","build-info.json");if(!Cf(e))return Cc;try{let t=JSON.parse(Of(e,"utf8"));return sk(t)?t:Cc}catch{return Cc}}var ik="https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod";function $t(e){return(e.LMCTL_LMMAIL_API_URL?.trim()||e.LMMAIL_API_URL?.trim()||ik).replace(/\/+$/,"")}import{createServer as ak}from"http";import{Http2ServerRequest as qf,constants as ck}from"http2";import{Http2ServerRequest as Mc}from"http2";import{Readable as Uf}from"stream";import yk from"crypto";var Zr=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},lk=e=>e instanceof Zr?e:new Zr(e.message,{cause:e}),uk=global.Request,Ao=class extends uk{constructor(e,t){typeof e=="object"&&Nn in e&&(e=e[Nn]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},dk=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},jf=Symbol("wrapBodyStream"),mk=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new Ao(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[jf]){let i;s.body=new ReadableStream({async pull(a){try{i||=Uf.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=Uf.toWeb(n);return new Ao(t,s)},Nn=Symbol("getRequestCache"),Hf=Symbol("requestCache"),ni=Symbol("incomingKey"),oi=Symbol("urlKey"),fk=Symbol("headersKey"),Rn=Symbol("abortControllerKey"),pk=Symbol("getAbortController"),$o={get method(){return this[ni].method||"GET"},get url(){return this[oi]},get headers(){return this[fk]||=dk(this[ni])},[pk](){return this[Nn](),this[Rn]},[Nn](){return this[Rn]||=new AbortController,this[Hf]||=mk(this.method,this[oi],this.headers,this[ni],this[Rn])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty($o,e,{get(){return this[Nn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty($o,e,{value:function(){return this[Nn]()[e]()}})});Object.defineProperty($o,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Hf]};return`Request (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf($o,Ao.prototype);var hk=(e,t)=>{let r=Object.create($o);r[ni]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Mc)throw new Zr("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[oi]=a.href}catch(a){throw new Zr("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Mc?e.authority:e.headers.host)||t;if(!o)throw new Zr("Missing host header");let s;if(e instanceof Mc){if(s=e.scheme,!(s==="http"||s==="https"))throw new Zr("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new Zr("Invalid host header");return r[oi]=i.href,r},Uc=Symbol("responseCache"),xn=Symbol("getResponseCache"),en=Symbol("cache"),jc=global.Response,In=class Bf{#t;#e;[xn](){return delete this[en],this[Uc]||=new jc(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof Bf){let o=r[Uc];if(o){this.#e=o,this[xn]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[en]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[en];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[xn]().headers}get status(){return this[en]?.[0]??this[xn]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(In.prototype,e,{get(){return this[xn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(In.prototype,e,{value:function(){return this[xn]()[e]()}})});Object.defineProperty(In.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Uc]};return`Response (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(In,jc);Object.setPrototypeOf(In.prototype,jc.prototype);async function gk(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Wf(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function _k(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Wf(e.getReader(),t)}var Fc=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},wk="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=yk);var Hc=Symbol("outgoingEnded"),Ff=Symbol("incomingDraining"),Ek=500,Tk=64*1024*1024,Pc=e=>{let t=e;if(e.destroyed||t[Ff])return;if(t[Ff]=!0,e instanceof qf){try{e.stream?.close?.(ck.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,Ek);s.unref?.();let i=a=>{r+=a.length,r>Tk&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},bk=()=>new Response(null,{status:400}),Gf=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),qc=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},Vf=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Jf=async(e,t)=>{let[r,n,o]=e[en],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=Fc(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Fc(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(Vf(t),await _k(n,t)?.catch(i=>qc(i,t))),t[Hc]?.()},Sk=e=>typeof e.then=="function",vk=async(e,t,r={})=>{if(Sk(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Gf);if(en in e)return Jf(e,t);let n=Fc(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await gk(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&Vf(t),await Wf(o,t,a))}else n[wk]||(t.writeHead(e.status,n),t.end());t[Hc]?.()},Ak=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Ao&&(Object.defineProperty(global,"Request",{value:Ao}),Object.defineProperty(global,"Response",{value:In})),async(n,o)=>{let s,i;try{i=hk(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[jf]=!0,n.on("end",()=>{a=!0}),n instanceof qf&&(o[Hc]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Pc(n)})})}),o.on("finish",()=>{a||Pc(n)})),o.on("close",()=>{i[Rn]&&(n.errored?i[Rn].abort(n.errored.toString()):o.writableFinished||i[Rn].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{Pc(n)})})}),s=e(i,{incoming:n,outgoing:o}),en in s)return Jf(s,o)}catch(a){if(s)return qc(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:lk(a)),!s)return}else i?s=Gf(a):s=bk()}try{return await vk(s,o,t)}catch(a){return qc(a,o)}}},$k=e=>{let t=e.fetch,r=Ak(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||ak)(e.serverOptions||{},r)},Kf=(e,t)=>{let r=$k(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var Bc=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var zf=Symbol();var Yf=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Qf=32,kk=1e4,si=e=>"headers"in e,ep=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(si(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?xk(e,{all:r,dot:n}):{}};async function xk(e,t){if(!si(e)&&e.bodyCache.formData)return Xf(await e.bodyCache.formData,t);let r=si(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=Yf(n,r.get("Content-Type")||"");si(e)||(e.bodyCache.formData=o);let s=await o;return s?Xf(s,t):{}}function Xf(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Rk(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Nk(r,o,s,n),delete r[o])}),r}var Rk=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},Nk=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",Qf+2);s.length>Qf+1&&Zf(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=kk&&Zf(),o[i]=Object.create(null)),o=o[i])})},Zf=()=>{throw new Error("Nesting limit exceeded")};var Gc=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},tp=e=>{let{groups:t,path:r}=Ik(e),n=Gc(r);return Lk(n,t)},Ik=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Lk=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},ii={},rp=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return ii[n]||(r[2]?ii[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:ii[n]=[e,r[1],!0]),ii[n]}return null},np=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Ck=e=>np(e,decodeURI),Vc=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Ck(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var op=e=>{let t=Vc(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},$r=(e,t,...r)=>(r.length&&(t=$r(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ai=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ci=e=>e.indexOf("%")!==-1?np(e,Ok):e,Wc=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),ci(e)),sp=(e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return Wc(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=Wc(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=Wc(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},ip=sp,ap=(e,t)=>sp(e,t,!0),Ok=decodeURIComponent;var cp=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&ci(r)}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=ci(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return ip(this.url,e)}queries(e){return ap(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return ep(this,e)}#o=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]()));return t[e]=r[e]()};json(){return this.#o("text").then(e=>JSON.parse(e))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#o("blob")}formData(){return this.#o("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[zf](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var lp={Stringify:1,BeforeStream:2,Stream:3},Dk=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Jc=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Jc(c,t,!1,n,o))).then(()=>o[0]));return r?Dk(await i,s):i};var Mk="text/plain; charset=UTF-8",Kc=(e,t)=>({"Content-Type":e,...t}),ko=(e,t)=>new Response(e,t),zc=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#m;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#m=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new cp(this.#t,this.#m,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=ko(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ko(e.body,e);for(let[t,r]of this.#o.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#o.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#o=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#o=ko(this.#o.body,this.#o));let n=this.#o?this.#o.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#o?new Headers(this.#o.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[s,i]of new Headers(t.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}}}let o=typeof t=="number"?t:t?.status??this.#s;return ko(e,{status:o,headers:n??r})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Kc(Mk,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Kc("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Kc("text/html; charset=UTF-8",r));return typeof e=="object"?Jc(e,lp.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>ko(),this.#l(this))};var Ke="ALL",up="all",dp=["get","post","put","delete","options","patch","query"],li="Can not add a route since the matcher is already built.",ui=class extends Error{};var mp="__COMPOSED_HANDLER";var Pk=e=>e.text("404 Not Found",404),fp=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},pp=class hp{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...dp,up].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(Ke,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??Vc:op}#e(){let t=new hp({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Pk;errorHandler=fp;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===fp?s=o.handler:(s=async(i,a)=>(await Bc([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[mp]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=$r(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=$r(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(Ke,$r(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=$r(this._basePath,r);let s={basePath:o!==void 0?$r(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#o(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new zc(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=Bc(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,a)}})()}fetch=(t,...r)=>this.#o(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${$r("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var He=()=>Object.create(null);var di=[];function Yc(e,t){let r=this.buildAllMatchers(),n=(o,s)=>{let i=r[o]||r[Ke],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],di];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=n,n(e,t)}var Ln="[^/]+",xr=".*",cr="(?:|/.*)",kr=Symbol(),gp=new Set(".\\+*[^]$()");function Uk(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===xr||e===cr?t===cr?-1:1:t===xr||t===cr?-1:e===Ln?1:t===Ln?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var _p=class Qc{#t;#e;#r=He();insert(t,r,n,o,s){let i=this;for(let a=0,c=t.length;a<c;a++){let l=t[a],u=l.length===1?l==="*"?a===c-1?["","",xr]:["","",Ln]:null:l==="/*"?["","",cr]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let m=u[1],f=u[2]||Ln;if(m&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&gp.has(f)))throw kr;if(d=i.#r[f],!d){if(f!==xr&&f!==cr){for(let p in i.#r)if((f.length>1||p.length>1)&&p!==xr&&p!==cr)throw kr}d=i.#r[f]=new Qc}m!==""&&(d.#e??=o.varIndex++,n.push([m,d.#e]))}else if(d=i.#r[l],!d){for(let m in i.#r)if(m.length>1&&m!==xr&&m!==cr)throw kr;d=i.#r[l]=new Qc}i=d}if(i.#t!==void 0)throw kr;i.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(Uk).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:gp.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Xc=class{#t={varIndex:0};#e=new _p;#r=0;paths=He();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=e;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var wp=He();function yp(e){return wp[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?cr:t==="*"?xr:`/:${Ln}`)}$`)}function mi(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(yp(r).test(t))return[...e[r]]}var fi=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[Ke]:He()},this.#e={[Ke]:He()},this.#r={[Ke]:new Xc}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===kr?new ui(t):r}}add(e,t,r){let n=this.#t,o=this.#e;if(!n)throw new Error(li);if(!n[e]){this.#r[e]=new Xc;for(let a of[n,o]){a[e]=He();for(let c in a[Ke])a[e][c]=[...a[Ke][c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e===Ke?Object.keys(n):[e];if(/\*$/.test(t)){let a=yp(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=mi(n[c],t)||mi(n[Ke],t)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,t]);return}let i=ai(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=mi(n[c],a)||mi(n[Ke],a)||[]),o[c][a].push([r,a])}match=Yc;buildAllMatchers(){let e=He();for(let t of Object.keys(this.#e))e[t]=this.#n(t);return this.#t=this.#e=this.#r=void 0,wp=He(),e}#n(e){let t=this.#t[e],r=this.#e[e],n=this.#r[e],o=He(),s=[],[i,a,c]=n.buildRegExp();for(let l of[t,r])for(let u in l){let d=l[u],m=n.paths[u];if(!m){o[u]=[d.map(([f])=>[f,He()]),di];continue}s[m[0]]=d.map(([f,p])=>[f,n.paths[p][1].reduceRight((h,[w],_)=>(h[w]=c[m[1][_][1]],h),He())])}return[i,a.map(l=>s[l]),o]}};var Zc=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(li);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof ui)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var el=He(),Fk=0,Ep=class Tp{#t=[];#e=He();#r=[];#s;#n=el;insert(t,r,n){let o=this,s=tp(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=rp(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),m=d?u[0]:u||c,f=o.#e[m]||=new Tp;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,d&&i.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++Fk}})}#o(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[Ke];if(l){l.params=He(),t.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let m=l.possibleKeys[u];l.params[m]=s?.[m]&&!u?s[m]:o[m]??s?.[m]}}}}search(t,r){let n=[];this.#n=el;let s=[this],i=Gc(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],m=u===c-1,f=[];for(let h=0,w=s.length;h<w;h++){let _=s[h],E=_.#e[d];E&&(E.#n=_.#n,m?(E.#e["*"]&&this.#o(n,E.#e["*"],t,_.#n),this.#o(n,E,t,_.#n)):f.push(E));for(let T of _.#r){let v=T.#s,S=_.#n===el?{}:{..._.#n};if(typeof v=="string"){(v==="*"||d.startsWith(v.slice(0,-1)))&&(this.#o(n,T,t,_.#n),v==="*"&&(T.#n=S,f.push(T)));continue}let[,N,x]=v;if(!(!d&&x===!0)){if(x!==!0){if(!l){l=[];let B=r[0]==="/"?1:0;for(let C=0;C<c;C++)l[C]=B,B+=i[C].length+1}let I=r.slice(l[u]),k=x.exec(I);if(k){S[N]=k[0],this.#o(n,T,t,_.#n,S),k[0].length===I.length&&T.#e["*"]&&this.#o(n,T.#e["*"],t,_.#n,S);for(let B in T.#e){T.#n=S;let C=k[0].match(/\//g)?.length??0;(a[C]||=[]).push(T);break}continue}}(x===!0||x.test(d))&&(S[N]=d,m?(this.#o(n,T,t,S,_.#n),T.#e["*"]&&this.#o(n,T.#e["*"],t,S,_.#n)):(T.#n=S,f.push(T)))}}}let p=a.shift();s=p?f.concat(p):f}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var tl=class{name="TrieRouter";#t=new Ep;add(e,t,r){for(let n of ai(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};var tn=class extends pp{constructor(e={}){super(e),this.router=e.router??new Zc({routers:[new fi,new tl]})}};import{join as qk}from"node:path";function jk(e){return e||(process.env.LMBEE_TEAMS_CONF?process.env.LMBEE_TEAMS_CONF:qk(process.cwd(),"teams.conf"))}function Hk(e,t){let r=process.env.LMBEE_TEAM_NAME;if(r===void 0)return;let n=t.find(o=>o.name===r);if(!(n===void 0||!H(n)))try{Xd(e.db,r,new Date().toISOString())}catch{}}function pi(e={}){let t=vs(e.dbPath,{readOnly:e.readOnly??!1}),r=jk(e.teamsConfPath),n=Jr(t.db,r);return e.readOnly||Hk(t,n),{db:t,teamsConfPath:r,teams:n}}import{existsSync as mI,readFileSync as fI,statSync as pI}from"node:fs";import{execFile as Bk}from"node:child_process";import{promisify as Wk}from"node:util";var hi=Wk(Bk),Ro=3,xo="auto_nudge_redirect:",rl=3,nl=5*60*6e4;function Tt(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(xo+t);if(r===void 0)return null;try{let n=JSON.parse(r.v);return typeof n.companionTeam!="string"||n.companionTeam.length===0?null:{companionTeam:n.companionTeam,workerAlias:typeof n.workerAlias=="string"&&n.workerAlias.length>0?n.workerAlias:"Worker",commitThreshold:typeof n.commitThreshold=="number"&&n.commitThreshold>0?n.commitThreshold:rl,hoursThresholdMs:typeof n.hoursThresholdMs=="number"&&n.hoursThresholdMs>0?n.hoursThresholdMs:nl,shiftStartedTs:typeof n.shiftStartedTs=="string"?n.shiftStartedTs:null,shiftStartedSha:typeof n.shiftStartedSha=="string"?n.shiftStartedSha:null,turnsDispatched:typeof n.turnsDispatched=="number"&&n.turnsDispatched>=0?n.turnsDispatched:0,lastReviewedTurn:typeof n.lastReviewedTurn=="number"&&n.lastReviewedTurn>=0?n.lastReviewedTurn:0}}catch{return null}}function ol(e){return e.prepare("SELECT k FROM kv WHERE k LIKE ?").all(xo+"%").map(r=>r.k.slice(xo.length))}function gi(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(xo+t,JSON.stringify(r))}function bp(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(xo+t)}async function Sp(e,t){try{let{stdout:r}=await t("git",["-C",e,"rev-parse","HEAD"],{timeout:1e4});return r.trim()||null}catch{return null}}async function Gk(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"rev-list","--count",`${t}..HEAD`],{timeout:1e4}),o=Number.parseInt(n.trim(),10);return Number.isNaN(o)?null:o}catch{return null}}async function vp(e,t,r,n,o,s=hi){let i=r.shiftStartedTs!==null,a=i?r.shiftStartedSha:await Sp(n,s);gi(e,t,{...r,turnsDispatched:r.turnsDispatched+1,shiftStartedTs:i?r.shiftStartedTs:o,shiftStartedSha:a})}async function Ap(e,t,r=Date.now(),n=hi){let o=[];for(let s of ol(e)){let i=Tt(e,s);if(i===null||i.shiftStartedTs===null)continue;let a=t.get(s);if(a===void 0)continue;let c=(r-Date.parse(i.shiftStartedTs))/(60*6e4),l=i.shiftStartedSha!==null?await Gk(a,i.shiftStartedSha,n):null,u=i.turnsDispatched<=Ro&&i.turnsDispatched>i.lastReviewedTurn,d=c*60*6e4>=i.hoursThresholdMs,m=l!==null&&l>=i.commitThreshold;(u||d||m)&&o.push({team:s,companionTeam:i.companionTeam,workerAlias:i.workerAlias,commitCount:l,hoursElapsed:c,shiftStartedTs:i.shiftStartedTs,shiftStartedSha:i.shiftStartedSha,isRampUp:u,turnNumber:i.turnsDispatched})}return o}async function $p(e,t,r,n,o=hi){let s=Tt(e,t);if(s===null)return;let i=await Sp(r,o);gi(e,t,{...s,shiftStartedTs:n,shiftStartedSha:i,lastReviewedTurn:s.turnsDispatched})}async function kp(e,t,r=hi){let n=e.hoursElapsed.toFixed(1),o=e.commitCount===null?"unknown (git check failed)":String(e.commitCount),s=null;if(e.shiftStartedSha!==null)try{let{stdout:a}=await r("git",["-C",t,"log","--oneline",`${e.shiftStartedSha}..HEAD`],{timeout:1e4});s=a.trim()}catch{s=null}let i=s!==null&&s.length>0?`
193
+ (${v.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+w,onSent:$}}var pe={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function c$(e,t){return t.running.some(r=>_n(e,r.from_identity))}function Xr(e,t){return t.dead.some(r=>_n(e,r.target))&&!Fe(e,t)}function Rc(e){if(e.isCurrentlyActive)return!1;let t=!e.hasInFlightWorker,r=e.timeSinceLastNudgeMs===null||e.timeSinceLastNudgeMs>e.config.cooldownMs;if(e.isDeadReclaimable)return t&&r;let n=!e.isCoordinator&&e.progressStatus==="UNKNOWN"&&(e.progressAgeMs===null||e.progressAgeMs>=e.config.idleThresholdMs),o=!e.heavyLockMayBeHeldByThisTeam&&e.hasStalePersistentInProgressWork;return t&&r&&(e.neverDispatched||n||o)}function Nc(e,t,r,n){let o;try{o=Q(t)}catch{return!1}let s=xe(e,o,t.leadAlias);if(s===null)return!1;let i=new Map(s.entities.map(a=>[a.id,a]));return s.entities.some(a=>(a.kind==="task"||a.kind==="subtask")&&le(a.status)==="in-progress"&&!Vt(e,a,i)&&n-Date.parse(a.updated_at)>=r&&!Lc(a,n))}function Lc(e,t){return e.hold_until!==null&&Date.parse(e.hold_until)>t}function Ic(e,t){if(Ue(e,t.name)!==null||ff(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return xe(e,r,t.leadAlias)===null}function l$(e){return Rc({...e,config:{...e.config,idleThresholdMs:0}})}function If(e){return`last_nudged:${e}`}function Cc(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(If(t))?.v??null}function ko(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(If(t),r)}function Cf(e,t,r,n,o,s,i){if(Ue(e,t.name)?.status==="BLOCKED")return null;let c=Ic(e,t),l=s?.progress_changed_ts==null?null:o-Date.parse(s.progress_changed_ts),u=Cc(e,t.name),d=u===null?null:o-Date.parse(u);return{isCurrentlyActive:Fe(t,r),hasInFlightWorker:c$(t,r),neverDispatched:c,progressStatus:s?.progress_status??null,progressAgeMs:l,isDeadReclaimable:Xr(t,r),hasStalePersistentInProgressWork:Nc(e,t,n.idleThresholdMs,o),timeSinceLastNudgeMs:d,config:n,isCoordinator:t.coordinator===!0,heavyLockMayBeHeldByThisTeam:i.held&&(i.holder===null||i.holder.holder===t.name)}}function Of(e,t,r,n,o,s,i){let a=Cf(e,t,r,o,s,i,n);return a!==null&&Rc(a)}async function Oc(e,t,r,n,o=pe,s=Date.now()){let i=await Xa(e,t,t.name,s);return Of(e,t,r,n,o,s,i)}function Dc(e,t,r,n,o=pe,s=Date.now()){return Of(e,t,r,n,o,s,ie(e,t.name))}async function $n(e,t,r,n,o=pe,s=Date.now(),i={}){let a=[];for(let c of t){if(!c.autoNudge||ie(e,c.name)?.confirmed_done_ts)continue;(i.readOnly?Dc(e,c,r,n,o,s):await Oc(e,c,r,n,o,s))&&!ie(e,c.name)?.confirmed_done_ts&&a.push(c.name)}return a}async function Df(e,t,r,n,o=pe,s=Date.now()){let i=[],a=[];for(let c of t){if(!c.autoNudge||ie(e,c.name)?.confirmed_done_ts)continue;let l=await Xa(e,c,c.name,s);if(ie(e,c.name)?.confirmed_done_ts)continue;let u=Cf(e,c,r,o,s,l,n);u!==null&&(Rc(u)&&i.push(c.name),l$(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as Mf,readFileSync as Pf}from"node:fs";import{dirname as Pc,join as Uf}from"node:path";import{fileURLToPath as Ff}from"node:url";var Mc={sha:"unknown",dirty:!0,builtAt:"unknown"};function u$(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.sha=="string"&&typeof t.dirty=="boolean"&&typeof t.builtAt=="string"}function qf(){let e=Pc(Ff(import.meta.url));for(let t=0;t<5;t+=1){let r=Uf(e,"package.json");if(Mf(r))try{let n=JSON.parse(Pf(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=Pc(e)}return"unknown"}function Uc(){let e=Uf(Pc(Ff(import.meta.url)),"..","build-info.json");if(!Mf(e))return Mc;try{let t=JSON.parse(Pf(e,"utf8"));return u$(t)?t:Mc}catch{return Mc}}var d$="https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod";function kt(e){return(e.LMCTL_LMMAIL_API_URL?.trim()||e.LMMAIL_API_URL?.trim()||d$).replace(/\/+$/,"")}import{createServer as m$}from"http";import{Http2ServerRequest as Bf,constants as f$}from"http2";import{Http2ServerRequest as Fc}from"http2";import{Readable as jf}from"stream";import v$ from"crypto";var Zr=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},p$=e=>e instanceof Zr?e:new Zr(e.message,{cause:e}),h$=global.Request,$o=class extends h${constructor(e,t){typeof e=="object"&&Nn in e&&(e=e[Nn]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},g$=e=>{let t=[],r=e.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&t.push([o,s])}return new Headers(t)},Wf=Symbol("wrapBodyStream"),_$=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new $o(t,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(e==="GET"||e==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[Wf]){let i;s.body=new ReadableStream({async pull(a){try{i||=jf.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=jf.toWeb(n);return new $o(t,s)},Nn=Symbol("getRequestCache"),Gf=Symbol("requestCache"),ai=Symbol("incomingKey"),ci=Symbol("urlKey"),w$=Symbol("headersKey"),Rn=Symbol("abortControllerKey"),y$=Symbol("getAbortController"),xo={get method(){return this[ai].method||"GET"},get url(){return this[ci]},get headers(){return this[w$]||=g$(this[ai])},[y$](){return this[Nn](),this[Rn]},[Nn](){return this[Rn]||=new AbortController,this[Gf]||=_$(this.method,this[ci],this.headers,this[ai],this[Rn])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(xo,e,{get(){return this[Nn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(xo,e,{value:function(){return this[Nn]()[e]()}})});Object.defineProperty(xo,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Gf]};return`Request (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(xo,$o.prototype);var E$=(e,t)=>{let r=Object.create(xo);r[ai]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Fc)throw new Zr("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[ci]=a.href}catch(a){throw new Zr("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Fc?e.authority:e.headers.host)||t;if(!o)throw new Zr("Missing host header");let s;if(e instanceof Fc){if(s=e.scheme,!(s==="http"||s==="https"))throw new Zr("Unsupported scheme")}else s=e.socket&&e.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new Zr("Invalid host header");return r[ci]=i.href,r},jc=Symbol("responseCache"),xn=Symbol("getResponseCache"),en=Symbol("cache"),Wc=global.Response,Ln=class Vf{#t;#e;[xn](){return delete this[en],this[jc]||=new Wc(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof Vf){let o=r[jc];if(o){this.#e=o,this[xn]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof t=="string"||typeof t?.getReader<"u"||t instanceof Blob||t instanceof Uint8Array)&&(this[en]=[r?.status||200,t,n||r?.headers])}get headers(){let t=this[en];return t?(t[2]instanceof Headers||(t[2]=new Headers(t[2]||{"content-type":"text/plain; charset=UTF-8"})),t[2]):this[xn]().headers}get status(){return this[en]?.[0]??this[xn]().status}get ok(){let t=this.status;return t>=200&&t<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(e=>{Object.defineProperty(Ln.prototype,e,{get(){return this[xn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Ln.prototype,e,{value:function(){return this[xn]()[e]()}})});Object.defineProperty(Ln.prototype,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[jc]};return`Response (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Ln,Wc);Object.setPrototypeOf(Ln.prototype,Wc.prototype);async function T$(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Jf(e,t,r){let n=a=>{e.cancel(a).catch(()=>{})};return t.on("close",n),t.on("error",n),(r??e.read()).then(i,o),e.closed.finally(()=>{t.off("close",n),t.off("error",n)});function o(a){a&&t.destroy(a)}function s(){e.read().then(i,o)}function i({done:a,value:c}){try{if(a)t.end();else if(!t.write(c))t.once("drain",s);else return e.read().then(i,o)}catch(l){o(l)}}}function b$(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Jf(e.getReader(),t)}var Hc=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let r=[];for(let[n,o]of e)n==="set-cookie"?r.push(o):t[n]=o;return r.length>0&&(t["set-cookie"]=r),t["content-type"]??="text/plain; charset=UTF-8",t},S$="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=v$);var Gc=Symbol("outgoingEnded"),Hf=Symbol("incomingDraining"),A$=500,k$=64*1024*1024,qc=e=>{let t=e;if(e.destroyed||t[Hf])return;if(t[Hf]=!0,e instanceof Bf){try{e.stream?.close?.(f$.NGHTTP2_NO_ERROR)}catch{}return}let r=0,n=()=>{clearTimeout(s),e.off("data",i),e.off("end",n),e.off("error",n)},o=()=>{n();let a=e.socket;a&&!a.destroyed&&a.destroySoon()},s=setTimeout(o,A$);s.unref?.();let i=a=>{r+=a.length,r>k$&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},$$=()=>new Response(null,{status:400}),Kf=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Bc=(e,t)=>{let r=e instanceof Error?e:new Error("unknown error",{cause:e});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":"text/plain"}),t.end(`Error: ${r.message}`),t.destroy(r))},zf=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Yf=async(e,t)=>{let[r,n,o]=e[en],s=!1;if(!o)o={"content-type":"text/plain; charset=UTF-8"};else if(o instanceof Headers)s=o.has("content-length"),o=Hc(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Hc(i)}else for(let i in o)if(i.length===14&&i.toLowerCase()==="content-length"){s=!0;break}s||(typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size)),t.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?t.end(n):n instanceof Blob?t.end(new Uint8Array(await n.arrayBuffer())):(zf(t),await b$(n,t)?.catch(i=>Bc(i,t))),t[Gc]?.()},x$=e=>typeof e.then=="function",R$=async(e,t,r={})=>{if(x$(e))if(r.errorHandler)try{e=await e}catch(o){let s=await r.errorHandler(o);if(!s)return;e=s}else e=await e.catch(Kf);if(en in e)return Yf(e,t);let n=Hc(e.headers);if(e.body){let o=e.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await T$(a).catch(d=>{console.error(d),i=!0});if(!u){if(l===1){await new Promise(d=>setTimeout(d)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}t.writeHead(e.status,n),s.forEach(c=>{t.write(c)}),i?t.end():(s.length===0&&zf(t),await Jf(o,t,a))}else n[S$]||(t.writeHead(e.status,n),t.end());t[Gc]?.()},N$=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==$o&&(Object.defineProperty(global,"Request",{value:$o}),Object.defineProperty(global,"Response",{value:Ln})),async(n,o)=>{let s,i;try{i=E$(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Wf]=!0,n.on("end",()=>{a=!0}),n instanceof Bf&&(o[Gc]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{qc(n)})})}),o.on("finish",()=>{a||qc(n)})),o.on("close",()=>{i[Rn]&&(n.errored?i[Rn].abort(n.errored.toString()):o.writableFinished||i[Rn].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{qc(n)})})}),s=e(i,{incoming:n,outgoing:o}),en in s)return Yf(s,o)}catch(a){if(s)return Bc(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:p$(a)),!s)return}else i?s=Kf(a):s=$$()}try{return await R$(s,o,t)}catch(a){return Bc(a,o)}}},L$=e=>{let t=e.fetch,r=N$(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||m$)(e.serverOptions||{},r)},Qf=(e,t)=>{let r=L$(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var Vc=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var Xf=Symbol();var Zf=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var ep=32,I$=1e4,li=e=>"headers"in e,np=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(li(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?C$(e,{all:r,dot:n}):{}};async function C$(e,t){if(!li(e)&&e.bodyCache.formData)return tp(await e.bodyCache.formData,t);let r=li(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=Zf(n,r.get("Content-Type")||"");li(e)||(e.bodyCache.formData=o);let s=await o;return s?tp(s,t):{}}function tp(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?O$(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(D$(r,o,s,n),delete r[o])}),r}var O$=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},D$=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",ep+2);s.length>ep+1&&rp(),s.forEach((i,a)=>{a===s.length-1?o[i]=r:((!o[i]||typeof o[i]!="object"||Array.isArray(o[i])||o[i]instanceof File)&&(n.count++>=I$&&rp(),o[i]=Object.create(null)),o=o[i])})},rp=()=>{throw new Error("Nesting limit exceeded")};var Kc=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},op=e=>{let{groups:t,path:r}=M$(e),n=Kc(r);return P$(n,t)},M$=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},P$=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},ui={},sp=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return ui[n]||(r[2]?ui[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:ui[n]=[e,r[1],!0]),ui[n]}return null},ip=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},U$=e=>ip(e,decodeURI),zc=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return U$(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var ap=e=>{let t=zc(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},$r=(e,t,...r)=>(r.length&&(t=$r(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),di=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.slice(0,-1);n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},mi=e=>e.indexOf("%")!==-1?ip(e,F$):e,Jc=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),mi(e)),cp=(e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return Jc(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=Jc(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=Jc(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},lp=cp,up=(e,t)=>cp(e,t,!0),F$=decodeURIComponent;var dp=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&mi(r)}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=mi(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return lp(this.url,e)}queries(e){return up(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return np(this,e)}#o=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]()));return t[e]=r[e]()};json(){return this.#o("text").then(e=>JSON.parse(e))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#o("blob")}formData(){return this.#o("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Xf](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var mp={Stringify:1,BeforeStream:2,Stream:3},q$=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Yc=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Yc(c,t,!1,n,o))).then(()=>o[0]));return r?q$(await i,s):i};var j$="text/plain; charset=UTF-8",Qc=(e,t)=>({"Content-Type":e,...t}),Ro=(e,t)=>new Response(e,t),Xc=class{#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#u;#c;#l;#a;#d;#m;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#m=t.path,this.#d=t.matchResult)}get req(){return this.#e??=new dp(this.#t,this.#m,this.#d),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#o||=Ro(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=Ro(e.body,e);for(let[t,r]of this.#o.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#o.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#o=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#o=Ro(this.#o.body,this.#o));let n=this.#o?this.#o.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#o?new Headers(this.#o.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[s,i]of new Headers(t.headers))s==="set-cookie"?n.append(s,i):n.set(s,i)}if(r){if(!n){let s=0;for(let i in r)if(++s>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let s in r){let i=r[s];if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}}}let o=typeof t=="number"?t:t?.status??this.#s;return Ro(e,{status:o,headers:n??r})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Qc(j$,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Qc("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Qc("text/html; charset=UTF-8",r));return typeof e=="object"?Yc(e,mp.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>Ro(),this.#l(this))};var Ke="ALL",fp="all",pp=["get","post","put","delete","options","patch","query"],fi="Can not add a route since the matcher is already built.",pi=class extends Error{};var hp="__COMPOSED_HANDLER";var H$=e=>e.text("404 Not Found",404),gp=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},_p=class wp{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...pp,fp].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#t=i:this.#s(s,this.#t,i),a.forEach(c=>{this.#s(s,this.#t,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#t=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#t,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#t=s:(this.#t="*",i.unshift(s)),i.forEach(a=>{this.#s(Ke,this.#t,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??zc:ap}#e(){let t=new wp({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=H$;errorHandler=gp;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===gp?s=o.handler:(s=async(i,a)=>(await Vc([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[hp]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=$r(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=$r(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(Ke,$r(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=$r(this._basePath,r);let s={basePath:o!==void 0?$r(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#o(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new Xc(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):l??this.#r(a)}let c=Vc(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#n(l,a)}})()}fetch=(t,...r)=>this.#o(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${$r("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})}};var He=()=>Object.create(null);var hi=[];function Zc(e,t){let r=this.buildAllMatchers(),n=(o,s)=>{let i=r[o]||r[Ke],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],hi];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=n,n(e,t)}var In="[^/]+",Rr=".*",cr="(?:|/.*)",xr=Symbol(),yp=new Set(".\\+*[^]$()");function B$(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===Rr||e===cr?t===cr?-1:1:t===Rr||t===cr?-1:e===In?1:t===In?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Ep=class el{#t;#e;#r=He();insert(t,r,n,o,s){let i=this;for(let a=0,c=t.length;a<c;a++){let l=t[a],u=l.length===1?l==="*"?a===c-1?["","",Rr]:["","",In]:null:l==="/*"?["","",cr]:l.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),d;if(u){let m=u[1],f=u[2]||In;if(m&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&yp.has(f)))throw xr;if(d=i.#r[f],!d){if(f!==Rr&&f!==cr){for(let p in i.#r)if((f.length>1||p.length>1)&&p!==Rr&&p!==cr)throw xr}d=i.#r[f]=new el}m!==""&&(d.#e??=o.varIndex++,n.push([m,d.#e]))}else if(d=i.#r[l],!d){for(let m in i.#r)if(m.length>1&&m!==Rr&&m!==cr)throw xr;d=i.#r[l]=new el}i=d}if(i.#t!==void 0)throw xr;i.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(B$).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:yp.has(n)?`\\${n}`:n)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&r.unshift(`#${this.#t}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var tl=class{#t={varIndex:0};#e=new Ep;#r=0;paths=He();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=e;for(let i=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return n[i]=[l,c],i++,a=!0,l}),!a)break}let s=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,n[i][1]);break}}this.#e.insert(s,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Tp=He();function bp(e){return Tp[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?cr:t==="*"?Rr:`/:${In}`)}$`)}function gi(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(bp(r).test(t))return[...e[r]]}var _i=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[Ke]:He()},this.#e={[Ke]:He()},this.#r={[Ke]:new tl}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===xr?new pi(t):r}}add(e,t,r){let n=this.#t,o=this.#e;if(!n)throw new Error(fi);if(!n[e]){this.#r[e]=new tl;for(let a of[n,o]){a[e]=He();for(let c in a[Ke])a[e][c]=[...a[Ke][c]],this.#s(e,c)}}t==="/*"&&(t="*");let s=e===Ke?Object.keys(n):[e];if(/\*$/.test(t)){let a=bp(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=gi(n[c],t)||gi(n[Ke],t)||[]);for(let c of[n,o])for(let l of s)for(let u in c[l])a.test(u)&&c[l][u].push([r,t]);return}let i=di(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=gi(n[c],a)||gi(n[Ke],a)||[]),o[c][a].push([r,a])}match=Zc;buildAllMatchers(){let e=He();for(let t of Object.keys(this.#e))e[t]=this.#n(t);return this.#t=this.#e=this.#r=void 0,Tp=He(),e}#n(e){let t=this.#t[e],r=this.#e[e],n=this.#r[e],o=He(),s=[],[i,a,c]=n.buildRegExp();for(let l of[t,r])for(let u in l){let d=l[u],m=n.paths[u];if(!m){o[u]=[d.map(([f])=>[f,He()]),hi];continue}s[m[0]]=d.map(([f,p])=>[f,n.paths[p][1].reduceRight((h,[w],_)=>(h[w]=c[m[1][_][1]],h),He())])}return[i,a.map(l=>s[l]),o]}};var rl=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(fi);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof pi)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};var nl=He(),W$=0,Sp=class vp{#t=[];#e=He();#r=[];#s;#n=nl;insert(t,r,n){let o=this,s=op(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=sp(c,l)||(l===void 0&&c&&c.indexOf("*")===c.length-1?c:null),d=Array.isArray(u),m=d?u[0]:u||c,f=o.#e[m]||=new vp;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,d&&i.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++W$}})}#o(t,r,n,o,s){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],l=c[n]||c[Ke];if(l){l.params=He(),t.push(l);for(let u=0,d=l.possibleKeys.length;u<d;u++){let m=l.possibleKeys[u];l.params[m]=s?.[m]&&!u?s[m]:o[m]??s?.[m]}}}}search(t,r){let n=[];this.#n=nl;let s=[this],i=Kc(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],m=u===c-1,f=[];for(let h=0,w=s.length;h<w;h++){let _=s[h],T=_.#e[d];T&&(T.#n=_.#n,m?(T.#e["*"]&&this.#o(n,T.#e["*"],t,_.#n),this.#o(n,T,t,_.#n)):f.push(T));for(let E of _.#r){let v=E.#s,S=_.#n===nl?{}:{..._.#n};if(typeof v=="string"){(v==="*"||d.startsWith(v.slice(0,-1)))&&(this.#o(n,E,t,_.#n),v==="*"&&(E.#n=S,f.push(E)));continue}let[,N,$]=v;if(!(!d&&$===!0)){if($!==!0){if(!l){l=[];let H=r[0]==="/"?1:0;for(let C=0;C<c;C++)l[C]=H,H+=i[C].length+1}let L=r.slice(l[u]),R=$.exec(L);if(R){S[N]=R[0],this.#o(n,E,t,_.#n,S),R[0].length===L.length&&E.#e["*"]&&this.#o(n,E.#e["*"],t,_.#n,S);for(let H in E.#e){E.#n=S;let C=R[0].match(/\//g)?.length??0;(a[C]||=[]).push(E);break}continue}}($===!0||$.test(d))&&(S[N]=d,m?(this.#o(n,E,t,S,_.#n),E.#e["*"]&&this.#o(n,E.#e["*"],t,S,_.#n)):(E.#n=S,f.push(E)))}}}let p=a.shift();s=p?f.concat(p):f}return n[1]&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var ol=class{name="TrieRouter";#t=new Sp;add(e,t,r){for(let n of di(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};var tn=class extends _p{constructor(e={}){super(e),this.router=e.router??new rl({routers:[new _i,new ol]})}};import{join as G$}from"node:path";function V$(e){return e||(process.env.LMBEE_TEAMS_CONF?process.env.LMBEE_TEAMS_CONF:G$(process.cwd(),"teams.conf"))}function J$(e,t){let r=process.env.LMBEE_TEAM_NAME;if(r===void 0)return;let n=t.find(o=>o.name===r);if(!(n===void 0||!B(n)))try{tm(e.db,r,new Date().toISOString())}catch{}}function wi(e={}){let t=xs(e.dbPath,{readOnly:e.readOnly??!1}),r=V$(e.teamsConfPath),n=Jr(t.db,r);return e.readOnly||J$(t,n),{db:t,teamsConfPath:r,teams:n}}import{existsSync as yL,readFileSync as EL,statSync as TL}from"node:fs";import{execFile as K$}from"node:child_process";import{promisify as z$}from"node:util";var yi=z$(K$),Lo=3,No="auto_nudge_redirect:",sl=3,il=5*60*6e4;function bt(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(No+t);if(r===void 0)return null;try{let n=JSON.parse(r.v);return typeof n.companionTeam!="string"||n.companionTeam.length===0?null:{companionTeam:n.companionTeam,workerAlias:typeof n.workerAlias=="string"&&n.workerAlias.length>0?n.workerAlias:"Worker",commitThreshold:typeof n.commitThreshold=="number"&&n.commitThreshold>0?n.commitThreshold:sl,hoursThresholdMs:typeof n.hoursThresholdMs=="number"&&n.hoursThresholdMs>0?n.hoursThresholdMs:il,shiftStartedTs:typeof n.shiftStartedTs=="string"?n.shiftStartedTs:null,shiftStartedSha:typeof n.shiftStartedSha=="string"?n.shiftStartedSha:null,turnsDispatched:typeof n.turnsDispatched=="number"&&n.turnsDispatched>=0?n.turnsDispatched:0,lastReviewedTurn:typeof n.lastReviewedTurn=="number"&&n.lastReviewedTurn>=0?n.lastReviewedTurn:0}}catch{return null}}function al(e){return e.prepare("SELECT k FROM kv WHERE k LIKE ?").all(No+"%").map(r=>r.k.slice(No.length))}function Ei(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(No+t,JSON.stringify(r))}function Ap(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(No+t)}async function kp(e,t){try{let{stdout:r}=await t("git",["-C",e,"rev-parse","HEAD"],{timeout:1e4});return r.trim()||null}catch{return null}}async function Y$(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"rev-list","--count",`${t}..HEAD`],{timeout:1e4}),o=Number.parseInt(n.trim(),10);return Number.isNaN(o)?null:o}catch{return null}}async function $p(e,t,r,n,o,s=yi){let i=r.shiftStartedTs!==null,a=i?r.shiftStartedSha:await kp(n,s);Ei(e,t,{...r,turnsDispatched:r.turnsDispatched+1,shiftStartedTs:i?r.shiftStartedTs:o,shiftStartedSha:a})}async function xp(e,t,r=Date.now(),n=yi){let o=[];for(let s of al(e)){let i=bt(e,s);if(i===null||i.shiftStartedTs===null)continue;let a=t.get(s);if(a===void 0)continue;let c=(r-Date.parse(i.shiftStartedTs))/(60*6e4),l=i.shiftStartedSha!==null?await Y$(a,i.shiftStartedSha,n):null,u=i.turnsDispatched<=Lo&&i.turnsDispatched>i.lastReviewedTurn,d=c*60*6e4>=i.hoursThresholdMs,m=l!==null&&l>=i.commitThreshold;(u||d||m)&&o.push({team:s,companionTeam:i.companionTeam,workerAlias:i.workerAlias,commitCount:l,hoursElapsed:c,shiftStartedTs:i.shiftStartedTs,shiftStartedSha:i.shiftStartedSha,isRampUp:u,turnNumber:i.turnsDispatched})}return o}async function Rp(e,t,r,n,o=yi){let s=bt(e,t);if(s===null)return;let i=await kp(r,o);Ei(e,t,{...s,shiftStartedTs:n,shiftStartedSha:i,lastReviewedTurn:s.turnsDispatched})}async function Np(e,t,r=yi){let n=e.hoursElapsed.toFixed(1),o=e.commitCount===null?"unknown (git check failed)":String(e.commitCount),s=null;if(e.shiftStartedSha!==null)try{let{stdout:a}=await r("git",["-C",t,"log","--oneline",`${e.shiftStartedSha}..HEAD`],{timeout:1e4});s=a.trim()}catch{s=null}let i=s!==null&&s.length>0?`
194
194
 
195
195
  Commits this shift:
196
- ${s}`:"";return e.isRampUp?`[auto-nudge-redirect] RAMP-UP turn ${e.turnNumber}/${Ro} for your Worker (${e.companionTeam}:${e.workerAlias}) -- always reviewed during ramp-up, regardless of commits/time. Please review this turn's own work and correct/coach as needed, then note (in a task note or reply) specifically WHAT you had to correct, if anything -- that's the data point that decides whether this coaching transfers to the next team's Worker.${i}`:`[auto-nudge-redirect] Your Worker (${e.companionTeam}:${e.workerAlias}) shift is due for review -- ${o} commit(s), ${n}h elapsed (threshold: commits or hours, whichever came first). Please review the Worker's own work and tie it up.${i}`}import{execFile as zk}from"node:child_process";import{existsSync as Yk,readdirSync as Ip,readFileSync as Lp,statSync as Qk}from"node:fs";import{hostname as Xk}from"node:os";import{promisify as Zk}from"node:util";import{existsSync as Vk,statSync as Jk}from"node:fs";var HB=15*6e4;function Kk(e,t,r={}){let n=r.existsSyncImpl??Vk,o=r.statSyncImpl??Jk,s=r.nowMs??Date.now();if(!n(e))return!1;if(t===void 0)return!0;try{let i=o(e).mtime.getTime();return s-i<=t}catch{return!1}}function sl(e,t,r){if(e===null)return!1;let n=Date.parse(e);return Number.isNaN(n)?!1:r-n<=t}function xp(e,t){if(e===null)return null;let r=Date.parse(e);return Number.isNaN(r)?null:t-r}function Cn(e,t,r,n,o={}){if(e!==void 0&&Kk(e,t,o))return!0;if(n===void 0)return!1;let s=o.nowMs??Date.now();return sl(r,n,s)}var ex=Zk(zk),tx=45*6e4,Cp=100,Rp=Cp,rx=3;async function nx(e,t=3e4){try{let{stdout:r}=await ex("lmctl",["status",e,"--json"],{timeout:t}),n=JSON.parse(r);return typeof n!="object"||n===null||!Array.isArray(n.members)?null:n}catch{return null}}function _i(e,t){try{let r=Lp(`${t}/${e}/stat`,"utf8"),n=r.lastIndexOf(")");if(n===-1)return null;let o=r.slice(n+1).trim().split(/\s+/),s=Number(o[1]),i=Number(o[11]),a=Number(o[12]);return!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(a)?null:{ppid:s,utime:i,stime:a}}catch{return null}}function Op(e,t="/proc"){let r=_i(e,t);return r===null?null:r.utime+r.stime}function Np(e,t){try{let r=Lp(`${t}/${e}/io`,"utf8"),n=r.match(/^rchar:\s*(\d+)/m),o=r.match(/^wchar:\s*(\d+)/m);if(!n||!o)return null;let s=Number(n[1]),i=Number(o[1]);return!Number.isFinite(s)||!Number.isFinite(i)?null:s+i}catch{return null}}function il(e,t="/proc"){let r=_i(e,t);if(r===null)return null;let n;try{n=Ip(t)}catch{return r.utime+r.stime}let o=new Map,s=new Map;for(let l of n){if(!/^\d+$/.test(l))continue;let u=Number(l);if(u===e)continue;let d=_i(u,t);if(d===null)continue;s.set(u,d);let m=o.get(d.ppid);m?m.push(u):o.set(d.ppid,[u])}let i=r.utime+r.stime,a=[...o.get(e)??[]],c=new Set([e]);for(;a.length>0;){let l=a.shift();c.has(l)||(c.add(l),i+=s.get(l).utime+s.get(l).stime,a.push(...o.get(l)??[]))}return i}function Dp(e,t="/proc"){let r=Np(e,t);if(r===null)return null;let n;try{n=Ip(t)}catch{return r}let o=new Map;for(let c of n){if(!/^\d+$/.test(c))continue;let l=Number(c);if(l===e)continue;let u=_i(l,t);if(u===null)continue;let d=o.get(u.ppid);d?d.push(l):o.set(u.ppid,[l])}let s=r,i=[...o.get(e)??[]],a=new Set([e]);for(;i.length>0;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=Np(c,t);l!==null&&(s+=l),i.push(...o.get(c)??[])}return s}function ox(e,t){if(e.state!=="busy")return null;if(e.inFlight!==null)return e.inFlight.holderPid!==null?{pid:e.inFlight.holderPid,startedAt:e.inFlight.startedAt}:null;if(e.terminalLock!==null)return e.terminalLock.holderHost!==t?null:{pid:e.terminalLock.holderPid,startedAt:e.terminalLock.startedAt};if(e.terminalInvocation!==null){let{holderPid:r,holderHost:n,startedAt:o}=e.terminalInvocation;return r===null||n!==t?null:{pid:r,startedAt:o}}return null}async function sx(e,t,r,n){let o=n.fetchHealthImpl??nx,s=n.readProcStatImpl??il,i=n.hostnameImpl??Xk,a=n.wallClockThresholdMs??tx,c=n.requiredLowCpuStreak??rx,l=await o(r);if(l===null)return;let u=l.members.find(N=>N.alias===t.leadAlias);if(u===void 0)return;let d=ox(u.liveness,i());if(d===null){let N=ie(e,t.name);(N?.holder_watch_pid!==null&&N?.holder_watch_pid!==void 0||N?.hung_holder_flagged_ts!==null&&N?.hung_holder_flagged_ts!==void 0)&&Ga(e,t.name);return}let m=new Date().toISOString(),f=s(d.pid);if(f===null){Wa(e,t.name,`${t.leadAlias}'s servicing lock has outlived its holder -- pid ${d.pid} (started ${d.startedAt}) is NOT RUNNING. Lock is leaked, not hung; nothing to kill, only the lock needs releasing.`,m);return}let p=ie(e,t.name);if(!(p?.holder_watch_pid===d.pid&&p?.holder_watch_started_at===d.startedAt)){Ba(e,t.name,d.pid,d.startedAt,f,m,0);return}let w=Date.now()-Date.parse(d.startedAt),_=p.holder_watch_cpu_ticks!==null?f-p.holder_watch_cpu_ticks:null,E=_!==null&&_<Rp,T=p.holder_watch_low_cpu_streak??0,v=E?T+1:0;if(Ba(e,t.name,d.pid,d.startedAt,f,m,v),w<a||v<c)return;let S=Math.round(w/6e4);Wa(e,t.name,`${t.leadAlias} has held its servicing lock for ~${S}m with under ${Rp/Cp}s of CPU time across ${v} consecutive checks -- possibly hung, not just slow.`,m)}async function Mp(e,t,r={}){let n=r.existsSyncImpl??Yk,o=r.statSyncImpl??Qk,s=r.nowMs??Date.now();for(let i of t){if(!H(i))continue;if(r.sessionAliveExemptTeamName!==void 0&&i.name===r.sessionAliveExemptTeamName&&Cn(r.sessionAliveExemptPath,r.sessionAliveFreshnessMs,r.activityFreshnessMs!==void 0?ie(e,i.name)?.last_cli_activity_ts??null:null,r.activityFreshnessMs,{existsSyncImpl:n,statSyncImpl:o,nowMs:s})){Ga(e,i.name);continue}let a;try{a=Q(i)}catch{continue}try{await sx(e,i,a,r)}catch{continue}}}var No="provider_disabled:";function Pp(e,t){try{let r=JSON.parse(t);return typeof r.disabledAt!="string"?null:{provider:e,disabledAt:r.disabledAt,reason:typeof r.reason=="string"?r.reason:null,expiresAt:typeof r.expiresAt=="string"?r.expiresAt:null}}catch{return null}}function wi(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(No+t);return r===void 0?null:Pp(t,r.v)}function yi(e,t,r={}){let n={provider:t,disabledAt:r.nowIso??new Date().toISOString(),reason:r.reason??null,expiresAt:r.expiresAt??null};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(No+t,JSON.stringify(n))}function Up(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(No+t)}function Io(e){let t=e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${No}%`),r=[];for(let n of t){let o=n.k.slice(No.length),s=Pp(o,n.v);s!==null&&r.push(s)}return r}function rt(e,t,r=Date.now()){let n;try{n=wi(e,t)}catch{return{disabled:!0,config:null,failClosed:!0}}return n===null?{disabled:!1,config:null,failClosed:!1}:n.expiresAt!==null&&Date.parse(n.expiresAt)<=r?{disabled:!1,config:null,failClosed:!1}:{disabled:!0,config:n,failClosed:!1}}import{existsSync as ix,readFileSync as ax,readdirSync as cx,statSync as Fp}from"node:fs";import{basename as Ei}from"node:path";var cl="orphan_would_reap",lx=5e3,ux=6e4,dx=100,mx=3,fx=45*6e4;function qp(e,t){try{let n=ax(`${e}/${t}/cmdline`,"utf8").split("\0").filter(a=>a.length>0),o=n.indexOf("chat");if(o<=0||o+1>=n.length)return null;let s=n[o-1]??"";if(!s.includes("lmctl")&&!s.includes("lctl"))return null;let i=n[o+1];return i.includes(".lmctl:")?i:null}catch{return null}}function jp(e,t){try{return Fp(`${e}/${t}`).mtime.getTime()}catch{return null}}function ll(e){let t;try{t=cx(e)}catch{return[]}let r=[];for(let n of t){if(!/^\d+$/.test(n))continue;let o=Number(n),s=qp(e,o);if(s===null)continue;let i=jp(e,o);i!==null&&r.push({pid:o,target:s,startedAtMs:i})}return r.sort((n,o)=>n.pid-o.pid),r}function al(e){let t=e.lastIndexOf(":");return t===-1?null:{teamfilePath:e.slice(0,t),alias:e.slice(t+1)}}function px(e,t){if(t===null)return!1;let r=al(e),n=al(t);return r===null||n===null?!1:r.alias===n.alias&&Ei(r.teamfilePath)===Ei(n.teamfilePath)}function hx(e,t,r){return t.some(s=>s.pid!==e.pid&&s.target===e.target&&(s.startedAtMs>e.startedAtMs||s.startedAtMs===e.startedAtMs&&s.pid>e.pid))?{action:"reap",reason:`target "${e.target}" has a NEWER OS process for the same target -- this one is a leftover from a prior attempt`,requiresCpuCorroboration:!0}:r.running.find(s=>s.kind==="chat"&&px(e.target,s.target))===void 0?{action:"reap",reason:`target "${e.target}" is not in lctl's own running (chat) bucket at all -- orphaned`,requiresCpuCorroboration:!0}:{action:"skip"}}function gx(e,t,r,n,o,s,i,a){let c=s(t.pid,a);if(c===null)return!1;let l=Zd(e,t.target,t.startedAtMs,t.pid);if(l===null||l.cpu_ticks===null)return Va(e,t.target,t.startedAtMs,t.pid,c,i,0),!1;let m=c-l.cpu_ticks<dx?l.low_cpu_streak+1:0;return Va(e,t.target,t.startedAtMs,t.pid,c,i,m),o-t.startedAtMs<n?!1:m>=r}function _x(e,t){let r=e.find(n=>n.name===t);if(r===void 0||!H(r))return null;try{return Q(r)}catch{return null}}function wx(e,t){let r=al(t);if(r===null)return t;for(let n of e)if(H(n))try{let o=Q(n);if(Ei(o)===Ei(r.teamfilePath))return n.name}catch{continue}return t}async function yx(e,t,r,n,o){if(qp(e,t.pid)!==t.target||jp(e,t.pid)!==t.startedAtMs)return!1;try{n(-t.pid,"SIGTERM")}catch{return!1}await o(r);try{n(-t.pid,0)}catch{return!0}try{n(-t.pid,"SIGKILL")}catch{}return!0}async function Hp(e,t,r,n={}){let o=n.procPath??"/proc",s=n.safetyMarginMs??ux,i=n.sigkillGraceMs??lx,a=n.requiredLowCpuStreak??mx,c=n.minCorroborationWallClockMs??fx,l=n.existsSyncImpl??ix,u=n.statSyncImpl??Fp,d=n.killImpl??process.kill.bind(process),m=n.sleepImpl??(N=>new Promise(x=>setTimeout(x,N))),f=n.readProcCpuTicksImpl??Op,p=n.insertEventImpl??tt,h=n.dryRun??!1,w=n.nowMs??Date.now(),_=new Date(w).toISOString(),E=n.sessionAliveExemptTeamName!==void 0&&Cn(n.sessionAliveExemptPath,n.sessionAliveFreshnessMs,n.activityFreshnessMs!==void 0?ie(e,n.sessionAliveExemptTeamName)?.last_cli_activity_ts??null:null,n.activityFreshnessMs,{existsSyncImpl:l,statSyncImpl:u,nowMs:w}),T=E?_x(t,n.sessionAliveExemptTeamName):null;E&&T===null&&process.stderr.write(`[orphan-reconciler] sessionAliveExemptTeamName "${n.sessionAliveExemptTeamName}" is configured and its session-alive file exists, but that team could not be resolved -- the exemption is NOT currently protecting it
197
- `);let v;try{v=ll(o)}catch{return}em(e,v.map(N=>({target:N.target,startedAtMs:N.startedAtMs,pid:N.pid})));let S=v.filter(N=>w-N.startedAtMs>=s);for(let N of v){if(w-N.startedAtMs<s)continue;if(T!==null){let I=N.target.lastIndexOf(":");if(N.target.slice(0,I)===T)continue}let x=hx(N,S,r);if(x.action!=="reap"){Ja(e,N.target,N.startedAtMs,N.pid);continue}if(!(x.requiresCpuCorroboration&&!gx(e,N,a,c,w,f,_,o))){if(h){try{try{p(e,wx(t,N.target),cl,w,{note:`pid ${N.pid} (${N.target}): ${x.reason}`})}catch{}n.onWouldReap?.({pid:N.pid,target:N.target,reason:x.reason}),process.stderr.write(`[orphan-reconciler] WOULD REAP pid ${N.pid} (${N.target}) [dry-run]: ${x.reason}
198
- `)}catch{}continue}try{let I=await yx(o,N,i,d,m);if(Ja(e,N.target,N.startedAtMs,N.pid),!I)continue;n.onReap?.({pid:N.pid,target:N.target,reason:x.reason}),process.stderr.write(`[orphan-reconciler] reaped pid ${N.pid} (${N.target}): ${x.reason}
199
- `)}catch{continue}}}}import{existsSync as Ex}from"node:fs";import{homedir as Tx}from"node:os";import{join as bx}from"node:path";function Sx(e){return e||(process.env.LCTL_STATE_DB?process.env.LCTL_STATE_DB:bx(Tx(),".lmctl","state.db"))}function On(e){let t=Sx(e);if(!Ex(t))throw new Error(`lctl-src state db not found at ${t} -- set LCTL_STATE_DB or check the path`);return new ht(t,{readonly:!0,fileMustExist:!0})}function vx(e){return e==="done"?"done":e==="error"||e==="aborted"?"failed":e==="busy"||e==="running"||e==="cancelled"?"contention":null}function Bp(e,t){let r=e.prepare("SELECT status, started_at, ended_at, meta FROM tracked_invocation WHERE kind = 'chat' AND started_at >= ? ORDER BY started_at ASC").all(t),n=[],o=0;for(let s of r){let i=vx(s.status);if(i===null){o++;continue}let a,c,l;try{let f=s.meta!==null?JSON.parse(s.meta):null;a=f?.provider,c=f?.model,l=f?.sessionid}catch{o++;continue}if(typeof a!="string"||a.length===0){o++;continue}let u=Date.parse(s.started_at),d=s.ended_at!==null?Date.parse(s.ended_at):NaN,m=s.ended_at!==null&&!Number.isNaN(u)&&!Number.isNaN(d)?d-u:null;n.push({provider:a,model:typeof c=="string"&&c.length>0?c:null,sessionid:typeof l=="string"&&l.length>0?l:null,outcome:i,startedAtIso:s.started_at,endedAtIso:s.ended_at,durationMs:m!==null&&m>=0?m:null})}return{rows:n,skippedUnattributable:o}}var Ax=30*24*60*6e4;function $x(e,t,r){let n;try{n=e(t)}catch{return"unknown"}try{return n.prepare("SELECT status FROM tracked_invocation WHERE holder_pid = ? AND ended_at IS NOT NULL ORDER BY ended_at DESC LIMIT 1").get(r)?.status??"unknown"}catch{return"unknown"}finally{n.close()}}function Wp(e,t={}){let r=t.procPath??"/proc",n=t.nowMs??Date.now(),o=new Date(n).toISOString(),s=t.retentionMs??Ax,i=t.openLctlDbImpl??On,a;try{a=ll(r)}catch{return}for(let u of a)try{let d=il(u.pid,r),m=Dp(u.pid,r);tm(e,u.target,u.startedAtMs,u.pid,o,d,m)}catch{}let c=new Set(a.map(u=>`${u.target}\0${u.startedAtMs}\0${u.pid}`)),l;try{l=e.prepare(`SELECT DISTINCT o.target, o.started_at_ms, o.pid FROM hang_probe_observation o
200
- WHERE NOT EXISTS (SELECT 1 FROM hang_probe_outcome h WHERE h.target = o.target AND h.started_at_ms = o.started_at_ms AND h.pid = o.pid)`).all()}catch{l=[]}for(let u of l)if(!c.has(`${u.target}\0${u.started_at_ms}\0${u.pid}`))try{let d=$x(i,t.lctlStateDbPath,u.pid);nm(e,u.target,u.started_at_ms,u.pid,d,o)}catch{}try{rm(e,new Date(n-s).toISOString())}catch{}}import{createHash as kx}from"node:crypto";var xx=24*60*6e4,Rx=200,Nx=new Set(["all_good","needs_review"]),Ix=24*60*6e4;function Lx(e,t){let r=e.prepare("SELECT * FROM entities WHERE parent_id = ?").all(t);if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=e.prepare(`SELECT * FROM entities WHERE parent_id IN (${n})`).all(...r.map(s=>s.id));return[...r,...o]}function Cx(e,t){return Lx(e,t).map(r=>{let n=Sn(e,r.id),o=zs(e,r.id),i=n!==null&&o!==null&&n.created_at<o?null:n;return{id:r.id,title:r.title,status:r.status,latestNoteBody:i?.body??null,latestNoteId:i?.id??null}})}function Ox(e,t){let r=JSON.stringify([e.status,e.title,e.description,t.map(n=>[n.id,n.status,n.latestNoteId])]);return kx("sha256").update(r,"utf8").digest("hex")}function Dx(e,t){let r=t.length===0?"(no child tasks/subtasks yet)":t.map(n=>`#${n.id}: ${n.title} [${n.status}]${n.latestNoteBody?` -- latest note: ${n.latestNoteBody}`:""}`).join(`
196
+ ${s}`:"";return e.isRampUp?`[auto-nudge-redirect] RAMP-UP turn ${e.turnNumber}/${Lo} for your Worker (${e.companionTeam}:${e.workerAlias}) -- always reviewed during ramp-up, regardless of commits/time. Please review this turn's own work and correct/coach as needed, then note (in a task note or reply) specifically WHAT you had to correct, if anything -- that's the data point that decides whether this coaching transfers to the next team's Worker.${i}`:`[auto-nudge-redirect] Your Worker (${e.companionTeam}:${e.workerAlias}) shift is due for review -- ${o} commit(s), ${n}h elapsed (threshold: commits or hours, whichever came first). Please review the Worker's own work and tie it up.${i}`}import{execFile as ex}from"node:child_process";import{existsSync as tx,readdirSync as Op,readFileSync as Dp,statSync as rx}from"node:fs";import{hostname as nx}from"node:os";import{promisify as ox}from"node:util";import{existsSync as Q$,statSync as X$}from"node:fs";var zB=15*6e4;function Z$(e,t,r={}){let n=r.existsSyncImpl??Q$,o=r.statSyncImpl??X$,s=r.nowMs??Date.now();if(!n(e))return!1;if(t===void 0)return!0;try{let i=o(e).mtime.getTime();return s-i<=t}catch{return!1}}function cl(e,t,r){if(e===null)return!1;let n=Date.parse(e);return Number.isNaN(n)?!1:r-n<=t}function Lp(e,t){if(e===null)return null;let r=Date.parse(e);return Number.isNaN(r)?null:t-r}function Cn(e,t,r,n,o={}){if(e!==void 0&&Z$(e,t,o))return!0;if(n===void 0)return!1;let s=o.nowMs??Date.now();return cl(r,n,s)}var sx=ox(ex),ix=45*6e4,Mp=100,Ip=Mp,ax=3;async function cx(e,t=3e4){try{let{stdout:r}=await sx("lmctl",["status",e,"--json"],{timeout:t}),n=JSON.parse(r);return typeof n!="object"||n===null||!Array.isArray(n.members)?null:n}catch{return null}}function Ti(e,t){try{let r=Dp(`${t}/${e}/stat`,"utf8"),n=r.lastIndexOf(")");if(n===-1)return null;let o=r.slice(n+1).trim().split(/\s+/),s=Number(o[1]),i=Number(o[11]),a=Number(o[12]);return!Number.isFinite(s)||!Number.isFinite(i)||!Number.isFinite(a)?null:{ppid:s,utime:i,stime:a}}catch{return null}}function Pp(e,t="/proc"){let r=Ti(e,t);return r===null?null:r.utime+r.stime}function Cp(e,t){try{let r=Dp(`${t}/${e}/io`,"utf8"),n=r.match(/^rchar:\s*(\d+)/m),o=r.match(/^wchar:\s*(\d+)/m);if(!n||!o)return null;let s=Number(n[1]),i=Number(o[1]);return!Number.isFinite(s)||!Number.isFinite(i)?null:s+i}catch{return null}}function ll(e,t="/proc"){let r=Ti(e,t);if(r===null)return null;let n;try{n=Op(t)}catch{return r.utime+r.stime}let o=new Map,s=new Map;for(let l of n){if(!/^\d+$/.test(l))continue;let u=Number(l);if(u===e)continue;let d=Ti(u,t);if(d===null)continue;s.set(u,d);let m=o.get(d.ppid);m?m.push(u):o.set(d.ppid,[u])}let i=r.utime+r.stime,a=[...o.get(e)??[]],c=new Set([e]);for(;a.length>0;){let l=a.shift();c.has(l)||(c.add(l),i+=s.get(l).utime+s.get(l).stime,a.push(...o.get(l)??[]))}return i}function Up(e,t="/proc"){let r=Cp(e,t);if(r===null)return null;let n;try{n=Op(t)}catch{return r}let o=new Map;for(let c of n){if(!/^\d+$/.test(c))continue;let l=Number(c);if(l===e)continue;let u=Ti(l,t);if(u===null)continue;let d=o.get(u.ppid);d?d.push(l):o.set(u.ppid,[l])}let s=r,i=[...o.get(e)??[]],a=new Set([e]);for(;i.length>0;){let c=i.shift();if(a.has(c))continue;a.add(c);let l=Cp(c,t);l!==null&&(s+=l),i.push(...o.get(c)??[])}return s}function lx(e,t){if(e.state!=="busy")return null;if(e.inFlight!==null)return e.inFlight.holderPid!==null?{pid:e.inFlight.holderPid,startedAt:e.inFlight.startedAt}:null;if(e.terminalLock!==null)return e.terminalLock.holderHost!==t?null:{pid:e.terminalLock.holderPid,startedAt:e.terminalLock.startedAt};if(e.terminalInvocation!==null){let{holderPid:r,holderHost:n,startedAt:o}=e.terminalInvocation;return r===null||n!==t?null:{pid:r,startedAt:o}}return null}async function ux(e,t,r,n){let o=n.fetchHealthImpl??cx,s=n.readProcStatImpl??ll,i=n.hostnameImpl??nx,a=n.wallClockThresholdMs??ix,c=n.requiredLowCpuStreak??ax,l=await o(r);if(l===null)return;let u=l.members.find(N=>N.alias===t.leadAlias);if(u===void 0)return;let d=lx(u.liveness,i());if(d===null){let N=ie(e,t.name);(N?.holder_watch_pid!==null&&N?.holder_watch_pid!==void 0||N?.hung_holder_flagged_ts!==null&&N?.hung_holder_flagged_ts!==void 0)&&Ka(e,t.name);return}let m=new Date().toISOString(),f=s(d.pid);if(f===null){Ja(e,t.name,`${t.leadAlias}'s servicing lock has outlived its holder -- pid ${d.pid} (started ${d.startedAt}) is NOT RUNNING. Lock is leaked, not hung; nothing to kill, only the lock needs releasing.`,m);return}let p=ie(e,t.name);if(!(p?.holder_watch_pid===d.pid&&p?.holder_watch_started_at===d.startedAt)){Va(e,t.name,d.pid,d.startedAt,f,m,0);return}let w=Date.now()-Date.parse(d.startedAt),_=p.holder_watch_cpu_ticks!==null?f-p.holder_watch_cpu_ticks:null,T=_!==null&&_<Ip,E=p.holder_watch_low_cpu_streak??0,v=T?E+1:0;if(Va(e,t.name,d.pid,d.startedAt,f,m,v),w<a||v<c)return;let S=Math.round(w/6e4);Ja(e,t.name,`${t.leadAlias} has held its servicing lock for ~${S}m with under ${Ip/Mp}s of CPU time across ${v} consecutive checks -- possibly hung, not just slow.`,m)}async function Fp(e,t,r={}){let n=r.existsSyncImpl??tx,o=r.statSyncImpl??rx,s=r.nowMs??Date.now();for(let i of t){if(!B(i))continue;if(r.sessionAliveExemptTeamName!==void 0&&i.name===r.sessionAliveExemptTeamName&&Cn(r.sessionAliveExemptPath,r.sessionAliveFreshnessMs,r.activityFreshnessMs!==void 0?ie(e,i.name)?.last_cli_activity_ts??null:null,r.activityFreshnessMs,{existsSyncImpl:n,statSyncImpl:o,nowMs:s})){Ka(e,i.name);continue}let a;try{a=Q(i)}catch{continue}try{await ux(e,i,a,r)}catch{continue}}}var Io="provider_disabled:";function qp(e,t){try{let r=JSON.parse(t);return typeof r.disabledAt!="string"?null:{provider:e,disabledAt:r.disabledAt,reason:typeof r.reason=="string"?r.reason:null,expiresAt:typeof r.expiresAt=="string"?r.expiresAt:null}}catch{return null}}function bi(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(Io+t);return r===void 0?null:qp(t,r.v)}function Si(e,t,r={}){let n={provider:t,disabledAt:r.nowIso??new Date().toISOString(),reason:r.reason??null,expiresAt:r.expiresAt??null};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Io+t,JSON.stringify(n))}function jp(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(Io+t)}function Co(e){let t=e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${Io}%`),r=[];for(let n of t){let o=n.k.slice(Io.length),s=qp(o,n.v);s!==null&&r.push(s)}return r}function rt(e,t,r=Date.now()){let n;try{n=bi(e,t)}catch{return{disabled:!0,config:null,failClosed:!0}}return n===null?{disabled:!1,config:null,failClosed:!1}:n.expiresAt!==null&&Date.parse(n.expiresAt)<=r?{disabled:!1,config:null,failClosed:!1}:{disabled:!0,config:n,failClosed:!1}}import{existsSync as dx,readFileSync as mx,readdirSync as fx,statSync as Hp}from"node:fs";import{basename as vi}from"node:path";var dl="orphan_would_reap",px=5e3,hx=6e4,gx=100,_x=3,wx=45*6e4;function Bp(e,t){try{let n=mx(`${e}/${t}/cmdline`,"utf8").split("\0").filter(a=>a.length>0),o=n.indexOf("chat");if(o<=0||o+1>=n.length)return null;let s=n[o-1]??"";if(!s.includes("lmctl")&&!s.includes("lctl"))return null;let i=n[o+1];return i.includes(".lmctl:")?i:null}catch{return null}}function Wp(e,t){try{return Hp(`${e}/${t}`).mtime.getTime()}catch{return null}}function ml(e){let t;try{t=fx(e)}catch{return[]}let r=[];for(let n of t){if(!/^\d+$/.test(n))continue;let o=Number(n),s=Bp(e,o);if(s===null)continue;let i=Wp(e,o);i!==null&&r.push({pid:o,target:s,startedAtMs:i})}return r.sort((n,o)=>n.pid-o.pid),r}function ul(e){let t=e.lastIndexOf(":");return t===-1?null:{teamfilePath:e.slice(0,t),alias:e.slice(t+1)}}function yx(e,t){if(t===null)return!1;let r=ul(e),n=ul(t);return r===null||n===null?!1:r.alias===n.alias&&vi(r.teamfilePath)===vi(n.teamfilePath)}function Ex(e,t,r){return t.some(s=>s.pid!==e.pid&&s.target===e.target&&(s.startedAtMs>e.startedAtMs||s.startedAtMs===e.startedAtMs&&s.pid>e.pid))?{action:"reap",reason:`target "${e.target}" has a NEWER OS process for the same target -- this one is a leftover from a prior attempt`,requiresCpuCorroboration:!0}:r.running.find(s=>s.kind==="chat"&&yx(e.target,s.target))===void 0?{action:"reap",reason:`target "${e.target}" is not in lctl's own running (chat) bucket at all -- orphaned`,requiresCpuCorroboration:!0}:{action:"skip"}}function Tx(e,t,r,n,o,s,i,a){let c=s(t.pid,a);if(c===null)return!1;let l=rm(e,t.target,t.startedAtMs,t.pid);if(l===null||l.cpu_ticks===null)return za(e,t.target,t.startedAtMs,t.pid,c,i,0),!1;let m=c-l.cpu_ticks<gx?l.low_cpu_streak+1:0;return za(e,t.target,t.startedAtMs,t.pid,c,i,m),o-t.startedAtMs<n?!1:m>=r}function bx(e,t){let r=e.find(n=>n.name===t);if(r===void 0||!B(r))return null;try{return Q(r)}catch{return null}}function Sx(e,t){let r=ul(t);if(r===null)return t;for(let n of e)if(B(n))try{let o=Q(n);if(vi(o)===vi(r.teamfilePath))return n.name}catch{continue}return t}async function vx(e,t,r,n,o){if(Bp(e,t.pid)!==t.target||Wp(e,t.pid)!==t.startedAtMs)return!1;try{n(-t.pid,"SIGTERM")}catch{return!1}await o(r);try{n(-t.pid,0)}catch{return!0}try{n(-t.pid,"SIGKILL")}catch{}return!0}async function Gp(e,t,r,n={}){let o=n.procPath??"/proc",s=n.safetyMarginMs??hx,i=n.sigkillGraceMs??px,a=n.requiredLowCpuStreak??_x,c=n.minCorroborationWallClockMs??wx,l=n.existsSyncImpl??dx,u=n.statSyncImpl??Hp,d=n.killImpl??process.kill.bind(process),m=n.sleepImpl??(N=>new Promise($=>setTimeout($,N))),f=n.readProcCpuTicksImpl??Pp,p=n.insertEventImpl??tt,h=n.dryRun??!1,w=n.nowMs??Date.now(),_=new Date(w).toISOString(),T=n.sessionAliveExemptTeamName!==void 0&&Cn(n.sessionAliveExemptPath,n.sessionAliveFreshnessMs,n.activityFreshnessMs!==void 0?ie(e,n.sessionAliveExemptTeamName)?.last_cli_activity_ts??null:null,n.activityFreshnessMs,{existsSyncImpl:l,statSyncImpl:u,nowMs:w}),E=T?bx(t,n.sessionAliveExemptTeamName):null;T&&E===null&&process.stderr.write(`[orphan-reconciler] sessionAliveExemptTeamName "${n.sessionAliveExemptTeamName}" is configured and its session-alive file exists, but that team could not be resolved -- the exemption is NOT currently protecting it
197
+ `);let v;try{v=ml(o)}catch{return}nm(e,v.map(N=>({target:N.target,startedAtMs:N.startedAtMs,pid:N.pid})));let S=v.filter(N=>w-N.startedAtMs>=s);for(let N of v){if(w-N.startedAtMs<s)continue;if(E!==null){let L=N.target.lastIndexOf(":");if(N.target.slice(0,L)===E)continue}let $=Ex(N,S,r);if($.action!=="reap"){Ya(e,N.target,N.startedAtMs,N.pid);continue}if(!($.requiresCpuCorroboration&&!Tx(e,N,a,c,w,f,_,o))){if(h){try{try{p(e,Sx(t,N.target),dl,w,{note:`pid ${N.pid} (${N.target}): ${$.reason}`})}catch{}n.onWouldReap?.({pid:N.pid,target:N.target,reason:$.reason}),process.stderr.write(`[orphan-reconciler] WOULD REAP pid ${N.pid} (${N.target}) [dry-run]: ${$.reason}
198
+ `)}catch{}continue}try{let L=await vx(o,N,i,d,m);if(Ya(e,N.target,N.startedAtMs,N.pid),!L)continue;n.onReap?.({pid:N.pid,target:N.target,reason:$.reason}),process.stderr.write(`[orphan-reconciler] reaped pid ${N.pid} (${N.target}): ${$.reason}
199
+ `)}catch{continue}}}}import{existsSync as Ax}from"node:fs";import{homedir as kx}from"node:os";import{join as $x}from"node:path";function xx(e){return e||(process.env.LCTL_STATE_DB?process.env.LCTL_STATE_DB:$x(kx(),".lmctl","state.db"))}function On(e){let t=xx(e);if(!Ax(t))throw new Error(`lctl-src state db not found at ${t} -- set LCTL_STATE_DB or check the path`);return new ht(t,{readonly:!0,fileMustExist:!0})}function Rx(e){return e==="done"?"done":e==="error"||e==="aborted"?"failed":e==="busy"||e==="running"||e==="cancelled"?"contention":null}function Vp(e,t){let r=e.prepare("SELECT status, started_at, ended_at, meta FROM tracked_invocation WHERE kind = 'chat' AND started_at >= ? ORDER BY started_at ASC").all(t),n=[],o=0;for(let s of r){let i=Rx(s.status);if(i===null){o++;continue}let a,c,l;try{let f=s.meta!==null?JSON.parse(s.meta):null;a=f?.provider,c=f?.model,l=f?.sessionid}catch{o++;continue}if(typeof a!="string"||a.length===0){o++;continue}let u=Date.parse(s.started_at),d=s.ended_at!==null?Date.parse(s.ended_at):NaN,m=s.ended_at!==null&&!Number.isNaN(u)&&!Number.isNaN(d)?d-u:null;n.push({provider:a,model:typeof c=="string"&&c.length>0?c:null,sessionid:typeof l=="string"&&l.length>0?l:null,outcome:i,startedAtIso:s.started_at,endedAtIso:s.ended_at,durationMs:m!==null&&m>=0?m:null})}return{rows:n,skippedUnattributable:o}}var Nx=30*24*60*6e4;function Lx(e,t,r){let n;try{n=e(t)}catch{return"unknown"}try{return n.prepare("SELECT status FROM tracked_invocation WHERE holder_pid = ? AND ended_at IS NOT NULL ORDER BY ended_at DESC LIMIT 1").get(r)?.status??"unknown"}catch{return"unknown"}finally{n.close()}}function Jp(e,t={}){let r=t.procPath??"/proc",n=t.nowMs??Date.now(),o=new Date(n).toISOString(),s=t.retentionMs??Nx,i=t.openLctlDbImpl??On,a;try{a=ml(r)}catch{return}for(let u of a)try{let d=ll(u.pid,r),m=Up(u.pid,r);om(e,u.target,u.startedAtMs,u.pid,o,d,m)}catch{}let c=new Set(a.map(u=>`${u.target}\0${u.startedAtMs}\0${u.pid}`)),l;try{l=e.prepare(`SELECT DISTINCT o.target, o.started_at_ms, o.pid FROM hang_probe_observation o
200
+ WHERE NOT EXISTS (SELECT 1 FROM hang_probe_outcome h WHERE h.target = o.target AND h.started_at_ms = o.started_at_ms AND h.pid = o.pid)`).all()}catch{l=[]}for(let u of l)if(!c.has(`${u.target}\0${u.started_at_ms}\0${u.pid}`))try{let d=Lx(i,t.lctlStateDbPath,u.pid);im(e,u.target,u.started_at_ms,u.pid,d,o)}catch{}try{sm(e,new Date(n-s).toISOString())}catch{}}import{createHash as Ix}from"node:crypto";var Cx=24*60*6e4,Ox=200,Dx=new Set(["all_good","needs_review"]),Mx=24*60*6e4;function Px(e,t){let r=e.prepare("SELECT * FROM entities WHERE parent_id = ?").all(t);if(r.length===0)return[];let n=r.map(()=>"?").join(","),o=e.prepare(`SELECT * FROM entities WHERE parent_id IN (${n})`).all(...r.map(s=>s.id));return[...r,...o]}function Ux(e,t){return Px(e,t).map(r=>{let n=Sn(e,r.id),o=Zs(e,r.id),i=n!==null&&o!==null&&n.created_at<o?null:n;return{id:r.id,title:r.title,status:r.status,latestNoteBody:i?.body??null,latestNoteId:i?.id??null}})}function Fx(e,t){let r=JSON.stringify([e.status,e.title,e.description,t.map(n=>[n.id,n.status,n.latestNoteId])]);return Ix("sha256").update(r,"utf8").digest("hex")}function qx(e,t){let r=t.length===0?"(no child tasks/subtasks yet)":t.map(n=>`#${n.id}: ${n.title} [${n.status}]${n.latestNoteBody?` -- latest note: ${n.latestNoteBody}`:""}`).join(`
201
201
  `);return`You are reviewing whether a software project's epic is healthy or needs the meta-lead's attention.
202
202
 
203
203
  Epic: ${e.title} [${e.status}]
@@ -216,10 +216,10 @@ Do NOT classify needs_review solely because an epic has no children yet, has few
216
216
  "todo" with nothing else wrong -- incompleteness alone is never a red flag. Only flag a REAL problem among
217
217
  whatever children currently exist (stalled/blocked, inconsistent, stuck).
218
218
 
219
- Respond with EXACTLY one line of strict JSON, no other text before or after: {"label": "<all_good or needs_review>", "reason": "<short human-readable reason, under 200 characters>"}`}function Mx(e){if(e===null)return null;let t;try{t=JSON.parse(e.trim())}catch{return null}if(typeof t!="object"||t===null)return null;let r=t;if(typeof r.label!="string"||!Nx.has(r.label)||typeof r.reason!="string"||r.reason.trim().length===0)return null;let n=r.reason.replace(/\s+/g," ").trim();return n.length===0?null:{label:r.label,reason:n.slice(0,Rx)}}async function Px(e,t,r,n){let o=n.decompositionGraceMs??Ix;if(r.length===0&&Date.now()-Date.parse(t.created_at)<o)return;let s=Ox(t,r),i=n.cooldownMs??xx,a=t.review_input_hash!==s,c=!t.review_time||Date.now()-Date.parse(t.review_time)>=i;if(!(a||c))return;let l=await ri(Dx(t,r),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),u=Mx(l);if(u===null)return;let d=new Date().toISOString();Ef(e,t.id,d,s,u.label==="needs_review"?{needsReview:!0,reason:u.reason}:{needsReview:!1})}async function Gp(e,t,r={}){for(let n of t){if(!H(n))continue;let o;try{o=Q(n)}catch{continue}let s=xe(e,o,n.leadAlias);if(s!==null)for(let i of s.entities.filter(ti)){let a=Cx(e,i.id);try{await Px(e,i,a,r)}catch{continue}}}}import{createHash as Bx}from"node:crypto";import{execFile as Ux}from"node:child_process";import{promisify as Fx}from"node:util";var Vp=Fx(Ux),qx=/^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) )?([A-Za-z0-9_]+): (.*)$/,jx="\u2026 [truncated older output \u2014 raise with --max-bytes]";function Hx(e){let t=[],r=!1;for(let n of e.split(`
220
- `)){if(n.length===0)continue;if(n===jx){r=!0;continue}if(/^\s/.test(n)){let s=t[t.length-1];s&&(s.text+=`
221
- ${n.replace(/^ {2}/,"")}`);continue}let o=qx.exec(n);if(o)t.push({ts:o[1]??null,role:o[2],text:o[3]});else{let s=t[t.length-1];s?s.text+=`
222
- ${n}`:t.push({ts:null,role:"unknown",text:n})}}return{turns:t,truncated:r}}async function Ti(e,t,r={}){let n=r.spawnPrefix??["lmctl"],o=[...n.slice(1),"tail",e,t,"--lines",String(r.lines??40)];r.since&&o.push("--since",r.since);let s=n[0],i;try{({stdout:i}=await Vp(s,o,{timeout:r.timeoutMs??3e4,maxBuffer:16*1024*1024}))}catch(a){let c=a.stderr;throw typeof c=="string"&&c.trim().length>0?new Error(`lmctl tail: ${c.trim()}`):a}return Hx(i)}async function bi(e,t,r={}){let n=r.spawnPrefix??["lmctl"],o=[...n.slice(1),"tail",e,t,"--json","--lines",String(r.lines??40)];r.since&&o.push("--since",r.since);let s=n[0],i;try{({stdout:i}=await Vp(s,o,{timeout:r.timeoutMs??3e4,maxBuffer:16*1024*1024}))}catch(a){let c=a.stderr;throw typeof c=="string"&&c.trim().length>0?new Error(`lmctl tail: ${c.trim()}`):a}return JSON.parse(i)}var Wx=200,Gx=new Set(["genuinely_done","blocked","stalled_needs_nudge","produced_output_no_report"]),Vx=2*60*6e4;function Jx(e,t,r){let n=xe(e,t,r);return n===null?[]:n.entities.filter(o=>!vc(o.status)).map(o=>({id:o.id,title:o.title,status:o.status}))}function Kx(e,t,r,n){let o=xe(e,t,r);return o===null?[]:o.entities.filter(s=>(s.kind==="task"||s.kind==="subtask")&&xc(s,n)).map(s=>({id:s.id,title:s.title,holdUntil:s.hold_until}))}function Jp(e,t,r=null,n=[]){let o=Bx("sha256").update(`${Buffer.byteLength(e,"utf8")}:`,"utf8").update(e,"utf8");for(let i of t)o.update(`\0${i.id}:${i.status}`,"utf8");r!==null&&(r.progress_status!==null||r.progress_changed_ts!==null)&&o.update(`\0progress:${r.progress_status??""}:${r.progress_changed_ts??""}`,"utf8");for(let i of n)o.update(`\0held:${i.id}:${i.holdUntil}`,"utf8");return o.digest("hex")}function zx(e,t,r,n,o=[]){let s=r.length===0?"(none -- this team has no non-terminal tasks in the tracker right now)":r.map(l=>`#${l.id}: ${l.title} [${l.status}]`).join(`
219
+ Respond with EXACTLY one line of strict JSON, no other text before or after: {"label": "<all_good or needs_review>", "reason": "<short human-readable reason, under 200 characters>"}`}function jx(e){if(e===null)return null;let t;try{t=JSON.parse(e.trim())}catch{return null}if(typeof t!="object"||t===null)return null;let r=t;if(typeof r.label!="string"||!Dx.has(r.label)||typeof r.reason!="string"||r.reason.trim().length===0)return null;let n=r.reason.replace(/\s+/g," ").trim();return n.length===0?null:{label:r.label,reason:n.slice(0,Ox)}}async function Hx(e,t,r,n){let o=n.decompositionGraceMs??Mx;if(r.length===0&&Date.now()-Date.parse(t.created_at)<o)return;let s=Fx(t,r),i=n.cooldownMs??Cx,a=t.review_input_hash!==s,c=!t.review_time||Date.now()-Date.parse(t.review_time)>=i;if(!(a||c))return;let l=await ii(qx(t,r),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),u=jx(l);if(u===null)return;let d=new Date().toISOString();Sf(e,t.id,d,s,u.label==="needs_review"?{needsReview:!0,reason:u.reason}:{needsReview:!1})}async function Kp(e,t,r={}){for(let n of t){if(!B(n))continue;let o;try{o=Q(n)}catch{continue}let s=xe(e,o,n.leadAlias);if(s!==null)for(let i of s.entities.filter(si)){let a=Ux(e,i.id);try{await Hx(e,i,a,r)}catch{continue}}}}import{createHash as Kx}from"node:crypto";import{execFile as Bx}from"node:child_process";import{promisify as Wx}from"node:util";var zp=Wx(Bx),Gx=/^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) )?([A-Za-z0-9_]+): (.*)$/,Vx="\u2026 [truncated older output \u2014 raise with --max-bytes]";function Jx(e){let t=[],r=!1;for(let n of e.split(`
220
+ `)){if(n.length===0)continue;if(n===Vx){r=!0;continue}if(/^\s/.test(n)){let s=t[t.length-1];s&&(s.text+=`
221
+ ${n.replace(/^ {2}/,"")}`);continue}let o=Gx.exec(n);if(o)t.push({ts:o[1]??null,role:o[2],text:o[3]});else{let s=t[t.length-1];s?s.text+=`
222
+ ${n}`:t.push({ts:null,role:"unknown",text:n})}}return{turns:t,truncated:r}}async function Ai(e,t,r={}){let n=r.spawnPrefix??["lmctl"],o=[...n.slice(1),"tail",e,t,"--lines",String(r.lines??40)];r.since&&o.push("--since",r.since);let s=n[0],i;try{({stdout:i}=await zp(s,o,{timeout:r.timeoutMs??3e4,maxBuffer:16*1024*1024}))}catch(a){let c=a.stderr;throw typeof c=="string"&&c.trim().length>0?new Error(`lmctl tail: ${c.trim()}`):a}return Jx(i)}async function ki(e,t,r={}){let n=r.spawnPrefix??["lmctl"],o=[...n.slice(1),"tail",e,t,"--json","--lines",String(r.lines??40)];r.since&&o.push("--since",r.since);let s=n[0],i;try{({stdout:i}=await zp(s,o,{timeout:r.timeoutMs??3e4,maxBuffer:16*1024*1024}))}catch(a){let c=a.stderr;throw typeof c=="string"&&c.trim().length>0?new Error(`lmctl tail: ${c.trim()}`):a}return JSON.parse(i)}var zx=200,Yx=new Set(["genuinely_done","blocked","stalled_needs_nudge","produced_output_no_report"]),Qx=2*60*6e4;function Xx(e,t,r){let n=xe(e,t,r);return n===null?[]:n.entities.filter(o=>!$c(o.status)).map(o=>({id:o.id,title:o.title,status:o.status}))}function Zx(e,t,r,n){let o=xe(e,t,r);return o===null?[]:o.entities.filter(s=>(s.kind==="task"||s.kind==="subtask")&&Lc(s,n)).map(s=>({id:s.id,title:s.title,holdUntil:s.hold_until}))}function Yp(e,t,r=null,n=[]){let o=Kx("sha256").update(`${Buffer.byteLength(e,"utf8")}:`,"utf8").update(e,"utf8");for(let i of t)o.update(`\0${i.id}:${i.status}`,"utf8");r!==null&&(r.progress_status!==null||r.progress_changed_ts!==null)&&o.update(`\0progress:${r.progress_status??""}:${r.progress_changed_ts??""}`,"utf8");for(let i of n)o.update(`\0held:${i.id}:${i.holdUntil}`,"utf8");return o.digest("hex")}function eR(e,t,r,n,o=[]){let s=r.length===0?"(none -- this team has no non-terminal tasks in the tracker right now)":r.map(l=>`#${l.id}: ${l.title} [${l.status}]`).join(`
223
223
  `),i=n===null||n.progress_status===null?"no scan yet -- no independent evidence available":`${n.progress_status}${n.progress_changed_ts?`, last changed ${n.progress_changed_ts}`:""}`,a=o.length===0?null:o.map(l=>`#${l.id}: ${l.title}, held until ${l.holdUntil}`).join(`
224
224
  `),c=a===null?"":`
225
225
  This team currently has task(s) DELIBERATELY HELD until a future time (this is a scheduled
@@ -255,21 +255,21 @@ If the file-scan progress signal says ACTIVE with a recent change, treat that as
255
255
  evidence of recent execution even if the transcript alone reads as stalled or dead -- the transcript
256
256
  may belong to a member who did none of the actual work.
257
257
 
258
- Respond with EXACTLY one line of strict JSON, no other text before or after: {"label": "<one of the four exact labels above>", "reason": "<short human-readable reason, under 200 characters>"}`}function Yx(e){if(e===null)return null;let t;try{t=JSON.parse(e.trim())}catch{return null}if(typeof t!="object"||t===null)return null;let r=t;if(typeof r.label!="string"||!Gx.has(r.label)||typeof r.reason!="string"||r.reason.trim().length===0)return null;let n=r.reason.replace(/\s+/g," ").trim();return n.length===0?null:{label:r.label,reason:n.slice(0,Wx)}}function Qx(e){if(e.length===1){let[t]=e;return`holding for #${t.id} ("${t.title}") until ${t.holdUntil} -- deliberately scheduled, not stalled`}return`holding for ${e.length} task(s), until ${e.map(t=>t.holdUntil).join(", ")} -- deliberately scheduled, not stalled`}async function Xx(e,t,r,n){let o=n.fetchTailJsonImpl??bi,s,i,a;try{s=(await o(r,t.leadAlias,{lines:20})).messages.map(T=>`${T.role}: ${typeof T.content=="string"?T.content:JSON.stringify(T.content)}`).join(`
259
- `),i=Jx(e,r,t.leadAlias),a=Kx(e,r,t.leadAlias,Date.now())}catch{return}let c=ie(e,t.name),l=Jp(s,i,c,a),u=Jp("",i,c,a),d=n.cooldownMs??Vx,m=c?.miniplayer_verdict_input_hash!==l,f=c?.miniplayer_verdict_structural_hash!==u,p=!c?.miniplayer_verdict_ts||Date.now()-Date.parse(c.miniplayer_verdict_ts)>=d;if(!(f||m&&p))return;let h=await ri(zx(t.name,s,i,c,a),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),w=Yx(h);if(w===null)return;let _=w.label==="stalled_needs_nudge"&&a.length>0&&i.length===0?{label:"blocked",reason:Qx(a)}:w;Bd(e,t.name,_.label,_.reason,new Date().toISOString(),l,u)}async function Kp(e,t,r,n={}){for(let o of t){let s=r.find(a=>a.name===o);if(s===void 0||!H(s))continue;let i;try{i=Q(s)}catch{continue}try{await Xx(e,s,i,n)}catch{continue}}}import{execFileSync as zR}from"node:child_process";var U=class extends Error{code;exitCode;constructor(t,r,n=2){super(r),this.code=t,this.exitCode=n}};function dl(e){let t;try{if(typeof e!="string")throw new Error("expected a cron expression string");let r=e.trim().split(/\s+/);if(r.length!==5)throw new Error("expected five fields: minute hour day-of-month month day-of-week");t="minute";let n=Lo(r[0],0,59);t="hour";let o=Lo(r[1],0,23);t="dayOfMonth";let s=Lo(r[2],1,31);t="month";let i=Lo(r[3],1,12);t="dayOfWeek";let a=Lo(r[4],0,7,l=>l===7?0:l);return{ok:!0,schedule:{__brand:"CronSchedule",minute:n,hour:o,dayOfMonth:s,month:i,dayOfWeek:a}}}catch(r){let n=r instanceof Error?r.message:String(r);return{ok:!1,error:t?{message:n,field:t}:{message:n}}}}function Lo(e,t,r,n=o=>o){if(e.length===0)throw new Error("empty field");let o=new Set;for(let s of e.split(",")){if(s.length===0)throw new Error(`invalid list in "${e}"`);let i=s.split("/");if(i.length>2)throw new Error(`invalid step in "${s}"`);let a=i[0],c=i[1]===void 0?1:ul(i[1],1,r-t+1,s),l=a.split("-");if(l.length>2)throw new Error(`invalid range in "${s}"`);let u=a==="*"?t:ul(l[0],t,r,s),d=a==="*"?r:l[1]!==void 0?ul(l[1],t,r,s):i[1]?r:u;if(u>d)throw new Error(`range starts after it ends in "${s}"`);for(let m=u;m<=d;m+=c)o.add(n(m))}return{values:o,wildcard:e.split(",").some(s=>s.split("/")[0]==="*")}}function ul(e,t,r,n){if(!/^\d+$/.test(e))throw new Error(`expected an integer in "${n}"`);let o=Number(e);if(!Number.isSafeInteger(o)||o<t||o>r)throw new Error(`value ${e} is outside ${t}-${r}`);return o}function Zx(e,t){let r=e;if(!r.minute.values.has(t.getMinutes())||!r.hour.values.has(t.getHours())||!r.month.values.has(t.getMonth()+1))return!1;let n=r.dayOfMonth.values.has(t.getDate()),o=r.dayOfWeek.values.has(t.getDay());return r.dayOfMonth.wildcard?o:r.dayOfWeek.wildcard?n:n||o}function zp(e,t,r){let n=t.getTime(),o=r.getTime();if(o<n)throw new RangeError("untilInclusive must not precede sinceExclusive");for(let s=(Math.floor(n/6e4)+1)*6e4;s<=o;s+=6e4)if(Zx(e,new Date(s)))return!0;return!1}import{spawn as eR}from"node:child_process";import{closeSync as tR,existsSync as rR,mkdirSync as nR,openSync as oR,readdirSync as sR,unlinkSync as iR}from"node:fs";import{homedir as aR}from"node:os";import{join as Si}from"node:path";var Yp=["systemd-run","--user","--scope","--collect","--quiet"],cR=10,Qp=50*6e4,lR=5e3;function vi(){return process.env.LMBEE_CRON_LOG_DIR?process.env.LMBEE_CRON_LOG_DIR:Si(aR(),".lmbee","cron-logs")}function uR(e,t){try{let r=sR(e).sort();for(let n of r.slice(0,Math.max(0,r.length-t)))try{iR(Si(e,n))}catch{}}catch{}}function dR(e,t){return[...t.spawnPrefix??(t.systemdUnitName!==void 0?[...Yp,"--unit",t.systemdUnitName,"--"]:[...Yp,"--"]),"sh","-c",e]}function Co(e,t={}){let r=Si(t.logDir??vi(),String(e.id));rR(r)||nR(r,{recursive:!0});let n=Si(r,`${new Date().toISOString().replace(/[:.]/g,"-")}.log`),o=oR(n,"a"),s=dR(e.action_payload,t),[i,...a]=s,c;try{c=eR(i,a,{detached:!0,stdio:["ignore",o,o],...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{}})}finally{tR(o)}c.unref();let l=c.pid??null,u=!1,d=t.timeoutMs===void 0?Qp:t.timeoutMs,m=t.sigkillGraceMs??lR,f=d===null?void 0:setTimeout(()=>{if(u)return;let h=c.pid;if(h!==void 0){try{process.kill(-h,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-h,0)}catch{return}try{process.kill(-h,"SIGKILL")}catch{}},m).unref()}process.stderr.write(`[lmcron] job ${e.id} timed out after ${d}ms, sending SIGTERM
260
- `)},d??Qp);f?.unref();let p=(h,w)=>{u||(u=!0,f!==void 0&&clearTimeout(f),uR(r,cR),t.onExit?.(h,w,l,n))};c.on("error",h=>{process.stderr.write(`[lmcron] job ${e.id} spawn error: ${h.message}
261
- `),p(null,h)}),c.on("exit",h=>{p(h)})}import{createHash as mR,randomUUID as fR}from"node:crypto";var rn=16*1024,Do=16*1024,ml=512,Ai=100,fl=4096,pl=1024*1024,Mo="('pending','running')",pR="execution_state != 'gone' OR (status = 'escalated' AND escalation_resolved_at IS NULL)";function Po(e){let{run_token_hash:t,...r}=e;return r}function Xp(e){return mR("sha256").update(e,"utf8").digest("hex")}function bt(e){try{return e()}catch(t){if(t instanceof U)throw t;if(t instanceof L)throw new U(t.code,t.message,t.exitCode);let r=t&&typeof t=="object"&&"code"in t?String(t.code):void 0,n=t instanceof Error?t.message:String(t);throw r!==void 0&&(r.startsWith("SQLITE_BUSY")||r.startsWith("SQLITE_LOCKED"))?new U("DB_BUSY","Database busy; retry after the current writer completes",5):r!==void 0&&r.startsWith("SQLITE_CONSTRAINT")?new U("STRUCTURAL_ERROR",n,2):new U("STORAGE_ERROR",n,1)}}function Zp(e,t){return bt(()=>e.prepare("SELECT * FROM cron_runs WHERE id = ?").get(t)??null)}function ze(e,t){let r=Zp(e,t);if(r===null)throw new U("NOT_FOUND",`Cron run ${t} does not exist`,3);return r}function hR(e,t){return e.prepare("SELECT * FROM cron_runs WHERE run_token_hash = ?").get(t)??null}function Rr(e,t){return bt(()=>e.prepare(`SELECT * FROM cron_runs WHERE job_id = ? AND (${pR}) ORDER BY id DESC LIMIT 1`).get(t)??null)}function hl(e,t,r,n){return bt(()=>{let o=Rr(e,t);if(o!==null)return o.status==="escalated"?{kind:"escalation",run:o}:{kind:"overlap",run:o};let s=fR(),i=de();try{let a=e.prepare(`INSERT INTO cron_runs(job_id, run_token_hash, status, execution_state, trigger_kind, config_snapshot, created_at, updated_at)
262
- VALUES (?, ?, 'pending', 'active', ?, ?, ?, ?)`).run(t,Xp(s),r,n,i,i);return{kind:"claimed",run:ze(e,Number(a.lastInsertRowid)),token:s}}catch(a){let c=a&&typeof a=="object"&&"code"in a?String(a.code):void 0;if(c!==void 0&&c.startsWith("SQLITE_CONSTRAINT")){let l=Rr(e,t);if(l!==null)return l.status==="escalated"?{kind:"escalation",run:l}:{kind:"overlap",run:l}}throw a}})}function $i(e,t,r,n){bt(()=>e.prepare(`UPDATE cron_runs SET status = 'running', execution_identity = ?, pid = ?, started_at = ?, updated_at = ?
263
- WHERE id = ? AND status = 'pending'`).run(JSON.stringify(r),n,de(),de(),t))}function gl(e,t,r,n){e.prepare("UPDATE cron_runs SET execution_identity = ?, pid = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(r),n,de(),t)}function gR(e,t){bt(()=>e.prepare(`UPDATE cron_runs SET execution_state = 'gone', execution_gone_at = ?, execution_uncertain_reason = NULL, updated_at = ?
264
- WHERE id = ? AND execution_state != 'gone'`).run(de(),de(),t))}function Uo(e,t,r){bt(()=>e.prepare(`UPDATE cron_runs SET execution_state = 'uncertain', execution_uncertain_reason = ?, updated_at = ?
265
- WHERE id = ? AND execution_state != 'gone'`).run(r.slice(0,1024),de(),t))}function Oo(e,t,r){let n=ye(e,t);if(Buffer.byteLength(n,"utf8")>r)throw new U("INVALID_ARGUMENT",`${t} exceeds ${r} bytes`);return n}function _R(e){if(e===void 0)return[];if(!Array.isArray(e))throw new U("INVALID_ARGUMENT","artifacts must be an array");if(e.length>Ai)throw new U("INVALID_ARGUMENT",`at most ${Ai} artifacts are allowed`);return e.map(t=>{if(typeof t!="string")throw new U("INVALID_ARGUMENT","artifacts must be strings");return Oo(t,"artifact",fl)})}function eh(e,t){if(e.status!=="succeeded"&&e.status!=="failed"&&e.status!=="escalated")throw new U("INVALID_ARGUMENT",'status must be "succeeded", "failed", or "escalated"');let r=Oo(e.summary,"summary",rn),n=_R(e.artifacts),o=null,s=null,i=null;if(e.status==="escalated"){o=Oo(e.action??"","requested action",Do),i=e.reason!==void 0?Oo(e.reason,"escalation reason",Do):r;let a=e.owner!==void 0?Oo(e.owner,"owner",ml):t;if(a===null||a.trim().length===0)throw new U("INVALID_ARGUMENT","an escalation requires an owner or a job with a configured default escalation owner");s=a}return{status:e.status,summary:r,artifacts:JSON.stringify(n),escalationAction:o,escalationOwner:s,escalationReason:i}}function th(e,t){return e.status===t.status&&e.summary===t.summary&&e.artifacts===t.artifacts&&e.escalation_action===t.escalationAction&&e.escalation_owner===t.escalationOwner&&e.escalation_reason===t.escalationReason}function rh(e){try{let t=JSON.parse(e.config_snapshot);return typeof t.escalationOwner=="string"&&t.escalationOwner.trim().length>0?t.escalationOwner:null}catch{return null}}function _l(e,t,r){let n=eh(r,rh(t)),o=de();if(e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, artifacts = ?, escalation_reason = ?, escalation_action = ?,
258
+ Respond with EXACTLY one line of strict JSON, no other text before or after: {"label": "<one of the four exact labels above>", "reason": "<short human-readable reason, under 200 characters>"}`}function tR(e){if(e===null)return null;let t;try{t=JSON.parse(e.trim())}catch{return null}if(typeof t!="object"||t===null)return null;let r=t;if(typeof r.label!="string"||!Yx.has(r.label)||typeof r.reason!="string"||r.reason.trim().length===0)return null;let n=r.reason.replace(/\s+/g," ").trim();return n.length===0?null:{label:r.label,reason:n.slice(0,zx)}}function rR(e){if(e.length===1){let[t]=e;return`holding for #${t.id} ("${t.title}") until ${t.holdUntil} -- deliberately scheduled, not stalled`}return`holding for ${e.length} task(s), until ${e.map(t=>t.holdUntil).join(", ")} -- deliberately scheduled, not stalled`}async function nR(e,t,r,n){let o=n.fetchTailJsonImpl??ki,s,i,a;try{s=(await o(r,t.leadAlias,{lines:20})).messages.map(E=>`${E.role}: ${typeof E.content=="string"?E.content:JSON.stringify(E.content)}`).join(`
259
+ `),i=Xx(e,r,t.leadAlias),a=Zx(e,r,t.leadAlias,Date.now())}catch{return}let c=ie(e,t.name),l=Yp(s,i,c,a),u=Yp("",i,c,a),d=n.cooldownMs??Qx,m=c?.miniplayer_verdict_input_hash!==l,f=c?.miniplayer_verdict_structural_hash!==u,p=!c?.miniplayer_verdict_ts||Date.now()-Date.parse(c.miniplayer_verdict_ts)>=d;if(!(f||m&&p))return;let h=await ii(eR(t.name,s,i,c,a),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),w=tR(h);if(w===null)return;let _=w.label==="stalled_needs_nudge"&&a.length>0&&i.length===0?{label:"blocked",reason:rR(a)}:w;Vd(e,t.name,_.label,_.reason,new Date().toISOString(),l,u)}async function Qp(e,t,r,n={}){for(let o of t){let s=r.find(a=>a.name===o);if(s===void 0||!B(s))continue;let i;try{i=Q(s)}catch{continue}try{await nR(e,s,i,n)}catch{continue}}}import{execFileSync as ZR}from"node:child_process";var U=class extends Error{code;exitCode;constructor(t,r,n=2){super(r),this.code=t,this.exitCode=n}};function pl(e){let t;try{if(typeof e!="string")throw new Error("expected a cron expression string");let r=e.trim().split(/\s+/);if(r.length!==5)throw new Error("expected five fields: minute hour day-of-month month day-of-week");t="minute";let n=Oo(r[0],0,59);t="hour";let o=Oo(r[1],0,23);t="dayOfMonth";let s=Oo(r[2],1,31);t="month";let i=Oo(r[3],1,12);t="dayOfWeek";let a=Oo(r[4],0,7,l=>l===7?0:l);return{ok:!0,schedule:{__brand:"CronSchedule",minute:n,hour:o,dayOfMonth:s,month:i,dayOfWeek:a}}}catch(r){let n=r instanceof Error?r.message:String(r);return{ok:!1,error:t?{message:n,field:t}:{message:n}}}}function Oo(e,t,r,n=o=>o){if(e.length===0)throw new Error("empty field");let o=new Set;for(let s of e.split(",")){if(s.length===0)throw new Error(`invalid list in "${e}"`);let i=s.split("/");if(i.length>2)throw new Error(`invalid step in "${s}"`);let a=i[0],c=i[1]===void 0?1:fl(i[1],1,r-t+1,s),l=a.split("-");if(l.length>2)throw new Error(`invalid range in "${s}"`);let u=a==="*"?t:fl(l[0],t,r,s),d=a==="*"?r:l[1]!==void 0?fl(l[1],t,r,s):i[1]?r:u;if(u>d)throw new Error(`range starts after it ends in "${s}"`);for(let m=u;m<=d;m+=c)o.add(n(m))}return{values:o,wildcard:e.split(",").some(s=>s.split("/")[0]==="*")}}function fl(e,t,r,n){if(!/^\d+$/.test(e))throw new Error(`expected an integer in "${n}"`);let o=Number(e);if(!Number.isSafeInteger(o)||o<t||o>r)throw new Error(`value ${e} is outside ${t}-${r}`);return o}function oR(e,t){let r=e;if(!r.minute.values.has(t.getMinutes())||!r.hour.values.has(t.getHours())||!r.month.values.has(t.getMonth()+1))return!1;let n=r.dayOfMonth.values.has(t.getDate()),o=r.dayOfWeek.values.has(t.getDay());return r.dayOfMonth.wildcard?o:r.dayOfWeek.wildcard?n:n||o}function Xp(e,t,r){let n=t.getTime(),o=r.getTime();if(o<n)throw new RangeError("untilInclusive must not precede sinceExclusive");for(let s=(Math.floor(n/6e4)+1)*6e4;s<=o;s+=6e4)if(oR(e,new Date(s)))return!0;return!1}import{spawn as sR}from"node:child_process";import{closeSync as iR,existsSync as aR,mkdirSync as cR,openSync as lR,readdirSync as uR,unlinkSync as dR}from"node:fs";import{homedir as mR}from"node:os";import{join as $i}from"node:path";var Zp=["systemd-run","--user","--scope","--collect","--quiet"],fR=10,eh=50*6e4,pR=5e3;function xi(){return process.env.LMBEE_CRON_LOG_DIR?process.env.LMBEE_CRON_LOG_DIR:$i(mR(),".lmbee","cron-logs")}function hR(e,t){try{let r=uR(e).sort();for(let n of r.slice(0,Math.max(0,r.length-t)))try{dR($i(e,n))}catch{}}catch{}}function gR(e,t){return[...t.spawnPrefix??(t.systemdUnitName!==void 0?[...Zp,"--unit",t.systemdUnitName,"--"]:[...Zp,"--"]),"sh","-c",e]}function Do(e,t={}){let r=$i(t.logDir??xi(),String(e.id));aR(r)||cR(r,{recursive:!0});let n=$i(r,`${new Date().toISOString().replace(/[:.]/g,"-")}.log`),o=lR(n,"a"),s=gR(e.action_payload,t),[i,...a]=s,c;try{c=sR(i,a,{detached:!0,stdio:["ignore",o,o],...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{}})}finally{iR(o)}c.unref();let l=c.pid??null,u=!1,d=t.timeoutMs===void 0?eh:t.timeoutMs,m=t.sigkillGraceMs??pR,f=d===null?void 0:setTimeout(()=>{if(u)return;let h=c.pid;if(h!==void 0){try{process.kill(-h,"SIGTERM")}catch{}setTimeout(()=>{try{process.kill(-h,0)}catch{return}try{process.kill(-h,"SIGKILL")}catch{}},m).unref()}process.stderr.write(`[lmcron] job ${e.id} timed out after ${d}ms, sending SIGTERM
260
+ `)},d??eh);f?.unref();let p=(h,w)=>{u||(u=!0,f!==void 0&&clearTimeout(f),hR(r,fR),t.onExit?.(h,w,l,n))};c.on("error",h=>{process.stderr.write(`[lmcron] job ${e.id} spawn error: ${h.message}
261
+ `),p(null,h)}),c.on("exit",h=>{p(h)})}import{createHash as _R,randomUUID as wR}from"node:crypto";var rn=16*1024,Po=16*1024,hl=512,Ri=100,gl=4096,_l=1024*1024,Uo="('pending','running')",yR="execution_state != 'gone' OR (status = 'escalated' AND escalation_resolved_at IS NULL)";function Fo(e){let{run_token_hash:t,...r}=e;return r}function th(e){return _R("sha256").update(e,"utf8").digest("hex")}function St(e){try{return e()}catch(t){if(t instanceof U)throw t;if(t instanceof I)throw new U(t.code,t.message,t.exitCode);let r=t&&typeof t=="object"&&"code"in t?String(t.code):void 0,n=t instanceof Error?t.message:String(t);throw r!==void 0&&(r.startsWith("SQLITE_BUSY")||r.startsWith("SQLITE_LOCKED"))?new U("DB_BUSY","Database busy; retry after the current writer completes",5):r!==void 0&&r.startsWith("SQLITE_CONSTRAINT")?new U("STRUCTURAL_ERROR",n,2):new U("STORAGE_ERROR",n,1)}}function rh(e,t){return St(()=>e.prepare("SELECT * FROM cron_runs WHERE id = ?").get(t)??null)}function ze(e,t){let r=rh(e,t);if(r===null)throw new U("NOT_FOUND",`Cron run ${t} does not exist`,3);return r}function ER(e,t){return e.prepare("SELECT * FROM cron_runs WHERE run_token_hash = ?").get(t)??null}function lr(e,t){return St(()=>e.prepare(`SELECT * FROM cron_runs WHERE job_id = ? AND (${yR}) ORDER BY id DESC LIMIT 1`).get(t)??null)}function qo(e,t,r,n){return St(()=>{let o=lr(e,t);if(o!==null)return o.status==="escalated"?{kind:"escalation",run:o}:{kind:"overlap",run:o};let s=wR(),i=de();try{let a=e.prepare(`INSERT INTO cron_runs(job_id, run_token_hash, status, execution_state, trigger_kind, config_snapshot, created_at, updated_at)
262
+ VALUES (?, ?, 'pending', 'active', ?, ?, ?, ?)`).run(t,th(s),r,n,i,i);return{kind:"claimed",run:ze(e,Number(a.lastInsertRowid)),token:s}}catch(a){let c=a&&typeof a=="object"&&"code"in a?String(a.code):void 0;if(c!==void 0&&c.startsWith("SQLITE_CONSTRAINT")){let l=lr(e,t);if(l!==null)return l.status==="escalated"?{kind:"escalation",run:l}:{kind:"overlap",run:l}}throw a}})}function Dn(e,t,r,n){St(()=>e.prepare(`UPDATE cron_runs SET status = 'running', execution_identity = ?, pid = ?, started_at = ?, updated_at = ?
263
+ WHERE id = ? AND status = 'pending'`).run(JSON.stringify(r),n,de(),de(),t))}function jo(e,t,r,n){e.prepare("UPDATE cron_runs SET execution_identity = ?, pid = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(r),n,de(),t)}function TR(e,t){St(()=>e.prepare(`UPDATE cron_runs SET execution_state = 'gone', execution_gone_at = ?, execution_uncertain_reason = NULL, updated_at = ?
264
+ WHERE id = ? AND execution_state != 'gone'`).run(de(),de(),t))}function Ho(e,t,r){St(()=>e.prepare(`UPDATE cron_runs SET execution_state = 'uncertain', execution_uncertain_reason = ?, updated_at = ?
265
+ WHERE id = ? AND execution_state != 'gone'`).run(r.slice(0,1024),de(),t))}function Mo(e,t,r){let n=ye(e,t);if(Buffer.byteLength(n,"utf8")>r)throw new U("INVALID_ARGUMENT",`${t} exceeds ${r} bytes`);return n}function bR(e){if(e===void 0)return[];if(!Array.isArray(e))throw new U("INVALID_ARGUMENT","artifacts must be an array");if(e.length>Ri)throw new U("INVALID_ARGUMENT",`at most ${Ri} artifacts are allowed`);return e.map(t=>{if(typeof t!="string")throw new U("INVALID_ARGUMENT","artifacts must be strings");return Mo(t,"artifact",gl)})}function nh(e,t){if(e.status!=="succeeded"&&e.status!=="failed"&&e.status!=="escalated")throw new U("INVALID_ARGUMENT",'status must be "succeeded", "failed", or "escalated"');let r=Mo(e.summary,"summary",rn),n=bR(e.artifacts),o=null,s=null,i=null;if(e.status==="escalated"){o=Mo(e.action??"","requested action",Po),i=e.reason!==void 0?Mo(e.reason,"escalation reason",Po):r;let a=e.owner!==void 0?Mo(e.owner,"owner",hl):t;if(a===null||a.trim().length===0)throw new U("INVALID_ARGUMENT","an escalation requires an owner or a job with a configured default escalation owner");s=a}return{status:e.status,summary:r,artifacts:JSON.stringify(n),escalationAction:o,escalationOwner:s,escalationReason:i}}function oh(e,t){return e.status===t.status&&e.summary===t.summary&&e.artifacts===t.artifacts&&e.escalation_action===t.escalationAction&&e.escalation_owner===t.escalationOwner&&e.escalation_reason===t.escalationReason}function sh(e){try{let t=JSON.parse(e.config_snapshot);return typeof t.escalationOwner=="string"&&t.escalationOwner.trim().length>0?t.escalationOwner:null}catch{return null}}function wl(e,t,r){let n=nh(r,sh(t)),o=de();if(e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, artifacts = ?, escalation_reason = ?, escalation_action = ?,
266
266
  escalation_owner = ?, reported_at = ?, finished_at = ?, updated_at = ?
267
- WHERE id = ? AND status IN ${Mo} AND reported_at IS NULL`).run(n.status,n.summary,n.artifacts,n.escalationReason,n.escalationAction,n.escalationOwner,o,o,o,t.id).changes===0){let i=ze(e,t.id);if(th(i,n))return i;throw new U("CONFLICTING_REPORT",`Cron run ${t.id} already has a different terminal report`,4)}return ze(e,t.id)}function nh(e,t,r){return bt(()=>{let n=hR(e,Xp(t));if(n===null)throw new U("NOT_FOUND","No cron run matches the supplied report token",3);if(n.reported_at!==null||n.status!=="pending"&&n.status!=="running"){let o=eh(r,rh(n));if(th(n,o))return n;throw new U("CONFLICTING_REPORT",`Cron run ${n.id} already has a different terminal report`,4)}return _l(e,n,r)})}function oh(e,t,r){let n=e.transaction(()=>{let o=ze(e,t);o.reported_at===null&&(o.status==="pending"||o.status==="running")&&r.report!==void 0&&_l(e,o,r.report);let s=ze(e,t);if(s.reported_at===null&&(s.status==="pending"||s.status==="running")&&r.fallback!==void 0){let i=r.fallback.ok?"succeeded":"failed";e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Mo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return gR(e,t),ze(e,t)});return bt(()=>n.immediate())}function sh(e,t,r){let n=e.transaction(()=>{let o=ze(e,t);o.reported_at===null&&(o.status==="pending"||o.status==="running")&&r.report!==void 0&&_l(e,o,r.report);let s=ze(e,t);if(s.reported_at===null&&(s.status==="pending"||s.status==="running")&&r.fallback!==void 0){let i=r.fallback.ok?"succeeded":"failed";e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Mo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return ze(e,t)});return bt(()=>n.immediate())}function wl(e,t,r){return bt(()=>{let n=Zp(e,t);if(n===null)return null;if(n.reported_at!==null||n.status!=="pending"&&n.status!=="running")return n;let o=r.ok?"succeeded":"failed";return e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Mo} AND reported_at IS NULL`).run(o,r.summary.slice(0,rn),de(),de(),n.id),ze(e,n.id)})}function ih(e,t,r={}){let n=e.transaction(()=>{let o=ze(e,t),s=r.resolution!==void 0?r.resolution.trim():"",i=r.actor!==void 0?r.actor.trim():"",a=r.note!==void 0?r.note.trim():"",c=!1;if(o.execution_state!=="gone"){if(r.confirmStopped!==!0)throw new U("EXECUTION_FENCED",`Cron run ${t} execution state is "${o.execution_state}"; verify the process is gone and retry with --confirm-stopped`,4);e.prepare(`UPDATE cron_runs SET execution_state = 'gone', execution_gone_at = ?, execution_uncertain_reason = NULL,
267
+ WHERE id = ? AND status IN ${Uo} AND reported_at IS NULL`).run(n.status,n.summary,n.artifacts,n.escalationReason,n.escalationAction,n.escalationOwner,o,o,o,t.id).changes===0){let i=ze(e,t.id);if(oh(i,n))return i;throw new U("CONFLICTING_REPORT",`Cron run ${t.id} already has a different terminal report`,4)}return ze(e,t.id)}function ih(e,t,r){return St(()=>{let n=ER(e,th(t));if(n===null)throw new U("NOT_FOUND","No cron run matches the supplied report token",3);if(n.reported_at!==null||n.status!=="pending"&&n.status!=="running"){let o=nh(r,sh(n));if(oh(n,o))return n;throw new U("CONFLICTING_REPORT",`Cron run ${n.id} already has a different terminal report`,4)}return wl(e,n,r)})}function Mn(e,t,r){let n=e.transaction(()=>{let o=ze(e,t);o.reported_at===null&&(o.status==="pending"||o.status==="running")&&r.report!==void 0&&wl(e,o,r.report);let s=ze(e,t);if(s.reported_at===null&&(s.status==="pending"||s.status==="running")&&r.fallback!==void 0){let i=r.fallback.ok?"succeeded":"failed";e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Uo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return TR(e,t),ze(e,t)});return St(()=>n.immediate())}function ah(e,t,r){let n=e.transaction(()=>{let o=ze(e,t);o.reported_at===null&&(o.status==="pending"||o.status==="running")&&r.report!==void 0&&wl(e,o,r.report);let s=ze(e,t);if(s.reported_at===null&&(s.status==="pending"||s.status==="running")&&r.fallback!==void 0){let i=r.fallback.ok?"succeeded":"failed";e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Uo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return ze(e,t)});return St(()=>n.immediate())}function yl(e,t,r){return St(()=>{let n=rh(e,t);if(n===null)return null;if(n.reported_at!==null||n.status!=="pending"&&n.status!=="running")return n;let o=r.ok?"succeeded":"failed";return e.prepare(`UPDATE cron_runs SET status = ?, summary = ?, finished_at = ?, updated_at = ? WHERE id = ? AND status IN ${Uo} AND reported_at IS NULL`).run(o,r.summary.slice(0,rn),de(),de(),n.id),ze(e,n.id)})}function ch(e,t,r={}){let n=e.transaction(()=>{let o=ze(e,t),s=r.resolution!==void 0?r.resolution.trim():"",i=r.actor!==void 0?r.actor.trim():"",a=r.note!==void 0?r.note.trim():"",c=!1;if(o.execution_state!=="gone"){if(r.confirmStopped!==!0)throw new U("EXECUTION_FENCED",`Cron run ${t} execution state is "${o.execution_state}"; verify the process is gone and retry with --confirm-stopped`,4);e.prepare(`UPDATE cron_runs SET execution_state = 'gone', execution_gone_at = ?, execution_uncertain_reason = NULL,
268
268
  execution_confirmation_note = ?, updated_at = ? WHERE id = ? AND execution_state != 'gone'`).run(de(),a||s||"confirmed stopped by operator",de(),t),c=!0}o.status==="escalated"&&o.escalation_resolved_at===null&&(e.prepare(`UPDATE cron_runs SET escalation_resolved_at = ?, escalation_resolution = ?, escalation_resolution_actor = ?,
269
269
  escalation_resolution_note = ?, updated_at = ? WHERE id = ? AND escalation_resolved_at IS NULL`).run(de(),s||"resolved",i||"operator",a||s||"resolved",de(),t),c=!0);let l=ze(e,t);if(l.reported_at===null&&(l.status==="pending"||l.status==="running")&&(e.prepare(`UPDATE cron_runs SET status = 'failed', summary = ?, finished_at = ?, updated_at = ?
270
- WHERE id = ? AND status IN ${Mo} AND reported_at IS NULL`).run(`reconciled by operator without a worker report: ${a||s||"execution confirmed stopped"}`.slice(0,rn),de(),de(),t),c=!0),!c)throw new U("INVALID_ARGUMENT",`Cron run ${t} has no fenced execution or unresolved escalation to resolve`);let u=de();return e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ? WHERE id = ? AND (last_checked_ts IS NULL OR last_checked_ts < ?)").run(u,u,o.job_id,u),ze(e,t)});return bt(()=>n.immediate())}function ki(e,t){if(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>Ne)throw new U("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return bt(()=>{let r=["id > ?"],n=[t.after];t.jobId!==void 0&&(r.push("job_id = ?"),n.push(t.jobId)),t.status!==void 0&&(r.push("status = ?"),n.push(t.status));let o=e.prepare(`SELECT * FROM cron_runs WHERE ${r.join(" AND ")} ORDER BY id LIMIT ?`).all(...n,t.limit+1),s=o.length>t.limit,i=s?o.slice(0,t.limit):o;return{rows:i,next_cursor:s?i[i.length-1].id:null}})}import{spawn as yl}from"node:child_process";import{createHash as wR}from"node:crypto";import{existsSync as yR,mkdirSync as ER,mkdtempSync as TR,readFileSync as bR,rmSync as ah,writeFileSync as dh}from"node:fs";import{homedir as SR,tmpdir as vR}from"node:os";import{isAbsolute as AR,join as jo,resolve as Dn}from"node:path";var $R=["lmctl"],kR=["miniplayer"],xR=10*6e4,RR=50*6e4,NR=50*6e4,ch=24*60*6e4,mh=5e3,xi=1024*1024;function Fo(){return{text:"",overflow:!1}}function qo(e,t){if(e.overflow)return;let r=e.text+t.toString("utf8");r.length>xi?(e.text=r.slice(0,xi),e.overflow=!0):e.text=r}function Ye(e){return e instanceof Error?e.message:String(e)}function IR(e,t,r){try{Uo(e,t,r)}catch{}}function Be(e,t,r){try{return oh(e,t,r),!0}catch(n){return process.stderr.write(`[lmcron] run ${t} completion could not be committed (fence retained): ${Ye(n)}
271
- `),!1}}function _t(e,t,r,n){IR(e,t,r);try{sh(e,t,n)}catch(o){process.stderr.write(`[lmcron] run ${t} outcome could not be persisted (fence retained): ${Ye(o)}
272
- `)}}function El(e,t,r){if(e===null)throw new Error(`${r}: disabling timeout is supported only for script workers`);let n=e??t;if(!Number.isFinite(n)||n<=0||n>ch)throw new Error(`${r} must be a positive number of milliseconds <= ${ch}`);return n}var lh=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","ClaudeMock"]),LR=/^[A-Za-z0-9][A-Za-z0-9._:@/+~-]*$/;function bl(e){if(!lh.has(e))throw new U("INVALID_ARGUMENT",`provider "${e}" is not one of lmctl's supported providers (${[...lh].join(", ")})`);return e}function Sl(e){if(!LR.test(e))throw new U("INVALID_ARGUMENT",`model "${e}" is not a safe lmctl model token (no whitespace, quotes, '=' or control characters)`);return e}function Ri(e){if(!AR(e))throw new U("INVALID_ARGUMENT",`sessiondir "${e}" must be an absolute path`);if(/["\u0000-\u001f\u007f]/.test(e))throw new U("INVALID_ARGUMENT",`sessiondir contains a quote, newline, or control character that lmctl cannot represent: ${JSON.stringify(e)}`);return e}function CR(e){let t=["_MEMBER_",`alias=${e.alias}`,`provider=${bl(e.provider)}`];return e.model!==null&&e.model!==void 0&&t.push(`model=${Sl(e.model)}`),t.push(`sessiondir="${Ri(e.sessiondir)}"`),t.join(" ")}function OR(e){let t=e.name,r=t!==void 0&&t.length>0?Dn(t):":memory:";return wR("sha256").update(r,"utf8").digest("hex").slice(0,16)}function DR(){return process.env.LMBEE_CRON_SESSION_DIR?process.env.LMBEE_CRON_SESSION_DIR:jo(SR(),".lmbee","cron-sessions")}function MR(e){return`'${e.replace(/'/g,"'\\''")}'`}function PR(e){let t=e.name;return t!==void 0&&t.length>0&&t!==":memory:"?`LMBEE_DB=${MR(Dn(t))} `:""}function UR(e,t,r){let n=PR(r);return`${e}
270
+ WHERE id = ? AND status IN ${Uo} AND reported_at IS NULL`).run(`reconciled by operator without a worker report: ${a||s||"execution confirmed stopped"}`.slice(0,rn),de(),de(),t),c=!0),!c)throw new U("INVALID_ARGUMENT",`Cron run ${t} has no fenced execution or unresolved escalation to resolve`);let u=de();return e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ? WHERE id = ? AND (last_checked_ts IS NULL OR last_checked_ts < ?)").run(u,u,o.job_id,u),ze(e,t)});return St(()=>n.immediate())}function Ni(e,t){if(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>Ne)throw new U("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return St(()=>{let r=["id > ?"],n=[t.after];t.jobId!==void 0&&(r.push("job_id = ?"),n.push(t.jobId)),t.status!==void 0&&(r.push("status = ?"),n.push(t.status));let o=e.prepare(`SELECT * FROM cron_runs WHERE ${r.join(" AND ")} ORDER BY id LIMIT ?`).all(...n,t.limit+1),s=o.length>t.limit,i=s?o.slice(0,t.limit):o;return{rows:i,next_cursor:s?i[i.length-1].id:null}})}import{spawn as El}from"node:child_process";import{createHash as SR}from"node:crypto";import{existsSync as vR,mkdirSync as AR,mkdtempSync as kR,readFileSync as $R,rmSync as lh,writeFileSync as fh}from"node:fs";import{homedir as xR,tmpdir as RR}from"node:os";import{isAbsolute as NR,join as Go,resolve as Pn}from"node:path";var LR=["lmctl"],IR=["miniplayer"],CR=10*6e4,OR=50*6e4,DR=50*6e4,uh=24*60*6e4,ph=5e3,Li=1024*1024;function Bo(){return{text:"",overflow:!1}}function Wo(e,t){if(e.overflow)return;let r=e.text+t.toString("utf8");r.length>Li?(e.text=r.slice(0,Li),e.overflow=!0):e.text=r}function Ye(e){return e instanceof Error?e.message:String(e)}function MR(e,t,r){try{Ho(e,t,r)}catch{}}function Be(e,t,r){try{return Mn(e,t,r),!0}catch(n){return process.stderr.write(`[lmcron] run ${t} completion could not be committed (fence retained): ${Ye(n)}
271
+ `),!1}}function _t(e,t,r,n){MR(e,t,r);try{ah(e,t,n)}catch(o){process.stderr.write(`[lmcron] run ${t} outcome could not be persisted (fence retained): ${Ye(o)}
272
+ `)}}function Tl(e,t,r){if(e===null)throw new Error(`${r}: disabling timeout is supported only for script workers`);let n=e??t;if(!Number.isFinite(n)||n<=0||n>uh)throw new Error(`${r} must be a positive number of milliseconds <= ${uh}`);return n}var dh=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","ClaudeMock"]),PR=/^[A-Za-z0-9][A-Za-z0-9._:@/+~-]*$/;function Sl(e){if(!dh.has(e))throw new U("INVALID_ARGUMENT",`provider "${e}" is not one of lmctl's supported providers (${[...dh].join(", ")})`);return e}function vl(e){if(!PR.test(e))throw new U("INVALID_ARGUMENT",`model "${e}" is not a safe lmctl model token (no whitespace, quotes, '=' or control characters)`);return e}function Ii(e){if(!NR(e))throw new U("INVALID_ARGUMENT",`sessiondir "${e}" must be an absolute path`);if(/["\u0000-\u001f\u007f]/.test(e))throw new U("INVALID_ARGUMENT",`sessiondir contains a quote, newline, or control character that lmctl cannot represent: ${JSON.stringify(e)}`);return e}function UR(e){let t=["_MEMBER_",`alias=${e.alias}`,`provider=${Sl(e.provider)}`];return e.model!==null&&e.model!==void 0&&t.push(`model=${vl(e.model)}`),t.push(`sessiondir="${Ii(e.sessiondir)}"`),t.join(" ")}function FR(e){let t=e.name,r=t!==void 0&&t.length>0?Pn(t):":memory:";return SR("sha256").update(r,"utf8").digest("hex").slice(0,16)}function qR(){return process.env.LMBEE_CRON_SESSION_DIR?process.env.LMBEE_CRON_SESSION_DIR:Go(xR(),".lmbee","cron-sessions")}function jR(e){return`'${e.replace(/'/g,"'\\''")}'`}function HR(e){let t=e.name;return t!==void 0&&t.length>0&&t!==":memory:"?`LMBEE_DB=${jR(Pn(t))} `:""}function BR(e,t,r){let n=HR(r);return`${e}
273
273
 
274
274
  ---
275
275
  When you have finished, report the outcome exactly once by running this command (the token is
@@ -279,7 +279,7 @@ run-specific; do not change it):
279
279
 
280
280
  Use --status failed if the work did not succeed, or --status escalated together with
281
281
  --requested-action "requested operator action" and optionally --owner NAME if a human decision is
282
- required. Never report succeeded unless the work actually succeeded.`}function FR(e,t){return`${e}
282
+ required. Never report succeeded unless the work actually succeeded.`}function WR(e,t){return`${e}
283
283
 
284
284
  ---
285
285
  Respond with EXACTLY one line of strict JSON and no other text, using this run token verbatim:
@@ -288,41 +288,41 @@ Respond with EXACTLY one line of strict JSON and no other text, using this run t
288
288
 
289
289
  For an escalation use {"run_token":"...","status":"escalated","summary":"...","escalation":{"owner":"...","reason":"...","requestedAction":"..."}}.
290
290
  Escalation reason and requestedAction are required. Never claim succeeded unless the work actually
291
- succeeded.`}var qR=new Set(["run_token","status","summary","artifacts","escalation"]),jR=new Set(["owner","reason","requestedAction"]);function fh(e,t){if(e===null)return{ok:!1,reason:"no output"};if(Buffer.byteLength(e,"utf8")>pl)return{ok:!1,reason:`result exceeds ${pl} bytes`};let r=e.trim();if(r.length===0)return{ok:!1,reason:"empty output"};let n;try{n=JSON.parse(r)}catch{return{ok:!1,reason:"output is not a single JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,reason:"output is not a JSON object"};let o=n;for(let c of Object.keys(o))if(!qR.has(c))return{ok:!1,reason:`unknown field "${c}"`};if(o.run_token!==t)return{ok:!1,reason:"run token missing or mismatched"};let s=o.status;if(s!=="succeeded"&&s!=="failed"&&s!=="escalated")return{ok:!1,reason:"status must be succeeded, failed, or escalated"};if(typeof o.summary!="string"||o.summary.trim().length===0)return{ok:!1,reason:"summary must be a nonblank string"};if(Buffer.byteLength(o.summary,"utf8")>rn)return{ok:!1,reason:"summary is too large"};let i=[];if(o.artifacts!==void 0){if(!Array.isArray(o.artifacts)||o.artifacts.length>Ai)return{ok:!1,reason:"artifacts must be an array of at most 100 strings"};for(let c of o.artifacts)if(typeof c!="string"||c.trim().length===0||Buffer.byteLength(c,"utf8")>fl)return{ok:!1,reason:"each artifact must be a nonblank string of at most 4096 bytes"};i=o.artifacts}let a={status:s,summary:o.summary.trim(),artifacts:i};if(s==="escalated"){let c=o.escalation;if(typeof c!="object"||c===null||Array.isArray(c))return{ok:!1,reason:"an escalated result requires an escalation object"};let l=c;for(let u of Object.keys(l))if(!jR.has(u))return{ok:!1,reason:`unknown escalation field "${u}"`};if(typeof l.reason!="string"||l.reason.trim().length===0||Buffer.byteLength(l.reason,"utf8")>Do)return{ok:!1,reason:"escalation.reason is required and bounded"};if(typeof l.requestedAction!="string"||l.requestedAction.trim().length===0||Buffer.byteLength(l.requestedAction,"utf8")>Do)return{ok:!1,reason:"escalation.requestedAction is required and bounded"};if(a.reason=l.reason.trim(),a.action=l.requestedAction.trim(),l.owner!==void 0){if(typeof l.owner!="string"||l.owner.trim().length===0||l.owner.length>ml)return{ok:!1,reason:"escalation.owner must be a nonblank string of at most 512 chars"};a.owner=l.owner.trim()}}return{ok:!0,result:a}}function HR(e,t,r){let n=t.session_alias??"Worker";if(t.working_directory===null||t.provider===null)throw new U("INVALID_ARGUMENT",`session job ${t.id} requires provider and an absolute working_directory`);let o=jo(r??DR(),OR(e)),s=t.session_generation??0,i=t.session_teamfile??jo(o,`job-${t.id}-g${s}.lmctl`);if(t.session_teamfile!==null)return{teamfile:t.session_teamfile,alias:n};if(yR(i))return e.prepare("UPDATE cron_jobs SET session_teamfile = ?, session_alias = ?, updated_at = ? WHERE id = ?").run(i,n,new Date().toISOString(),t.id),{teamfile:i,alias:n};ER(o,{recursive:!0});let a=CR({alias:n,provider:t.provider,model:t.model,sessiondir:t.working_directory});return dh(i,`#teamfile: ${i}
291
+ succeeded.`}var GR=new Set(["run_token","status","summary","artifacts","escalation"]),VR=new Set(["owner","reason","requestedAction"]);function hh(e,t){if(e===null)return{ok:!1,reason:"no output"};if(Buffer.byteLength(e,"utf8")>_l)return{ok:!1,reason:`result exceeds ${_l} bytes`};let r=e.trim();if(r.length===0)return{ok:!1,reason:"empty output"};let n;try{n=JSON.parse(r)}catch{return{ok:!1,reason:"output is not a single JSON object"}}if(typeof n!="object"||n===null||Array.isArray(n))return{ok:!1,reason:"output is not a JSON object"};let o=n;for(let c of Object.keys(o))if(!GR.has(c))return{ok:!1,reason:`unknown field "${c}"`};if(o.run_token!==t)return{ok:!1,reason:"run token missing or mismatched"};let s=o.status;if(s!=="succeeded"&&s!=="failed"&&s!=="escalated")return{ok:!1,reason:"status must be succeeded, failed, or escalated"};if(typeof o.summary!="string"||o.summary.trim().length===0)return{ok:!1,reason:"summary must be a nonblank string"};if(Buffer.byteLength(o.summary,"utf8")>rn)return{ok:!1,reason:"summary is too large"};let i=[];if(o.artifacts!==void 0){if(!Array.isArray(o.artifacts)||o.artifacts.length>Ri)return{ok:!1,reason:"artifacts must be an array of at most 100 strings"};for(let c of o.artifacts)if(typeof c!="string"||c.trim().length===0||Buffer.byteLength(c,"utf8")>gl)return{ok:!1,reason:"each artifact must be a nonblank string of at most 4096 bytes"};i=o.artifacts}let a={status:s,summary:o.summary.trim(),artifacts:i};if(s==="escalated"){let c=o.escalation;if(typeof c!="object"||c===null||Array.isArray(c))return{ok:!1,reason:"an escalated result requires an escalation object"};let l=c;for(let u of Object.keys(l))if(!VR.has(u))return{ok:!1,reason:`unknown escalation field "${u}"`};if(typeof l.reason!="string"||l.reason.trim().length===0||Buffer.byteLength(l.reason,"utf8")>Po)return{ok:!1,reason:"escalation.reason is required and bounded"};if(typeof l.requestedAction!="string"||l.requestedAction.trim().length===0||Buffer.byteLength(l.requestedAction,"utf8")>Po)return{ok:!1,reason:"escalation.requestedAction is required and bounded"};if(a.reason=l.reason.trim(),a.action=l.requestedAction.trim(),l.owner!==void 0){if(typeof l.owner!="string"||l.owner.trim().length===0||l.owner.length>hl)return{ok:!1,reason:"escalation.owner must be a nonblank string of at most 512 chars"};a.owner=l.owner.trim()}}return{ok:!0,result:a}}function JR(e,t,r){let n=t.session_alias??"Worker";if(t.working_directory===null||t.provider===null)throw new U("INVALID_ARGUMENT",`session job ${t.id} requires provider and an absolute working_directory`);let o=Go(r??qR(),FR(e)),s=t.session_generation??0,i=t.session_teamfile??Go(o,`job-${t.id}-g${s}.lmctl`);if(t.session_teamfile!==null)return{teamfile:t.session_teamfile,alias:n};if(vR(i))return e.prepare("UPDATE cron_jobs SET session_teamfile = ?, session_alias = ?, updated_at = ? WHERE id = ?").run(i,n,new Date().toISOString(),t.id),{teamfile:i,alias:n};AR(o,{recursive:!0});let a=UR({alias:n,provider:t.provider,model:t.model,sessiondir:t.working_directory});return fh(i,`#teamfile: ${i}
292
292
  # private single-member session for lmbee cron job ${t.id} (generation ${s})
293
293
 
294
294
  ${a}
295
- `,{mode:384}),e.prepare("UPDATE cron_jobs SET session_teamfile = ?, session_alias = ?, updated_at = ? WHERE id = ?").run(i,n,new Date().toISOString(),t.id),{teamfile:i,alias:n}}function vl(e){try{return process.kill(-e,0),!0}catch{return!1}}function Tl(e,t){if(e.pid===void 0)return;let r=e.pid;try{process.kill(-r,"SIGTERM")}catch{return}setTimeout(()=>{try{process.kill(-r,0)}catch{return}try{process.kill(-r,"SIGKILL")}catch{}},t).unref()}function BR(e){let t=null,r=null,n=null,o=null;for(let s of e.split(`
296
- `)){let i=s.trim();if(i.length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}if(typeof a!="object"||a===null)continue;let c=a,l=typeof c.message=="string"?c.message:String(c.status);c.status==="ok"&&typeof c.replyText=="string"?t=c.replyText:c.status==="stalled"?r=l:c.status==="busy"?n=l:(c.status==="error"||c.status==="failed")&&(o=l)}return r!==null?{kind:"stalled",message:r}:n!==null?{kind:"busy",message:n}:o!==null?{kind:"error",message:o}:t!==null?{kind:"completed",text:t}:{kind:"none"}}function WR(e,t){try{let r=bR(e,"utf8").trim();return r.length>t?r.slice(-t):r}catch{return""}}var GR=500,uh=75;function VR(e){let{db:t,job:r,run:n}=e;try{$i(t,n.id,{kind:"script",cwd:r.working_directory},null)}catch(o){Be(t,n.id,{fallback:{ok:!1,summary:`script setup failed before spawn: ${Ye(o)}`}});return}try{Co({id:r.id,action_payload:r.action_payload},{...e.logDir!==void 0?{logDir:e.logDir}:{},...r.working_directory!==null?{cwd:r.working_directory}:{},...e.spawnPrefixes?.script!==void 0?{spawnPrefix:e.spawnPrefixes.script}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.sigkillGraceMs!==void 0?{sigkillGraceMs:e.sigkillGraceMs}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Dn(t.name)}}:{},onExit:(o,s,i,a)=>{if(s!==void 0){Be(t,n.id,{fallback:{ok:!1,summary:`script spawn error: ${s.message}`}});return}let c=o===0||o===uh,l=WR(a,GR),u=o===uh?`script no-op (exit ${o})${l?`: ${l}`:""}`:`script exited with code ${o}${l?`: ${l}`:""}`;i!==null&&vl(i)?_t(t,n.id,"process group still alive after exit",{fallback:{ok:c,summary:u}}):Be(t,n.id,{fallback:{ok:c,summary:u}})}})}catch(o){Be(t,n.id,{fallback:{ok:!1,summary:`script spawn error: ${Ye(o)}`}})}}function JR(e){let{db:t,job:r,run:n}=e,o,s,i,a;try{o=El(e.timeoutMs,xR,"timeoutMs"),s=e.sigkillGraceMs??mh,i=[...e.spawnPrefixes?.miniplayer??kR,"run",...r.model!==null?["-m",r.model]:[]],a=FR(r.action_payload,e.runToken)}catch(w){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer setup failed before spawn: ${Ye(w)}`}});return}let[c,...l]=i,u;try{u=yl(c,l,{detached:!0,stdio:["pipe","pipe","pipe"],...r.working_directory!==null?{cwd:r.working_directory}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Dn(t.name)}}:{}})}catch(w){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer spawn error: ${Ye(w)}`}});return}u.unref();let d=Fo(),m=Fo(),f=!1,p=!1,h=setTimeout(()=>{f||(f=!0,Tl(u,s),_t(t,n.id,`miniplayer timed out after ${o}ms`,{fallback:{ok:!1,summary:`miniplayer timed out after ${o}ms`}}))},o);h.unref(),u.on("spawn",()=>p=!0),u.stdout?.on("data",w=>qo(d,w)),u.stderr?.on("data",w=>qo(m,w)),u.stdin?.on("error",()=>{}),u.on("error",w=>{if(f)return;f=!0,clearTimeout(h);let _={fallback:{ok:!1,summary:`miniplayer spawn error: ${w.message}`}};p?_t(t,n.id,`miniplayer post-spawn error: ${w.message}`,_):Be(t,n.id,_)}),u.on("close",(w,_)=>{if(f)return;f=!0,clearTimeout(h);let E=u.pid??null,T=E!==null&&vl(E),v=d.overflow?{ok:!1,reason:`output exceeded the ${xi}-byte capture limit`}:fh(d.text,e.runToken),S=v.ok?{report:v.result}:{fallback:{ok:!1,summary:`miniplayer produced no valid structured result (${v.reason})`+(w!==0||_!==null?`; exit ${_??w}: ${m.text.trim().slice(-300)}`:"")}};T?_t(t,n.id,"miniplayer process group still alive after wrapper exit",S):d.overflow?_t(t,n.id,"miniplayer output exceeded the capture limit; result not trusted",S):Be(t,n.id,S)});try{$i(t,n.id,{kind:"miniplayer",model:r.model},u.pid??null)}catch(w){process.stderr.write(`[lmcron] miniplayer run ${n.id} state write failed after spawn: ${Ye(w)}
295
+ `,{mode:384}),e.prepare("UPDATE cron_jobs SET session_teamfile = ?, session_alias = ?, updated_at = ? WHERE id = ?").run(i,n,new Date().toISOString(),t.id),{teamfile:i,alias:n}}function Al(e){try{return process.kill(-e,0),!0}catch{return!1}}function bl(e,t){if(e.pid===void 0)return;let r=e.pid;try{process.kill(-r,"SIGTERM")}catch{return}setTimeout(()=>{try{process.kill(-r,0)}catch{return}try{process.kill(-r,"SIGKILL")}catch{}},t).unref()}function KR(e){let t=null,r=null,n=null,o=null;for(let s of e.split(`
296
+ `)){let i=s.trim();if(i.length===0)continue;let a;try{a=JSON.parse(i)}catch{continue}if(typeof a!="object"||a===null)continue;let c=a,l=typeof c.message=="string"?c.message:String(c.status);c.status==="ok"&&typeof c.replyText=="string"?t=c.replyText:c.status==="stalled"?r=l:c.status==="busy"?n=l:(c.status==="error"||c.status==="failed")&&(o=l)}return r!==null?{kind:"stalled",message:r}:n!==null?{kind:"busy",message:n}:o!==null?{kind:"error",message:o}:t!==null?{kind:"completed",text:t}:{kind:"none"}}function kl(e,t){try{let r=$R(e,"utf8").trim();return r.length>t?r.slice(-t):r}catch{return""}}var zR=500,mh=75;function YR(e){let{db:t,job:r,run:n}=e;try{Dn(t,n.id,{kind:"script",cwd:r.working_directory},null)}catch(o){Be(t,n.id,{fallback:{ok:!1,summary:`script setup failed before spawn: ${Ye(o)}`}});return}try{Do({id:r.id,action_payload:r.action_payload},{...e.logDir!==void 0?{logDir:e.logDir}:{},...r.working_directory!==null?{cwd:r.working_directory}:{},...e.spawnPrefixes?.script!==void 0?{spawnPrefix:e.spawnPrefixes.script}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},...e.sigkillGraceMs!==void 0?{sigkillGraceMs:e.sigkillGraceMs}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Pn(t.name)}}:{},onExit:(o,s,i,a)=>{if(s!==void 0){Be(t,n.id,{fallback:{ok:!1,summary:`script spawn error: ${s.message}`}});return}let c=o===0||o===mh,l=kl(a,zR),u=o===mh?`script no-op (exit ${o})${l?`: ${l}`:""}`:`script exited with code ${o}${l?`: ${l}`:""}`;i!==null&&Al(i)?_t(t,n.id,"process group still alive after exit",{fallback:{ok:c,summary:u}}):Be(t,n.id,{fallback:{ok:c,summary:u}})}})}catch(o){Be(t,n.id,{fallback:{ok:!1,summary:`script spawn error: ${Ye(o)}`}})}}function QR(e){let{db:t,job:r,run:n}=e,o,s,i,a;try{o=Tl(e.timeoutMs,CR,"timeoutMs"),s=e.sigkillGraceMs??ph,i=[...e.spawnPrefixes?.miniplayer??IR,"run",...r.model!==null?["-m",r.model]:[]],a=WR(r.action_payload,e.runToken)}catch(w){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer setup failed before spawn: ${Ye(w)}`}});return}let[c,...l]=i,u;try{u=El(c,l,{detached:!0,stdio:["pipe","pipe","pipe"],...r.working_directory!==null?{cwd:r.working_directory}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Pn(t.name)}}:{}})}catch(w){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer spawn error: ${Ye(w)}`}});return}u.unref();let d=Bo(),m=Bo(),f=!1,p=!1,h=setTimeout(()=>{f||(f=!0,bl(u,s),_t(t,n.id,`miniplayer timed out after ${o}ms`,{fallback:{ok:!1,summary:`miniplayer timed out after ${o}ms`}}))},o);h.unref(),u.on("spawn",()=>p=!0),u.stdout?.on("data",w=>Wo(d,w)),u.stderr?.on("data",w=>Wo(m,w)),u.stdin?.on("error",()=>{}),u.on("error",w=>{if(f)return;f=!0,clearTimeout(h);let _={fallback:{ok:!1,summary:`miniplayer spawn error: ${w.message}`}};p?_t(t,n.id,`miniplayer post-spawn error: ${w.message}`,_):Be(t,n.id,_)}),u.on("close",(w,_)=>{if(f)return;f=!0,clearTimeout(h);let T=u.pid??null,E=T!==null&&Al(T),v=d.overflow?{ok:!1,reason:`output exceeded the ${Li}-byte capture limit`}:hh(d.text,e.runToken),S=v.ok?{report:v.result}:{fallback:{ok:!1,summary:`miniplayer produced no valid structured result (${v.reason})`+(w!==0||_!==null?`; exit ${_??w}: ${m.text.trim().slice(-300)}`:"")}};E?_t(t,n.id,"miniplayer process group still alive after wrapper exit",S):d.overflow?_t(t,n.id,"miniplayer output exceeded the capture limit; result not trusted",S):Be(t,n.id,S)});try{Dn(t,n.id,{kind:"miniplayer",model:r.model},u.pid??null)}catch(w){process.stderr.write(`[lmcron] miniplayer run ${n.id} state write failed after spawn: ${Ye(w)}
297
297
  `)}try{u.stdin?.write(a),u.stdin?.end()}catch(w){process.stderr.write(`[lmcron] miniplayer run ${n.id} stdin write failed: ${Ye(w)}
298
- `)}}function KR(e){let{db:t,job:r,run:n}=e,o,s,i;try{o=El(e.timeoutMs,RR,"timeoutMs"),s=El(e.seedTimeoutMs,NR,"seedTimeoutMs"),i=e.sigkillGraceMs??mh}catch(T){Be(t,n.id,{fallback:{ok:!1,summary:`session setup failed before spawn: ${Ye(T)}`}});return}let a,c;try{({teamfile:a,alias:c}=HR(t,r,e.sessionDir))}catch(T){Be(t,n.id,{fallback:{ok:!1,summary:`session teamfile creation failed: ${Ye(T)}`}});return}let l=()=>{let T=e.spawnPrefixes?.chat??Kr,v,S,N;try{let J=UR(r.action_payload,e.runToken,t);v=TR(jo(vR(),"lmbee-cron-session-")),S=jo(v,`${n.id}.md`),dh(S,J,{mode:384}),N=[...T,"chat",`${a}:${c}`,"--prompt-file",S,"--json"]}catch(J){Be(t,n.id,{fallback:{ok:!1,summary:`session dispatch setup failed before spawn: ${Ye(J)}`}});return}let[x,...I]=N,k;try{k=yl(x,I,{detached:!0,stdio:["ignore","pipe","pipe"],...r.working_directory!==null?{cwd:r.working_directory}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Dn(t.name)}}:{}})}catch(J){try{ah(v,{recursive:!0,force:!0})}catch{}Be(t,n.id,{fallback:{ok:!1,summary:`session dispatch spawn error: ${Ye(J)}`}});return}k.unref();let B=Fo(),C=Fo(),g=!1,y=!1,R=()=>{try{ah(v,{recursive:!0,force:!0})}catch{}},P=setTimeout(()=>{g||(g=!0,Tl(k,i),_t(t,n.id,`session timed out after ${o}ms`,{fallback:{ok:!1,summary:`session timed out after ${o}ms`}}))},o);P.unref(),k.on("spawn",()=>y=!0),k.stdout?.on("data",J=>qo(B,J)),k.stderr?.on("data",J=>qo(C,J)),k.on("error",J=>{if(g)return;g=!0,clearTimeout(P);let ee={fallback:{ok:!1,summary:`session dispatch spawn error: ${J.message}`}};y?_t(t,n.id,`session post-spawn error: ${J.message}`,ee):(R(),Be(t,n.id,ee))}),k.on("close",J=>{if(g)return;g=!0,clearTimeout(P);let ee=k.pid??null,oe=ee!==null&&vl(ee),V=B.overflow?{kind:"overflow"}:BR(B.text),se=V.kind==="completed"?fh(V.text,e.runToken):null,$=V.kind==="completed"&&!oe&&!B.overflow,O=se!==null&&se.ok?{report:se.result}:{fallback:{ok:!1,summary:(V.kind==="completed"?"session ended without a valid report":V.kind==="stalled"?"session stalled (native turn still running)":V.kind==="busy"?"session was busy; not started":V.kind==="error"?`session provider error: ${V.message}`:V.kind==="overflow"?`session output exceeded the ${xi}-byte capture limit`:"session ended without positive completion")+(J!==0?` (exit ${J}: ${C.text.trim().slice(-300)})`:"")}};if($){if(se!==null&&!se.ok){R(),Be(t,n.id,O);return}if(Be(t,n.id,O)){R();return}return}let A=V.kind==="stalled"?`session stalled (native turn still running): ${V.message}`:V.kind==="busy"?`session busy (a live worker may own it): ${V.message}`:V.kind==="error"?`session provider error (termination unconfirmed): ${V.message}`:V.kind==="overflow"?"session output exceeded the capture limit; result not trusted":oe?"session process group still alive after wrapper exit":`session wrapper exited without positive completion (code ${J})`;_t(t,n.id,A,O)});try{$i(t,n.id,{kind:"session",provider:r.provider,model:r.model,teamfile:a,alias:c},k.pid??null)}catch(J){process.stderr.write(`[lmcron] session run ${n.id} state write failed after spawn: ${Ye(J)}
299
- `)}try{gl(t,n.id,{kind:"session",phase:"dispatch",teamfile:a,alias:c},k.pid??null)}catch{}};if(r.session_seeded_at!==null){l();return}let d=[...e.spawnPrefixes?.seed??$R,"seed",a],m=d[0],f=d.slice(1),p;try{p=yl(m,f,{detached:!0,stdio:["ignore","ignore","pipe"],...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Dn(t.name)}}:{}})}catch(T){Be(t,n.id,{fallback:{ok:!1,summary:`session seed spawn error: ${Ye(T)}`}});return}p.unref();let h=Fo(),w=!1,_=!1,E=setTimeout(()=>{w||(w=!0,Tl(p,i),_t(t,n.id,`session seed timed out after ${s}ms; provider initialization may still be running`,{fallback:{ok:!1,summary:`session seed timed out after ${s}ms`}}))},s);E.unref(),p.on("spawn",()=>_=!0),p.stderr?.on("data",T=>qo(h,T)),p.on("error",T=>{if(w)return;w=!0,clearTimeout(E);let v={fallback:{ok:!1,summary:`session seed spawn error: ${T.message}`}};_?_t(t,n.id,`session seed post-spawn error: ${T.message}`,v):Be(t,n.id,v)}),p.on("close",T=>{if(!w){if(w=!0,clearTimeout(E),T!==0){_t(t,n.id,`session seed failed (exit ${T}); provider initialization may still be running`,{fallback:{ok:!1,summary:`session seed failed (exit ${T}): ${h.text.trim().slice(-300)}`}});return}try{t.prepare("UPDATE cron_jobs SET session_seeded_at = ?, updated_at = ? WHERE id = ?").run(new Date().toISOString(),new Date().toISOString(),r.id)}catch(v){_t(t,n.id,`session seeded but recording identity failed: ${Ye(v)}`,{fallback:{ok:!1,summary:"session seeded but recording seed state failed; will recover on retry"}});return}l()}});try{gl(t,n.id,{kind:"session",phase:"seed",teamfile:a,alias:c},p.pid??null)}catch{}}function Al(e){try{switch(e.job.action_kind){case"script":VR(e);return;case"miniplayer":JR(e);return;case"session":KR(e);return;default:Be(e.db,e.run.id,{fallback:{ok:!1,summary:`unsupported run worker kind: ${e.job.action_kind}`}})}}catch(t){_t(e.db,e.run.id,`unexpected worker dispatch failure: ${Ye(t)}`,{fallback:{ok:!1,summary:`worker dispatch error: ${Ye(t)}`}})}}function YR(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}function QR(e){return e==="script"||e==="session"||e==="miniplayer"}function St(e){return e instanceof Error?e.message:String(e)}function Mn(e){let t=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;if(t!==void 0&&(t.startsWith("SQLITE_BUSY")||t.startsWith("SQLITE_LOCKED")))throw new U("DB_BUSY","Database busy; retry after the current writer completes",5);let r=e instanceof Error?e.message:String(e);throw t!==void 0&&t.startsWith("SQLITE_CONSTRAINT")?new U("STRUCTURAL_ERROR",r,2):new U("STORAGE_ERROR",r,1)}function lr(e){try{return e()}catch(t){if(t instanceof U)throw t;if(t instanceof L)throw new U(t.code,t.message,t.exitCode);return Mn(t)}}function Ni(e,t){e.prepare("UPDATE cron_jobs SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}function Ii(e,t){return lr(()=>e.prepare("SELECT * FROM cron_jobs WHERE id = ?").get(t)??null)}function Ie(e,t){let r=Ii(e,t);if(r===null)throw new U("NOT_FOUND",`Cron job ${t} does not exist`,3);return r}function XR(e){let t;try{t=JSON.parse(e)}catch{throw new U("INVALID_ARGUMENT","enqueue action_payload must be valid JSON")}if(typeof t!="object"||t===null)throw new U("INVALID_ARGUMENT","enqueue action_payload must be a JSON object");let{to:r,prompt:n,from:o}=t;if(typeof r!="string"||r.trim().length===0)throw new U("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "to"');if(typeof n!="string"||n.trim().length===0)throw new U("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "prompt"');if(o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new U("INVALID_ARGUMENT",'enqueue action_payload "from", if given, must be a nonblank string')}function gh(e,t){ye(t,"action_payload"),e==="enqueue"&&XR(t)}function _h(e){let{actionKind:t}=e;if(t==="session"){if(e.provider===void 0||e.provider===null||e.provider.trim().length===0)throw new U("INVALID_ARGUMENT","a session job requires a nonblank provider");if(bl(e.provider),e.workingDirectory===void 0||e.workingDirectory===null||e.workingDirectory.trim().length===0)throw new U("INVALID_ARGUMENT","a session job requires an absolute working_directory (--cwd)");Ri(e.workingDirectory)}else if(e.provider!==void 0&&e.provider!==null&&e.provider.trim().length>0)throw new U("INVALID_ARGUMENT",`provider is only valid for session jobs (not ${t})`);if(e.model!==void 0&&e.model!==null&&e.model.trim().length===0)throw new U("INVALID_ARGUMENT","model, if given, must be nonblank");if(e.model!==void 0&&e.model!==null&&e.model.trim().length>0&&t!=="session"&&t!=="miniplayer")throw new U("INVALID_ARGUMENT",`model is only valid for session/miniplayer jobs (not ${t})`);if(e.model!==void 0&&e.model!==null&&e.model.trim().length>0&&Sl(e.model),e.workingDirectory!==void 0&&e.workingDirectory!==null&&e.workingDirectory.trim().length>0&&t==="enqueue")throw new U("INVALID_ARGUMENT","working_directory is not valid for enqueue jobs");if(e.workingDirectory!==void 0&&e.workingDirectory!==null&&e.workingDirectory.trim().length===0)throw new U("INVALID_ARGUMENT","working_directory, if given, must be nonblank");if(e.escalationOwner!==void 0&&e.escalationOwner!==null&&e.escalationOwner.trim().length===0)throw new U("INVALID_ARGUMENT","escalation_owner, if given, must be nonblank")}function wh(e){let t=ye(e,"timezone");try{new Intl.DateTimeFormat(void 0,{timeZone:t})}catch{throw new U("INVALID_ARGUMENT",`timezone "${t}" is not a recognized IANA zone name`)}return t}function yh(e){let t=dl(e);if(!t.ok){let r=t.error.field?` (field: ${t.error.field})`:"";throw new U("INVALID_SCHEDULE",`${t.error.message}${r}`)}}function Pn(e,t){let r=e.transaction(()=>{if(t.id!==void 0&&(!Number.isSafeInteger(t.id)||t.id<1))throw new U("INVALID_ARGUMENT","id, if given, must be a positive safe integer");let n=ye(t.title,"title");if(!YR(t.actionKind))throw new U("INVALID_ARGUMENT",'action_kind must be "enqueue", "command", "script", "session", or "miniplayer"');yh(t.scheduleExpr),gh(t.actionKind,t.actionPayload),_h({actionKind:t.actionKind,provider:t.provider??null,model:t.model??null,workingDirectory:t.workingDirectory??null,escalationOwner:t.escalationOwner??null});let o=t.timezone!==void 0?wh(t.timezone):null,s=de();try{let i=e.prepare(t.id!==void 0?`INSERT INTO cron_jobs(id, title, schedule_expr, action_kind, action_payload, provider, model,
298
+ `)}}function XR(e){let{db:t,job:r,run:n}=e,o,s,i;try{o=Tl(e.timeoutMs,OR,"timeoutMs"),s=Tl(e.seedTimeoutMs,DR,"seedTimeoutMs"),i=e.sigkillGraceMs??ph}catch(E){Be(t,n.id,{fallback:{ok:!1,summary:`session setup failed before spawn: ${Ye(E)}`}});return}let a,c;try{({teamfile:a,alias:c}=JR(t,r,e.sessionDir))}catch(E){Be(t,n.id,{fallback:{ok:!1,summary:`session teamfile creation failed: ${Ye(E)}`}});return}let l=()=>{let E=e.spawnPrefixes?.chat??Kr,v,S,N;try{let J=BR(r.action_payload,e.runToken,t);v=kR(Go(RR(),"lmbee-cron-session-")),S=Go(v,`${n.id}.md`),fh(S,J,{mode:384}),N=[...E,"chat",`${a}:${c}`,"--prompt-file",S,"--json"]}catch(J){Be(t,n.id,{fallback:{ok:!1,summary:`session dispatch setup failed before spawn: ${Ye(J)}`}});return}let[$,...L]=N,R;try{R=El($,L,{detached:!0,stdio:["ignore","pipe","pipe"],...r.working_directory!==null?{cwd:r.working_directory}:{},...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Pn(t.name)}}:{}})}catch(J){try{lh(v,{recursive:!0,force:!0})}catch{}Be(t,n.id,{fallback:{ok:!1,summary:`session dispatch spawn error: ${Ye(J)}`}});return}R.unref();let H=Bo(),C=Bo(),g=!1,y=!1,x=()=>{try{lh(v,{recursive:!0,force:!0})}catch{}},P=setTimeout(()=>{g||(g=!0,bl(R,i),_t(t,n.id,`session timed out after ${o}ms`,{fallback:{ok:!1,summary:`session timed out after ${o}ms`}}))},o);P.unref(),R.on("spawn",()=>y=!0),R.stdout?.on("data",J=>Wo(H,J)),R.stderr?.on("data",J=>Wo(C,J)),R.on("error",J=>{if(g)return;g=!0,clearTimeout(P);let ee={fallback:{ok:!1,summary:`session dispatch spawn error: ${J.message}`}};y?_t(t,n.id,`session post-spawn error: ${J.message}`,ee):(x(),Be(t,n.id,ee))}),R.on("close",J=>{if(g)return;g=!0,clearTimeout(P);let ee=R.pid??null,oe=ee!==null&&Al(ee),V=H.overflow?{kind:"overflow"}:KR(H.text),se=V.kind==="completed"?hh(V.text,e.runToken):null,k=V.kind==="completed"&&!oe&&!H.overflow,O=se!==null&&se.ok?{report:se.result}:{fallback:{ok:!1,summary:(V.kind==="completed"?"session ended without a valid report":V.kind==="stalled"?"session stalled (native turn still running)":V.kind==="busy"?"session was busy; not started":V.kind==="error"?`session provider error: ${V.message}`:V.kind==="overflow"?`session output exceeded the ${Li}-byte capture limit`:"session ended without positive completion")+(J!==0?` (exit ${J}: ${C.text.trim().slice(-300)})`:"")}};if(k){if(se!==null&&!se.ok){x(),Be(t,n.id,O);return}if(Be(t,n.id,O)){x();return}return}let A=V.kind==="stalled"?`session stalled (native turn still running): ${V.message}`:V.kind==="busy"?`session busy (a live worker may own it): ${V.message}`:V.kind==="error"?`session provider error (termination unconfirmed): ${V.message}`:V.kind==="overflow"?"session output exceeded the capture limit; result not trusted":oe?"session process group still alive after wrapper exit":`session wrapper exited without positive completion (code ${J})`;_t(t,n.id,A,O)});try{Dn(t,n.id,{kind:"session",provider:r.provider,model:r.model,teamfile:a,alias:c},R.pid??null)}catch(J){process.stderr.write(`[lmcron] session run ${n.id} state write failed after spawn: ${Ye(J)}
299
+ `)}try{jo(t,n.id,{kind:"session",phase:"dispatch",teamfile:a,alias:c},R.pid??null)}catch{}};if(r.session_seeded_at!==null){l();return}let d=[...e.spawnPrefixes?.seed??LR,"seed",a],m=d[0],f=d.slice(1),p;try{p=El(m,f,{detached:!0,stdio:["ignore","ignore","pipe"],...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Pn(t.name)}}:{}})}catch(E){Be(t,n.id,{fallback:{ok:!1,summary:`session seed spawn error: ${Ye(E)}`}});return}p.unref();let h=Bo(),w=!1,_=!1,T=setTimeout(()=>{w||(w=!0,bl(p,i),_t(t,n.id,`session seed timed out after ${s}ms; provider initialization may still be running`,{fallback:{ok:!1,summary:`session seed timed out after ${s}ms`}}))},s);T.unref(),p.on("spawn",()=>_=!0),p.stderr?.on("data",E=>Wo(h,E)),p.on("error",E=>{if(w)return;w=!0,clearTimeout(T);let v={fallback:{ok:!1,summary:`session seed spawn error: ${E.message}`}};_?_t(t,n.id,`session seed post-spawn error: ${E.message}`,v):Be(t,n.id,v)}),p.on("close",E=>{if(!w){if(w=!0,clearTimeout(T),E!==0){_t(t,n.id,`session seed failed (exit ${E}); provider initialization may still be running`,{fallback:{ok:!1,summary:`session seed failed (exit ${E}): ${h.text.trim().slice(-300)}`}});return}try{t.prepare("UPDATE cron_jobs SET session_seeded_at = ?, updated_at = ? WHERE id = ?").run(new Date().toISOString(),new Date().toISOString(),r.id)}catch(v){_t(t,n.id,`session seeded but recording identity failed: ${Ye(v)}`,{fallback:{ok:!1,summary:"session seeded but recording seed state failed; will recover on retry"}});return}l()}});try{jo(t,n.id,{kind:"session",phase:"seed",teamfile:a,alias:c},p.pid??null)}catch{}}function $l(e){try{switch(e.job.action_kind){case"script":YR(e);return;case"miniplayer":QR(e);return;case"session":XR(e);return;default:Be(e.db,e.run.id,{fallback:{ok:!1,summary:`unsupported run worker kind: ${e.job.action_kind}`}})}}catch(t){_t(e.db,e.run.id,`unexpected worker dispatch failure: ${Ye(t)}`,{fallback:{ok:!1,summary:`worker dispatch error: ${Ye(t)}`}})}}function eN(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}function tN(e){return e==="script"||e==="session"||e==="miniplayer"}function wt(e){return e instanceof Error?e.message:String(e)}function Un(e){let t=e&&typeof e=="object"&&"code"in e?String(e.code):void 0;if(t!==void 0&&(t.startsWith("SQLITE_BUSY")||t.startsWith("SQLITE_LOCKED")))throw new U("DB_BUSY","Database busy; retry after the current writer completes",5);let r=e instanceof Error?e.message:String(e);throw t!==void 0&&t.startsWith("SQLITE_CONSTRAINT")?new U("STRUCTURAL_ERROR",r,2):new U("STORAGE_ERROR",r,1)}function ur(e){try{return e()}catch(t){if(t instanceof U)throw t;if(t instanceof I)throw new U(t.code,t.message,t.exitCode);return Un(t)}}function Ci(e,t){e.prepare("UPDATE cron_jobs SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}function Oi(e,t){return ur(()=>e.prepare("SELECT * FROM cron_jobs WHERE id = ?").get(t)??null)}function Le(e,t){let r=Oi(e,t);if(r===null)throw new U("NOT_FOUND",`Cron job ${t} does not exist`,3);return r}function rN(e){let t;try{t=JSON.parse(e)}catch{throw new U("INVALID_ARGUMENT","enqueue action_payload must be valid JSON")}if(typeof t!="object"||t===null)throw new U("INVALID_ARGUMENT","enqueue action_payload must be a JSON object");let{to:r,prompt:n,from:o}=t;if(typeof r!="string"||r.trim().length===0)throw new U("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "to"');if(typeof n!="string"||n.trim().length===0)throw new U("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "prompt"');if(o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new U("INVALID_ARGUMENT",'enqueue action_payload "from", if given, must be a nonblank string')}function wh(e,t){ye(t,"action_payload"),e==="enqueue"&&rN(t)}function yh(e){let{actionKind:t}=e;if(t==="session"){if(e.provider===void 0||e.provider===null||e.provider.trim().length===0)throw new U("INVALID_ARGUMENT","a session job requires a nonblank provider");if(Sl(e.provider),e.workingDirectory===void 0||e.workingDirectory===null||e.workingDirectory.trim().length===0)throw new U("INVALID_ARGUMENT","a session job requires an absolute working_directory (--cwd)");Ii(e.workingDirectory)}else if(e.provider!==void 0&&e.provider!==null&&e.provider.trim().length>0)throw new U("INVALID_ARGUMENT",`provider is only valid for session jobs (not ${t})`);if(e.model!==void 0&&e.model!==null&&e.model.trim().length===0)throw new U("INVALID_ARGUMENT","model, if given, must be nonblank");if(e.model!==void 0&&e.model!==null&&e.model.trim().length>0&&t!=="session"&&t!=="miniplayer")throw new U("INVALID_ARGUMENT",`model is only valid for session/miniplayer jobs (not ${t})`);if(e.model!==void 0&&e.model!==null&&e.model.trim().length>0&&vl(e.model),e.workingDirectory!==void 0&&e.workingDirectory!==null&&e.workingDirectory.trim().length>0&&t==="enqueue")throw new U("INVALID_ARGUMENT","working_directory is not valid for enqueue jobs");if(e.workingDirectory!==void 0&&e.workingDirectory!==null&&e.workingDirectory.trim().length===0)throw new U("INVALID_ARGUMENT","working_directory, if given, must be nonblank");if(e.escalationOwner!==void 0&&e.escalationOwner!==null&&e.escalationOwner.trim().length===0)throw new U("INVALID_ARGUMENT","escalation_owner, if given, must be nonblank")}function Eh(e){let t=ye(e,"timezone");try{new Intl.DateTimeFormat(void 0,{timeZone:t})}catch{throw new U("INVALID_ARGUMENT",`timezone "${t}" is not a recognized IANA zone name`)}return t}function Th(e){let t=pl(e);if(!t.ok){let r=t.error.field?` (field: ${t.error.field})`:"";throw new U("INVALID_SCHEDULE",`${t.error.message}${r}`)}}function Fn(e,t){let r=e.transaction(()=>{if(t.id!==void 0&&(!Number.isSafeInteger(t.id)||t.id<1))throw new U("INVALID_ARGUMENT","id, if given, must be a positive safe integer");let n=ye(t.title,"title");if(!eN(t.actionKind))throw new U("INVALID_ARGUMENT",'action_kind must be "enqueue", "command", "script", "session", or "miniplayer"');Th(t.scheduleExpr),wh(t.actionKind,t.actionPayload),yh({actionKind:t.actionKind,provider:t.provider??null,model:t.model??null,workingDirectory:t.workingDirectory??null,escalationOwner:t.escalationOwner??null});let o=t.timezone!==void 0?Eh(t.timezone):null,s=de();try{let i=e.prepare(t.id!==void 0?`INSERT INTO cron_jobs(id, title, schedule_expr, action_kind, action_payload, provider, model,
300
300
  working_directory, escalation_owner, enabled, timezone, created_at, updated_at)
301
301
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`:`INSERT INTO cron_jobs(title, schedule_expr, action_kind, action_payload, provider, model,
302
302
  working_directory, escalation_owner, enabled, timezone, created_at, updated_at)
303
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(...t.id!==void 0?[t.id]:[],n,t.scheduleExpr,t.actionKind,t.actionPayload,t.provider??null,t.model??null,t.workingDirectory??null,t.escalationOwner??null,t.enabled===!1?0:1,o,s,s);return Ie(e,Number(i.lastInsertRowid))}catch(i){Mn(i)}});return lr(r)}function Li(e,t){if(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>Ne)throw new U("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return lr(()=>{let r=["id > ?"],n=[t.after];t.enabled!==void 0&&(r.push("enabled = ?"),n.push(t.enabled?1:0));let o=e.prepare(`SELECT * FROM cron_jobs WHERE ${r.join(" AND ")} ORDER BY id LIMIT ?`).all(...n,t.limit+1),s=o.length>t.limit,i=s?o.slice(0,t.limit):o;return{rows:i,meta:{next_cursor:s?i[i.length-1].id:null}}})}function Eh(e,t,r){let n=e.transaction(()=>{let o=Ie(e,t);if(r.ifRevision!==void 0&&o.revision!==r.ifRevision)throw new U("REVISION_CONFLICT",`Expected revision ${r.ifRevision}; current is ${o.revision}`,4);let s={};if(r.title!==void 0&&(s.title=ye(r.title,"title")),r.scheduleExpr!==void 0&&(yh(r.scheduleExpr),s.schedule_expr=r.scheduleExpr),r.actionPayload!==void 0&&(gh(o.action_kind,r.actionPayload),s.action_payload=r.actionPayload),r.timezone!==void 0&&(s.timezone=r.timezone===null?null:wh(r.timezone)),o.session_teamfile!==null&&(r.provider!==void 0&&r.provider!==o.provider||r.model!==void 0&&r.model!==o.model||r.workingDirectory!==void 0&&r.workingDirectory!==o.working_directory))throw new U("SESSION_IMMUTABLE","provider/model/cwd cannot change while a session is seeded; run `cron reset-session` first",2);if(r.provider!==void 0&&(s.provider=r.provider),r.model!==void 0&&(s.model=r.model),(r.provider!==void 0||r.model!==void 0)&&_h({actionKind:o.action_kind,provider:r.provider??o.provider,model:r.model??o.model,workingDirectory:r.workingDirectory!==void 0?r.workingDirectory:o.working_directory}),r.workingDirectory!==void 0){if(o.action_kind==="enqueue")throw new U("INVALID_ARGUMENT","working_directory is not valid for enqueue jobs");if(r.workingDirectory===null){if(o.action_kind==="session")throw new U("INVALID_ARGUMENT","a session job requires an absolute working_directory");s.working_directory=null}else{let i=ye(r.workingDirectory,"working_directory");o.action_kind==="session"&&Ri(i),s.working_directory=i}}if(r.escalationOwner!==void 0&&(s.escalation_owner=r.escalationOwner===null?null:ye(r.escalationOwner,"escalation_owner")),Object.keys(s).length===0)throw new U("INVALID_ARGUMENT","Update requires at least one field");try{e.prepare(`UPDATE cron_jobs SET ${Object.keys(s).map(i=>`${i} = ?`).join(",")} WHERE id = ?`).run(...Object.values(s),t)}catch(i){Mn(i)}return Ni(e,t),Ie(e,t)});return lr(n)}function Ci(e,t,r){let n=e.transaction(()=>{Ie(e,t);try{e.prepare("UPDATE cron_jobs SET enabled = ? WHERE id = ?").run(r?1:0,t)}catch(o){Mn(o)}return Ni(e,t),Ie(e,t)});return lr(n)}function Th(e,t){let r=e.transaction(()=>{let n=Ie(e,t);if(Rr(e,t)!==null)throw new U("EXECUTION_FENCED",`Cron job ${t} has a fenced execution or unresolved escalation; resolve it before removing the job`,4);try{e.prepare("DELETE FROM cron_jobs WHERE id = ?").run(t)}catch(o){Mn(o)}return n});return lr(r)}function bh(e,t){let r=e.transaction(()=>{if(Ie(e,t).action_kind!=="session")throw new U("INVALID_ARGUMENT",`Cron job ${t} is not a session job`);if(Rr(e,t)!==null)throw new U("SESSION_ACTIVE",`Cron job ${t} has an active run; resolve it before resetting the session`,4);return e.prepare(`UPDATE cron_jobs SET session_teamfile = NULL, session_seeded_at = NULL, session_alias = NULL,
304
- session_generation = session_generation + 1 WHERE id = ?`).run(t),Ni(e,t),Ie(e,t)});return lr(r)}var ZR=24*60*60*1e3;function Sh(e,t=zR){try{return t("systemctl",["--user","is-active","--quiet",e]),"active"}catch(r){return r.status===3?"confirmed-gone":"unknown"}}async function vh(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Co,i=n.isUnitStillRunningImpl??Sh,a=new Date(r).toISOString(),c=[],l=lr(()=>e.prepare("SELECT * FROM cron_jobs WHERE enabled = 1 ORDER BY id").all());for(let u of l)try{eN(e,u,t,r,a,o,s,i,n.logDir,c,n.onJobError,{...n.runSpawnPrefixes!==void 0?{runSpawnPrefixes:n.runSpawnPrefixes}:{},...n.sessionDir!==void 0?{sessionDir:n.sessionDir}:{},...n.runTimeoutMs!==void 0?{runTimeoutMs:n.runTimeoutMs}:{},...n.runSeedTimeoutMs!==void 0?{runSeedTimeoutMs:n.runSeedTimeoutMs}:{},executeRunImpl:n.executeRunImpl??Al})}catch(d){try{n.onJobError?.(u.id,d)}catch{}try{Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",St(d),a],u)}catch{}}return c}function ph(e,t){let r=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(e),n=o=>Number(r.find(s=>s.type===o).value);return new Date(n("year"),n("month")-1,n("day"),n("hour"),n("minute"),n("second"))}function eN(e,t,r,n,o,s,i,a,c,l,u,d){let m=dl(t.schedule_expr);if(!m.ok){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",`Unparseable schedule_expr: ${m.error.message}`,o],t);return}let f=m.schedule;if(t.action_kind==="command"&&t.running_since_ts!==null){if(t.running_systemd_unit!==null&&a(t.running_systemd_unit)==="confirmed-gone"){e.prepare(`UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?,
303
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(...t.id!==void 0?[t.id]:[],n,t.scheduleExpr,t.actionKind,t.actionPayload,t.provider??null,t.model??null,t.workingDirectory??null,t.escalationOwner??null,t.enabled===!1?0:1,o,s,s);return Le(e,Number(i.lastInsertRowid))}catch(i){Un(i)}});return ur(r)}function Di(e,t){if(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>Ne)throw new U("INVALID_ARGUMENT",`limit must be a positive integer <= ${Ne}`);return ur(()=>{let r=["id > ?"],n=[t.after];t.enabled!==void 0&&(r.push("enabled = ?"),n.push(t.enabled?1:0));let o=e.prepare(`SELECT * FROM cron_jobs WHERE ${r.join(" AND ")} ORDER BY id LIMIT ?`).all(...n,t.limit+1),s=o.length>t.limit,i=s?o.slice(0,t.limit):o;return{rows:i,meta:{next_cursor:s?i[i.length-1].id:null}}})}function bh(e,t,r){let n=e.transaction(()=>{let o=Le(e,t);if(r.ifRevision!==void 0&&o.revision!==r.ifRevision)throw new U("REVISION_CONFLICT",`Expected revision ${r.ifRevision}; current is ${o.revision}`,4);let s={};if(r.title!==void 0&&(s.title=ye(r.title,"title")),r.scheduleExpr!==void 0&&(Th(r.scheduleExpr),s.schedule_expr=r.scheduleExpr),r.actionPayload!==void 0&&(wh(o.action_kind,r.actionPayload),s.action_payload=r.actionPayload),r.timezone!==void 0&&(s.timezone=r.timezone===null?null:Eh(r.timezone)),o.session_teamfile!==null&&(r.provider!==void 0&&r.provider!==o.provider||r.model!==void 0&&r.model!==o.model||r.workingDirectory!==void 0&&r.workingDirectory!==o.working_directory))throw new U("SESSION_IMMUTABLE","provider/model/cwd cannot change while a session is seeded; run `cron reset-session` first",2);if(r.provider!==void 0&&(s.provider=r.provider),r.model!==void 0&&(s.model=r.model),(r.provider!==void 0||r.model!==void 0)&&yh({actionKind:o.action_kind,provider:r.provider??o.provider,model:r.model??o.model,workingDirectory:r.workingDirectory!==void 0?r.workingDirectory:o.working_directory}),r.workingDirectory!==void 0){if(o.action_kind==="enqueue")throw new U("INVALID_ARGUMENT","working_directory is not valid for enqueue jobs");if(r.workingDirectory===null){if(o.action_kind==="session")throw new U("INVALID_ARGUMENT","a session job requires an absolute working_directory");s.working_directory=null}else{let i=ye(r.workingDirectory,"working_directory");o.action_kind==="session"&&Ii(i),s.working_directory=i}}if(r.escalationOwner!==void 0&&(s.escalation_owner=r.escalationOwner===null?null:ye(r.escalationOwner,"escalation_owner")),Object.keys(s).length===0)throw new U("INVALID_ARGUMENT","Update requires at least one field");try{e.prepare(`UPDATE cron_jobs SET ${Object.keys(s).map(i=>`${i} = ?`).join(",")} WHERE id = ?`).run(...Object.values(s),t)}catch(i){Un(i)}return Ci(e,t),Le(e,t)});return ur(n)}function Mi(e,t,r){let n=e.transaction(()=>{Le(e,t);try{e.prepare("UPDATE cron_jobs SET enabled = ? WHERE id = ?").run(r?1:0,t)}catch(o){Un(o)}return Ci(e,t),Le(e,t)});return ur(n)}function Sh(e,t){let r=e.transaction(()=>{let n=Le(e,t);if(lr(e,t)!==null)throw new U("EXECUTION_FENCED",`Cron job ${t} has a fenced execution or unresolved escalation; resolve it before removing the job`,4);try{e.prepare("DELETE FROM cron_jobs WHERE id = ?").run(t)}catch(o){Un(o)}return n});return ur(r)}function vh(e,t){let r=e.transaction(()=>{if(Le(e,t).action_kind!=="session")throw new U("INVALID_ARGUMENT",`Cron job ${t} is not a session job`);if(lr(e,t)!==null)throw new U("SESSION_ACTIVE",`Cron job ${t} has an active run; resolve it before resetting the session`,4);return e.prepare(`UPDATE cron_jobs SET session_teamfile = NULL, session_seeded_at = NULL, session_alias = NULL,
304
+ session_generation = session_generation + 1 WHERE id = ?`).run(t),Ci(e,t),Le(e,t)});return ur(r)}var nN=24*60*60*1e3;function Ah(e,t=ZR){try{return t("systemctl",["--user","is-active","--quiet",e]),"active"}catch(r){return r.status===3?"confirmed-gone":"unknown"}}async function kh(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Do,i=n.isUnitStillRunningImpl??Ah,a=new Date(r).toISOString(),c=[],l=ur(()=>e.prepare("SELECT * FROM cron_jobs WHERE enabled = 1 ORDER BY id").all());for(let u of l)try{aN(e,u,t,r,a,o,s,i,n.logDir,c,n.onJobError,{...n.runSpawnPrefixes!==void 0?{runSpawnPrefixes:n.runSpawnPrefixes}:{},...n.sessionDir!==void 0?{sessionDir:n.sessionDir}:{},...n.runTimeoutMs!==void 0?{runTimeoutMs:n.runTimeoutMs}:{},...n.runSeedTimeoutMs!==void 0?{runSeedTimeoutMs:n.runSeedTimeoutMs}:{},executeRunImpl:n.executeRunImpl??$l})}catch(d){try{n.onJobError?.(u.id,d)}catch{}try{Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",wt(d),a],u)}catch{}}return c}function gh(e,t){let r=new Intl.DateTimeFormat("en-US",{timeZone:t,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(e),n=o=>Number(r.find(s=>s.type===o).value);return new Date(n("year"),n("month")-1,n("day"),n("hour"),n("minute"),n("second"))}var oN=500;function sN(e){return JSON.stringify({kind:"command",payload:e.action_payload,provider:e.provider,model:e.model,workingDirectory:e.working_directory,escalationOwner:e.escalation_owner})}function iN(e){if(e.execution_identity===null)return null;try{let t=JSON.parse(e.execution_identity);return typeof t.systemdUnit=="string"?t.systemdUnit:null}catch{return null}}function xl(e,t,r){let n=lr(e,t);if(n!==null)try{Mn(e,n.id,{fallback:{ok:!1,summary:r}})}catch{}}function $h(e,t,r,n,o){try{let s=sN(t),i=qo(e,t.id,r,s);if(i.kind!=="claimed"){let a=iN(i.run);a!==null&&o(a)==="confirmed-gone"&&(xl(e,t.id,"reconciled: previous command execution confirmed gone before a new fire"),i=qo(e,t.id,r,s))}return i.kind!=="claimed"?null:(Dn(e,i.run.id,{kind:"command",systemdUnit:n},null),i.run.id)}catch{return null}}function xh(e,t,r,n,o,s,i){if(t!==null)try{if(o!==null)try{jo(e,t,{kind:"command",systemdUnit:i},o)}catch{}let a=kl(s,oN),c=n?`command spawn error: ${n.message}`:`command exited with code ${r}${a?`: ${a}`:""}`;Mn(e,t,{fallback:{ok:n===void 0&&r===0,summary:c}})}catch{}}function Rh(e,t,r){if(t!==null)try{Mn(e,t,{fallback:{ok:!1,summary:`command spawn failed: ${wt(r)}`}})}catch{}}function aN(e,t,r,n,o,s,i,a,c,l,u,d){let m=pl(t.schedule_expr);if(!m.ok){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",`Unparseable schedule_expr: ${m.error.message}`,o],t);return}let f=m.schedule;if(t.action_kind==="command"&&t.running_since_ts!==null){if(t.running_systemd_unit!==null&&a(t.running_systemd_unit)==="confirmed-gone"){e.prepare(`UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?,
305
305
  last_fire_error = NULL, updated_at = ?
306
- WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts = ? AND running_systemd_unit = ?`).run("reconciled",o,t.id,t.revision,t.running_since_ts,t.running_systemd_unit);return}e.prepare("UPDATE cron_jobs SET last_fire_status = ?, updated_at = ? WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts = ?").run("skipped_overlap",o,t.id,t.revision,t.running_since_ts);return}let p=t.last_checked_ts!==null?Date.parse(t.last_checked_ts):Date.parse(t.created_at);if(p>n){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, last_fire_status = ?, last_fire_error = ?, updated_at = ?",[o,"error",`last_checked_ts (${t.last_checked_ts??t.created_at}) is after the current tick time -- checkpoint reset without firing`,o],t);return}let h=new Date(p),w=new Date(n);if(n-p>ZR){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, last_fire_status = ?, updated_at = ?",[o,"skipped_stale",o],t);return}let _=t.timezone!==null?ph(h,t.timezone):h,E=t.timezone!==null?ph(w,t.timezone):w;if(!zp(f,_,E)){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ?",[o,o],t);return}let v=Ii(e,t.id);if(!(v===null||v.enabled===0||v.revision!==t.revision)){if(QR(t.action_kind)){tN(e,t,o,l,u,d);return}if(t.action_kind==="enqueue")try{let S=JSON.parse(t.action_payload),N={from:S.from??"autopilot",dedupeKey:`cron:${t.id}:${h.toISOString()}`};e.transaction(()=>{let I=e.prepare("SELECT enabled, revision, last_checked_ts FROM cron_jobs WHERE id = ?").get(t.id);return I===void 0||I.enabled===0||I.revision!==t.revision||I.last_checked_ts!==t.last_checked_ts?!1:(s(e,r,S.to,S.prompt,N),e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(o,o,"ok",o,t.id),!0)}).immediate()&&l.push(t.title)}catch(S){try{u?.(t.id,S)}catch{}try{Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",St(S),o],t)}catch{}}else{let S=o,N=`lmcron-job-${t.id}-${S.replace(/[:.]/g,"-")}.scope`;if(e.prepare(`UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, running_since_ts = ?, running_systemd_unit = ?, updated_at = ?
307
- WHERE id = ? AND enabled = 1 AND revision = ? AND (last_checked_ts IS ?) AND (running_since_ts IS ?)`).run(o,o,"ok",o,N,o,t.id,t.revision,t.last_checked_ts,t.running_since_ts).changes===0)return;let I={logDir:c,systemdUnitName:N,onExit:(k,B)=>{let C=k===0?"ok":"error",g=C==="ok"?null:B?St(B):`Command exited with code ${k} -- see ${c??vi()}/${t.id}/ for output`;if(B)try{u?.(t.id,B)}catch{}try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = ?, updated_at = ? WHERE id = ? AND running_since_ts = ?").run(C,g,new Date().toISOString(),t.id,S)}catch{}}};try{i({id:t.id,action_payload:t.action_payload},I),l.push(t.title)}catch(k){try{u?.(t.id,k)}catch{}try{e.prepare("UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, running_since_ts = NULL, running_systemd_unit = NULL, updated_at = ? WHERE id = ? AND running_since_ts = ?").run("error",St(k),o,t.id,S)}catch{}}}}}async function hh(e,t){for(;!e();)await new Promise(r=>setTimeout(r,t))}async function Ho(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Co,i=n.isUnitStillRunningImpl??Sh,a=n.executeRunImpl??Al,c=n.logDir,l=n.pollMs??250,u=Ie(e,t);if(u.enabled===0)throw new U("DISABLED",`Cron job ${t} is disabled -- enable it first (\`cron enable ${t}\`), or a manual trigger would silently exercise a job the operator turned off on purpose`,4);let d=de();if(u.action_kind==="command"){if(u.running_since_ts!==null)return u.running_systemd_unit!==null&&i(u.running_systemd_unit)==="confirmed-gone"?(e.prepare(`UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = NULL, updated_at = ?
308
- WHERE id = ? AND revision = ? AND running_since_ts = ? AND running_systemd_unit = ?`).run("reconciled",d,u.id,u.revision,u.running_since_ts,u.running_systemd_unit),await Ho(e,t,r,n)):{kind:"skipped_overlap",job:u};let p=d,h=`lmcron-job-${u.id}-${p.replace(/[:.]/g,"-")}-manual.scope`;if(e.prepare(`UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, running_since_ts = ?, running_systemd_unit = ?, updated_at = ?
309
- WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts IS ?`).run(d,"ok",p,h,d,u.id,u.revision,u.running_since_ts).changes===0)return{kind:"skipped_overlap",job:Ie(e,t)};let _={logDir:c,systemdUnitName:h,onExit:(E,T)=>{let v=E===0?"ok":"error",S=v==="ok"?null:T?St(T):`Command exited with code ${E} -- see ${c??vi()}/${u.id}/ for output`;try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = ?, updated_at = ? WHERE id = ? AND running_since_ts = ?").run(v,S,new Date().toISOString(),u.id,p)}catch{}}};try{s({id:u.id,action_payload:u.action_payload},_)}catch(E){try{e.prepare("UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, running_since_ts = NULL, running_systemd_unit = NULL, updated_at = ? WHERE id = ? AND running_since_ts = ?").run("error",St(E),d,u.id,p)}catch{}throw new U("SPAWN_FAILED",`manual trigger of job ${t} failed to spawn: ${St(E)}`,1)}return await hh(()=>Ie(e,t).running_since_ts!==p,l),{kind:"fired",job:Ie(e,t)}}if(u.action_kind==="enqueue"){let p=JSON.parse(u.action_payload);return o(e,r,p.to,p.prompt,{from:p.from??"autopilot"}),e.prepare("UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(d,"ok",d,u.id),{kind:"fired",job:Ie(e,t)}}let m=JSON.stringify({kind:u.action_kind,payload:u.action_payload,provider:u.provider,model:u.model,workingDirectory:u.working_directory,escalationOwner:u.escalation_owner}),f=e.transaction(()=>{let p=e.prepare("SELECT enabled, revision FROM cron_jobs WHERE id = ?").get(u.id);if(p===void 0||p.enabled===0||p.revision!==u.revision)return null;let h=hl(e,u.id,`${u.action_kind}:manual`,m);return h.kind==="claimed"&&e.prepare("UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(d,"ok",d,u.id),h}).immediate();if(f===null)throw new U("CONFLICT",`Cron job ${t} was modified concurrently -- re-run \`cron trigger ${t}\``,5);if(f.kind==="escalation")return{kind:"blocked_escalation",job:Ie(e,t)};if(f.kind==="overlap")return{kind:"skipped_overlap",job:Ie(e,t)};try{a({db:e,job:u,run:f.run,runToken:f.token,...n.runSpawnPrefixes!==void 0?{spawnPrefixes:n.runSpawnPrefixes}:{},...n.sessionDir!==void 0?{sessionDir:n.sessionDir}:{},...n.runTimeoutMs!==void 0?{timeoutMs:n.runTimeoutMs}:{},...n.runSeedTimeoutMs!==void 0?{seedTimeoutMs:n.runSeedTimeoutMs}:{}})}catch(p){try{Uo(e,f.run.id,`worker dispatch threw: ${St(p)}`),wl(e,f.run.id,{ok:!1,summary:`worker dispatch error: ${St(p)}`})}catch{}throw new U("SPAWN_FAILED",`manual trigger of job ${t} failed to dispatch: ${St(p)}`,1)}return n.waitForCompletion===!1?{kind:"fired",job:Ie(e,t),runId:f.run.id}:(await hh(()=>{let p=ze(e,f.run.id);return p.status!=="pending"&&p.status!=="running"},l),{kind:"fired",job:Ie(e,t),runId:f.run.id})}function tN(e,t,r,n,o,s){let i=JSON.stringify({kind:t.action_kind,payload:t.action_payload,provider:t.provider,model:t.model,workingDirectory:t.working_directory,escalationOwner:t.escalation_owner}),a=e.transaction(()=>{let c=e.prepare("SELECT enabled, revision, last_checked_ts FROM cron_jobs WHERE id = ?").get(t.id);if(c===void 0||c.enabled===0||c.revision!==t.revision||c.last_checked_ts!==t.last_checked_ts)return null;let l=hl(e,t.id,t.action_kind,i);return l.kind==="claimed"&&e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(r,r,"ok",r,t.id),l}).immediate();if(a!==null){if(a.kind==="escalation"){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, updated_at = ?",["blocked_escalation",r],t);return}if(a.kind==="overlap"){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, updated_at = ?",["skipped_overlap",r],t);return}n.push(t.title);try{s.executeRunImpl({db:e,job:t,run:a.run,runToken:a.token,...s.runSpawnPrefixes!==void 0?{spawnPrefixes:s.runSpawnPrefixes}:{},...s.sessionDir!==void 0?{sessionDir:s.sessionDir}:{},...s.runTimeoutMs!==void 0?{timeoutMs:s.runTimeoutMs}:{},...s.runSeedTimeoutMs!==void 0?{seedTimeoutMs:s.runSeedTimeoutMs}:{}})}catch(c){try{Uo(e,a.run.id,`worker dispatch threw: ${St(c)}`),wl(e,a.run.id,{ok:!1,summary:`worker dispatch error: ${St(c)}`})}catch{}try{o?.(t.id,c)}catch{}}}}function Nr(e,t,r,n){e.prepare(`${t} WHERE id = ? AND enabled = 1 AND revision = ? AND (last_checked_ts IS ?)`).run(...r,n.id,n.revision,n.last_checked_ts)}function Ah(e,t){let r=e.transaction(()=>{Ie(e,t);try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL WHERE id = ?").run(t)}catch(n){Mn(n)}return Ni(e,t),Ie(e,t)});return lr(r)}import{execFileSync as rN}from"node:child_process";import{existsSync as nN,readFileSync as $h}from"node:fs";import{homedir as kh}from"node:os";import{join as xh}from"node:path";function Fn(){return process.env.LMBEE_HEAVY_STATUS??xh(kh(),".lmbee","heavy.status")}function qn(){return process.env.LMBEE_HEAVY_LOCK??xh(kh(),".lmbee","heavy.lock")}var Un=class extends Error{};function oN(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.holder=="string"&&typeof t.pid=="number"&&typeof t.command=="string"&&typeof t.startedAt=="string"}function sN(e){let t;try{t=$h(e,"utf8")}catch{return null}try{let r=JSON.parse(t);return oN(r)?r:null}catch{return null}}function iN(e,t){return e===null||t===null?e===t:e.holder===t.holder&&e.pid===t.pid&&e.command===t.command&&e.startedAt===t.startedAt}function aN(e){try{let t=$h(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[0]==="Z"}catch{return!1}}function cN(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return!aN(e)}function lN(e,t=rN){if(!nN(e))return!1;try{return t("flock",["-n",e,"-c","true"],{stdio:"ignore"}),!1}catch(r){if((r&&typeof r=="object"?r.status:void 0)===1)return!0;let o=r instanceof Error?r.message:String(r);throw new Un(`heavy-lock probe failed (flock did not run or exited abnormally): ${o}`)}}function $l(e=Fn(),t=qn(),r=sN,n=lN,o=cN){for(let s=0;s<3;s++){let i=r(e),a=n(t),c=r(e);if(i!==null&&iN(i,c)){if(!a)return{held:!1,holder:null};if(o(i.pid))return{held:!0,holder:i}}}return{held:n(t),holder:null}}function lt(e=Fn(),t=qn(),r=$l,n){try{return r(e,t)}catch(o){if(!(o instanceof Un))throw o;return n?.(o),{held:!0,holder:null}}}var Oi={observedAt:null,report:null,lastErrorAt:null,lastError:null};function Rh(e,t){Oi={observedAt:t,report:e,lastErrorAt:null,lastError:null}}function Nh(e,t){Oi={...Oi,lastErrorAt:t,lastError:e}}function Bo(){return Oi}import{execFile as uN}from"node:child_process";import{promisify as dN}from"node:util";function me(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1e3)return"0s";if(e<6e4)return`${Math.floor(e/1e3)}s`;if(e<36e5)return`${Math.floor(e/6e4)}m`;if(e<864e5*2)return`${Math.floor(e/36e5)}h`;let t=Math.floor(e/864e5),r=Math.floor(e%864e5/36e5);return r===0?`${t}d`:`${t}d ${r}h`}function he(e,t=Date.now()){let r=Date.parse(e);if(Number.isNaN(r))return"?";let n=t-r;return n<6e4?"just now":`${me(n)} ago`}var mN=dN(uN);function fN(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return(typeof t.target=="string"||t.target===null)&&typeof t.from_identity=="string"}function pN(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!Array.isArray(t.running)||!Array.isArray(t.dead)||!Array.isArray(t.idle))throw new Error("unexpected `lmctl running --json` shape: missing running/dead/idle arrays");let r=t;for(let n of["running","dead","idle"])if(!r[n].every(fN))throw new Error(`unexpected \`lmctl running --json\` shape: a malformed element (bad/missing target or from_identity) in \`${n}\``);return r}async function Ae(e=3e4){let{stdout:t}=await mN("lmctl",["running","--json"],{timeout:e});return pN(t)}function kl(e,t=Date.now()){return{schema_version:e.schema_version,running:e.running.map(r=>({...r,running_for_human:me(r.running_for_ms),started_human:he(r.started_at,t)})),dead:e.dead.map(r=>({...r,stale_for_human:me(r.stale_for_ms),started_human:he(r.started_at,t)})),idle:e.idle.map(r=>({...r,ran_human:me(r.ran_ms)}))}}import{readFileSync as hN}from"node:fs";import{randomUUID as gN}from"node:crypto";var xl={staleThresholdMs:2*60*6e4,escalationCooldownMs:60*6e4,digestTimeoutMs:9e4,leaseTimeoutMs:10*6e4,providerQuotaBackoffMs:24*60*6e4,operatorStaleThresholdMs:6e4,operatorEscalationCooldownMs:6e4};function _N(e){return/usage limit/i.test(e)&&/quota/i.test(e)}function wN(e){let t=[];for(let r of e)try{t.push({row:r,content:hN(r.prompt_file,"utf8")})}catch{continue}return t}function yN(e){let t=e.map(({row:r,content:n})=>`--- from "${r.from_id}", queued ${r.created_ts} ---
306
+ WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts = ? AND running_systemd_unit = ?`).run("reconciled",o,t.id,t.revision,t.running_since_ts,t.running_systemd_unit),xl(e,t.id,"reconciled: command execution confirmed gone by systemd probe; no exit callback survived the restart");return}e.prepare("UPDATE cron_jobs SET last_fire_status = ?, updated_at = ? WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts = ?").run("skipped_overlap",o,t.id,t.revision,t.running_since_ts);return}let p=t.last_checked_ts!==null?Date.parse(t.last_checked_ts):Date.parse(t.created_at);if(p>n){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, last_fire_status = ?, last_fire_error = ?, updated_at = ?",[o,"error",`last_checked_ts (${t.last_checked_ts??t.created_at}) is after the current tick time -- checkpoint reset without firing`,o],t);return}let h=new Date(p),w=new Date(n);if(n-p>nN){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, last_fire_status = ?, updated_at = ?",[o,"skipped_stale",o],t);return}let _=t.timezone!==null?gh(h,t.timezone):h,T=t.timezone!==null?gh(w,t.timezone):w;if(!Xp(f,_,T)){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ?",[o,o],t);return}let v=Oi(e,t.id);if(!(v===null||v.enabled===0||v.revision!==t.revision)){if(tN(t.action_kind)){cN(e,t,o,l,u,d);return}if(t.action_kind==="enqueue")try{let S=JSON.parse(t.action_payload),N={from:S.from??"autopilot",dedupeKey:`cron:${t.id}:${h.toISOString()}`};e.transaction(()=>{let L=e.prepare("SELECT enabled, revision, last_checked_ts FROM cron_jobs WHERE id = ?").get(t.id);return L===void 0||L.enabled===0||L.revision!==t.revision||L.last_checked_ts!==t.last_checked_ts?!1:(s(e,r,S.to,S.prompt,N),e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(o,o,"ok",o,t.id),!0)}).immediate()&&l.push(t.title)}catch(S){try{u?.(t.id,S)}catch{}try{Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, updated_at = ?",["error",wt(S),o],t)}catch{}}else{let S=o,N=`lmcron-job-${t.id}-${S.replace(/[:.]/g,"-")}.scope`;if(e.prepare(`UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, running_since_ts = ?, running_systemd_unit = ?, updated_at = ?
307
+ WHERE id = ? AND enabled = 1 AND revision = ? AND (last_checked_ts IS ?) AND (running_since_ts IS ?)`).run(o,o,"ok",o,N,o,t.id,t.revision,t.last_checked_ts,t.running_since_ts).changes===0)return;let L=$h(e,t,t.action_kind,N,a),R={logDir:c,systemdUnitName:N,onExit:(H,C,g,y)=>{let x=H===0?"ok":"error",P=x==="ok"?null:C?wt(C):`Command exited with code ${H} -- see ${c??xi()}/${t.id}/ for output`;if(C)try{u?.(t.id,C)}catch{}try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = ?, updated_at = ? WHERE id = ? AND running_since_ts = ?").run(x,P,new Date().toISOString(),t.id,S)}catch{}xh(e,L,H,C,g,y,N)}};try{i({id:t.id,action_payload:t.action_payload},R),l.push(t.title)}catch(H){try{u?.(t.id,H)}catch{}try{e.prepare("UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, running_since_ts = NULL, running_systemd_unit = NULL, updated_at = ? WHERE id = ? AND running_since_ts = ?").run("error",wt(H),o,t.id,S)}catch{}Rh(e,L,H)}}}}async function _h(e,t){for(;!e();)await new Promise(r=>setTimeout(r,t))}async function Vo(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Do,i=n.isUnitStillRunningImpl??Ah,a=n.executeRunImpl??$l,c=n.logDir,l=n.pollMs??250,u=Le(e,t);if(u.enabled===0)throw new U("DISABLED",`Cron job ${t} is disabled -- enable it first (\`cron enable ${t}\`), or a manual trigger would silently exercise a job the operator turned off on purpose`,4);let d=de();if(u.action_kind==="command"){if(u.running_since_ts!==null)return u.running_systemd_unit!==null&&i(u.running_systemd_unit)==="confirmed-gone"?(e.prepare(`UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = NULL, updated_at = ?
308
+ WHERE id = ? AND revision = ? AND running_since_ts = ? AND running_systemd_unit = ?`).run("reconciled",d,u.id,u.revision,u.running_since_ts,u.running_systemd_unit),xl(e,u.id,"reconciled: command execution confirmed gone by systemd probe; no exit callback survived the restart"),await Vo(e,t,r,n)):{kind:"skipped_overlap",job:u};let p=d,h=`lmcron-job-${u.id}-${p.replace(/[:.]/g,"-")}-manual.scope`;if(e.prepare(`UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, running_since_ts = ?, running_systemd_unit = ?, updated_at = ?
309
+ WHERE id = ? AND enabled = 1 AND revision = ? AND running_since_ts IS ?`).run(d,"ok",p,h,d,u.id,u.revision,u.running_since_ts).changes===0)return{kind:"skipped_overlap",job:Le(e,t)};let _=$h(e,u,`${u.action_kind}:manual`,h,i),T={logDir:c,systemdUnitName:h,onExit:(E,v,S,N)=>{let $=E===0?"ok":"error",L=$==="ok"?null:v?wt(v):`Command exited with code ${E} -- see ${c??xi()}/${u.id}/ for output`;try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL, last_fire_status = ?, last_fire_error = ?, updated_at = ? WHERE id = ? AND running_since_ts = ?").run($,L,new Date().toISOString(),u.id,p)}catch{}xh(e,_,E,v,S,N,h)}};try{s({id:u.id,action_payload:u.action_payload},T)}catch(E){Rh(e,_,E);try{e.prepare("UPDATE cron_jobs SET last_fire_status = ?, last_fire_error = ?, running_since_ts = NULL, running_systemd_unit = NULL, updated_at = ? WHERE id = ? AND running_since_ts = ?").run("error",wt(E),d,u.id,p)}catch{}throw new U("SPAWN_FAILED",`manual trigger of job ${t} failed to spawn: ${wt(E)}`,1)}return await _h(()=>Le(e,t).running_since_ts!==p,l),{kind:"fired",job:Le(e,t)}}if(u.action_kind==="enqueue"){let p=JSON.parse(u.action_payload);return o(e,r,p.to,p.prompt,{from:p.from??"autopilot"}),e.prepare("UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(d,"ok",d,u.id),{kind:"fired",job:Le(e,t)}}let m=JSON.stringify({kind:u.action_kind,payload:u.action_payload,provider:u.provider,model:u.model,workingDirectory:u.working_directory,escalationOwner:u.escalation_owner}),f=e.transaction(()=>{let p=e.prepare("SELECT enabled, revision FROM cron_jobs WHERE id = ?").get(u.id);if(p===void 0||p.enabled===0||p.revision!==u.revision)return null;let h=qo(e,u.id,`${u.action_kind}:manual`,m);return h.kind==="claimed"&&e.prepare("UPDATE cron_jobs SET last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(d,"ok",d,u.id),h}).immediate();if(f===null)throw new U("CONFLICT",`Cron job ${t} was modified concurrently -- re-run \`cron trigger ${t}\``,5);if(f.kind==="escalation")return{kind:"blocked_escalation",job:Le(e,t)};if(f.kind==="overlap")return{kind:"skipped_overlap",job:Le(e,t)};try{a({db:e,job:u,run:f.run,runToken:f.token,...n.runSpawnPrefixes!==void 0?{spawnPrefixes:n.runSpawnPrefixes}:{},...n.sessionDir!==void 0?{sessionDir:n.sessionDir}:{},...n.runTimeoutMs!==void 0?{timeoutMs:n.runTimeoutMs}:{},...n.runSeedTimeoutMs!==void 0?{seedTimeoutMs:n.runSeedTimeoutMs}:{}})}catch(p){try{Ho(e,f.run.id,`worker dispatch threw: ${wt(p)}`),yl(e,f.run.id,{ok:!1,summary:`worker dispatch error: ${wt(p)}`})}catch{}throw new U("SPAWN_FAILED",`manual trigger of job ${t} failed to dispatch: ${wt(p)}`,1)}return n.waitForCompletion===!1?{kind:"fired",job:Le(e,t),runId:f.run.id}:(await _h(()=>{let p=ze(e,f.run.id);return p.status!=="pending"&&p.status!=="running"},l),{kind:"fired",job:Le(e,t),runId:f.run.id})}function cN(e,t,r,n,o,s){let i=JSON.stringify({kind:t.action_kind,payload:t.action_payload,provider:t.provider,model:t.model,workingDirectory:t.working_directory,escalationOwner:t.escalation_owner}),a=e.transaction(()=>{let c=e.prepare("SELECT enabled, revision, last_checked_ts FROM cron_jobs WHERE id = ?").get(t.id);if(c===void 0||c.enabled===0||c.revision!==t.revision||c.last_checked_ts!==t.last_checked_ts)return null;let l=qo(e,t.id,t.action_kind,i);return l.kind==="claimed"&&e.prepare("UPDATE cron_jobs SET last_checked_ts = ?, last_fired_ts = ?, last_fire_status = ?, last_fire_error = NULL, updated_at = ? WHERE id = ?").run(r,r,"ok",r,t.id),l}).immediate();if(a!==null){if(a.kind==="escalation"){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, updated_at = ?",["blocked_escalation",r],t);return}if(a.kind==="overlap"){Nr(e,"UPDATE cron_jobs SET last_fire_status = ?, updated_at = ?",["skipped_overlap",r],t);return}n.push(t.title);try{s.executeRunImpl({db:e,job:t,run:a.run,runToken:a.token,...s.runSpawnPrefixes!==void 0?{spawnPrefixes:s.runSpawnPrefixes}:{},...s.sessionDir!==void 0?{sessionDir:s.sessionDir}:{},...s.runTimeoutMs!==void 0?{timeoutMs:s.runTimeoutMs}:{},...s.runSeedTimeoutMs!==void 0?{seedTimeoutMs:s.runSeedTimeoutMs}:{}})}catch(c){try{Ho(e,a.run.id,`worker dispatch threw: ${wt(c)}`),yl(e,a.run.id,{ok:!1,summary:`worker dispatch error: ${wt(c)}`})}catch{}try{o?.(t.id,c)}catch{}}}}function Nr(e,t,r,n){e.prepare(`${t} WHERE id = ? AND enabled = 1 AND revision = ? AND (last_checked_ts IS ?)`).run(...r,n.id,n.revision,n.last_checked_ts)}function Nh(e,t){let r=e.transaction(()=>{Le(e,t);try{e.prepare("UPDATE cron_jobs SET running_since_ts = NULL, running_systemd_unit = NULL WHERE id = ?").run(t)}catch(n){Un(n)}return Ci(e,t),Le(e,t)});return ur(r)}import{execFileSync as lN}from"node:child_process";import{existsSync as uN,readFileSync as Lh}from"node:fs";import{homedir as Ih}from"node:os";import{join as Ch}from"node:path";function jn(){return process.env.LMBEE_HEAVY_STATUS??Ch(Ih(),".lmbee","heavy.status")}function Hn(){return process.env.LMBEE_HEAVY_LOCK??Ch(Ih(),".lmbee","heavy.lock")}var qn=class extends Error{};function dN(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.holder=="string"&&typeof t.pid=="number"&&typeof t.command=="string"&&typeof t.startedAt=="string"}function mN(e){let t;try{t=Lh(e,"utf8")}catch{return null}try{let r=JSON.parse(t);return dN(r)?r:null}catch{return null}}function fN(e,t){return e===null||t===null?e===t:e.holder===t.holder&&e.pid===t.pid&&e.command===t.command&&e.startedAt===t.startedAt}function pN(e){try{let t=Lh(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[0]==="Z"}catch{return!1}}function hN(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return!pN(e)}function gN(e,t=lN){if(!uN(e))return!1;try{return t("flock",["-n",e,"-c","true"],{stdio:"ignore"}),!1}catch(r){if((r&&typeof r=="object"?r.status:void 0)===1)return!0;let o=r instanceof Error?r.message:String(r);throw new qn(`heavy-lock probe failed (flock did not run or exited abnormally): ${o}`)}}function Rl(e=jn(),t=Hn(),r=mN,n=gN,o=hN){for(let s=0;s<3;s++){let i=r(e),a=n(t),c=r(e);if(i!==null&&fN(i,c)){if(!a)return{held:!1,holder:null};if(o(i.pid))return{held:!0,holder:i}}}return{held:n(t),holder:null}}function lt(e=jn(),t=Hn(),r=Rl,n){try{return r(e,t)}catch(o){if(!(o instanceof qn))throw o;return n?.(o),{held:!0,holder:null}}}var Pi={observedAt:null,report:null,lastErrorAt:null,lastError:null};function Oh(e,t){Pi={observedAt:t,report:e,lastErrorAt:null,lastError:null}}function Dh(e,t){Pi={...Pi,lastErrorAt:t,lastError:e}}function Jo(){return Pi}import{execFile as _N}from"node:child_process";import{promisify as wN}from"node:util";function me(e){if(!Number.isFinite(e)||e<0)return"?";if(e<1e3)return"0s";if(e<6e4)return`${Math.floor(e/1e3)}s`;if(e<36e5)return`${Math.floor(e/6e4)}m`;if(e<864e5*2)return`${Math.floor(e/36e5)}h`;let t=Math.floor(e/864e5),r=Math.floor(e%864e5/36e5);return r===0?`${t}d`:`${t}d ${r}h`}function he(e,t=Date.now()){let r=Date.parse(e);if(Number.isNaN(r))return"?";let n=t-r;return n<6e4?"just now":`${me(n)} ago`}var yN=wN(_N);function EN(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return(typeof t.target=="string"||t.target===null)&&typeof t.from_identity=="string"}function TN(e){let t=JSON.parse(e);if(typeof t!="object"||t===null||!Array.isArray(t.running)||!Array.isArray(t.dead)||!Array.isArray(t.idle))throw new Error("unexpected `lmctl running --json` shape: missing running/dead/idle arrays");let r=t;for(let n of["running","dead","idle"])if(!r[n].every(EN))throw new Error(`unexpected \`lmctl running --json\` shape: a malformed element (bad/missing target or from_identity) in \`${n}\``);return r}async function Ae(e=3e4){let{stdout:t}=await yN("lmctl",["running","--json"],{timeout:e});return TN(t)}function Nl(e,t=Date.now()){return{schema_version:e.schema_version,running:e.running.map(r=>({...r,running_for_human:me(r.running_for_ms),started_human:he(r.started_at,t)})),dead:e.dead.map(r=>({...r,stale_for_human:me(r.stale_for_ms),started_human:he(r.started_at,t)})),idle:e.idle.map(r=>({...r,ran_human:me(r.ran_ms)}))}}import{readFileSync as bN}from"node:fs";import{randomUUID as SN}from"node:crypto";var Ll={staleThresholdMs:2*60*6e4,escalationCooldownMs:60*6e4,digestTimeoutMs:9e4,leaseTimeoutMs:10*6e4,providerQuotaBackoffMs:24*60*6e4,operatorStaleThresholdMs:6e4,operatorEscalationCooldownMs:6e4};function vN(e){return/usage limit/i.test(e)&&/quota/i.test(e)}function AN(e){let t=[];for(let r of e)try{t.push({row:r,content:bN(r.prompt_file,"utf8")})}catch{continue}return t}function kN(e){let t=e.map(({row:r,content:n})=>`--- from "${r.from_id}", queued ${r.created_ts} ---
310
310
  ${n}`);return`You have ${e.length} queued message(s) that couldn't be delivered automatically (presence-gated for a while) -- bundled here as a digest:
311
311
 
312
312
  ${t.join(`
313
313
 
314
- `)}`}function EN(e,t,r){let n=new Date(r-t).toISOString();e.prepare(`UPDATE queue SET status = 'pending', escalation_claimed_ts = NULL, escalation_claim_token = NULL
315
- WHERE status = 'escalating' AND (escalation_claimed_ts IS NULL OR escalation_claimed_ts < ?)`).run(n)}function TN(e,t){let r=new Set,n=new Date().toISOString(),o=gN();return e.transaction(()=>{for(let i of t)e.prepare("UPDATE queue SET status = 'escalating', escalation_claimed_ts = ?, escalation_claim_token = ? WHERE id = ? AND status = 'pending'").run(n,o,i).changes>0&&r.add(i)}).immediate(),{claimed:r,token:o}}function Di(e,t,r,n,o){let s=new Date().toISOString(),i=!1;e.transaction(()=>{for(let c of t)(n?e.prepare(`UPDATE queue SET status = 'sent', sent_ts = ?, delivered_via_escalation = 1, escalation_claimed_ts = NULL, escalation_claim_token = NULL
314
+ `)}`}function $N(e,t,r){let n=new Date(r-t).toISOString();e.prepare(`UPDATE queue SET status = 'pending', escalation_claimed_ts = NULL, escalation_claim_token = NULL
315
+ WHERE status = 'escalating' AND (escalation_claimed_ts IS NULL OR escalation_claimed_ts < ?)`).run(n)}function xN(e,t){let r=new Set,n=new Date().toISOString(),o=SN();return e.transaction(()=>{for(let i of t)e.prepare("UPDATE queue SET status = 'escalating', escalation_claimed_ts = ?, escalation_claim_token = ? WHERE id = ? AND status = 'pending'").run(n,o,i).changes>0&&r.add(i)}).immediate(),{claimed:r,token:o}}function Ui(e,t,r,n,o){let s=new Date().toISOString(),i=!1;e.transaction(()=>{for(let c of t)(n?e.prepare(`UPDATE queue SET status = 'sent', sent_ts = ?, delivered_via_escalation = 1, escalation_claimed_ts = NULL, escalation_claim_token = NULL
316
316
  WHERE id = ? AND status = 'escalating' AND escalation_claim_token = ?`).run(s,c,r):e.prepare(`UPDATE queue SET status = 'pending', escalation_claimed_ts = NULL, escalation_claim_token = NULL
317
- WHERE id = ? AND status = 'escalating' AND escalation_claim_token = ?`).run(c,r)).changes>0&&(i=!0);i&&o?.()}).immediate()}async function Ih(e,t,r=xl,n=Date.now(),o={}){let s=o.sendAwaited??Ht,i=[];EN(e,r.leaseTimeoutMs,n);let a=e.prepare("SELECT * FROM queue WHERE status = 'pending' ORDER BY to_id, id").all(),c=new Map;for(let u of a){let d=c.get(u.to_id);d?d.push(u):c.set(u.to_id,[u])}let l=[...c.entries()].sort(([,u],[,d])=>{let m=u.some(p=>p.operator_priority===1)?0:1,f=d.some(p=>p.operator_priority===1)?0:1;return m-f});for(let[u,d]of l){let m=t.find(C=>C.name===u);if(m===void 0)continue;let f=d.some(C=>C.operator_priority===1),p=f?r.operatorStaleThresholdMs:r.staleThresholdMs,h=f?r.operatorEscalationCooldownMs:r.escalationCooldownMs,w=d[0];if(n-Date.parse(w.created_ts)<p)continue;let E=ie(e,u),T=E?.last_escalation_attempt_ts?Date.parse(E.last_escalation_attempt_ts):null;if(T!==null&&n-T<h)continue;let v=E?.quota_exhausted_last_seen_ts?Date.parse(E.quota_exhausted_last_seen_ts):null;if(v!==null){let C=T!==null?Math.max(v,T):v;if(n-C<r.providerQuotaBackoffMs)continue}if(Ps(e,u,m.leadAlias,n))continue;let S;try{S=Q(m)}catch{continue}let N=wN(d);if(N.length===0)continue;let{claimed:x,token:I}=TN(e,N.map(C=>C.row.id)),k=N.filter(C=>x.has(C.row.id));if(k.length===0)continue;let B=!1;try{let C=yN(k);im(e,u,new Date().toISOString());let g=await s({teamfilePath:S,alias:m.leadAlias},C,{timeoutMs:r.digestTimeoutMs});if(g.kind==="ok"||g.kind==="stalled")Di(e,x,I,!0,()=>sm(e,u)),B=!0,i.push(u);else if(g.kind==="error"&&_N(g.message)){let y=new Date().toISOString();Di(e,x,I,!1,()=>om(e,u,y,g.message)),B=!0}else Di(e,x,I,!1),B=!0}catch{}finally{if(!B)try{Di(e,x,I,!1)}catch{}}}return i}var Rl={minStaleMs:12e5,maxTotalAgeMs:144e5};function Lh(e,t,r=Rl,n=Date.now()){return[]}var Nl={staleMs:72e5,maxAgeMs:864e5,cooldownMs:36e5};function Ch(e,t,r,n=Nl,o=Date.now()){return[]}import{execFile as $N}from"node:child_process";import{promisify as kN}from"node:util";var bN=["ok","provider_unavailable","auth_expired","not_applicable","reader_throttled"];function SN(e){return typeof e=="string"&&bN.includes(e)}function Il(e){return typeof e=="object"&&e!==null}function vN(e){if(!Il(e))return null;let t=e.bucket_id,r=e.used_fraction;if(typeof t!="string"||t.length===0||typeof r!="number"||!Number.isFinite(r))return null;let n={bucket_id:t,used_fraction:r};return typeof e.window_type=="string"&&(n.window_type=e.window_type),typeof e.group_name=="string"&&(n.group_name=e.group_name),typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&(n.resets_at=e.resets_at),typeof e.resets_at_iso=="string"&&(n.resets_at_iso=e.resets_at_iso),typeof e.is_exhausted=="boolean"&&(n.is_exhausted=e.is_exhausted),"raw_value"in e&&(n.raw_value=e.raw_value),typeof e.raw_scale=="string"&&(n.raw_scale=e.raw_scale),n}function AN(e){if(!Il(e))return null;let t=e.provider,r=e.status,n=e.read_at;if(typeof t!="string"||t.length===0||!SN(r)||typeof n!="number"||!Number.isFinite(n))return null;let o={provider:t,status:r,read_at:n};return typeof e.source=="string"&&(o.source=e.source),Array.isArray(e.buckets)&&(o.buckets=e.buckets.map(vN).filter(s=>s!==null)),typeof e.reason=="string"&&(o.reason=e.reason),typeof e.detail=="string"&&(o.detail=e.detail),typeof e.retry_after_seconds=="number"&&(o.retry_after_seconds=e.retry_after_seconds),o}function Oh(e){let t;try{t=JSON.parse(e)}catch{return null}return!Il(t)||!Array.isArray(t.readings)?null:t.readings.map(AN).filter(r=>r!==null)}var xN=kN($N);function Dh(){return process.env.LMBEE_RATE_LIMIT_BIN??"lmctl"}async function RN(e=Dh(),t=xN){try{let{stdout:r}=await t(e,["ratelimit","--json"]);return Oh(r)}catch{return null}}function NN(e){return e==null?null:typeof e=="string"?e:JSON.stringify(e)}function IN(e,t,r){let n=e.prepare(`INSERT INTO rate_limit_readings (provider, status, source, read_at, reason, detail, retry_after_seconds, inserted_at)
317
+ WHERE id = ? AND status = 'escalating' AND escalation_claim_token = ?`).run(c,r)).changes>0&&(i=!0);i&&o?.()}).immediate()}async function Mh(e,t,r=Ll,n=Date.now(),o={}){let s=o.sendAwaited??Ht,i=[];$N(e,r.leaseTimeoutMs,n);let a=e.prepare("SELECT * FROM queue WHERE status = 'pending' ORDER BY to_id, id").all(),c=new Map;for(let u of a){let d=c.get(u.to_id);d?d.push(u):c.set(u.to_id,[u])}let l=[...c.entries()].sort(([,u],[,d])=>{let m=u.some(p=>p.operator_priority===1)?0:1,f=d.some(p=>p.operator_priority===1)?0:1;return m-f});for(let[u,d]of l){let m=t.find(C=>C.name===u);if(m===void 0)continue;let f=d.some(C=>C.operator_priority===1),p=f?r.operatorStaleThresholdMs:r.staleThresholdMs,h=f?r.operatorEscalationCooldownMs:r.escalationCooldownMs,w=d[0];if(n-Date.parse(w.created_ts)<p)continue;let T=ie(e,u),E=T?.last_escalation_attempt_ts?Date.parse(T.last_escalation_attempt_ts):null;if(E!==null&&n-E<h)continue;let v=T?.quota_exhausted_last_seen_ts?Date.parse(T.quota_exhausted_last_seen_ts):null;if(v!==null){let C=E!==null?Math.max(v,E):v;if(n-C<r.providerQuotaBackoffMs)continue}if(js(e,u,m.leadAlias,n))continue;let S;try{S=Q(m)}catch{continue}let N=AN(d);if(N.length===0)continue;let{claimed:$,token:L}=xN(e,N.map(C=>C.row.id)),R=N.filter(C=>$.has(C.row.id));if(R.length===0)continue;let H=!1;try{let C=kN(R);lm(e,u,new Date().toISOString());let g=await s({teamfilePath:S,alias:m.leadAlias},C,{timeoutMs:r.digestTimeoutMs});if(g.kind==="ok"||g.kind==="stalled")Ui(e,$,L,!0,()=>cm(e,u)),H=!0,i.push(u);else if(g.kind==="error"&&vN(g.message)){let y=new Date().toISOString();Ui(e,$,L,!1,()=>am(e,u,y,g.message)),H=!0}else Ui(e,$,L,!1),H=!0}catch{}finally{if(!H)try{Ui(e,$,L,!1)}catch{}}}return i}var Il={minStaleMs:12e5,maxTotalAgeMs:144e5};function Ph(e,t,r=Il,n=Date.now()){return[]}var Cl={staleMs:72e5,maxAgeMs:864e5,cooldownMs:36e5};function Uh(e,t,r,n=Cl,o=Date.now()){return[]}import{execFile as CN}from"node:child_process";import{promisify as ON}from"node:util";var RN=["ok","provider_unavailable","auth_expired","not_applicable","reader_throttled"];function NN(e){return typeof e=="string"&&RN.includes(e)}function Ol(e){return typeof e=="object"&&e!==null}function LN(e){if(!Ol(e))return null;let t=e.bucket_id,r=e.used_fraction;if(typeof t!="string"||t.length===0||typeof r!="number"||!Number.isFinite(r))return null;let n={bucket_id:t,used_fraction:r};return typeof e.window_type=="string"&&(n.window_type=e.window_type),typeof e.group_name=="string"&&(n.group_name=e.group_name),typeof e.resets_at=="number"&&Number.isFinite(e.resets_at)&&(n.resets_at=e.resets_at),typeof e.resets_at_iso=="string"&&(n.resets_at_iso=e.resets_at_iso),typeof e.is_exhausted=="boolean"&&(n.is_exhausted=e.is_exhausted),"raw_value"in e&&(n.raw_value=e.raw_value),typeof e.raw_scale=="string"&&(n.raw_scale=e.raw_scale),n}function IN(e){if(!Ol(e))return null;let t=e.provider,r=e.status,n=e.read_at;if(typeof t!="string"||t.length===0||!NN(r)||typeof n!="number"||!Number.isFinite(n))return null;let o={provider:t,status:r,read_at:n};return typeof e.source=="string"&&(o.source=e.source),Array.isArray(e.buckets)&&(o.buckets=e.buckets.map(LN).filter(s=>s!==null)),typeof e.reason=="string"&&(o.reason=e.reason),typeof e.detail=="string"&&(o.detail=e.detail),typeof e.retry_after_seconds=="number"&&(o.retry_after_seconds=e.retry_after_seconds),o}function Fh(e){let t;try{t=JSON.parse(e)}catch{return null}return!Ol(t)||!Array.isArray(t.readings)?null:t.readings.map(IN).filter(r=>r!==null)}var DN=ON(CN);function qh(){return process.env.LMBEE_RATE_LIMIT_BIN??"lmctl"}async function MN(e=qh(),t=DN){try{let{stdout:r}=await t(e,["ratelimit","--json"]);return Fh(r)}catch{return null}}function PN(e){return e==null?null:typeof e=="string"?e:JSON.stringify(e)}function UN(e,t,r){let n=e.prepare(`INSERT INTO rate_limit_readings (provider, status, source, read_at, reason, detail, retry_after_seconds, inserted_at)
318
318
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.provider,t.status,t.source??null,t.read_at,t.reason??null,t.detail??null,t.retry_after_seconds??null,r);if(t.status!=="ok")return;let o=n.lastInsertRowid,s=e.prepare(`INSERT INTO rate_limit_bucket_samples
319
319
  (reading_id, provider, bucket_id, window_type, group_name, used_fraction, resets_at, resets_at_iso, raw_value, raw_scale, is_exhausted, read_at)
320
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let i of t.buckets??[]){if(typeof i.resets_at!="number")continue;let a=i.window_type==="five_hour"||i.window_type==="weekly"?i.window_type:"unknown";s.run(o,t.provider,i.bucket_id,a,i.group_name??null,i.used_fraction??0,i.resets_at,i.resets_at_iso??null,NN(i.raw_value),i.raw_scale??null,i.is_exhausted===!0?1:i.is_exhausted===!1?0:null,t.read_at)}}var Mh="rate_limit_collect:last_run_ms",LN=5*6e4;function CN(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(Mh);if(n===void 0)return!0;let o=Number(n.v);return Number.isFinite(o)?t-o>=r:!0}function ON(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Mh,String(t))}async function Ph(e,t={}){let r=t.nowMs??Date.now(),n=t.cooldownMs??LN;if(!CN(e,r,n))return{outcome:"skipped-cooldown"};let s=await(t.fetchImpl??RN)(t.binPath??Dh());if(s===null)return{outcome:"fetch-failed"};let i=Math.floor(r/1e3);return e.transaction(c=>{for(let l of c)IN(e,l,i)})(s),ON(e,r),{outcome:"collected",readingsStored:s.length}}var Ll={five_hour:9e5,weekly:36e5},Mi={five_hour:"five_hour_15m",weekly:"weekly_1h"};function Pi(e,t){if(e.length<3)return{kind:"insufficient_data",reason:`only ${e.length} sample(s), need >= 3`};let r=[...e].sort((_,E)=>_.readAt-E.readAt),n=r[0],o=r[r.length-1],s=(o.readAt-n.readAt)*1e3;if(s<6e5)return{kind:"insufficient_data",reason:`samples span only ${Math.round(s/1e3)}s, need >= ${6e5/1e3}s`};let i=t-o.readAt*1e3;if(i>9e5)return{kind:"insufficient_data",reason:`freshest sample is ${Math.round(i/1e3)}s old, exceeds ${9e5/1e3}s staleness limit`};let a=r.length,c=r.reduce((_,E)=>_+E.readAt,0)/a,l=r.reduce((_,E)=>_+E.usedFraction,0)/a,u=0,d=0;for(let _ of r){let E=_.readAt-c;u+=E*(_.usedFraction-l),d+=E*E}if(d===0)return{kind:"insufficient_data",reason:"samples have no time spread"};let m=u/d;if(m<=0)return{kind:"no_forecast"};let h=(1-(l-m*c+m*o.readAt))/m;return{kind:"forecast",forecastAtMs:o.readAt*1e3+h*1e3,burnFractionPerMin:m*60,latestReadAtMs:o.readAt*1e3}}function Uh(e,t,r){return e.kind!=="forecast"?!1:e.forecastAtMs-r<=Ll[t]}var DN=new Set(["claude:week-scoped-Fable","codex:codex_bengalfox-5h","codex:codex_bengalfox-weekly"]);function Fh(e,t){return DN.has(`${e}:${t}`)}var MN=Ll.weekly;function PN(e){let t=[...e].sort((o,s)=>o.readAt-s.readAt),r=t[0],n=t[t.length-1];return{count:t.length,spanMinutes:Math.round((n.readAt-r.readAt)/60*10)/10,latestUsedFraction:n.usedFraction}}function UN(e){return new Date(e*1e3).toISOString()}function FN(e,t,r,n,o,s){let i=new Date(n.forecastAtMs).toISOString(),a=Math.round((n.forecastAtMs-s)/6e4),c=Math.round(n.burnFractionPerMin*100*100)/100;return`auto-disable: ${e} bucket=${t} (${r}) forecast reaches 100% at ${i} (~${a}m); burn rate ${c}%/min over ${o.count} samples spanning ${o.spanMinutes}m; current used_fraction=${o.latestUsedFraction}; rule=${Mi[r]}`}function jn(e,t,r,n,o,s,i){e.prepare("INSERT INTO rate_limit_policy_log (ts, provider, bucket_id, window_type, outcome, detail) VALUES (?, ?, ?, ?, ?, ?)").run(t,r,n,o,s,i)}function Ui(e,t,r,n){e.prepare("DELETE FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at = ?").run(t,r,n)}function qN(e,t,r,n){return e.prepare("SELECT rule, armed_at, armed_latest_read_at, armed_used_fraction, forecast_at FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at = ?").get(t,r,n)??null}function jN(e,t,r,n,o,s,i,a,c){e.prepare(`INSERT INTO rate_limit_policy_arm (provider, bucket_id, resets_at, rule, armed_at, armed_latest_read_at, armed_used_fraction, forecast_at)
320
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);for(let i of t.buckets??[]){if(typeof i.resets_at!="number")continue;let a=i.window_type==="five_hour"||i.window_type==="weekly"?i.window_type:"unknown";s.run(o,t.provider,i.bucket_id,a,i.group_name??null,i.used_fraction??0,i.resets_at,i.resets_at_iso??null,PN(i.raw_value),i.raw_scale??null,i.is_exhausted===!0?1:i.is_exhausted===!1?0:null,t.read_at)}}var jh="rate_limit_collect:last_run_ms",FN=5*6e4;function qN(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(jh);if(n===void 0)return!0;let o=Number(n.v);return Number.isFinite(o)?t-o>=r:!0}function jN(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(jh,String(t))}async function Hh(e,t={}){let r=t.nowMs??Date.now(),n=t.cooldownMs??FN;if(!qN(e,r,n))return{outcome:"skipped-cooldown"};let s=await(t.fetchImpl??MN)(t.binPath??qh());if(s===null)return{outcome:"fetch-failed"};let i=Math.floor(r/1e3);return e.transaction(c=>{for(let l of c)UN(e,l,i)})(s),jN(e,r),{outcome:"collected",readingsStored:s.length}}var Dl={five_hour:9e5,weekly:36e5},Fi={five_hour:"five_hour_15m",weekly:"weekly_1h"};function qi(e,t){if(e.length<3)return{kind:"insufficient_data",reason:`only ${e.length} sample(s), need >= 3`};let r=[...e].sort((_,T)=>_.readAt-T.readAt),n=r[0],o=r[r.length-1],s=(o.readAt-n.readAt)*1e3;if(s<6e5)return{kind:"insufficient_data",reason:`samples span only ${Math.round(s/1e3)}s, need >= ${6e5/1e3}s`};let i=t-o.readAt*1e3;if(i>9e5)return{kind:"insufficient_data",reason:`freshest sample is ${Math.round(i/1e3)}s old, exceeds ${9e5/1e3}s staleness limit`};let a=r.length,c=r.reduce((_,T)=>_+T.readAt,0)/a,l=r.reduce((_,T)=>_+T.usedFraction,0)/a,u=0,d=0;for(let _ of r){let T=_.readAt-c;u+=T*(_.usedFraction-l),d+=T*T}if(d===0)return{kind:"insufficient_data",reason:"samples have no time spread"};let m=u/d;if(m<=0)return{kind:"no_forecast"};let h=(1-(l-m*c+m*o.readAt))/m;return{kind:"forecast",forecastAtMs:o.readAt*1e3+h*1e3,burnFractionPerMin:m*60,latestReadAtMs:o.readAt*1e3}}function Bh(e,t,r){return e.kind!=="forecast"?!1:e.forecastAtMs-r<=Dl[t]}var HN=new Set(["claude:week-scoped-Fable","codex:codex_bengalfox-5h","codex:codex_bengalfox-weekly"]);function Wh(e,t){return HN.has(`${e}:${t}`)}var BN=Dl.weekly;function WN(e){let t=[...e].sort((o,s)=>o.readAt-s.readAt),r=t[0],n=t[t.length-1];return{count:t.length,spanMinutes:Math.round((n.readAt-r.readAt)/60*10)/10,latestUsedFraction:n.usedFraction}}function GN(e){return new Date(e*1e3).toISOString()}function VN(e,t,r,n,o,s){let i=new Date(n.forecastAtMs).toISOString(),a=Math.round((n.forecastAtMs-s)/6e4),c=Math.round(n.burnFractionPerMin*100*100)/100;return`auto-disable: ${e} bucket=${t} (${r}) forecast reaches 100% at ${i} (~${a}m); burn rate ${c}%/min over ${o.count} samples spanning ${o.spanMinutes}m; current used_fraction=${o.latestUsedFraction}; rule=${Fi[r]}`}function Bn(e,t,r,n,o,s,i){e.prepare("INSERT INTO rate_limit_policy_log (ts, provider, bucket_id, window_type, outcome, detail) VALUES (?, ?, ?, ?, ?, ?)").run(t,r,n,o,s,i)}function ji(e,t,r,n){e.prepare("DELETE FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at = ?").run(t,r,n)}function JN(e,t,r,n){return e.prepare("SELECT rule, armed_at, armed_latest_read_at, armed_used_fraction, forecast_at FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at = ?").get(t,r,n)??null}function KN(e,t,r,n,o,s,i,a,c){e.prepare(`INSERT INTO rate_limit_policy_arm (provider, bucket_id, resets_at, rule, armed_at, armed_latest_read_at, armed_used_fraction, forecast_at)
321
321
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
322
322
  ON CONFLICT(provider, bucket_id, resets_at) DO UPDATE SET
323
323
  rule = excluded.rule, armed_at = excluded.armed_at, armed_latest_read_at = excluded.armed_latest_read_at,
324
- armed_used_fraction = excluded.armed_used_fraction, forecast_at = excluded.forecast_at`).run(t,r,n,o,s,i,a,c)}function qh(e,t={}){let r=t.nowMs??Date.now(),n=t.dryRun??!0,o=t.checkProviderDisabledImpl??rt,s=t.setProviderDisableImpl??yi,i=e.prepare("SELECT DISTINCT provider, bucket_id AS bucketId, window_type AS windowType FROM rate_limit_bucket_samples WHERE window_type IN ('five_hour', 'weekly')").all(),a=[];for(let{provider:c,bucketId:l,windowType:u}of i){if(Fh(c,l)){a.push({provider:c,bucketId:l,windowType:u,outcome:"excluded-non-representative",detail:"scoped sub-limit or retired bucket -- never independently disable-eligible"});continue}let m=e.prepare("SELECT MAX(resets_at) AS resetsAt FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ?").get(c,l).resetsAt;if(m===null)continue;let f=e.prepare("SELECT resets_at AS resetsAt, rule FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at != ?").all(c,l,m);for(let I of f)Ui(e,c,l,I.resetsAt),jn(e,r,c,l,u,"disarmed",`window rolled over (resets_at advanced from ${I.resetsAt} to ${m}) while armed under rule=${I.rule} -- orphaned arm swept, never confirmed`);let p=Math.floor((r-18e5)/1e3),h=e.prepare(`SELECT id AS readingId, used_fraction AS usedFraction, read_at AS readAt, resets_at_iso AS resetsAtIso
325
- FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ? AND resets_at = ? AND read_at >= ? ORDER BY read_at ASC`).all(c,l,m,p),w=h.map(I=>({readAt:I.readAt,usedFraction:I.usedFraction})),_=Pi(w,r);if(_.kind==="insufficient_data"){a.push({provider:c,bucketId:l,windowType:u,outcome:"insufficient-data",detail:_.reason});continue}let E=qN(e,c,l,m);if(_.kind==="no_forecast"||!Uh(_,u,r)){E!==null&&(Ui(e,c,l,m),jn(e,r,c,l,u,"disarmed",`forecast no longer crosses the ${Mi[u]} threshold`)),a.push({provider:c,bucketId:l,windowType:u,outcome:_.kind==="no_forecast"?"no-forecast":"below-threshold",detail:""});continue}let T=w[w.length-1].usedFraction;if(E===null){jN(e,c,l,m,Mi[u],r,_.latestReadAtMs,T,_.forecastAtMs);let I=`armed on first crossing, forecast ${new Date(_.forecastAtMs).toISOString()}`;jn(e,r,c,l,u,"armed",I),a.push({provider:c,bucketId:l,windowType:u,outcome:"armed",detail:I});continue}if(_.latestReadAtMs<=E.armed_latest_read_at){a.push({provider:c,bucketId:l,windowType:u,outcome:"still-armed",detail:"awaiting a newer sample to confirm"});continue}if(T<=E.armed_used_fraction){a.push({provider:c,bucketId:l,windowType:u,outcome:"still-armed",detail:`newer sample available (used_fraction=${T}) but no increase over the armed reference (${E.armed_used_fraction}) -- awaiting real movement to confirm`});continue}let v=o(e,c,r),S=PN(w),N=FN(c,l,u,_,S,r);if(v.disabled){let I=v.config?`reason=${JSON.stringify(v.config.reason)}, expiresAt=${v.config.expiresAt??"indefinite"}`:"fail-closed (read error)",k=`would have fired (${N}) but ${c} is already disabled (${I}) -- deferring, never shortening or overwriting an existing hold`;jn(e,r,c,l,u,"confirmed_deferred_existing_disable",k),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-deferred",detail:k});continue}if(n){Ui(e,c,l,m);let I=`would have fired (policy step is disabled -- collection only): ${N}`;jn(e,r,c,l,u,"confirmed_would_fire_policy_disabled",I),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-would-fire",detail:I});continue}let x=u==="weekly"?new Date(r+MN).toISOString():h[h.length-1]?.resetsAtIso??UN(m);s(e,c,{reason:N,expiresAt:x}),Ui(e,c,l,m),jn(e,r,c,l,u,"confirmed_fired",N),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-fired",detail:N})}return HN(e,r,a),a}var jh="rate_limit_policy_heartbeat";function HN(e,t,r){let n={};for(let s of r)n[s.outcome]=(n[s.outcome]??0)+1;let o={lastRunAtMs:t,seriesEvaluated:r.length,outcomeCounts:n};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(jh,JSON.stringify(o))}function qi(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(jh);if(t===void 0)return null;try{return JSON.parse(t.v)}catch{return null}}var BN=15*6e4;function Hh(e,t=Date.now(),r=BN){let n=e.prepare("SELECT MAX(read_at) AS readAt FROM rate_limit_bucket_samples").get();if(n.readAt===null||t-n.readAt*1e3>r)return null;let s=qi(e);if(s===null)return{status:"never-run",reason:"rate-limit policy has never completed an evaluation while collection is active",ageMs:1/0};let i=t-s.lastRunAtMs;return i>r?{status:"stale",reason:`rate-limit policy last ran ${Math.round(i/6e4)}m ago while collection is active`,ageMs:i}:null}var WN=.85;function Bh(e,t=WN){return e.prepare(`SELECT s.provider AS provider, s.bucket_id AS bucketId, s.window_type AS windowType, s.used_fraction AS usedFraction, s.resets_at_iso AS resetsAtIso
324
+ armed_used_fraction = excluded.armed_used_fraction, forecast_at = excluded.forecast_at`).run(t,r,n,o,s,i,a,c)}function Gh(e,t={}){let r=t.nowMs??Date.now(),n=t.dryRun??!0,o=t.checkProviderDisabledImpl??rt,s=t.setProviderDisableImpl??Si,i=e.prepare("SELECT DISTINCT provider, bucket_id AS bucketId, window_type AS windowType FROM rate_limit_bucket_samples WHERE window_type IN ('five_hour', 'weekly')").all(),a=[];for(let{provider:c,bucketId:l,windowType:u}of i){if(Wh(c,l)){a.push({provider:c,bucketId:l,windowType:u,outcome:"excluded-non-representative",detail:"scoped sub-limit or retired bucket -- never independently disable-eligible"});continue}let m=e.prepare("SELECT MAX(resets_at) AS resetsAt FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ?").get(c,l).resetsAt;if(m===null)continue;let f=e.prepare("SELECT resets_at AS resetsAt, rule FROM rate_limit_policy_arm WHERE provider = ? AND bucket_id = ? AND resets_at != ?").all(c,l,m);for(let L of f)ji(e,c,l,L.resetsAt),Bn(e,r,c,l,u,"disarmed",`window rolled over (resets_at advanced from ${L.resetsAt} to ${m}) while armed under rule=${L.rule} -- orphaned arm swept, never confirmed`);let p=Math.floor((r-18e5)/1e3),h=e.prepare(`SELECT id AS readingId, used_fraction AS usedFraction, read_at AS readAt, resets_at_iso AS resetsAtIso
325
+ FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ? AND resets_at = ? AND read_at >= ? ORDER BY read_at ASC`).all(c,l,m,p),w=h.map(L=>({readAt:L.readAt,usedFraction:L.usedFraction})),_=qi(w,r);if(_.kind==="insufficient_data"){a.push({provider:c,bucketId:l,windowType:u,outcome:"insufficient-data",detail:_.reason});continue}let T=JN(e,c,l,m);if(_.kind==="no_forecast"||!Bh(_,u,r)){T!==null&&(ji(e,c,l,m),Bn(e,r,c,l,u,"disarmed",`forecast no longer crosses the ${Fi[u]} threshold`)),a.push({provider:c,bucketId:l,windowType:u,outcome:_.kind==="no_forecast"?"no-forecast":"below-threshold",detail:""});continue}let E=w[w.length-1].usedFraction;if(T===null){KN(e,c,l,m,Fi[u],r,_.latestReadAtMs,E,_.forecastAtMs);let L=`armed on first crossing, forecast ${new Date(_.forecastAtMs).toISOString()}`;Bn(e,r,c,l,u,"armed",L),a.push({provider:c,bucketId:l,windowType:u,outcome:"armed",detail:L});continue}if(_.latestReadAtMs<=T.armed_latest_read_at){a.push({provider:c,bucketId:l,windowType:u,outcome:"still-armed",detail:"awaiting a newer sample to confirm"});continue}if(E<=T.armed_used_fraction){a.push({provider:c,bucketId:l,windowType:u,outcome:"still-armed",detail:`newer sample available (used_fraction=${E}) but no increase over the armed reference (${T.armed_used_fraction}) -- awaiting real movement to confirm`});continue}let v=o(e,c,r),S=WN(w),N=VN(c,l,u,_,S,r);if(v.disabled){let L=v.config?`reason=${JSON.stringify(v.config.reason)}, expiresAt=${v.config.expiresAt??"indefinite"}`:"fail-closed (read error)",R=`would have fired (${N}) but ${c} is already disabled (${L}) -- deferring, never shortening or overwriting an existing hold`;Bn(e,r,c,l,u,"confirmed_deferred_existing_disable",R),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-deferred",detail:R});continue}if(n){ji(e,c,l,m);let L=`would have fired (policy step is disabled -- collection only): ${N}`;Bn(e,r,c,l,u,"confirmed_would_fire_policy_disabled",L),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-would-fire",detail:L});continue}let $=u==="weekly"?new Date(r+BN).toISOString():h[h.length-1]?.resetsAtIso??GN(m);s(e,c,{reason:N,expiresAt:$}),ji(e,c,l,m),Bn(e,r,c,l,u,"confirmed_fired",N),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-fired",detail:N})}return zN(e,r,a),a}var Vh="rate_limit_policy_heartbeat";function zN(e,t,r){let n={};for(let s of r)n[s.outcome]=(n[s.outcome]??0)+1;let o={lastRunAtMs:t,seriesEvaluated:r.length,outcomeCounts:n};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Vh,JSON.stringify(o))}function Bi(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Vh);if(t===void 0)return null;try{return JSON.parse(t.v)}catch{return null}}var YN=15*6e4;function Jh(e,t=Date.now(),r=YN){let n=e.prepare("SELECT MAX(read_at) AS readAt FROM rate_limit_bucket_samples").get();if(n.readAt===null||t-n.readAt*1e3>r)return null;let s=Bi(e);if(s===null)return{status:"never-run",reason:"rate-limit policy has never completed an evaluation while collection is active",ageMs:1/0};let i=t-s.lastRunAtMs;return i>r?{status:"stale",reason:`rate-limit policy last ran ${Math.round(i/6e4)}m ago while collection is active`,ageMs:i}:null}var QN=.85;function Kh(e,t=QN){return e.prepare(`SELECT s.provider AS provider, s.bucket_id AS bucketId, s.window_type AS windowType, s.used_fraction AS usedFraction, s.resets_at_iso AS resetsAtIso
326
326
  FROM rate_limit_bucket_samples s
327
327
  INNER JOIN (
328
328
  SELECT provider, bucket_id, MAX(read_at) AS maxReadAt
@@ -330,7 +330,7 @@ ${t.join(`
330
330
  WHERE window_type = 'weekly'
331
331
  GROUP BY provider, bucket_id
332
332
  ) latest ON latest.provider = s.provider AND latest.bucket_id = s.bucket_id AND latest.maxReadAt = s.read_at
333
- WHERE s.window_type = 'weekly'`).all().filter(n=>!Fh(n.provider,n.bucketId)&&n.usedFraction>=t)}var Cl="auto_scan_paused";function Ir(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Cl);if(t===void 0)return null;try{let r=JSON.parse(t.v);return{paused_at:typeof r.paused_at=="string"?r.paused_at:"unknown",actor:typeof r.actor=="string"?r.actor:null,note:typeof r.note=="string"?r.note:null,resume_after:typeof r.resume_after=="string"?r.resume_after:null}}catch{return{paused_at:"unknown",actor:null,note:null,resume_after:null}}}var GN=3*24*60*6e4;function Wh(e,t=Date.now()){let r=Ir(e);if(r===null)return null;let n=Date.parse(r.paused_at);if(Number.isNaN(n))return{status:"unevaluable",state:r,reason:"corrupt-paused-at"};let o=t-n;if(r.resume_after!==null){let s=Date.parse(r.resume_after);return Number.isNaN(s)?{status:"unevaluable",state:r,reason:"corrupt-resume-after"}:t>=s?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!0}:null}return o>=GN?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!1}:null}function Gh(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Cl,JSON.stringify(t))}function Vh(e){e.prepare("DELETE FROM kv WHERE k = ?").run(Cl)}var VN=/usage limit|rate limit|too many requests|quota exceeded|insufficient_quota/i;function ji(e,t,r=36e5,n=Date.now()){let o=e.idle.find(i=>i.target===t);if(o===void 0||o.error===null||o.error===void 0||!VN.test(o.error))return!1;let s=Date.parse(o.ended_at);return Number.isFinite(s)?n-s<r:!1}import{existsSync as Ol,mkdirSync as JN,readFileSync as KN,writeFileSync as zN}from"node:fs";import{homedir as YN}from"node:os";import{join as Jh}from"node:path";var QN=`# Autopilot check-in -- advance your work, then report status
333
+ WHERE s.window_type = 'weekly'`).all().filter(n=>!Wh(n.provider,n.bucketId)&&n.usedFraction>=t)}var Ml="auto_scan_paused";function Lr(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Ml);if(t===void 0)return null;try{let r=JSON.parse(t.v);return{paused_at:typeof r.paused_at=="string"?r.paused_at:"unknown",actor:typeof r.actor=="string"?r.actor:null,note:typeof r.note=="string"?r.note:null,resume_after:typeof r.resume_after=="string"?r.resume_after:null}}catch{return{paused_at:"unknown",actor:null,note:null,resume_after:null}}}var XN=3*24*60*6e4;function zh(e,t=Date.now()){let r=Lr(e);if(r===null)return null;let n=Date.parse(r.paused_at);if(Number.isNaN(n))return{status:"unevaluable",state:r,reason:"corrupt-paused-at"};let o=t-n;if(r.resume_after!==null){let s=Date.parse(r.resume_after);return Number.isNaN(s)?{status:"unevaluable",state:r,reason:"corrupt-resume-after"}:t>=s?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!0}:null}return o>=XN?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!1}:null}function Yh(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Ml,JSON.stringify(t))}function Qh(e){e.prepare("DELETE FROM kv WHERE k = ?").run(Ml)}var ZN=/usage limit|rate limit|too many requests|quota exceeded|insufficient_quota/i;function Wi(e,t,r=36e5,n=Date.now()){let o=e.idle.find(i=>i.target===t);if(o===void 0||o.error===null||o.error===void 0||!ZN.test(o.error))return!1;let s=Date.parse(o.ended_at);return Number.isFinite(s)?n-s<r:!1}import{existsSync as Pl,mkdirSync as e0,readFileSync as t0,writeFileSync as r0}from"node:fs";import{homedir as n0}from"node:os";import{join as Xh}from"node:path";var o0=`# Autopilot check-in -- advance your work, then report status
334
334
 
335
335
  You are being polled. Advance the work you have established (see your own durable memory for what that
336
336
  is) -- do a REAL unit of work this turn, not just a status echo. Before reporting DONE or going idle,
@@ -346,29 +346,29 @@ On the VERY LAST LINE, emit ONE flag ONLY when it applies:
346
346
  - BLOCKED -- you need a decision/escalation, or are holding on a go-ahead before proceeding.
347
347
  - DONE -- everything is complete AND verified AND committed+pushed+tested, nothing pending.
348
348
  If neither applies, reply normally describing what you advanced and omit the flag.
349
- `;function Hi(e){return e||(process.env.LMBEE_PROMPTS_DIR?process.env.LMBEE_PROMPTS_DIR:Jh(YN(),".lmbee","prompts"))}function Kh(e,t){return Jh(e,`${t}.md`)}function XN(e){Ol(e)||JN(e,{recursive:!0});let t=Kh(e,"default");Ol(t)||zN(t,QN)}function ZN(e,t){let r=Kh(e,t);if(!Ol(r))if(t==="default")XN(e);else throw new Error(`loadPromptTemplate: no prompt file for "${t}" at ${r} -- prepare it (S1) before this team can be auto-nudged`);return KN(r,"utf8")}function Bi(e,t){return ZN(e,t.promptName)}import{existsSync as e0,readFileSync as Yh,rmSync as t0}from"node:fs";import{resolve as zh,sep as r0}from"node:path";function vt(e,t){if(t!==null)return{lifecycle:"finished",lifecycleBasis:"answer",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:t.answered_at};if(e.retracted_ts!==null)return{lifecycle:"finished",lifecycleBasis:"retracted",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:null};if(e.status==="merged")return{lifecycle:"finished",lifecycleBasis:"merged",pulledAt:null,answeredAt:null};if(e.in_reply_to!=null){let r=e.status==="sent"||e.status==="retrieved";return{lifecycle:r?"finished":"queued",lifecycleBasis:"reply",pulledAt:r?e.sent_ts??e.retrieved_ts:null,answeredAt:null}}return!e.expects_response&&(e.status==="sent"||e.status==="retrieved")?{lifecycle:"finished",lifecycleBasis:"informational",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:null}:e.status==="retrieved"?{lifecycle:"processing",lifecycleBasis:"confirmed",pulledAt:e.retrieved_ts,answeredAt:null}:e.status==="sent"?{lifecycle:"processing",lifecycleBasis:"dispatched",pulledAt:e.sent_ts,answeredAt:null}:{lifecycle:"queued",lifecycleBasis:"dispatched",pulledAt:null,answeredAt:null}}function Ce(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? AND superseded_at IS NULL").get(t)??null}function Qh(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? ORDER BY created_at ASC, id ASC").all(t)}var n0=`q.status != 'merged'
349
+ `;function Gi(e){return e||(process.env.LMBEE_PROMPTS_DIR?process.env.LMBEE_PROMPTS_DIR:Xh(n0(),".lmbee","prompts"))}function Zh(e,t){return Xh(e,`${t}.md`)}function s0(e){Pl(e)||e0(e,{recursive:!0});let t=Zh(e,"default");Pl(t)||r0(t,o0)}function i0(e,t){let r=Zh(e,t);if(!Pl(r))if(t==="default")s0(e);else throw new Error(`loadPromptTemplate: no prompt file for "${t}" at ${r} -- prepare it (S1) before this team can be auto-nudged`);return t0(r,"utf8")}function Vi(e,t){return i0(e,t.promptName)}import{existsSync as a0,readFileSync as tg,rmSync as c0}from"node:fs";import{resolve as eg,sep as l0}from"node:path";function vt(e,t){if(t!==null)return{lifecycle:"finished",lifecycleBasis:"answer",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:t.answered_at};if(e.retracted_ts!==null)return{lifecycle:"finished",lifecycleBasis:"retracted",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:null};if(e.status==="merged")return{lifecycle:"finished",lifecycleBasis:"merged",pulledAt:null,answeredAt:null};if(e.in_reply_to!=null){let r=e.status==="sent"||e.status==="retrieved";return{lifecycle:r?"finished":"queued",lifecycleBasis:"reply",pulledAt:r?e.sent_ts??e.retrieved_ts:null,answeredAt:null}}return!e.expects_response&&(e.status==="sent"||e.status==="retrieved")?{lifecycle:"finished",lifecycleBasis:"informational",pulledAt:e.sent_ts??e.retrieved_ts,answeredAt:null}:e.status==="retrieved"?{lifecycle:"processing",lifecycleBasis:"confirmed",pulledAt:e.retrieved_ts,answeredAt:null}:e.status==="sent"?{lifecycle:"processing",lifecycleBasis:"dispatched",pulledAt:e.sent_ts,answeredAt:null}:{lifecycle:"queued",lifecycleBasis:"dispatched",pulledAt:null,answeredAt:null}}function Ce(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? AND superseded_at IS NULL").get(t)??null}function rg(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? ORDER BY created_at ASC, id ASC").all(t)}var u0=`q.status != 'merged'
350
350
  AND q.retracted_ts IS NULL
351
351
  AND NOT EXISTS (SELECT 1 FROM answers r WHERE r.prompt_queue_id = q.id)
352
- AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`;function Xh(e,t){return e.prepare(`SELECT q.* FROM queue q
352
+ AND NOT ((q.expects_response = 0 OR q.in_reply_to IS NOT NULL) AND q.status IN ('sent', 'retrieved'))`;function ng(e,t){return e.prepare(`SELECT q.* FROM queue q
353
353
  WHERE q.to_id = ?
354
- AND ${n0}
355
- ORDER BY q.id`).all(t)}function Zh(e,t,r){let n=new Date(r-t.maxAgeMs).toISOString(),o=["status IN ('sent', 'retrieved')","from_id != 'autopilot'","COALESCE(sent_ts, retrieved_ts) >= ?"],s=[n];t.fromId!==void 0&&(o.push("from_id = ?"),s.push(t.fromId));let i=e.prepare(`SELECT * FROM queue WHERE ${o.join(" AND ")}`).all(...s),a=[];for(let c of i){let l=vt(c,Ce(e,c.id));if(l.lifecycle!=="processing"||l.pulledAt===null)continue;let u=r-Date.parse(l.pulledAt);u>=t.minAgeMs&&u<=t.maxAgeMs&&a.push({row:c,ageMs:u})}return a.sort((c,l)=>l.ageMs-c.ageMs),a}function eg(e,t,r){let n=e.prepare("SELECT * FROM queue WHERE from_id = 'operator' AND to_id = ? AND status IN ('pending', 'escalating', 'sent', 'retrieved')").all(t),o=[];for(let s of n)vt(s,Ce(e,s.id)).lifecycle!=="finished"&&o.push({row:s,ageMs:r-Date.parse(s.created_ts)});return o.sort((s,i)=>i.ageMs-s.ageMs),o}function Dl(e,t){let r=[t.from_id,t.to_id,t.escalation_only,t.to_alias],o=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...r,t.id).id??Number.MAX_SAFE_INTEGER;return e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ?").all(...r,t.id,o)}function Ml(e,t){if(t.status!=="merged")return null;if(t.merged_into_id!==null){let o=e.prepare("SELECT * FROM queue WHERE id = ?").get(t.merged_into_id);if(o)return o}let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status != 'merged' AND id < ? ORDER BY id").all(t.to_id,t.id),n=`--- addendum, ${t.created_ts} ---`;for(let o of r){let s;try{s=Yh(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function nn(e,t){return 1+Dl(e,t).length}function Wo(e,t){return(t.retracted_ts!==null?1:0)+Dl(e,t).filter(n=>n.retracted_ts!==null).length}function tg(e,t,r,n,o={}){let s=ye(n,"reason");return e.transaction(()=>{let a=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(a===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(a.from_id!==r)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} was not sent by "${r}" -- cannot retract another team's claim`,2);if(a.retracted_ts!==null)throw new L("CONFLICT",`Queue prompt ${t} was already retracted: ${a.retracted_reason??"(no reason recorded)"}`,4);if(a.status!=="merged"){let f=Dl(e,a).filter(p=>p.retracted_ts===null);if(f.length>0)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} has ${f.length} still-live merged escalation(s) (ids: ${f.map(p=>p.id).join(", ")}) folded into it -- retract those individually first, or the whole coalesced thread would silently disappear`,2)}let c=Ce(e,t)!==null;if(!c&&a.status==="pending"){tt(e,r,"queue_retracted_deleted",Date.parse(de()),{note:`queue#${t} (was ${a.from_id} -> ${a.to_id}, sent ${a.created_ts}, never retrieved): ${s}`}),e.prepare("DELETE FROM queue WHERE id = ?").run(t);let f=zh(Ws()),p=zh(a.prompt_file);if((p===f||p.startsWith(f+r0))&&e0(p))try{t0(p,{force:!0})}catch{}return{kind:"deleted",id:t,reason:s}}let l=de();e.prepare("UPDATE queue SET retracted_ts = ?, retracted_reason = ? WHERE id = ?").run(l,s,t);let u=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(c||u.status==="merged"||o.noNotice===!0)return{kind:"retracted",row:u};let d=u.to_alias===null?u.to_id:`${u.to_id}:${u.to_alias}`,m=_e(e,[{name:u.to_id}],d,`RETRACTED: queue#${t} -- ${s}`,{from:u.from_id,expectsResponse:!1,retractionNotice:!0});return{kind:"retracted-with-notice",row:u,noticeId:m}}).immediate()}function Go(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = 'operator' AND status IN ('pending', 'escalating', 'sent', 'retrieved')").all(),n=[];for(let o of r)vt(o,Ce(e,o.id)).lifecycle!=="finished"&&n.push({row:o,ageMs:t-Date.parse(o.created_ts)});return n.sort((o,s)=>s.ageMs-o.ageMs),n}var o0=5;function s0(e,t,r){let n=new Set([t.from_id,t.to_id]);if(r.length>0){let a="";try{a=Yh(t.prompt_file,"utf8").split(`
356
- `)[0]??""}catch{}for(let c of r)a.includes(c)&&n.add(c)}let o=e.prepare("SELECT * FROM queue WHERE (from_id = ? OR to_id = ?) AND created_ts > ? AND id != ? ORDER BY created_ts ASC"),s=new Set([t.id]),i=[];for(let a of n)for(let c of o.all(a,a,t.created_ts,t.id))s.has(c.id)||(s.add(c.id),i.push({row:c,matchedTeam:a}));return i.sort((a,c)=>Date.parse(a.row.created_ts)-Date.parse(c.row.created_ts)),i.slice(0,o0)}function on(e,t,r,n=[]){let o=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating', 'sent', 'retrieved') AND retraction_notice = 0 AND in_reply_to IS NULL").all(t),s=[];for(let i of o){if(vt(i,Ce(e,i.id)).lifecycle==="finished")continue;let c=e.prepare("SELECT 1 FROM queue WHERE from_id = ? AND to_id = ? AND created_ts > ? LIMIT 1").get(t,i.from_id,i.created_ts)!==void 0,l=s0(e,i,n);s.push({row:i,ageMs:r-Date.parse(i.created_ts),hasReplyTrafficSince:c,laterRelatedTraffic:l})}return s.sort((i,a)=>a.ageMs-i.ageMs),s}function rg(e,t,r){let n=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'sent' AND escalation_only = 0").all(t),o=[];for(let s of n)vt(s,Ce(e,s.id)).lifecycleBasis==="dispatched"&&o.push({row:s,ageMs:r-Date.parse(s.sent_ts??s.created_ts)});return o.sort((s,i)=>i.ageMs-s.ageMs),o}function ng(e,t,r){let n=ye(r,"reason"),s=e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.status!=="sent")throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is not in a redeliverable state (status: ${i.status}) -- only a dispatched-but-unconfirmed ('sent') row can be redelivered`,2);if(i.escalation_only)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is an operator-escalation row -- redelivery does not apply to that lane`,2);if(Ce(e,t)!==null)throw new L("CONFLICT",`Queue prompt ${t} already has a recorded answer -- nothing to redeliver`,4);if(i.retracted_ts!==null)throw new L("CONFLICT",`Queue prompt ${t} was retracted: ${i.retracted_reason??"(no reason recorded)"} -- nothing to redeliver`,4);return e.prepare("UPDATE queue SET status = 'pending', sent_ts = NULL WHERE id = ?").run(t),e.prepare("SELECT * FROM queue WHERE id = ?").get(t)}).immediate();return tt(e,s.to_id,"redelivery-requeued",Date.parse(de()),{note:`queue#${t}: ${n}`}),s}function Wi(e,t,r,n){let o=e.prepare("SELECT * FROM queue WHERE from_id = ?").all(t),s=[];for(let i of o){let a=Ce(e,i.id);if(a===null)continue;let c=n-Date.parse(a.answered_at);Number.isNaN(c)||c>r||s.push({row:i,answer:a,ageMs:c})}return s.sort((i,a)=>i.ageMs-a.ageMs),s}function og(e,t,r){e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ?").run(r,t)}function sg(e,t,r){let n=t.subject_id!==null?/^task:(\d+)$/.exec(t.subject_id):null;if(n!==null)try{let o=Number(n[1]),s=at(e,o);s!==null&&s.blocked_on===t.to_id&&(Ks(e,o,{clearBlockedOn:!0}),Bt(e,o,{body:`blocked_on ("${t.to_id}") auto-cleared: escalation #${r} was answered.`}))}catch{}}function sn(e,t,r,n){let o=ye(n,"answer");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!==r)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is not addressed to "${r}" -- cannot answer on another team's behalf`,2);if(i.status!=="pending"&&i.status!=="escalating"&&i.status!=="sent"&&i.status!=="retrieved")throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is not in an answerable state (status: ${i.status}) -- cannot finish a prompt that is not currently open`,2);if(i.retracted_ts!==null)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot answer a withdrawn prompt`,2);if(Ce(e,t)!==null)throw new L("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4);let c=de();try{return e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,o,c,c),og(e,t,c),sg(e,i,t),Ce(e,t)}catch(l){if(l instanceof L)throw l;let u=l&&typeof l=="object"&&"code"in l?String(l.code):void 0;throw u!==void 0&&u.startsWith("SQLITE_CONSTRAINT")?new L("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4):new L("STORAGE_ERROR",l instanceof Error?l.message:String(l),1)}}).immediate()}function ig(e,t,r,n){let o=ye(n,"reason");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!=="operator")throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is addressed to "${i.to_id}", not "operator" -- proxy resolution only exists for the operator's own un-owned inbox; ${i.to_id} must answer for itself via \`queue answer\``,2);if(i.status!=="pending"&&i.status!=="escalating"&&i.status!=="sent"&&i.status!=="retrieved")throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is not in an answerable state (status: ${i.status}) -- cannot resolve a prompt that is not currently open`,2);if(i.retracted_ts!==null)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot resolve a withdrawn prompt`,2);if(Ce(e,t)!==null)throw new L("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4);let c=de();try{return e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,`[resolved by proxy ${r}]: ${o}`,c,c),og(e,t,c),sg(e,i,t),Ce(e,t)}catch(l){if(l instanceof L)throw l;let u=l&&typeof l=="object"&&"code"in l?String(l.code):void 0;throw u!==void 0&&u.startsWith("SQLITE_CONSTRAINT")?new L("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4):new L("STORAGE_ERROR",l instanceof Error?l.message:String(l),1)}}).immediate()}function ag(e,t,r,n){let o=ye(n,"answer");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!==r)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is not addressed to "${r}" -- cannot amend an answer on another team's behalf`,2);if(i.retracted_ts!==null)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot amend an answer to a withdrawn prompt`,2);return lg(e,t,o)}).immediate()}function cg(e,t,r,n){let o=ye(n,"reason");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new L("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!=="operator")throw new L("INVALID_ARGUMENT",`Queue prompt ${t} is addressed to "${i.to_id}", not "operator" -- proxy amendment only exists for the operator's own un-owned inbox; ${i.to_id} must amend for itself via \`queue answer --amend\``,2);if(i.retracted_ts!==null)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot amend a resolution to a withdrawn prompt`,2);return lg(e,t,`[resolved by proxy ${r}]: ${o}`)}).immediate()}function lg(e,t,r){let n=Ce(e,t);if(n===null)throw new L("INVALID_ARGUMENT",`Queue prompt ${t} has no current answer to amend -- use \`queue answer\`/\`queue resolve\` for a first answer`,2);let o=de();return e.prepare("UPDATE answers SET superseded_at = ? WHERE id = ?").run(o,n.id),e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,r,o,o),Ce(e,t)}var i0=/standing by|standby|\bready\b|on-call/i,a0=4*60*6e4,dg=5;function c0(e,t){if(e.length===0)return"";let r=e.slice(0,dg),n=r.map(({row:o,ageMs:s})=>` #${o.id} from ${o.from_id} (${me(s)} ago) -- \`lmbee queue answer ${o.id} "<your reply>" --from ${t}\``);return e.length>r.length&&n.push(` ...and ${e.length-r.length} more (\`lmbee queue inbox ${t}\` lists all of them)`),`
354
+ AND ${u0}
355
+ ORDER BY q.id`).all(t)}function og(e,t,r){let n=new Date(r-t.maxAgeMs).toISOString(),o=["status IN ('sent', 'retrieved')","from_id != 'autopilot'","COALESCE(sent_ts, retrieved_ts) >= ?"],s=[n];t.fromId!==void 0&&(o.push("from_id = ?"),s.push(t.fromId));let i=e.prepare(`SELECT * FROM queue WHERE ${o.join(" AND ")}`).all(...s),a=[];for(let c of i){let l=vt(c,Ce(e,c.id));if(l.lifecycle!=="processing"||l.pulledAt===null)continue;let u=r-Date.parse(l.pulledAt);u>=t.minAgeMs&&u<=t.maxAgeMs&&a.push({row:c,ageMs:u})}return a.sort((c,l)=>l.ageMs-c.ageMs),a}function sg(e,t,r){let n=e.prepare("SELECT * FROM queue WHERE from_id = 'operator' AND to_id = ? AND status IN ('pending', 'escalating', 'sent', 'retrieved')").all(t),o=[];for(let s of n)vt(s,Ce(e,s.id)).lifecycle!=="finished"&&o.push({row:s,ageMs:r-Date.parse(s.created_ts)});return o.sort((s,i)=>i.ageMs-s.ageMs),o}function Ul(e,t){let r=[t.from_id,t.to_id,t.escalation_only,t.to_alias],o=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...r,t.id).id??Number.MAX_SAFE_INTEGER;return e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ?").all(...r,t.id,o)}function Fl(e,t){if(t.status!=="merged")return null;if(t.merged_into_id!==null){let o=e.prepare("SELECT * FROM queue WHERE id = ?").get(t.merged_into_id);if(o)return o}let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status != 'merged' AND id < ? ORDER BY id").all(t.to_id,t.id),n=`--- addendum, ${t.created_ts} ---`;for(let o of r){let s;try{s=tg(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function nn(e,t){return 1+Ul(e,t).length}function Ko(e,t){return(t.retracted_ts!==null?1:0)+Ul(e,t).filter(n=>n.retracted_ts!==null).length}function ig(e,t,r,n,o={}){let s=ye(n,"reason");return e.transaction(()=>{let a=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(a===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(a.from_id!==r)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} was not sent by "${r}" -- cannot retract another team's claim`,2);if(a.retracted_ts!==null)throw new I("CONFLICT",`Queue prompt ${t} was already retracted: ${a.retracted_reason??"(no reason recorded)"}`,4);if(a.status!=="merged"){let f=Ul(e,a).filter(p=>p.retracted_ts===null);if(f.length>0)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} has ${f.length} still-live merged escalation(s) (ids: ${f.map(p=>p.id).join(", ")}) folded into it -- retract those individually first, or the whole coalesced thread would silently disappear`,2)}let c=Ce(e,t)!==null;if(!c&&a.status==="pending"){tt(e,r,"queue_retracted_deleted",Date.parse(de()),{note:`queue#${t} (was ${a.from_id} -> ${a.to_id}, sent ${a.created_ts}, never retrieved): ${s}`}),e.prepare("DELETE FROM queue WHERE id = ?").run(t);let f=eg(Ks()),p=eg(a.prompt_file);if((p===f||p.startsWith(f+l0))&&a0(p))try{c0(p,{force:!0})}catch{}return{kind:"deleted",id:t,reason:s}}let l=de();e.prepare("UPDATE queue SET retracted_ts = ?, retracted_reason = ? WHERE id = ?").run(l,s,t);let u=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(c||u.status==="merged"||o.noNotice===!0)return{kind:"retracted",row:u};let d=u.to_alias===null?u.to_id:`${u.to_id}:${u.to_alias}`,m=_e(e,[{name:u.to_id}],d,`RETRACTED: queue#${t} -- ${s}`,{from:u.from_id,expectsResponse:!1,retractionNotice:!0});return{kind:"retracted-with-notice",row:u,noticeId:m}}).immediate()}function zo(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = 'operator' AND status IN ('pending', 'escalating', 'sent', 'retrieved')").all(),n=[];for(let o of r)vt(o,Ce(e,o.id)).lifecycle!=="finished"&&n.push({row:o,ageMs:t-Date.parse(o.created_ts)});return n.sort((o,s)=>s.ageMs-o.ageMs),n}var d0=5;function m0(e,t,r){let n=new Set([t.from_id,t.to_id]);if(r.length>0){let a="";try{a=tg(t.prompt_file,"utf8").split(`
356
+ `)[0]??""}catch{}for(let c of r)a.includes(c)&&n.add(c)}let o=e.prepare("SELECT * FROM queue WHERE (from_id = ? OR to_id = ?) AND created_ts > ? AND id != ? ORDER BY created_ts ASC"),s=new Set([t.id]),i=[];for(let a of n)for(let c of o.all(a,a,t.created_ts,t.id))s.has(c.id)||(s.add(c.id),i.push({row:c,matchedTeam:a}));return i.sort((a,c)=>Date.parse(a.row.created_ts)-Date.parse(c.row.created_ts)),i.slice(0,d0)}function on(e,t,r,n=[]){let o=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('pending', 'escalating', 'sent', 'retrieved') AND retraction_notice = 0 AND in_reply_to IS NULL").all(t),s=[];for(let i of o){if(vt(i,Ce(e,i.id)).lifecycle==="finished")continue;let c=e.prepare("SELECT 1 FROM queue WHERE from_id = ? AND to_id = ? AND created_ts > ? LIMIT 1").get(t,i.from_id,i.created_ts)!==void 0,l=m0(e,i,n);s.push({row:i,ageMs:r-Date.parse(i.created_ts),hasReplyTrafficSince:c,laterRelatedTraffic:l})}return s.sort((i,a)=>a.ageMs-i.ageMs),s}function ag(e,t,r){let n=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status = 'sent' AND escalation_only = 0").all(t),o=[];for(let s of n)vt(s,Ce(e,s.id)).lifecycleBasis==="dispatched"&&o.push({row:s,ageMs:r-Date.parse(s.sent_ts??s.created_ts)});return o.sort((s,i)=>i.ageMs-s.ageMs),o}function cg(e,t,r){let n=ye(r,"reason"),s=e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.status!=="sent")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not in a redeliverable state (status: ${i.status}) -- only a dispatched-but-unconfirmed ('sent') row can be redelivered`,2);if(i.escalation_only)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is an operator-escalation row -- redelivery does not apply to that lane`,2);if(Ce(e,t)!==null)throw new I("CONFLICT",`Queue prompt ${t} already has a recorded answer -- nothing to redeliver`,4);if(i.retracted_ts!==null)throw new I("CONFLICT",`Queue prompt ${t} was retracted: ${i.retracted_reason??"(no reason recorded)"} -- nothing to redeliver`,4);return e.prepare("UPDATE queue SET status = 'pending', sent_ts = NULL WHERE id = ?").run(t),e.prepare("SELECT * FROM queue WHERE id = ?").get(t)}).immediate();return tt(e,s.to_id,"redelivery-requeued",Date.parse(de()),{note:`queue#${t}: ${n}`}),s}function Ji(e,t,r,n){let o=e.prepare("SELECT * FROM queue WHERE from_id = ?").all(t),s=[];for(let i of o){let a=Ce(e,i.id);if(a===null)continue;let c=n-Date.parse(a.answered_at);Number.isNaN(c)||c>r||s.push({row:i,answer:a,ageMs:c})}return s.sort((i,a)=>i.ageMs-a.ageMs),s}function lg(e,t,r){e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ?").run(r,t)}function ug(e,t,r){let n=t.subject_id!==null?/^task:(\d+)$/.exec(t.subject_id):null;if(n!==null)try{let o=Number(n[1]),s=at(e,o);s!==null&&s.blocked_on===t.to_id&&(Xs(e,o,{clearBlockedOn:!0}),Bt(e,o,{body:`blocked_on ("${t.to_id}") auto-cleared: escalation #${r} was answered.`}))}catch{}}function sn(e,t,r,n){let o=ye(n,"answer");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!==r)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not addressed to "${r}" -- cannot answer on another team's behalf`,2);if(i.status!=="pending"&&i.status!=="escalating"&&i.status!=="sent"&&i.status!=="retrieved")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not in an answerable state (status: ${i.status}) -- cannot finish a prompt that is not currently open`,2);if(i.retracted_ts!==null)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot answer a withdrawn prompt`,2);if(Ce(e,t)!==null)throw new I("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4);let c=de();try{return e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,o,c,c),lg(e,t,c),ug(e,i,t),Ce(e,t)}catch(l){if(l instanceof I)throw l;let u=l&&typeof l=="object"&&"code"in l?String(l.code):void 0;throw u!==void 0&&u.startsWith("SQLITE_CONSTRAINT")?new I("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4):new I("STORAGE_ERROR",l instanceof Error?l.message:String(l),1)}}).immediate()}function dg(e,t,r,n){let o=ye(n,"reason");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!=="operator")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is addressed to "${i.to_id}", not "operator" -- proxy resolution only exists for the operator's own un-owned inbox; ${i.to_id} must answer for itself via \`queue answer\``,2);if(i.status!=="pending"&&i.status!=="escalating"&&i.status!=="sent"&&i.status!=="retrieved")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not in an answerable state (status: ${i.status}) -- cannot resolve a prompt that is not currently open`,2);if(i.retracted_ts!==null)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot resolve a withdrawn prompt`,2);if(Ce(e,t)!==null)throw new I("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4);let c=de();try{return e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,`[resolved by proxy ${r}]: ${o}`,c,c),lg(e,t,c),ug(e,i,t),Ce(e,t)}catch(l){if(l instanceof I)throw l;let u=l&&typeof l=="object"&&"code"in l?String(l.code):void 0;throw u!==void 0&&u.startsWith("SQLITE_CONSTRAINT")?new I("CONFLICT",`Queue prompt ${t} already has a recorded answer`,4):new I("STORAGE_ERROR",l instanceof Error?l.message:String(l),1)}}).immediate()}function mg(e,t,r,n){let o=ye(n,"answer");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!==r)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not addressed to "${r}" -- cannot amend an answer on another team's behalf`,2);if(i.retracted_ts!==null)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot amend an answer to a withdrawn prompt`,2);return pg(e,t,o)}).immediate()}function fg(e,t,r,n){let o=ye(n,"reason");return e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.to_id!=="operator")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is addressed to "${i.to_id}", not "operator" -- proxy amendment only exists for the operator's own un-owned inbox; ${i.to_id} must amend for itself via \`queue answer --amend\``,2);if(i.retracted_ts!==null)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} was retracted by its sender (${i.retracted_reason??"no reason recorded"}) -- cannot amend a resolution to a withdrawn prompt`,2);return pg(e,t,`[resolved by proxy ${r}]: ${o}`)}).immediate()}function pg(e,t,r){let n=Ce(e,t);if(n===null)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} has no current answer to amend -- use \`queue answer\`/\`queue resolve\` for a first answer`,2);let o=de();return e.prepare("UPDATE answers SET superseded_at = ? WHERE id = ?").run(o,n.id),e.prepare("INSERT INTO answers(prompt_queue_id, answer_text, answered_at, created_at) VALUES (?, ?, ?, ?)").run(t,r,o,o),Ce(e,t)}var f0=/standing by|standby|\bready\b|on-call/i,p0=4*60*6e4,gg=5;function h0(e,t){if(e.length===0)return"";let r=e.slice(0,gg),n=r.map(({row:o,ageMs:s})=>` #${o.id} from ${o.from_id} (${me(s)} ago) -- \`lmbee queue answer ${o.id} "<your reply>" --from ${t}\``);return e.length>r.length&&n.push(` ...and ${e.length-r.length} more (\`lmbee queue inbox ${t}\` lists all of them)`),`
357
357
 
358
358
  (Also: you have ${e.length} request(s) awaiting a DURABLE response -- replying in chat/prose alone does NOT close these, only \`queue answer\` does:
359
359
  ${n.join(`
360
360
  `)}
361
- )`}var ug=140,l0=4*60*6e4;function u0(e){let t=e.trim().split(`
362
- `)[0]??"";return t.length>ug?`${t.slice(0,ug)}\u2026`:t}function d0(e){if(e.length===0)return"";let t=e.slice(0,dg).map(({row:r,answer:n,ageMs:o})=>` #${r.id} to ${r.to_id} (${me(o)} ago) -- "${u0(n.answer_text)}"`);return e.length>t.length&&t.push(` ...and ${e.length-t.length} more`),`
361
+ )`}var hg=140,g0=4*60*6e4;function _0(e){let t=e.trim().split(`
362
+ `)[0]??"";return t.length>hg?`${t.slice(0,hg)}\u2026`:t}function w0(e){if(e.length===0)return"";let t=e.slice(0,gg).map(({row:r,answer:n,ageMs:o})=>` #${r.id} to ${r.to_id} (${me(o)} ago) -- "${_0(n.answer_text)}"`);return e.length>t.length&&t.push(` ...and ${e.length-t.length} more`),`
363
363
 
364
364
  (Also: ${e.length} of your own request(s) received an answer recently:
365
365
  ${t.join(`
366
366
  `)}
367
- )`}async function m0(e,t){try{let r=Q(e),{turns:n}=await t(r,e.leadAlias,{lines:6}),o=[...n].reverse().find(s=>s.role==="assistant");return o?{text:o.text,ts:o.ts}:null}catch(r){return process.stderr.write(`[auto-continue] tail check failed for ${e.name} (treating as no reply available): ${r instanceof Error?r.message:String(r)}
368
- `),null}}function f0(e,t,r){if(e===null)return!0;let n=Date.parse(e.replace(" ","T"));return Number.isFinite(n)?r-n>=t:!0}async function mg(e,t,r,n={}){let o=n.config??pe,s=n.nowMs??Date.now(),i=n.fetchTailImpl??Ti,a=Hi(n.promptsDir),c=n.readHeavyLockStatusImpl??lt;function l(){return c(n.heavyLockStatusPath,n.heavyLockPath,void 0,h=>{process.stderr.write(`[auto-continue] heavy-lock probe failed, treating conservatively as held: ${h.message}
369
- `)})}let u=new Set(n.stalledTeamNames??await kn(e,t,r,n.heavyLock??l(),o,s)),d=[];function m(h){let w=Ue(e,h.name);if(w===null||w.status==="BLOCKED"||ie(e,h.name)?.confirmed_done_ts||qe(e,h.name,{fromAutopilot:!0}).length>0)return!1;let _=l();if(_.held&&(_.holder===null||_.holder.holder===h.name))return!1;try{let E=`${Q(h)}:${h.leadAlias}`;if(ji(r,E,n.providerExhaustionBackoffMs))return!1}catch{}return!0}let f=n.clearAutoNudgeSuspendedImpl??Vd,p=n.recordAutoNudgeSuspendedImpl??Gd;for(let h of t)if(!u.has(h.name)){f(e,h.name);continue}for(let h of t){if(!u.has(h.name)||(f(e,h.name),!m(h)))continue;let w=await m0(h,i);if(w!==null&&i0.test(w.text)&&!f0(w.ts,n.standbyStaleMs??a0,s)){p(e,h.name,"standby_reply_active",`last reply matches the standby pattern and is not yet stale: "${w.text.slice(0,200)}"`,new Date(s).toISOString());continue}if(!m(h))continue;let _=n.loadTeamTaskStateImpl??xe,E=n.deriveTaskAwareNudgeImpl??xf,T=null;try{T=_(e,Q(h),h.leadAlias)}catch{}let v,S;if(T!==null){let oe=await E(e,T,{backoffMs:o.cooldownMs});if(oe===null||(v=oe.message,S=oe.onSent,!m(h)))continue}else try{v=Bi(a,h)}catch{continue}let x=(n.findOwedResponsesImpl??on)(e,h.name,s);v+=c0(x,h.name);let k=(n.findRecentlyAnsweredForSenderImpl??Wi)(e,h.name,l0,s);v+=d0(k);let C=(n.loadAutoNudgeRedirectImpl??Tt)(e,h.name),g=C===null?h.name:`${C.companionTeam}:${C.workerAlias}`,y=C===null?h.name:C.companionTeam,R=C===null?h.leadAlias:C.workerAlias,P=C===null?h.repoPath:t.find(oe=>oe.name===y)?.repoPath??h.repoPath,ee=(n.resolveMemberProviderImpl??jt)({repoPath:P,name:y},R);if(!(ee!==null&&(n.checkProviderDisabledImpl??rt)(e,ee,s).disabled)){if(_e(e,t,g,v,{from:"autopilot"}),C!==null){let oe=n.recordRedirectedDispatchImpl??vp;try{await oe(e,h.name,C,h.repoPath,new Date(s).toISOString())}catch(V){process.stderr.write(`[auto-continue] failed to record redirected dispatch for ${h.name}'s redirect to ${C.companionTeam}:${C.workerAlias} (nudge already sent, continuing): ${V instanceof Error?V.message:String(V)}
367
+ )`}async function y0(e,t){try{let r=Q(e),{turns:n}=await t(r,e.leadAlias,{lines:6}),o=[...n].reverse().find(s=>s.role==="assistant");return o?{text:o.text,ts:o.ts}:null}catch(r){return process.stderr.write(`[auto-continue] tail check failed for ${e.name} (treating as no reply available): ${r instanceof Error?r.message:String(r)}
368
+ `),null}}function E0(e,t,r){if(e===null)return!0;let n=Date.parse(e.replace(" ","T"));return Number.isFinite(n)?r-n>=t:!0}async function _g(e,t,r,n={}){let o=n.config??pe,s=n.nowMs??Date.now(),i=n.fetchTailImpl??Ai,a=Gi(n.promptsDir),c=n.readHeavyLockStatusImpl??lt;function l(){return c(n.heavyLockStatusPath,n.heavyLockPath,void 0,h=>{process.stderr.write(`[auto-continue] heavy-lock probe failed, treating conservatively as held: ${h.message}
369
+ `)})}let u=new Set(n.stalledTeamNames??await $n(e,t,r,n.heavyLock??l(),o,s)),d=[];function m(h){let w=Ue(e,h.name);if(w===null||w.status==="BLOCKED"||ie(e,h.name)?.confirmed_done_ts||qe(e,h.name,{fromAutopilot:!0}).length>0)return!1;let _=l();if(_.held&&(_.holder===null||_.holder.holder===h.name))return!1;try{let T=`${Q(h)}:${h.leadAlias}`;if(Wi(r,T,n.providerExhaustionBackoffMs))return!1}catch{}return!0}let f=n.clearAutoNudgeSuspendedImpl??zd,p=n.recordAutoNudgeSuspendedImpl??Kd;for(let h of t)if(!u.has(h.name)){f(e,h.name);continue}for(let h of t){if(!u.has(h.name)||(f(e,h.name),!m(h)))continue;let w=await y0(h,i);if(w!==null&&f0.test(w.text)&&!E0(w.ts,n.standbyStaleMs??p0,s)){p(e,h.name,"standby_reply_active",`last reply matches the standby pattern and is not yet stale: "${w.text.slice(0,200)}"`,new Date(s).toISOString());continue}if(!m(h))continue;let _=n.loadTeamTaskStateImpl??xe,T=n.deriveTaskAwareNudgeImpl??Lf,E=null;try{E=_(e,Q(h),h.leadAlias)}catch{}let v,S;if(E!==null){let oe=await T(e,E,{backoffMs:o.cooldownMs});if(oe===null||(v=oe.message,S=oe.onSent,!m(h)))continue}else try{v=Vi(a,h)}catch{continue}let $=(n.findOwedResponsesImpl??on)(e,h.name,s);v+=h0($,h.name);let R=(n.findRecentlyAnsweredForSenderImpl??Ji)(e,h.name,g0,s);v+=w0(R);let C=(n.loadAutoNudgeRedirectImpl??bt)(e,h.name),g=C===null?h.name:`${C.companionTeam}:${C.workerAlias}`,y=C===null?h.name:C.companionTeam,x=C===null?h.leadAlias:C.workerAlias,P=C===null?h.repoPath:t.find(oe=>oe.name===y)?.repoPath??h.repoPath,ee=(n.resolveMemberProviderImpl??jt)({repoPath:P,name:y},x);if(!(ee!==null&&(n.checkProviderDisabledImpl??rt)(e,ee,s).disabled)){if(_e(e,t,g,v,{from:"autopilot"}),C!==null){let oe=n.recordRedirectedDispatchImpl??$p;try{await oe(e,h.name,C,h.repoPath,new Date(s).toISOString())}catch(V){process.stderr.write(`[auto-continue] failed to record redirected dispatch for ${h.name}'s redirect to ${C.companionTeam}:${C.workerAlias} (nudge already sent, continuing): ${V instanceof Error?V.message:String(V)}
370
370
  `)}}try{S?.()}catch(oe){process.stderr.write(`[auto-continue] onSent bookkeeping failed for ${h.name} (nudge already sent, continuing): ${oe instanceof Error?oe.message:String(oe)}
371
- `)}vo(e,h.name,new Date().toISOString()),d.push(h.name)}}return d}import{readFileSync as p0}from"node:fs";function fg(e){return`last_maintainer_wake:${e}`}function h0(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(fg(t))?.v??null}function g0(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(fg(t),r)}function _0(e,t,r,n){for(let o of t)if(o.autoNudge&&o.name!==n&&!ie(e,o.name)?.confirmed_done_ts&&!Fe(o,r))return!0;return!1}function pg(e,t,r,n,o=a=>p0(a,"utf8"),s=Date.now(),i){let a=t.find(m=>m.name===n.teamName);if(!a||!H(a)||!(i??_0(e,t.filter(H),r,n.teamName))||Fe(a,r)||qe(e,n.teamName,{fromAutopilot:!0}).length>0)return!1;let l=n.cooldownMs??pe.cooldownMs,u=h0(e,n.teamName);if(u!==null&&s-Date.parse(u)<=l)return!1;let d;try{d=o(n.promptFile)}catch{return!1}return _e(e,t,n.teamName,d,{from:"autopilot"}),g0(e,n.teamName,new Date(s).toISOString()),!0}function Gi(e){return`blocked:${e}`}function hg(e,t,r,n){let o=r.map(s=>{let i=Sn(e,s.id),a=i!==null?`note: "${i.body}"`:"no note recorded";return`#${s.id} ("${s.title}", ${a})`});return`Team "${t}" has ${r.length} task(s) awaiting ${n}: ${o.join(", ")} -- \`lmauto tasks show <id>\` for full context. Resolve then \`lmauto tasks update <id> --status todo\` (or \`in_progress\`) to unblock, or escalate to the operator.`}async function gg(e,t,r,n,o=pe,s=Date.now()){if(!n.some(a=>a.name===r))return[];let i=[];for(let a of t){if(a.name===r)continue;let c=ie(e,a.name),l=c?.blocked_surfaced_ts?Date.parse(c.blocked_surfaced_ts):null;if(l!==null&&s-l<=o.cooldownMs)continue;let u;try{u=Q(a)}catch{continue}let d=xe(e,u,a.leadAlias);if(d===null)continue;let m=$n(e,d);if(m.length===0)continue;let f=[],p=new Map;for(let w of m)if(w.blocked_on!=="operator"){if(w.blocked_on===null){f.push(w);continue}if(n.some(_=>_.name===w.blocked_on)){let _=p.get(w.blocked_on)??[];_.push(w),p.set(w.blocked_on,_)}else f.push(w)}let h=!1;f.length>0&&(new Set(qe(e,r).map(_=>_.subject_id).filter(_=>_!==null)).has(Gi(a.name))||(_e(e,n,r,hg(e,a.name,f,"your decision"),{from:"autopilot",subject:Gi(a.name)}),h=!0));for(let[w,_]of p)new Set(qe(e,w).map(T=>T.subject_id).filter(T=>T!==null)).has(Gi(a.name))||(_e(e,n,w,hg(e,a.name,_,"your decision"),{from:"autopilot",subject:Gi(a.name)}),h=!0);h&&(qd(e,a.name,new Date().toISOString()),i.push(a.name))}return i}var w0=30*6e4;function y0(e){return`unresolvable-teamfile:${e}`}async function _g(e,t,r,n,o=pe,s=Date.now(),i=w0,a=()=>new Date().toISOString()){if(!n.some(l=>l.name===r))return[];let c=[];for(let l of t){if(l.name===r)continue;try{Q(l),zd(e,l.name);continue}catch{}Kd(e,l.name,a());let u=Yd(e,l.name);if(u===null)continue;let d=s-Date.parse(u.first_observed_ts);if(d<i)continue;let m=u.surfaced_ts!==null?Date.parse(u.surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f=y0(l.name);if(qe(e,r).map(_=>_.subject_id).filter(_=>_!==null).includes(f))continue;let h=Math.round(d/6e4),w=`[status-engine] Team "${l.name}" has had an unresolvable teamfile for over ${h} minutes -- expected "${l.name}.lmctl" under repo_path "${l.repoPath}" to exist. Every other per-team check silently skips this team until the registry entry or teamfile is fixed. \`lmauto teams\` to review the current registry.`;_e(e,n,r,w,{from:"autopilot",subject:f}),Qd(e,l.name,a()),c.push(l.name)}return c}var Pl="epic_closed_surfaced_ts";function Vi(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=!1;for(let i of o){let a=Wt(i.body);if(a!==null){if(a[Tr]===!0)break;typeof a[Pl]=="string"&&(s=!0)}}return{entity:n,status:n.status,alreadySurfacedThisEpisode:s}})()}function wg(e){return`epic-closed:${e}`}async function yg(e,t,r,n,o=pe,s=Date.now(),i={}){let a=n.find(u=>u.name===r);if(!a)return[];if(!H(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(wg(u.name)))continue;let d=ie(e,u.name),m=d?.epic_closed_surfaced_ts?Date.parse(d.epic_closed_surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f;try{f=Q(u)}catch{continue}let p=xe(e,f,u.leadAlias);if(p===null)continue;let h=p.entities.filter(T=>T.kind==="epic"&&An.has(le(T.status)));if(h.length===0)continue;i.beforeRevalidate?.();let w=At(Q(u)),_=!1;e.transaction(()=>{let T=[];for(let x of h){let I=Vi(e,x.id);if(I===null)continue;let k=I.entity;An.has(le(k.status))&&(k.owner_team_path!==w||k.owner_alias!==u.leadAlias||I.alreadySurfacedThisEpisode||T.push(k))}if(T.length===0)return;let v=T.map(x=>`#${x.id} ("${x.title}")`),S=`Team "${u.name}" closed ${T.length} epic(s): ${v.join(", ")} -- review with \`lmauto tasks show <id>\`. If more work remains, add task(s) + \`lmauto tasks update <id> --status open\` to reopen; otherwise no action needed, it stays closed.`;_e(e,n,r,S,{from:"autopilot",subject:wg(u.name),escalationOnly:!0});let N=new Date().toISOString();for(let x of T)Bt(e,x.id,{body:JSON.stringify({[Pl]:N})});Hd(e,u.name,N),_=!0}).immediate(),_&&l.push(u.name)}return l}function Eg(e){return`done-check:${e}`}var bg="consistency_alert_ts";function Tg(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=null,i=n.updated_at,a=!1;for(let c of o){let l=Wt(c.body);if(l!==null){if(l[Tr]===!0){s=c.id,typeof l.to=="string"&&le(l.to)==="done"&&(i=c.created_at);break}typeof l[bg]=="string"&&(a=!0)}}return{entity:n,status:n.status,epochId:s,doneTransitionIso:i,alreadyAlertedThisEpisode:a}})()}async function E0(e,t,r){let n=new Date(Date.parse(t)-r).toISOString();for(let o of e)if(await Ka(o,n))return!0;return!1}async function Sg(e,t,r,n,o=pe,s={}){let i=s.hasEvidenceAroundDoneImpl??E0,a=n.find(u=>u.name===r);if(!a)return[];if(!H(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(Eg(u.name)))continue;let d;try{d=Q(u)}catch{continue}let m=xe(e,d,u.leadAlias);if(m===null)continue;let f=new Map(m.entities.map(S=>[S.id,S])),p=m.entities.filter(S=>(S.kind==="task"||S.kind==="subtask")&&le(S.status)==="done"&&!Vt(e,S,f));if(p.length===0)continue;let h=u.folders&&u.folders.length>0?u.folders:[u.repoPath],w=[];for(let S of p){let N=Tg(e,S.id);if(N===null||N.alreadyAlertedThisEpisode)continue;await i(h,N.doneTransitionIso,o.idleThresholdMs)||w.push({entity:S,epochId:N.epochId})}if(w.length===0)continue;let _=At(d),E=new Date().toISOString(),T=!1;e.transaction(()=>{let S=[];for(let{entity:I,epochId:k}of w){let B=Tg(e,I.id);if(B===null)continue;let C=B.entity;le(C.status)==="done"&&(C.owner_team_path!==_||C.owner_alias!==u.leadAlias||Vt(e,C,new Map)||B.epochId!==k||B.alreadyAlertedThisEpisode||S.push(C))}if(S.length===0)return;let N=S.map(I=>`#${I.id} ("${I.title}")`),x=`Team "${u.name}" reported ${S.length} task(s) done with no commit/file-write found in its tracked path(s) around that time: ${N.join(", ")} -- please verify (\`lmauto tasks show <id>\` for details). This is a soft signal only; no action is needed if the work is genuinely fileless (design/coordination, or landed outside the team's tracked folders).`;_e(e,n,r,x,{from:"autopilot",subject:Eg(u.name),escalationOnly:!0});for(let I of S)Bt(e,I.id,{body:JSON.stringify({[bg]:E})});T=!0}).immediate(),T&&l.push(u.name)}return l}function vg(e){return`fault:${e}`}async function Ag(e,t,r,n,o=pe,s=Date.now(),i={}){if(!n.some(l=>l.name===r))return[];let a=new Set(qe(e,r).map(l=>l.subject_id).filter(l=>l!==null)),c=[];for(let l of t){if(l.name===r||a.has(vg(l.name)))continue;let u=ie(e,l.name),d=u?.fault_surfaced_ts?Date.parse(u.fault_surfaced_ts):null;if(d!==null&&s-d<=o.cooldownMs)continue;let m;try{m=Q(l)}catch{continue}let f=xe(e,m,l.leadAlias);if(f===null)continue;let p=So(e,f,o.cooldownMs,s);if(p.length===0)continue;i.beforeRevalidate?.();let h=!1;e.transaction(()=>{let _=[];for(let v of p){let S=at(e,v.id);if(S===null)continue;let N=So(e,{entities:[S]},o.cooldownMs,s,{team:Q(l),alias:l.leadAlias});N.length!==0&&_.push(N[0])}if(_.length===0)return;let E=_.map(v=>{let S=Sn(e,v.id),N=S!==null?`note: "${S.body}"`:"no note recorded";return`#${v.id} ("${v.title}", ${v.status}, ${N})`}),T=`Team "${l.name}" has ${_.length} task(s) stuck in a fault state past expected recovery: ${E.join(", ")} -- \`lmauto tasks show <id>\` for full context. The team is still being nudged with a back-off template on its own cadence; this is a distinct heads-up that the fault has persisted, not a request to intervene on the team's behalf.`;_e(e,n,r,T,{from:"autopilot",subject:vg(l.name)}),jd(e,l.name,new Date().toISOString()),h=!0}).immediate(),h&&c.push(l.name)}return c}function $g(e,t,r,n,o,s=288e5){let i=new Date(o-n).toISOString(),a=new Date(o-s).toISOString();return e.prepare(`SELECT EXISTS(
371
+ `)}ko(e,h.name,new Date().toISOString()),d.push(h.name)}}return d}import{readFileSync as T0}from"node:fs";function wg(e){return`last_maintainer_wake:${e}`}function b0(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(wg(t))?.v??null}function S0(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(wg(t),r)}function v0(e,t,r,n){for(let o of t)if(o.autoNudge&&o.name!==n&&!ie(e,o.name)?.confirmed_done_ts&&!Fe(o,r))return!0;return!1}function yg(e,t,r,n,o=a=>T0(a,"utf8"),s=Date.now(),i){let a=t.find(m=>m.name===n.teamName);if(!a||!B(a)||!(i??v0(e,t.filter(B),r,n.teamName))||Fe(a,r)||qe(e,n.teamName,{fromAutopilot:!0}).length>0)return!1;let l=n.cooldownMs??pe.cooldownMs,u=b0(e,n.teamName);if(u!==null&&s-Date.parse(u)<=l)return!1;let d;try{d=o(n.promptFile)}catch{return!1}return _e(e,t,n.teamName,d,{from:"autopilot"}),S0(e,n.teamName,new Date(s).toISOString()),!0}function Ki(e){return`blocked:${e}`}function Eg(e,t,r,n){let o=r.map(s=>{let i=Sn(e,s.id),a=i!==null?`note: "${i.body}"`:"no note recorded";return`#${s.id} ("${s.title}", ${a})`});return`Team "${t}" has ${r.length} task(s) awaiting ${n}: ${o.join(", ")} -- \`lmauto tasks show <id>\` for full context. Resolve then \`lmauto tasks update <id> --status todo\` (or \`in_progress\`) to unblock, or escalate to the operator.`}async function Tg(e,t,r,n,o=pe,s=Date.now()){if(!n.some(a=>a.name===r))return[];let i=[];for(let a of t){if(a.name===r)continue;let c=ie(e,a.name),l=c?.blocked_surfaced_ts?Date.parse(c.blocked_surfaced_ts):null;if(l!==null&&s-l<=o.cooldownMs)continue;let u;try{u=Q(a)}catch{continue}let d=xe(e,u,a.leadAlias);if(d===null)continue;let m=kn(e,d);if(m.length===0)continue;let f=[],p=new Map;for(let w of m)if(w.blocked_on!=="operator"){if(w.blocked_on===null){f.push(w);continue}if(n.some(_=>_.name===w.blocked_on)){let _=p.get(w.blocked_on)??[];_.push(w),p.set(w.blocked_on,_)}else f.push(w)}let h=!1;f.length>0&&(new Set(qe(e,r).map(_=>_.subject_id).filter(_=>_!==null)).has(Ki(a.name))||(_e(e,n,r,Eg(e,a.name,f,"your decision"),{from:"autopilot",subject:Ki(a.name)}),h=!0));for(let[w,_]of p)new Set(qe(e,w).map(E=>E.subject_id).filter(E=>E!==null)).has(Ki(a.name))||(_e(e,n,w,Eg(e,a.name,_,"your decision"),{from:"autopilot",subject:Ki(a.name)}),h=!0);h&&(Bd(e,a.name,new Date().toISOString()),i.push(a.name))}return i}var A0=30*6e4;function k0(e){return`unresolvable-teamfile:${e}`}async function bg(e,t,r,n,o=pe,s=Date.now(),i=A0,a=()=>new Date().toISOString()){if(!n.some(l=>l.name===r))return[];let c=[];for(let l of t){if(l.name===r)continue;try{Q(l),Xd(e,l.name);continue}catch{}Qd(e,l.name,a());let u=Zd(e,l.name);if(u===null)continue;let d=s-Date.parse(u.first_observed_ts);if(d<i)continue;let m=u.surfaced_ts!==null?Date.parse(u.surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f=k0(l.name);if(qe(e,r).map(_=>_.subject_id).filter(_=>_!==null).includes(f))continue;let h=Math.round(d/6e4),w=`[status-engine] Team "${l.name}" has had an unresolvable teamfile for over ${h} minutes -- expected "${l.name}.lmctl" under repo_path "${l.repoPath}" to exist. Every other per-team check silently skips this team until the registry entry or teamfile is fixed. \`lmauto teams\` to review the current registry.`;_e(e,n,r,w,{from:"autopilot",subject:f}),em(e,l.name,a()),c.push(l.name)}return c}var ql="epic_closed_surfaced_ts";function zi(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=!1;for(let i of o){let a=Wt(i.body);if(a!==null){if(a[br]===!0)break;typeof a[ql]=="string"&&(s=!0)}}return{entity:n,status:n.status,alreadySurfacedThisEpisode:s}})()}function Sg(e){return`epic-closed:${e}`}async function vg(e,t,r,n,o=pe,s=Date.now(),i={}){let a=n.find(u=>u.name===r);if(!a)return[];if(!B(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(Sg(u.name)))continue;let d=ie(e,u.name),m=d?.epic_closed_surfaced_ts?Date.parse(d.epic_closed_surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f;try{f=Q(u)}catch{continue}let p=xe(e,f,u.leadAlias);if(p===null)continue;let h=p.entities.filter(E=>E.kind==="epic"&&An.has(le(E.status)));if(h.length===0)continue;i.beforeRevalidate?.();let w=At(Q(u)),_=!1;e.transaction(()=>{let E=[];for(let $ of h){let L=zi(e,$.id);if(L===null)continue;let R=L.entity;An.has(le(R.status))&&(R.owner_team_path!==w||R.owner_alias!==u.leadAlias||L.alreadySurfacedThisEpisode||E.push(R))}if(E.length===0)return;let v=E.map($=>`#${$.id} ("${$.title}")`),S=`Team "${u.name}" closed ${E.length} epic(s): ${v.join(", ")} -- review with \`lmauto tasks show <id>\`. If more work remains, add task(s) + \`lmauto tasks update <id> --status open\` to reopen; otherwise no action needed, it stays closed.`;_e(e,n,r,S,{from:"autopilot",subject:Sg(u.name),escalationOnly:!0});let N=new Date().toISOString();for(let $ of E)Bt(e,$.id,{body:JSON.stringify({[ql]:N})});Gd(e,u.name,N),_=!0}).immediate(),_&&l.push(u.name)}return l}function Ag(e){return`done-check:${e}`}var $g="consistency_alert_ts";function kg(e,t){return e.transaction(()=>{let n=at(e,t);if(n===null)return null;let o=e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t),s=null,i=n.updated_at,a=!1;for(let c of o){let l=Wt(c.body);if(l!==null){if(l[br]===!0){s=c.id,typeof l.to=="string"&&le(l.to)==="done"&&(i=c.created_at);break}typeof l[$g]=="string"&&(a=!0)}}return{entity:n,status:n.status,epochId:s,doneTransitionIso:i,alreadyAlertedThisEpisode:a}})()}async function $0(e,t,r){let n=new Date(Date.parse(t)-r).toISOString();for(let o of e)if(await Qa(o,n))return!0;return!1}async function xg(e,t,r,n,o=pe,s={}){let i=s.hasEvidenceAroundDoneImpl??$0,a=n.find(u=>u.name===r);if(!a)return[];if(!B(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(Ag(u.name)))continue;let d;try{d=Q(u)}catch{continue}let m=xe(e,d,u.leadAlias);if(m===null)continue;let f=new Map(m.entities.map(S=>[S.id,S])),p=m.entities.filter(S=>(S.kind==="task"||S.kind==="subtask")&&le(S.status)==="done"&&!Vt(e,S,f));if(p.length===0)continue;let h=u.folders&&u.folders.length>0?u.folders:[u.repoPath],w=[];for(let S of p){let N=kg(e,S.id);if(N===null||N.alreadyAlertedThisEpisode)continue;await i(h,N.doneTransitionIso,o.idleThresholdMs)||w.push({entity:S,epochId:N.epochId})}if(w.length===0)continue;let _=At(d),T=new Date().toISOString(),E=!1;e.transaction(()=>{let S=[];for(let{entity:L,epochId:R}of w){let H=kg(e,L.id);if(H===null)continue;let C=H.entity;le(C.status)==="done"&&(C.owner_team_path!==_||C.owner_alias!==u.leadAlias||Vt(e,C,new Map)||H.epochId!==R||H.alreadyAlertedThisEpisode||S.push(C))}if(S.length===0)return;let N=S.map(L=>`#${L.id} ("${L.title}")`),$=`Team "${u.name}" reported ${S.length} task(s) done with no commit/file-write found in its tracked path(s) around that time: ${N.join(", ")} -- please verify (\`lmauto tasks show <id>\` for details). This is a soft signal only; no action is needed if the work is genuinely fileless (design/coordination, or landed outside the team's tracked folders).`;_e(e,n,r,$,{from:"autopilot",subject:Ag(u.name),escalationOnly:!0});for(let L of S)Bt(e,L.id,{body:JSON.stringify({[$g]:T})});E=!0}).immediate(),E&&l.push(u.name)}return l}function Rg(e){return`fault:${e}`}async function Ng(e,t,r,n,o=pe,s=Date.now(),i={}){if(!n.some(l=>l.name===r))return[];let a=new Set(qe(e,r).map(l=>l.subject_id).filter(l=>l!==null)),c=[];for(let l of t){if(l.name===r||a.has(Rg(l.name)))continue;let u=ie(e,l.name),d=u?.fault_surfaced_ts?Date.parse(u.fault_surfaced_ts):null;if(d!==null&&s-d<=o.cooldownMs)continue;let m;try{m=Q(l)}catch{continue}let f=xe(e,m,l.leadAlias);if(f===null)continue;let p=Ao(e,f,o.cooldownMs,s);if(p.length===0)continue;i.beforeRevalidate?.();let h=!1;e.transaction(()=>{let _=[];for(let v of p){let S=at(e,v.id);if(S===null)continue;let N=Ao(e,{entities:[S]},o.cooldownMs,s,{team:Q(l),alias:l.leadAlias});N.length!==0&&_.push(N[0])}if(_.length===0)return;let T=_.map(v=>{let S=Sn(e,v.id),N=S!==null?`note: "${S.body}"`:"no note recorded";return`#${v.id} ("${v.title}", ${v.status}, ${N})`}),E=`Team "${l.name}" has ${_.length} task(s) stuck in a fault state past expected recovery: ${T.join(", ")} -- \`lmauto tasks show <id>\` for full context. The team is still being nudged with a back-off template on its own cadence; this is a distinct heads-up that the fault has persisted, not a request to intervene on the team's behalf.`;_e(e,n,r,E,{from:"autopilot",subject:Rg(l.name)}),Wd(e,l.name,new Date().toISOString()),h=!0}).immediate(),h&&c.push(l.name)}return c}function Lg(e,t,r,n,o,s=288e5){let i=new Date(o-n).toISOString(),a=new Date(o-s).toISOString();return e.prepare(`SELECT EXISTS(
372
372
  SELECT 1 FROM tracked_invocation
373
373
  WHERE target_teamfile = ? AND target_alias = ?
374
374
  AND (
@@ -376,22 +376,22 @@ ${t.join(`
376
376
  OR started_at >= ?
377
377
  OR ended_at >= ?
378
378
  )
379
- ) AS found`).get(t,r,a,i,i).found===1}function kg(e){return`unknown:${e}`}async function xg(e,t,r,n,o=pe,s=Date.now(),i=On){if(!n.some(l=>l.name===r))return[];let a;function c(){return a??=i(),a}try{return await T0(e,t,r,n,o,s,c)}finally{a!==void 0&&a.close()}}async function T0(e,t,r,n,o,s,i){let a=new Map(n.map(u=>[u.name,u])),c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u===r||c.has(kg(u))||c.has(u))continue;let d=ie(e,u),m=d?.surfaced_ts?Date.parse(d.surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f=a.get(u);if(f?.repoPath!==void 0&&f?.leadAlias!==void 0){let v;try{v=Q({name:u,repoPath:f.repoPath})}catch{v=""}if(v!==""&&$g(i(),v,f.leadAlias,o.idleThresholdMs,s))continue}let p=a.get(u),h=p?.repoPath!==void 0&&p?.leadAlias!==void 0,w=h?Rc(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias}):Ue(e,u)===null,_=d===null||d.progress_status==="ACTIVE",E=!w&&h&&_&&kc(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias},o.idleThresholdMs,s);if(!w&&!E)continue;let T=w?`[status-engine] Team "${u}" is registered but has never been dispatched to -- needs S1 prep / a first dispatch, not a "no progress" investigation.`:`[status-engine] Team "${u}" has an in-progress lmtasks entity with no recent activity for over ${Math.round(o.idleThresholdMs/6e4)} minutes, though its own file-scan progress does not itself show stalled evidence (no scan yet, or last reported ACTIVE). This is OBJECTIVE lmtasks-activity evidence only -- please investigate (\`lmauto oversee ${u}\`) and either re-prep/re-dispatch it or confirm it is truly done.`;_e(e,n,r,T,{from:"autopilot",subject:kg(u)}),Fd(e,u,new Date().toISOString()),l.push(u)}return l}import{execFile as b0}from"node:child_process";import{promisify as S0}from"node:util";function Vo(e){switch(e.kind){case"provider_disabled":return`provider ${e.provider} disabled (no dispatch attempted)`;case"parked":return"parked, confirmed done (no dispatch attempted)";case"presence_gated":return"a session is currently held (actively observed right now)";case"auto_nudge_disabled":return"auto-nudge disabled for this team (on-demand)";case"fleet_scan_paused":return"fleet-wide auto-scan paused";case"provider_exhausted_backoff":return`provider ${e.provider} in quota backoff (no dispatch attempted)`;case"no_continuous_observer":return"nothing has classified this team since (no continuous observer)"}}function Ji(e,t,r,n,o={}){let s=o.resolveMemberProviderImpl??jt,i=o.checkProviderDisabledImpl??rt,a=o.isProviderExhaustedImpl??ji,c=o.allLocalTeams??[t],l=Tt(e,t.name),u=l===null?t.name:l.companionTeam,d=l===null?t.leadAlias:l.workerAlias,m=l===null?t.repoPath:c.find(p=>p.name===u)?.repoPath??t.repoPath,f=s({repoPath:m,name:u},d);if(f!==null&&i(e,f,n).disabled)return{kind:"provider_disabled",provider:f};if(ie(e,t.name)?.confirmed_done_ts)return{kind:"parked"};if(Fe(t,r))return{kind:"presence_gated"};if(!t.autoNudge)return{kind:"auto_nudge_disabled"};if(Ir(e)!==null)return{kind:"fleet_scan_paused"};try{let p=`${Q(t)}:${t.leadAlias}`;if(a(r,p))return{kind:"provider_exhausted_backoff",provider:s(t,t.leadAlias)??"unknown"}}catch{}return{kind:"no_continuous_observer"}}var Rg=S0(b0),v0=new Set(["ENV-ERROR","NO-OUTPUT"]),A0=24*60*6e4,$0=3;async function Jo(e,t,r=Rg){try{return await r("lmctl",["tail",e,t,"--lines","1"],{timeout:1e4}),{sessionResolves:!0,provider:null,detail:"dispatch completes, session resolves; cause unknown"}}catch(n){let o=n&&typeof n=="object"&&"stderr"in n?String(n.stderr).trim():"",s=/session not found/i.test(o),i=/provider=([\w.-]+)/.exec(o);return{sessionResolves:!s,provider:s?i?.[1]??null:null,detail:o.length>0?o:"lmctl tail failed with no output"}}}async function Ng(e,t,r,n,o,s={}){let i=s.execImpl??Rg,a=s.whyNotObservedImpl??Ji,c=s.flappingWindowMs??A0,l=s.flappingOccurrenceThreshold??$0,u=s.listRecentEventsByStatusImpl??As,d=[],m=[];for(let f of t){let p=Pd(e,f.name);if(p.kind==="never-observed")continue;let h=a(e,f,r,n,s.whyNotObservedOptions);if(h.kind==="presence_gated")continue;let{value:w,observedAt:_,changedAt:E}=p,T=n-Date.parse(_),v=new Date(n-c).toISOString(),S=[...u(e,"ENV-ERROR",v,100),...u(e,"NO-OUTPUT",v,100)].filter(k=>k.team===f.name).sort((k,B)=>Date.parse(B.ts)-Date.parse(k.ts)),N=S.length>=l,x=v0.has(w.status)&&!Number.isNaN(T)&&T>=o;if(!x&&!N)continue;if(N&&!x){let k=S[0],B={kind:"flapping",team:f.name,mostRecentStatus:k.status,mostRecentAt:k.ts,occurrenceCount:S.length,windowMs:c};h.kind==="no_continuous_observer"?d.push(B):m.push({team:f.name,status:k.status,changedAt:k.ts,observedAt:_,ageMs:T,suspension:h});continue}let I=w.status;if(h.kind==="no_continuous_observer"){let k=null;if(I==="NO-OUTPUT")try{k=await Jo(Q(f),f.leadAlias,i)}catch{k=null}d.push({kind:"continuous",team:f.name,status:I,changedAt:E,observedAt:_,ageMs:T,cause:k})}else m.push({team:f.name,status:I,changedAt:E,observedAt:_,ageMs:T,suspension:h})}return d.sort((f,p)=>f.kind==="continuous"&&p.kind==="continuous"?p.ageMs-f.ageMs:0),m.sort((f,p)=>p.ageMs-f.ageMs),{unreachable:d,notObserved:m}}import{execFile as k0}from"node:child_process";import{promisify as x0}from"node:util";var R0=x0(k0);async function Ig(e,t=R0){try{let{stdout:r}=await t("git",["-C",e,"status","--porcelain"],{timeout:1e4});return r.split(`
380
- `).filter(n=>n.trim().length>0).length}catch{return null}}import{execFile as N0}from"node:child_process";import{promisify as I0}from"node:util";var L0=I0(N0);async function Cg(e,t=L0){try{let{stderr:r}=await t("lmctl",["lint",e],{timeout:15e3});return Lg(r)}catch(r){let n=r&&typeof r=="object"&&"stderr"in r?String(r.stderr):"",o=Lg(n);return o.length>0?o:null}}function Lg(e){return e.split(`
381
- `).map(t=>t.trim()).filter(t=>t.startsWith("warning:")||t.startsWith("error:"))}import{existsSync as Ul}from"node:fs";function Fl(e,t,r=new Set){if(t.owner_team_path!==null)return{ownerTeamPath:t.owner_team_path,ownerAlias:t.owner_alias,explicit:!0};if(t.parent_id===null||r.has(t.id))return null;r.add(t.id);let n=at(e,t.parent_id);if(n===null)return null;let o=Fl(e,n,r);return o===null?null:{...o,explicit:!1}}function Ki(e,t){if(t===null)return null;for(let r of e)if(H(r))try{if(Q(r)===t)return r.name}catch{continue}return null}function Og(e){return e.prepare("SELECT * FROM entities WHERE kind = 'epic' AND owner_team_path IS NULL").all().filter(r=>!gt(r.status))}function Dg(e,t,r=Ul){return Ki(e,t)!==null?"registered":r(t)?"on_demand":"dangling"}function Mg(e,t,r={}){let n=r.existsSyncImpl??Ul,o=e.prepare("SELECT * FROM entities WHERE kind IN ('task', 'subtask')").all(),s=[];for(let i of o){if(gt(i.status))continue;let a=Fl(e,i);if(a===null){s.push({entity:i,reason:i.parent_id===null?"no owner, and no parent epic to inherit from":"no owner, and its parent epic has none to inherit either"});continue}Dg(t,a.ownerTeamPath,n)==="dangling"&&s.push({entity:i,reason:a.explicit?`owner "${a.ownerTeamPath}" does not resolve to any known team (no registered entry, no on-disk teamfile)`:`inherited owner "${a.ownerTeamPath}" (from its epic) does not resolve to any known team`})}return s}function Pg(e){return e.prepare("SELECT * FROM entities WHERE status = 'blocked'").all().filter(r=>(ct(e,r.id,"outgoing").outgoing??[]).length===0)}function C0(e,t){return e.prepare("SELECT 1 FROM queue WHERE to_id = ? LIMIT 1").get(t)!==void 0}function Ug(e,t,r,n=Ul){let o=Fl(e,r);if(o===null)return{ownerKind:"dangling",everContacted:null};let s=Dg(t,o.ownerTeamPath,n);if(s==="dangling")return{ownerKind:s,everContacted:null};if(s==="on_demand")return{ownerKind:s,everContacted:!1};let i=Ki(t,o.ownerTeamPath);return{ownerKind:s,everContacted:C0(e,i)}}function qg(e,t){let r=ct(e,t,"outgoing").outgoing??[];return new Set(r.filter(n=>!gt(n.status)).map(n=>n.id))}function zi(e,t,r=new Set){if(r.has(t))return[];r.add(t);let o=(ct(e,t,"outgoing").outgoing??[]).filter(a=>!gt(a.status)),s=[];for(let a of o)(ct(e,a.id,"outgoing").outgoing??[]).filter(u=>!gt(u.status)).length===0?s.push(Le(e,a.id)):s.push(...zi(e,a.id,r));let i=new Set;return s.filter(a=>i.has(a.id)?!1:(i.add(a.id),!0))}function O0(e,t){let r=new Set([t]),n=(ct(e,t,"incoming").incoming??[]).map(s=>s.id),o=[];for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let i=Le(e,s);gt(i.status)||(o.push(i),n.push(...(ct(e,s,"incoming").incoming??[]).map(a=>a.id)))}return o}function Fg(e){let t=e.trim().toLowerCase();return t==="todo"?0:t==="in_progress"||t==="in-progress"?1:2}function jg(e,t,r){let n=new Map;for(let s of t)for(let i of zi(e,s.id))n.set(i.id,i);let o=[];for(let s of n.values()){let i=O0(e,s.id),a=new Set;for(let l of i){let u=Ki(r,l.owner_team_path);u!==null&&a.add(u)}let c=Ug(e,r,s);o.push({entity:s,downstreamCount:i.length,downstreamTeams:[...a].sort(),ownerKind:c.ownerKind,everContacted:c.everContacted})}return o.sort((s,i)=>{if(s.downstreamTeams.length!==i.downstreamTeams.length)return i.downstreamTeams.length-s.downstreamTeams.length;if(s.downstreamCount!==i.downstreamCount)return i.downstreamCount-s.downstreamCount;let a=Fg(s.entity.status)-Fg(i.entity.status);return a!==0?a:s.entity.id-i.entity.id}),o}import{execFile as D0}from"node:child_process";import{readFileSync as M0}from"node:fs";import{basename as P0,resolve as U0}from"node:path";import{promisify as F0}from"node:util";var ql=F0(D0),q0=[/\.env\.(example|sample|template)$/i],j0=[/\.pem$/,/\.key$/,/(^|\/)id_rsa$/,/(^|\/)id_ed25519$/,/(^|\/)id_ecdsa$/],H0=[/(^|\/)\.env(\..+)?$/,/(^|\/)\.mcp\.json$/,/(^|\/)\.netrc$/,/(^|\/)\.npmrc$/],Bg=[/\b(?:api[_-]?key|app[_-]?key|secret|token|password|passwd|access[_-]?key)\b\s*[:=]\s*['"]?[A-Za-z0-9+/_.\-]{12,}/i,/\bsk-[A-Za-z0-9]{20,}\b/,/\bghp_[A-Za-z0-9]{30,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bBearer\s+[A-Za-z0-9\-_.]{20,}/],B0=[...Bg,/\b_(?:authToken|auth|password)\b\s*[:=]\s*['"]?[A-Za-z0-9+/_.\-]{8,}/i,/\bmachine\s+\S+[\s\S]{0,200}?\blogin\s+\S+[\s\S]{0,200}?\bpassword\s+\S+/i,/\bAWS_SECRET_ACCESS_KEY\b\s*[:=]?\s*['"]?[A-Za-z0-9+/]{20,}/i],Yi=20*1024*1024;async function Wg(e,t){try{let{stdout:r}=await t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Yi});return r.split(`
382
- `).filter(n=>n.length>0)}catch{return null}}async function jl(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"show",`HEAD:${t}`],{timeout:1e4,maxBuffer:Yi});return n}catch{return null}}async function Gg(e,t=ql){let r=await Wg(e,t);if(r===null)return null;let n=a=>!q0.some(c=>c.test(a)),o=r.filter(a=>j0.some(c=>c.test(a))&&n(a)),s=r.filter(a=>H0.some(c=>c.test(a))&&n(a)),i=[];for(let a of s){let c=await jl(e,a,t);c!==null&&B0.some(l=>l.test(c))&&i.push(a)}return[...o,...i]}async function Vg(e,t=ql){let r=await Wg(e,t);if(r===null)return null;let n=r.filter(s=>s.endsWith(".lmctl")),o=[];for(let s of n){let i=await jl(e,s,t);if(i===null)continue;let a=Bg.reduce((c,l)=>c+(l.test(i)?1:0),0);a>0&&o.push({path:s,matchCount:a})}return o}var W0=[/(^|\/)template\.lmctl$/i,/(^|\/)examples\/.*\.lmctl$/i],Hg=/_MEMBER_\b|\bsessionid\s*=\s*\S/;async function Jg(e,t=ql){try{let[r,n]=await Promise.all([t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Yi}),t("git",["-C",e,"ls-files","--others","--exclude-standard"],{timeout:1e4,maxBuffer:Yi})]),o=u=>!W0.some(d=>d.test(u)),s=u=>P0(u).includes(".lmctl")&&o(u),i=r.stdout.split(`
379
+ ) AS found`).get(t,r,a,i,i).found===1}function Ig(e){return`unknown:${e}`}async function Cg(e,t,r,n,o=pe,s=Date.now(),i=On){if(!n.some(l=>l.name===r))return[];let a;function c(){return a??=i(),a}try{return await x0(e,t,r,n,o,s,c)}finally{a!==void 0&&a.close()}}async function x0(e,t,r,n,o,s,i){let a=new Map(n.map(u=>[u.name,u])),c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u===r||c.has(Ig(u))||c.has(u))continue;let d=ie(e,u),m=d?.surfaced_ts?Date.parse(d.surfaced_ts):null;if(m!==null&&s-m<=o.cooldownMs)continue;let f=a.get(u);if(f?.repoPath!==void 0&&f?.leadAlias!==void 0){let v;try{v=Q({name:u,repoPath:f.repoPath})}catch{v=""}if(v!==""&&Lg(i(),v,f.leadAlias,o.idleThresholdMs,s))continue}let p=a.get(u),h=p?.repoPath!==void 0&&p?.leadAlias!==void 0,w=h?Ic(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias}):Ue(e,u)===null,_=d===null||d.progress_status==="ACTIVE",T=!w&&h&&_&&Nc(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias},o.idleThresholdMs,s);if(!w&&!T)continue;let E=w?`[status-engine] Team "${u}" is registered but has never been dispatched to -- needs S1 prep / a first dispatch, not a "no progress" investigation.`:`[status-engine] Team "${u}" has an in-progress lmtasks entity with no recent activity for over ${Math.round(o.idleThresholdMs/6e4)} minutes, though its own file-scan progress does not itself show stalled evidence (no scan yet, or last reported ACTIVE). This is OBJECTIVE lmtasks-activity evidence only -- please investigate (\`lmauto oversee ${u}\`) and either re-prep/re-dispatch it or confirm it is truly done.`;_e(e,n,r,E,{from:"autopilot",subject:Ig(u)}),Hd(e,u,new Date().toISOString()),l.push(u)}return l}import{execFile as R0}from"node:child_process";import{promisify as N0}from"node:util";function Yo(e){switch(e.kind){case"provider_disabled":return`provider ${e.provider} disabled (no dispatch attempted)`;case"parked":return"parked, confirmed done (no dispatch attempted)";case"presence_gated":return"a session is currently held (actively observed right now)";case"auto_nudge_disabled":return"auto-nudge disabled for this team (on-demand)";case"fleet_scan_paused":return"fleet-wide auto-scan paused";case"provider_exhausted_backoff":return`provider ${e.provider} in quota backoff (no dispatch attempted)`;case"no_continuous_observer":return"nothing has classified this team since (no continuous observer)"}}function Yi(e,t,r,n,o={}){let s=o.resolveMemberProviderImpl??jt,i=o.checkProviderDisabledImpl??rt,a=o.isProviderExhaustedImpl??Wi,c=o.allLocalTeams??[t],l=bt(e,t.name),u=l===null?t.name:l.companionTeam,d=l===null?t.leadAlias:l.workerAlias,m=l===null?t.repoPath:c.find(p=>p.name===u)?.repoPath??t.repoPath,f=s({repoPath:m,name:u},d);if(f!==null&&i(e,f,n).disabled)return{kind:"provider_disabled",provider:f};if(ie(e,t.name)?.confirmed_done_ts)return{kind:"parked"};if(Fe(t,r))return{kind:"presence_gated"};if(!t.autoNudge)return{kind:"auto_nudge_disabled"};if(Lr(e)!==null)return{kind:"fleet_scan_paused"};try{let p=`${Q(t)}:${t.leadAlias}`;if(a(r,p))return{kind:"provider_exhausted_backoff",provider:s(t,t.leadAlias)??"unknown"}}catch{}return{kind:"no_continuous_observer"}}var Og=N0(R0),L0=new Set(["ENV-ERROR","NO-OUTPUT"]),I0=24*60*6e4,C0=3;async function Qo(e,t,r=Og){try{return await r("lmctl",["tail",e,t,"--lines","1"],{timeout:1e4}),{sessionResolves:!0,provider:null,detail:"dispatch completes, session resolves; cause unknown"}}catch(n){let o=n&&typeof n=="object"&&"stderr"in n?String(n.stderr).trim():"",s=/session not found/i.test(o),i=/provider=([\w.-]+)/.exec(o);return{sessionResolves:!s,provider:s?i?.[1]??null:null,detail:o.length>0?o:"lmctl tail failed with no output"}}}async function Dg(e,t,r,n,o,s={}){let i=s.execImpl??Og,a=s.whyNotObservedImpl??Yi,c=s.flappingWindowMs??I0,l=s.flappingOccurrenceThreshold??C0,u=s.listRecentEventsByStatusImpl??Rs,d=[],m=[];for(let f of t){let p=qd(e,f.name);if(p.kind==="never-observed")continue;let h=a(e,f,r,n,s.whyNotObservedOptions);if(h.kind==="presence_gated")continue;let{value:w,observedAt:_,changedAt:T}=p,E=n-Date.parse(_),v=new Date(n-c).toISOString(),S=[...u(e,"ENV-ERROR",v,100),...u(e,"NO-OUTPUT",v,100)].filter(R=>R.team===f.name).sort((R,H)=>Date.parse(H.ts)-Date.parse(R.ts)),N=S.length>=l,$=L0.has(w.status)&&!Number.isNaN(E)&&E>=o;if(!$&&!N)continue;if(N&&!$){let R=S[0],H={kind:"flapping",team:f.name,mostRecentStatus:R.status,mostRecentAt:R.ts,occurrenceCount:S.length,windowMs:c};h.kind==="no_continuous_observer"?d.push(H):m.push({team:f.name,status:R.status,changedAt:R.ts,observedAt:_,ageMs:E,suspension:h});continue}let L=w.status;if(h.kind==="no_continuous_observer"){let R=null;if(L==="NO-OUTPUT")try{R=await Qo(Q(f),f.leadAlias,i)}catch{R=null}d.push({kind:"continuous",team:f.name,status:L,changedAt:T,observedAt:_,ageMs:E,cause:R})}else m.push({team:f.name,status:L,changedAt:T,observedAt:_,ageMs:E,suspension:h})}return d.sort((f,p)=>f.kind==="continuous"&&p.kind==="continuous"?p.ageMs-f.ageMs:0),m.sort((f,p)=>p.ageMs-f.ageMs),{unreachable:d,notObserved:m}}import{execFile as O0}from"node:child_process";import{promisify as D0}from"node:util";var M0=D0(O0);async function Mg(e,t=M0){try{let{stdout:r}=await t("git",["-C",e,"status","--porcelain"],{timeout:1e4});return r.split(`
380
+ `).filter(n=>n.trim().length>0).length}catch{return null}}import{execFile as P0}from"node:child_process";import{promisify as U0}from"node:util";var F0=U0(P0);async function Ug(e,t=F0){try{let{stderr:r}=await t("lmctl",["lint",e],{timeout:15e3});return Pg(r)}catch(r){let n=r&&typeof r=="object"&&"stderr"in r?String(r.stderr):"",o=Pg(n);return o.length>0?o:null}}function Pg(e){return e.split(`
381
+ `).map(t=>t.trim()).filter(t=>t.startsWith("warning:")||t.startsWith("error:"))}import{existsSync as jl}from"node:fs";function Hl(e,t,r=new Set){if(t.owner_team_path!==null)return{ownerTeamPath:t.owner_team_path,ownerAlias:t.owner_alias,explicit:!0};if(t.parent_id===null||r.has(t.id))return null;r.add(t.id);let n=at(e,t.parent_id);if(n===null)return null;let o=Hl(e,n,r);return o===null?null:{...o,explicit:!1}}function Qi(e,t){if(t===null)return null;for(let r of e)if(B(r))try{if(Q(r)===t)return r.name}catch{continue}return null}function Fg(e){return e.prepare("SELECT * FROM entities WHERE kind = 'epic' AND owner_team_path IS NULL").all().filter(r=>!gt(r.status))}function qg(e,t,r=jl){return Qi(e,t)!==null?"registered":r(t)?"on_demand":"dangling"}function jg(e,t,r={}){let n=r.existsSyncImpl??jl,o=e.prepare("SELECT * FROM entities WHERE kind IN ('task', 'subtask')").all(),s=[];for(let i of o){if(gt(i.status))continue;let a=Hl(e,i);if(a===null){s.push({entity:i,reason:i.parent_id===null?"no owner, and no parent epic to inherit from":"no owner, and its parent epic has none to inherit either"});continue}qg(t,a.ownerTeamPath,n)==="dangling"&&s.push({entity:i,reason:a.explicit?`owner "${a.ownerTeamPath}" does not resolve to any known team (no registered entry, no on-disk teamfile)`:`inherited owner "${a.ownerTeamPath}" (from its epic) does not resolve to any known team`})}return s}function Hg(e){return e.prepare("SELECT * FROM entities WHERE status = 'blocked'").all().filter(r=>(ct(e,r.id,"outgoing").outgoing??[]).length===0)}function q0(e,t){return e.prepare("SELECT 1 FROM queue WHERE to_id = ? LIMIT 1").get(t)!==void 0}function Bg(e,t,r,n=jl){let o=Hl(e,r);if(o===null)return{ownerKind:"dangling",everContacted:null};let s=qg(t,o.ownerTeamPath,n);if(s==="dangling")return{ownerKind:s,everContacted:null};if(s==="on_demand")return{ownerKind:s,everContacted:!1};let i=Qi(t,o.ownerTeamPath);return{ownerKind:s,everContacted:q0(e,i)}}function Gg(e,t){let r=ct(e,t,"outgoing").outgoing??[];return new Set(r.filter(n=>!gt(n.status)).map(n=>n.id))}function Xi(e,t,r=new Set){if(r.has(t))return[];r.add(t);let o=(ct(e,t,"outgoing").outgoing??[]).filter(a=>!gt(a.status)),s=[];for(let a of o)(ct(e,a.id,"outgoing").outgoing??[]).filter(u=>!gt(u.status)).length===0?s.push(Ie(e,a.id)):s.push(...Xi(e,a.id,r));let i=new Set;return s.filter(a=>i.has(a.id)?!1:(i.add(a.id),!0))}function j0(e,t){let r=new Set([t]),n=(ct(e,t,"incoming").incoming??[]).map(s=>s.id),o=[];for(;n.length>0;){let s=n.pop();if(r.has(s))continue;r.add(s);let i=Ie(e,s);gt(i.status)||(o.push(i),n.push(...(ct(e,s,"incoming").incoming??[]).map(a=>a.id)))}return o}function Wg(e){let t=e.trim().toLowerCase();return t==="todo"?0:t==="in_progress"||t==="in-progress"?1:2}function Vg(e,t,r){let n=new Map;for(let s of t)for(let i of Xi(e,s.id))n.set(i.id,i);let o=[];for(let s of n.values()){let i=j0(e,s.id),a=new Set;for(let l of i){let u=Qi(r,l.owner_team_path);u!==null&&a.add(u)}let c=Bg(e,r,s);o.push({entity:s,downstreamCount:i.length,downstreamTeams:[...a].sort(),ownerKind:c.ownerKind,everContacted:c.everContacted})}return o.sort((s,i)=>{if(s.downstreamTeams.length!==i.downstreamTeams.length)return i.downstreamTeams.length-s.downstreamTeams.length;if(s.downstreamCount!==i.downstreamCount)return i.downstreamCount-s.downstreamCount;let a=Wg(s.entity.status)-Wg(i.entity.status);return a!==0?a:s.entity.id-i.entity.id}),o}import{execFile as H0}from"node:child_process";import{readFileSync as B0}from"node:fs";import{basename as W0,resolve as G0}from"node:path";import{promisify as V0}from"node:util";var Bl=V0(H0),J0=[/\.env\.(example|sample|template)$/i],K0=[/\.pem$/,/\.key$/,/(^|\/)id_rsa$/,/(^|\/)id_ed25519$/,/(^|\/)id_ecdsa$/],z0=[/(^|\/)\.env(\..+)?$/,/(^|\/)\.mcp\.json$/,/(^|\/)\.netrc$/,/(^|\/)\.npmrc$/],Kg=[/\b(?:api[_-]?key|app[_-]?key|secret|token|password|passwd|access[_-]?key)\b\s*[:=]\s*['"]?[A-Za-z0-9+/_.\-]{12,}/i,/\bsk-[A-Za-z0-9]{20,}\b/,/\bghp_[A-Za-z0-9]{30,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bBearer\s+[A-Za-z0-9\-_.]{20,}/],Y0=[...Kg,/\b_(?:authToken|auth|password)\b\s*[:=]\s*['"]?[A-Za-z0-9+/_.\-]{8,}/i,/\bmachine\s+\S+[\s\S]{0,200}?\blogin\s+\S+[\s\S]{0,200}?\bpassword\s+\S+/i,/\bAWS_SECRET_ACCESS_KEY\b\s*[:=]?\s*['"]?[A-Za-z0-9+/]{20,}/i],Zi=20*1024*1024;async function zg(e,t){try{let{stdout:r}=await t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Zi});return r.split(`
382
+ `).filter(n=>n.length>0)}catch{return null}}async function Wl(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"show",`HEAD:${t}`],{timeout:1e4,maxBuffer:Zi});return n}catch{return null}}async function Yg(e,t=Bl){let r=await zg(e,t);if(r===null)return null;let n=a=>!J0.some(c=>c.test(a)),o=r.filter(a=>K0.some(c=>c.test(a))&&n(a)),s=r.filter(a=>z0.some(c=>c.test(a))&&n(a)),i=[];for(let a of s){let c=await Wl(e,a,t);c!==null&&Y0.some(l=>l.test(c))&&i.push(a)}return[...o,...i]}async function Qg(e,t=Bl){let r=await zg(e,t);if(r===null)return null;let n=r.filter(s=>s.endsWith(".lmctl")),o=[];for(let s of n){let i=await Wl(e,s,t);if(i===null)continue;let a=Kg.reduce((c,l)=>c+(l.test(i)?1:0),0);a>0&&o.push({path:s,matchCount:a})}return o}var Q0=[/(^|\/)template\.lmctl$/i,/(^|\/)examples\/.*\.lmctl$/i],Jg=/_MEMBER_\b|\bsessionid\s*=\s*\S/;async function Xg(e,t=Bl){try{let[r,n]=await Promise.all([t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Zi}),t("git",["-C",e,"ls-files","--others","--exclude-standard"],{timeout:1e4,maxBuffer:Zi})]),o=u=>!Q0.some(d=>d.test(u)),s=u=>W0(u).includes(".lmctl")&&o(u),i=r.stdout.split(`
383
383
  `).filter(u=>u.length>0&&s(u)),a=n.stdout.split(`
384
- `).filter(u=>u.length>0&&s(u)),c=[];for(let u of i){let d=await jl(e,u,t);d!==null&&Hg.test(d)&&c.push(u)}let l=[];for(let u of a){let d;try{d=M0(U0(e,u),"utf8")}catch{continue}Hg.test(d)&&l.push(u)}return{tracked:c,unprotected:l}}catch{return null}}import{execFile as G0}from"node:child_process";import{statSync as Kg}from"node:fs";import{homedir as V0}from"node:os";import{join as zg}from"node:path";import{promisify as J0}from"node:util";var Hl=J0(G0);var K0="mike.ma@lmctl.com",Bl="mike-lmctl";async function Yg(e,t=Hl){let r,n;try{r=(await t("git",["-C",e,"config","user.name"],{timeout:1e4})).stdout.trim()||null}catch{r=null}try{n=(await t("git",["-C",e,"config","user.email"],{timeout:1e4})).stdout.trim()||null}catch{n=null}return r===null&&n===null?null:{name:r,email:n,matchesPolicy:n===K0}}var z0=6e4,Qi;async function Xi(e=Hl,t=Date.now(),r=Kg){let n=e===Hl&&r===Kg;if(n&&Qi!==void 0&&t-Qi.atMs<z0)return Qi.result;let o=await Q0(e,r);return n&&(Qi={result:o,atMs:t}),o}function Y0(){let e=process.env.GH_CONFIG_DIR;return e?zg(e,"hosts.yml"):zg(V0(),".config","gh","hosts.yml")}async function Q0(e,t){let r;try{r=(await e("gh",["auth","status"],{timeout:1e4})).stdout}catch(l){let u=l&&typeof l=="object"&&"stdout"in l?String(l.stdout):"";if(u.length===0)return null;r=u}let n=r.split(`
385
- `),o=n.findIndex(l=>/Active account: true/.test(l));if(o===-1)return null;let a=n.slice(0,o).reverse().find(l=>/Logged in to .* account /.test(l))?.match(/account\s+(\S+)/)?.[1]??null;if(a===null)return null;let c;try{c=t(Y0()).mtime.toISOString()}catch{c=null}return{account:a,matchesPolicy:a===Bl,hostsFileChangedAt:c}}var X0=7*24*60*6e4,Z0=500,eI=3*60*6e4,tI=3*60*6e4,Ko=4*60*6e4,rI=24*60*6e4,nI=48*60*6e4,oI=24*60*6e4,sI=20,Gl=24*60*6e4;function iI(e,t){let r=me(t);return`${t>Gl?`possible ${e}`:e} as of ${r} ago (not re-observed)`}var aI=7*24*60*6e4,cI=24*60*6e4;function lI(e,t,r,n,o){if(e?.confirmed_done_ts)return{kind:"confirmed-done",confirmedDoneTs:e.confirmed_done_ts};if(r!==null){let i=n-Date.parse(r);if(Number.isFinite(i)&&i<=cI)return null}else return o!==void 0&&oc(o)===0?{kind:"unseeded"}:{kind:"never-active"};if(t===null)return{kind:"no-state"};if(t.status!=="ACTIVE")return{kind:"self-report",status:t.status,changedTs:t.changed_ts};let s=n-Date.parse(t.changed_ts);return!Number.isFinite(s)||s>aI?{kind:"self-report",status:t.status,changedTs:t.changed_ts}:null}function uI(e,t){let r=e.teams.filter(H);return t===void 0?r:r.filter(n=>n.name===t)}function dI(e,t,r){let n=r(e);if(n.length===0)return null;let o=[],s=[];for(let i of n)i.provider!==null&&t.has(i.provider)?o.push({alias:i.alias,provider:i.provider}):s.push({alias:i.alias,provider:i.provider});return{totalMembers:n.length,quiescedMembers:o,liveMembers:s}}async function Zi(e,t={}){let r=e.db.db,n=t.config??pe,o=t.nowMs??Date.now(),s=uI(e,t.team),i=t.awaitingReviewThresholdMs??Ac,a=[],c=[],l=[],u=[],d=[],m=new Set(Go(r,o).map(F=>F.row.subject_id).filter(F=>F!==null)),f=[],p=[],h=[],w=[],_=[],E=[],T=t.countDirtyGitFilesImpl??Ig,v=[],S=t.lintTeamfileWarningsImpl??Cg,N=[],x=[],I=[],k=[],B=[],C=t.findNeverTrackFilesImpl??Gg,g=t.findSecretBearingTeamfilesImpl??Vg,y=t.checkTeamfileTrackingImpl??Jg,R=t.checkRepoGitIdentityImpl??Yg,P=t.resolveMemberProviderImpl??jt,J=t.listTeamMembersImpl??Vr,ee=[],oe=!1;try{ee=Io(r).filter(F=>rt(r,F.provider,o).disabled)}catch{oe=!0}let V=Hh(r,o),se=Bh(r),$=null;try{$=Wh(r,o)}catch{$=null}let O=new Set(ee.map(F=>F.provider)),A=[],q=e.teams.filter(H),M=e.teams.map(F=>F.name);for(let F of s){let ge;try{ge=Q(F)}catch{continue}let Pe=await S(ge);Pe!==null&&Pe.length>0&&v.push({team:F.name,warnings:Pe});let it=await C(F.repoPath);it!==null&&it.length>0&&N.push({team:F.name,files:it});let fn=await g(F.repoPath);fn!==null&&fn.length>0&&x.push({team:F.name,files:fn});let Ot=await y(F.repoPath);Ot!==null&&(Ot.tracked.length>0&&I.push({team:F.name,files:Ot.tracked}),Ot.unprotected.length>0&&k.push({team:F.name,files:Ot.unprotected}));let Br=await R(F.repoPath);Br!==null&&!Br.matchesPolicy&&B.push({team:F.name,identity:{name:Br.name,email:Br.email}});let Dt=O.size>0?dI(F,O,J):null;if(O.size>0){let ce=Tt(r,F.name),Mt=ce===null?F.name:ce.companionTeam,La=ce===null?F.leadAlias:ce.workerAlias,ho=ce===null?F.repoPath:q.find(go=>go.name===Mt)?.repoPath??F.repoPath,Wr=P({repoPath:ho,name:Mt},La);if(Wr!==null&&O.has(Wr)){let go=ee.find(Nv=>Nv.provider===Wr)?.expiresAt??null;A.push({team:F.name,provider:Wr,expiresAt:go,totalMembers:Dt?.totalMembers??1,liveMembers:Dt?.liveMembers??[]})}}let Na=on(r,F.name,o,M);Na.length>0&&l.push({team:F.name,rows:Na,...Dt!==null&&Dt.quiescedMembers.length>0?{quiescedMembers:Dt.quiescedMembers,totalMembers:Dt.totalMembers}:{}});let yd=Na.filter(ce=>ce.row.status==="sent"||ce.row.status==="retrieved");if(yd.length>0){let ce=r.prepare("SELECT MAX(created_ts) AS ts FROM queue WHERE from_id = ?").get(F.name),Mt=lI(ie(r,F.name),Ue(r,F.name),ce.ts,o,F);Mt!==null&&d.push({team:F.name,rows:yd,reason:Mt})}let Ed=Wi(r,F.name,Ko,o);Ed.length>0&&u.push({team:F.name,rows:Ed});let wr=xe(r,ge,F.leadAlias);if(wr===null)continue;for(let ce of $n(r,wr)){let Mt;try{let ho=qg(r,ce.id),Wr=zi(r,ce.id).filter(go=>!ho.has(go.id));Wr.length>0&&(Mt=Wr)}catch{Mt=void 0}let La=zs(r,ce.id);a.push({team:F.name,entity:ce,blockedSinceTs:La,...Mt!==void 0?{roots:Mt}:{}}),ce.blocked_on==="operator"?m.has(`task:${ce.id}`)||c.push({team:F.name,entity:ce,blockedOn:"operator",reason:"operator-uncorrelated"}):ce.blocked_on!==null&&!e.teams.some(ho=>ho.name===ce.blocked_on)&&c.push({team:F.name,entity:ce,blockedOn:ce.blocked_on,reason:"team-unresolvable"})}for(let ce of So(r,wr,n.cooldownMs,o))f.push({team:F.name,entity:ce});for(let ce of $f(r,wr,i,o))p.push({team:F.name,task:ce});for(let ce of kf(r,wr,o))h.push({team:F.name,task:ce});for(let ce of wr.entities)ce.kind==="epic"&&ce.needs_review===1&&ti(ce)&&w.push({team:F.name,entity:ce});for(let ce of wr.entities)ce.kind!=="epic"||!An.has(le(ce.status))||Vi(r,ce.id)?.alreadySurfacedThisEpisode||_.push({team:F.name,entity:ce});let Ia=wr.entities.filter(ce=>le(ce.status)==="todo");if(Ia.length>0){let ce=await T(F.repoPath);ce!==null&&ce>0&&E.push({team:F.name,dirtyCount:ce,todoCount:Ia.length,exampleEntity:Ia[0]})}}let W=await(t.fetchReportImpl??Ae)(),ae=t.heavyLockImpl?t.heavyLockImpl():lt(void 0,void 0,void 0,()=>{}),Ee=await kn(r,s,W,ae,n,o,{readOnly:!0}),ne=new Set(A.map(F=>F.team)),D=Ee.filter(F=>!ne.has(F)),j=t.findPersistentDispatchFailuresImpl??Ng,{unreachable:Y,notObserved:K}=await j(r,s,W,o,Ko),re=[];for(let F of D){let ge=ie(r,F);if(ge?.miniplayer_verdict_label&&ge.miniplayer_verdict_reason&&ge.miniplayer_verdict_ts){let Pe=Ue(r,F),it=ge.miniplayer_verdict_label!=="genuinely_done"&&Pe?.status==="DONE"?{changedTs:Pe.changed_ts}:void 0;re.push({team:F,label:ge.miniplayer_verdict_label,reason:ge.miniplayer_verdict_reason,ts:ge.miniplayer_verdict_ts,...it!==void 0?{selfReportedDone:it}:{}})}}let te=[];for(let F of s){let ge=ie(r,F.name);ge?.hung_holder_flagged_ts&&ge.hung_holder_reason&&te.push({team:F.name,reason:ge.hung_holder_reason,flaggedTs:ge.hung_holder_flagged_ts})}let ue=Jd(r).map(F=>({team:F.team,reason:F.reason,detail:F.detail,suspendedAt:F.suspended_at})),$e=t.blockedSelfReportUrgentThresholdMs??rI,be=t.blockedSelfReportUnconfirmedThresholdMs??nI,z=[];for(let F of s){let ge=Ue(r,F.name);if(ge?.status==="BLOCKED"){let Pe=o-Date.parse(ge.changed_ts),it=Pe>=be;z.push({team:F.name,changedTs:ge.changed_ts,ageMs:Pe,urgent:!it&&Pe>=$e,unconfirmed:it})}}z.sort((F,ge)=>ge.ageMs-F.ageMs);let Te=t.orphanReapCandidateWindowMs??X0,Ge=new Date(o-Te).toISOString(),Ct=As(r,cl,Ge,Z0).filter(F=>t.team===void 0||F.team===t.team).map(F=>({team:F.team,ts:F.ts,reason:F.note??"(no reason recorded)"})),G=t.maintainer===void 0?null:[...qe(r,t.maintainer),...Gs(r,t.maintainer)].sort((F,ge)=>F.id-ge.id).filter(F=>F.from_id!=="autopilot"),we=t.maintainer===void 0?[]:eg(r,t.maintainer,o).map(F=>({row:F.row,constituentCount:nn(r,F.row)})),st=t.maintainer===void 0?[]:Go(r,o).map(F=>{let ge=nn(r,F.row),Pe=Wo(r,F.row),it=F.ageMs>=Ko||ge>=2&&F.row.sent_ts===null;return{row:F.row,constituentCount:ge,retractedCount:Pe,urgent:it}}),Ze=t.maintainerStaleThresholdMs??eI,ft=[];if(t.maintainer!==void 0&&G!==null){let ge=ie(r,t.maintainer)?.last_cli_activity_ts??null,Pe=xp(ge,o),it=!sl(ge,Ze,o),fn=G[0],Ot=fn?o-Date.parse(fn.created_ts):null,Br=Ot!==null&&Ot>Ze;if(it||Br){let Dt=[];it&&Dt.push(ge===null?"no CLI activity ever recorded":`no CLI activity in ${me(Pe)}`),Br&&Dt.push(`oldest queued item is ${me(Ot)} old`),ft.push({team:t.maintainer,reason:Dt.join("; "),ageMs:Pe===null?1/0:Math.max(Pe,Ot??0)})}}let Ve;if(t.team===void 0)Ve=a.map(F=>F.entity);else{Ve=[];for(let F of e.teams.filter(H)){let ge;try{ge=Q(F)}catch{continue}let Pe=xe(r,ge,F.leadAlias);Pe!==null&&Ve.push(...$n(r,Pe))}}let mn=jg(r,Ve,e.teams),gr=Og(r),or=Mg(r,e.teams),et=Pg(r),_r=[];for(let F of e.teams.filter(H)){try{Q(F)}catch{continue}oc(F)===0&&_r.push({team:F.name,repoPath:F.repoPath})}let po=t.stuckProcessingThresholdMs??tI,ys=t.stuckProcessingMaxAgeMs??oI,Ra=t.maintainer!==void 0&&t.stuckProcessingFleetWide!==!0?t.maintainer:void 0,Rv=Zh(r,{minAgeMs:po,maxAgeMs:ys,fromId:Ra},o).map(F=>({queueId:F.row.id,fromId:F.row.from_id,toId:F.row.to_id,ageMs:F.ageMs,constituentCount:nn(r,F.row)}));return{blocked:a,blockedOnUnresolved:c,owedAnswers:l,recentlyAnsweredForSender:u,parkedTeamsWithOwedPrompts:d,awaitingDecision:f,awaitingReview:p,stalled:D,stalledVerdicts:re,hungHolders:te,autoNudgeSuspended:ue,blockedSelfReports:z,flaggedEpics:w,closedEpicsToReview:_,orphanReapCandidates:Ct,maintainerStale:ft,blockingRoots:mn,epicsWithoutOwner:gr,unresolvableOwnerEntities:or,untrackedBlockers:et,unseededTeams:_r,stuckProcessing:Rv,inbox:G,memory:(t.readMemoryAvailabilityImpl??To)(),operatorPrompts:we,operatorEscalations:st,uncommittedWork:E,teamfileLintWarnings:v,expiredHolds:h,neverTrackFiles:N,secretBearingTeamfiles:x,trackedTeamfiles:I,unprotectedTeamfiles:k,gitIdentityMismatches:B,activeGhAccount:await(t.checkActiveGhAccountImpl??Xi)(),disabledProviders:ee,providerDisableReadFailed:oe,quiescedByProviderDisable:A,staleAutoScanPause:$,persistentDispatchFailures:Y,notObserved:K,rateLimitPolicyHealth:V,rateLimitLevelWarnings:se}}function Wl(e){return` ${e.team}: #${e.entity.id} ("${e.entity.title}")`}function Qg(e){return e.length===0?"":`
386
- later traffic worth checking before ruling on this (not proof it was answered): ${e.map(r=>`#${r.row.id} ${r.row.from_id}->${r.row.to_id} (${he(r.row.created_ts)}, via ${r.matchedTeam})`).join("; ")}`}function zo(e,t={}){if(t.json)return JSON.stringify(e);let r=[];if(e.operatorPrompts.length>0){let c=Date.now(),l=e.operatorPrompts.map(m=>` #${m.row.id} -- sent ${me(c-Date.parse(m.row.created_ts))} ago, unanswered`+(m.constituentCount>1?` (${m.constituentCount} merged into this one)`:"")),u=e.operatorPrompts.reduce((m,f)=>m+f.constituentCount,0),d=u===e.operatorPrompts.length?`${e.operatorPrompts.length}`:`${u} in ${e.operatorPrompts.length} thread${e.operatorPrompts.length===1?"":"s"}`;r.push(`OPERATOR MESSAGE, UNANSWERED (${d}):
384
+ `).filter(u=>u.length>0&&s(u)),c=[];for(let u of i){let d=await Wl(e,u,t);d!==null&&Jg.test(d)&&c.push(u)}let l=[];for(let u of a){let d;try{d=B0(G0(e,u),"utf8")}catch{continue}Jg.test(d)&&l.push(u)}return{tracked:c,unprotected:l}}catch{return null}}import{execFile as X0}from"node:child_process";import{statSync as Zg}from"node:fs";import{homedir as Z0}from"node:os";import{join as e_}from"node:path";import{promisify as eL}from"node:util";var Gl=eL(X0);var tL="mike.ma@lmctl.com",Vl="mike-lmctl";async function t_(e,t=Gl){let r,n;try{r=(await t("git",["-C",e,"config","user.name"],{timeout:1e4})).stdout.trim()||null}catch{r=null}try{n=(await t("git",["-C",e,"config","user.email"],{timeout:1e4})).stdout.trim()||null}catch{n=null}return r===null&&n===null?null:{name:r,email:n,matchesPolicy:n===tL}}var rL=6e4,ea;async function ta(e=Gl,t=Date.now(),r=Zg){let n=e===Gl&&r===Zg;if(n&&ea!==void 0&&t-ea.atMs<rL)return ea.result;let o=await oL(e,r);return n&&(ea={result:o,atMs:t}),o}function nL(){let e=process.env.GH_CONFIG_DIR;return e?e_(e,"hosts.yml"):e_(Z0(),".config","gh","hosts.yml")}async function oL(e,t){let r;try{r=(await e("gh",["auth","status"],{timeout:1e4})).stdout}catch(l){let u=l&&typeof l=="object"&&"stdout"in l?String(l.stdout):"";if(u.length===0)return null;r=u}let n=r.split(`
385
+ `),o=n.findIndex(l=>/Active account: true/.test(l));if(o===-1)return null;let a=n.slice(0,o).reverse().find(l=>/Logged in to .* account /.test(l))?.match(/account\s+(\S+)/)?.[1]??null;if(a===null)return null;let c;try{c=t(nL()).mtime.toISOString()}catch{c=null}return{account:a,matchesPolicy:a===Vl,hostsFileChangedAt:c}}var sL=7*24*60*6e4,iL=500,aL=3*60*6e4,cL=3*60*6e4,Xo=4*60*6e4,lL=24*60*6e4,uL=48*60*6e4,dL=24*60*6e4,mL=20,Kl=24*60*6e4;function fL(e,t){let r=me(t);return`${t>Kl?`possible ${e}`:e} as of ${r} ago (not re-observed)`}var pL=7*24*60*6e4,hL=24*60*6e4;function gL(e,t,r,n,o){if(e?.confirmed_done_ts)return{kind:"confirmed-done",confirmedDoneTs:e.confirmed_done_ts};if(r!==null){let i=n-Date.parse(r);if(Number.isFinite(i)&&i<=hL)return null}else return o!==void 0&&ac(o)===0?{kind:"unseeded"}:{kind:"never-active"};if(t===null)return{kind:"no-state"};if(t.status!=="ACTIVE")return{kind:"self-report",status:t.status,changedTs:t.changed_ts};let s=n-Date.parse(t.changed_ts);return!Number.isFinite(s)||s>pL?{kind:"self-report",status:t.status,changedTs:t.changed_ts}:null}function _L(e,t){let r=e.teams.filter(B);return t===void 0?r:r.filter(n=>n.name===t)}function wL(e,t,r){let n=r(e);if(n.length===0)return null;let o=[],s=[];for(let i of n)i.provider!==null&&t.has(i.provider)?o.push({alias:i.alias,provider:i.provider}):s.push({alias:i.alias,provider:i.provider});return{totalMembers:n.length,quiescedMembers:o,liveMembers:s}}async function ra(e,t={}){let r=e.db.db,n=t.config??pe,o=t.nowMs??Date.now(),s=_L(e,t.team),i=t.awaitingReviewThresholdMs??xc,a=[],c=[],l=[],u=[],d=[],m=new Set(zo(r,o).map(F=>F.row.subject_id).filter(F=>F!==null)),f=[],p=[],h=[],w=[],_=[],T=[],E=t.countDirtyGitFilesImpl??Mg,v=[],S=t.lintTeamfileWarningsImpl??Ug,N=[],$=[],L=[],R=[],H=[],C=t.findNeverTrackFilesImpl??Yg,g=t.findSecretBearingTeamfilesImpl??Qg,y=t.checkTeamfileTrackingImpl??Xg,x=t.checkRepoGitIdentityImpl??t_,P=t.resolveMemberProviderImpl??jt,J=t.listTeamMembersImpl??Vr,ee=[],oe=!1;try{ee=Co(r).filter(F=>rt(r,F.provider,o).disabled)}catch{oe=!0}let V=Jh(r,o),se=Kh(r),k=null;try{k=zh(r,o)}catch{k=null}let O=new Set(ee.map(F=>F.provider)),A=[],q=e.teams.filter(B),M=e.teams.map(F=>F.name);for(let F of s){let ge;try{ge=Q(F)}catch{continue}let Pe=await S(ge);Pe!==null&&Pe.length>0&&v.push({team:F.name,warnings:Pe});let it=await C(F.repoPath);it!==null&&it.length>0&&N.push({team:F.name,files:it});let fn=await g(F.repoPath);fn!==null&&fn.length>0&&$.push({team:F.name,files:fn});let Ot=await y(F.repoPath);Ot!==null&&(Ot.tracked.length>0&&L.push({team:F.name,files:Ot.tracked}),Ot.unprotected.length>0&&R.push({team:F.name,files:Ot.unprotected}));let Br=await x(F.repoPath);Br!==null&&!Br.matchesPolicy&&H.push({team:F.name,identity:{name:Br.name,email:Br.email}});let Dt=O.size>0?wL(F,O,J):null;if(O.size>0){let ce=bt(r,F.name),Mt=ce===null?F.name:ce.companionTeam,Da=ce===null?F.leadAlias:ce.workerAlias,_o=ce===null?F.repoPath:q.find(wo=>wo.name===Mt)?.repoPath??F.repoPath,Wr=P({repoPath:_o,name:Mt},Da);if(Wr!==null&&O.has(Wr)){let wo=ee.find(Dv=>Dv.provider===Wr)?.expiresAt??null;A.push({team:F.name,provider:Wr,expiresAt:wo,totalMembers:Dt?.totalMembers??1,liveMembers:Dt?.liveMembers??[]})}}let Ca=on(r,F.name,o,M);Ca.length>0&&l.push({team:F.name,rows:Ca,...Dt!==null&&Dt.quiescedMembers.length>0?{quiescedMembers:Dt.quiescedMembers,totalMembers:Dt.totalMembers}:{}});let bd=Ca.filter(ce=>ce.row.status==="sent"||ce.row.status==="retrieved");if(bd.length>0){let ce=r.prepare("SELECT MAX(created_ts) AS ts FROM queue WHERE from_id = ?").get(F.name),Mt=gL(ie(r,F.name),Ue(r,F.name),ce.ts,o,F);Mt!==null&&d.push({team:F.name,rows:bd,reason:Mt})}let Sd=Ji(r,F.name,Xo,o);Sd.length>0&&u.push({team:F.name,rows:Sd});let yr=xe(r,ge,F.leadAlias);if(yr===null)continue;for(let ce of kn(r,yr)){let Mt;try{let _o=Gg(r,ce.id),Wr=Xi(r,ce.id).filter(wo=>!_o.has(wo.id));Wr.length>0&&(Mt=Wr)}catch{Mt=void 0}let Da=Zs(r,ce.id);a.push({team:F.name,entity:ce,blockedSinceTs:Da,...Mt!==void 0?{roots:Mt}:{}}),ce.blocked_on==="operator"?m.has(`task:${ce.id}`)||c.push({team:F.name,entity:ce,blockedOn:"operator",reason:"operator-uncorrelated"}):ce.blocked_on!==null&&!e.teams.some(_o=>_o.name===ce.blocked_on)&&c.push({team:F.name,entity:ce,blockedOn:ce.blocked_on,reason:"team-unresolvable"})}for(let ce of Ao(r,yr,n.cooldownMs,o))f.push({team:F.name,entity:ce});for(let ce of Rf(r,yr,i,o))p.push({team:F.name,task:ce});for(let ce of Nf(r,yr,o))h.push({team:F.name,task:ce});for(let ce of yr.entities)ce.kind==="epic"&&ce.needs_review===1&&si(ce)&&w.push({team:F.name,entity:ce});for(let ce of yr.entities)ce.kind!=="epic"||!An.has(le(ce.status))||zi(r,ce.id)?.alreadySurfacedThisEpisode||_.push({team:F.name,entity:ce});let Oa=yr.entities.filter(ce=>le(ce.status)==="todo");if(Oa.length>0){let ce=await E(F.repoPath);ce!==null&&ce>0&&T.push({team:F.name,dirtyCount:ce,todoCount:Oa.length,exampleEntity:Oa[0]})}}let W=await(t.fetchReportImpl??Ae)(),ae=t.heavyLockImpl?t.heavyLockImpl():lt(void 0,void 0,void 0,()=>{}),Ee=await $n(r,s,W,ae,n,o,{readOnly:!0}),ne=new Set(A.map(F=>F.team)),D=Ee.filter(F=>!ne.has(F)),j=t.findPersistentDispatchFailuresImpl??Dg,{unreachable:Y,notObserved:K}=await j(r,s,W,o,Xo),re=[];for(let F of D){let ge=ie(r,F);if(ge?.miniplayer_verdict_label&&ge.miniplayer_verdict_reason&&ge.miniplayer_verdict_ts){let Pe=Ue(r,F),it=ge.miniplayer_verdict_label!=="genuinely_done"&&Pe?.status==="DONE"?{changedTs:Pe.changed_ts}:void 0;re.push({team:F,label:ge.miniplayer_verdict_label,reason:ge.miniplayer_verdict_reason,ts:ge.miniplayer_verdict_ts,...it!==void 0?{selfReportedDone:it}:{}})}}let te=[];for(let F of s){let ge=ie(r,F.name);ge?.hung_holder_flagged_ts&&ge.hung_holder_reason&&te.push({team:F.name,reason:ge.hung_holder_reason,flaggedTs:ge.hung_holder_flagged_ts})}let ue=Yd(r).map(F=>({team:F.team,reason:F.reason,detail:F.detail,suspendedAt:F.suspended_at})),ke=t.blockedSelfReportUrgentThresholdMs??lL,be=t.blockedSelfReportUnconfirmedThresholdMs??uL,z=[];for(let F of s){let ge=Ue(r,F.name);if(ge?.status==="BLOCKED"){let Pe=o-Date.parse(ge.changed_ts),it=Pe>=be;z.push({team:F.name,changedTs:ge.changed_ts,ageMs:Pe,urgent:!it&&Pe>=ke,unconfirmed:it})}}z.sort((F,ge)=>ge.ageMs-F.ageMs);let Te=t.orphanReapCandidateWindowMs??sL,Ge=new Date(o-Te).toISOString(),Ct=Rs(r,dl,Ge,iL).filter(F=>t.team===void 0||F.team===t.team).map(F=>({team:F.team,ts:F.ts,reason:F.note??"(no reason recorded)"})),G=t.maintainer===void 0?null:[...qe(r,t.maintainer),...zs(r,t.maintainer)].sort((F,ge)=>F.id-ge.id).filter(F=>F.from_id!=="autopilot"),we=t.maintainer===void 0?[]:sg(r,t.maintainer,o).map(F=>({row:F.row,constituentCount:nn(r,F.row)})),st=t.maintainer===void 0?[]:zo(r,o).map(F=>{let ge=nn(r,F.row),Pe=Ko(r,F.row),it=F.ageMs>=Xo||ge>=2&&F.row.sent_ts===null;return{row:F.row,constituentCount:ge,retractedCount:Pe,urgent:it}}),Ze=t.maintainerStaleThresholdMs??aL,ft=[];if(t.maintainer!==void 0&&G!==null){let ge=ie(r,t.maintainer)?.last_cli_activity_ts??null,Pe=Lp(ge,o),it=!cl(ge,Ze,o),fn=G[0],Ot=fn?o-Date.parse(fn.created_ts):null,Br=Ot!==null&&Ot>Ze;if(it||Br){let Dt=[];it&&Dt.push(ge===null?"no CLI activity ever recorded":`no CLI activity in ${me(Pe)}`),Br&&Dt.push(`oldest queued item is ${me(Ot)} old`),ft.push({team:t.maintainer,reason:Dt.join("; "),ageMs:Pe===null?1/0:Math.max(Pe,Ot??0)})}}let Ve;if(t.team===void 0)Ve=a.map(F=>F.entity);else{Ve=[];for(let F of e.teams.filter(B)){let ge;try{ge=Q(F)}catch{continue}let Pe=xe(r,ge,F.leadAlias);Pe!==null&&Ve.push(...kn(r,Pe))}}let mn=Vg(r,Ve,e.teams),_r=Fg(r),or=jg(r,e.teams),et=Hg(r),wr=[];for(let F of e.teams.filter(B)){try{Q(F)}catch{continue}ac(F)===0&&wr.push({team:F.name,repoPath:F.repoPath})}let go=t.stuckProcessingThresholdMs??cL,Ss=t.stuckProcessingMaxAgeMs??dL,Ia=t.maintainer!==void 0&&t.stuckProcessingFleetWide!==!0?t.maintainer:void 0,Ov=og(r,{minAgeMs:go,maxAgeMs:Ss,fromId:Ia},o).map(F=>({queueId:F.row.id,fromId:F.row.from_id,toId:F.row.to_id,ageMs:F.ageMs,constituentCount:nn(r,F.row)}));return{blocked:a,blockedOnUnresolved:c,owedAnswers:l,recentlyAnsweredForSender:u,parkedTeamsWithOwedPrompts:d,awaitingDecision:f,awaitingReview:p,stalled:D,stalledVerdicts:re,hungHolders:te,autoNudgeSuspended:ue,blockedSelfReports:z,flaggedEpics:w,closedEpicsToReview:_,orphanReapCandidates:Ct,maintainerStale:ft,blockingRoots:mn,epicsWithoutOwner:_r,unresolvableOwnerEntities:or,untrackedBlockers:et,unseededTeams:wr,stuckProcessing:Ov,inbox:G,memory:(t.readMemoryAvailabilityImpl??So)(),operatorPrompts:we,operatorEscalations:st,uncommittedWork:T,teamfileLintWarnings:v,expiredHolds:h,neverTrackFiles:N,secretBearingTeamfiles:$,trackedTeamfiles:L,unprotectedTeamfiles:R,gitIdentityMismatches:H,activeGhAccount:await(t.checkActiveGhAccountImpl??ta)(),disabledProviders:ee,providerDisableReadFailed:oe,quiescedByProviderDisable:A,staleAutoScanPause:k,persistentDispatchFailures:Y,notObserved:K,rateLimitPolicyHealth:V,rateLimitLevelWarnings:se}}function Jl(e){return` ${e.team}: #${e.entity.id} ("${e.entity.title}")`}function r_(e){return e.length===0?"":`
386
+ later traffic worth checking before ruling on this (not proof it was answered): ${e.map(r=>`#${r.row.id} ${r.row.from_id}->${r.row.to_id} (${he(r.row.created_ts)}, via ${r.matchedTeam})`).join("; ")}`}function Zo(e,t={}){if(t.json)return JSON.stringify(e);let r=[];if(e.operatorPrompts.length>0){let c=Date.now(),l=e.operatorPrompts.map(m=>` #${m.row.id} -- sent ${me(c-Date.parse(m.row.created_ts))} ago, unanswered`+(m.constituentCount>1?` (${m.constituentCount} merged into this one)`:"")),u=e.operatorPrompts.reduce((m,f)=>m+f.constituentCount,0),d=u===e.operatorPrompts.length?`${e.operatorPrompts.length}`:`${u} in ${e.operatorPrompts.length} thread${e.operatorPrompts.length===1?"":"s"}`;r.push(`OPERATOR MESSAGE, UNANSWERED (${d}):
387
387
  ${l.join(`
388
388
  `)}`)}if(e.operatorEscalations.length>0){let c=Date.now(),l=f=>{let p=f.constituentCount>1?` (${f.constituentCount} merged into this one${f.retractedCount>0?`, ${f.retractedCount} retracted`:""})`:"";return` #${f.row.id} from ${f.row.from_id} -- sent ${me(c-Date.parse(f.row.created_ts))} ago, unanswered${p}`},u=f=>{let p=f.reduce((h,w)=>h+w.constituentCount,0);return p===f.length?`${f.length}`:`${p} in ${f.length} thread${f.length===1?"":"s"}`},d=e.operatorEscalations.filter(f=>f.urgent),m=e.operatorEscalations.filter(f=>!f.urgent);d.length>0&&r.push(`ESCALATED TO OPERATOR, URGENT (${u(d)}) -- past 4h old or an undelivered pileup:
389
389
  ${d.map(l).join(`
390
390
  `)}`),m.length>0&&r.push(`ESCALATED TO OPERATOR, UNANSWERED (${u(m)}):
391
391
  ${m.map(l).join(`
392
- `)}`)}if(e.persistentDispatchFailures.length>0){let c=e.persistentDispatchFailures.map(l=>{if(l.kind==="flapping"){let d=me(l.windowMs);return` ${l.team}: flapping -- ${l.occurrenceCount} occurrences of ${l.mostRecentStatus} in the last ${d}, most recently at ${l.mostRecentAt}`}let u=iI(l.status,l.ageMs);if(l.status==="NO-OUTPUT"&&l.cause!==null){let d=l.cause.sessionResolves?"dispatch completes, session resolves; cause unknown":`session not found${l.cause.provider?` (provider=${l.cause.provider})`:""}; member needs a refresh`;return` ${l.team}: ${u} -- ${d}`}return` ${l.team}: ${u}`});r.push(`UNREACHABLE (${e.persistentDispatchFailures.length}):
392
+ `)}`)}if(e.persistentDispatchFailures.length>0){let c=e.persistentDispatchFailures.map(l=>{if(l.kind==="flapping"){let d=me(l.windowMs);return` ${l.team}: flapping -- ${l.occurrenceCount} occurrences of ${l.mostRecentStatus} in the last ${d}, most recently at ${l.mostRecentAt}`}let u=fL(l.status,l.ageMs);if(l.status==="NO-OUTPUT"&&l.cause!==null){let d=l.cause.sessionResolves?"dispatch completes, session resolves; cause unknown":`session not found${l.cause.provider?` (provider=${l.cause.provider})`:""}; member needs a refresh`;return` ${l.team}: ${u} -- ${d}`}return` ${l.team}: ${u}`});r.push(`UNREACHABLE (${e.persistentDispatchFailures.length}):
393
393
  ${c.join(`
394
- `)}`)}if(e.notObserved.length>0){let c=e.notObserved.map(l=>{let u=me(l.ageMs),d=l.ageMs>Gl?`possible ${l.status}`:l.status;return` ${l.team}: last checked ${u} ago, ${d} then -- ${Vo(l.suspension)}`});r.push(`NOT OBSERVED (${e.notObserved.length}):
394
+ `)}`)}if(e.notObserved.length>0){let c=e.notObserved.map(l=>{let u=me(l.ageMs),d=l.ageMs>Kl?`possible ${l.status}`:l.status;return` ${l.team}: last checked ${u} ago, ${d} then -- ${Yo(l.suspension)}`});r.push(`NOT OBSERVED (${e.notObserved.length}):
395
395
  ${c.join(`
396
396
  `)}`)}if(e.parkedTeamsWithOwedPrompts.length>0){let c=(u,d)=>u.kind==="confirmed-done"?`\`lmbee state reopen ${d}\` to un-park it`:u.kind==="never-active"?"no outbound traffic in this team's entire history -- may never have actually run; check before assuming a `state set` fixes it":u.kind==="unseeded"?"teamfile has NO seeded session (zero `sessionid=` on any `_MEMBER_` line) -- no nudge, state set, or queue delivery can ever reach it; seed it (`lctl seed`), do not nudge or reopen state":u.kind==="no-state"?`no self-report on record -- \`lmbee state set ${d} ACTIVE\` if it genuinely is`:`self-report is \`${u.status}\`${u.changedTs?` since ${he(u.changedTs)}`:""} -- \`lmbee state set ${d} ACTIVE\` if it genuinely is`,l=e.parkedTeamsWithOwedPrompts.map(u=>{let d=u.rows[0];return` ${u.team}: ${u.rows.length} prompt(s) unanswered, oldest #${d.row.id} from ${d.row.from_id} (${me(d.ageMs)} ago) -- ${c(u.reason,u.team)}`});r.push(`PARKED TEAM HAS UNANSWERED INBOUND (${e.parkedTeamsWithOwedPrompts.length}) -- confirmed-done or self-reported non-active, no follow-up mechanism will ever retry:
397
397
  ${l.join(`
@@ -413,17 +413,17 @@ ${c.join(`
413
413
  ${c.join(`
414
414
  `)}`)}if(e.quiescedByProviderDisable.length>0){let c=e.quiescedByProviderDisable.map(l=>{let u=l.expiresAt!==null?` disabled until ${l.expiresAt}`:" disabled indefinitely",d=l.totalMembers-l.liveMembers.length,m="";if(l.liveMembers.length>0){let f=new Map;for(let h of l.liveMembers){let w=h.provider??"(no provider set)",_=f.get(w)??[];_.push(h.alias),f.set(w,_)}m=`; ${[...f.entries()].map(([h,w])=>`${w.join(", ")} still live on ${h}`).join("; ")}`}return` ${l.team}: quiesced (${d}/${l.totalMembers} members${m}), provider ${l.provider}${u}`});r.push(`TEAMS QUIESCED BY A DISABLED PROVIDER (${e.quiescedByProviderDisable.length}) -- manual nudge/enqueue/lctl chat is unaffected:
415
415
  ${c.join(`
416
- `)}`)}if(e.blocked.length>0){let c=e.blocked.map(l=>{let u=Wl(l),d=l.blockedSinceTs===null?" (blocked-since unknown)":(()=>{let f=Date.now()-Date.parse(l.blockedSinceTs),p=me(f);return f>Gl?` -- STALE, blocked ${p} ago`:` (blocked ${p} ago)`})(),m=l.roots&&l.roots.length>0?` -- blocked on ${l.roots.map(f=>`#${f.id} (root, ${le(f.status)})`).join(", ")}`:"";return`${u}${d}${m}`});r.push(`blocked (${e.blocked.length}):
416
+ `)}`)}if(e.blocked.length>0){let c=e.blocked.map(l=>{let u=Jl(l),d=l.blockedSinceTs===null?" (blocked-since unknown)":(()=>{let f=Date.now()-Date.parse(l.blockedSinceTs),p=me(f);return f>Kl?` -- STALE, blocked ${p} ago`:` (blocked ${p} ago)`})(),m=l.roots&&l.roots.length>0?` -- blocked on ${l.roots.map(f=>`#${f.id} (root, ${le(f.status)})`).join(", ")}`:"";return`${u}${d}${m}`});r.push(`blocked (${e.blocked.length}):
417
417
  ${c.join(`
418
418
  `)}`)}if(e.blockedOnUnresolved.length>0){let c=e.blockedOnUnresolved.map(l=>{let u=l.reason==="operator-uncorrelated"?"claims blocked on the operator, no matching unresolved escalation found":`claims blocked on team "${l.blockedOn}", which is not currently registered`;return` ${l.team}: #${l.entity.id} ("${l.entity.title}") -- ${u}`});r.push(`BLOCKED-ON CLAIM UNRESOLVED (${e.blockedOnUnresolved.length}) -- nothing is currently re-prompting anyone about ${e.blockedOnUnresolved.length===1?"this task":"these tasks"}, look directly:
419
419
  ${c.join(`
420
- `)}`)}if(e.owedAnswers.length>0){let c=[...e.owedAnswers].sort((m,f)=>{let p=m.rows.some(w=>!w.hasReplyTrafficSince)?0:1,h=f.rows.some(w=>!w.hasReplyTrafficSince)?0:1;return p-h}),l=c.filter(m=>m.rows.some(f=>!f.hasReplyTrafficSince)).length,u=c.length-l,d=c.map(m=>{let f=m.rows.filter(w=>!w.hasReplyTrafficSince),p=m.rows.filter(w=>w.hasReplyTrafficSince),h=[];if(f.length>0){let w=f.filter(E=>E.row.status!=="retrieved"),_=f.filter(E=>E.row.status==="retrieved");if(w.length>0){let E=w[0];h.push(`${w.length} NEVER RECEIVED (undelivered-to-inbox, not a decision delay) -- oldest #${E.row.id} from ${E.row.from_id} (${me(E.ageMs)} ago), status ${E.row.status}`+Qg(E.laterRelatedTraffic))}if(_.length>0){let E=_[0];h.push(`${_.length} unanswered -- no reply traffic from ${m.team} since the prompt, oldest #${E.row.id} from ${E.row.from_id} (${me(E.ageMs)} ago)`+Qg(E.laterRelatedTraffic))}}if(p.length>0){let w=p.map(_=>`#${_.row.id}`).join(", ");h.push(`${p.length} likely answered in prose (reply traffic exists since the prompt), row(s) unclosed: needs queue answer ${w}`)}if(m.quiescedMembers!==void 0&&m.totalMembers!==void 0){let w=new Map;for(let E of m.quiescedMembers){let T=w.get(E.provider)??[];T.push(E.alias),w.set(E.provider,T)}let _=[...w.entries()].map(([E,T])=>`${E}: ${T.join(", ")}`).join("; ");h.push(`${m.quiescedMembers.length}/${m.totalMembers} members quiesced by a disabled provider (${_})`)}return` ${m.team}: ${h.join("; ")}`});r.push(`TEAMS OWING A DURABLE ANSWER (${l} owed, ${u} unclosed-but-answered) -- for the RECIPIENT, a prose/chat reply alone does not close these; for reading fleet health, reply traffic since the prompt means likely answered:
420
+ `)}`)}if(e.owedAnswers.length>0){let c=[...e.owedAnswers].sort((m,f)=>{let p=m.rows.some(w=>!w.hasReplyTrafficSince)?0:1,h=f.rows.some(w=>!w.hasReplyTrafficSince)?0:1;return p-h}),l=c.filter(m=>m.rows.some(f=>!f.hasReplyTrafficSince)).length,u=c.length-l,d=c.map(m=>{let f=m.rows.filter(w=>!w.hasReplyTrafficSince),p=m.rows.filter(w=>w.hasReplyTrafficSince),h=[];if(f.length>0){let w=f.filter(T=>T.row.status!=="retrieved"),_=f.filter(T=>T.row.status==="retrieved");if(w.length>0){let T=w[0];h.push(`${w.length} NEVER RECEIVED (undelivered-to-inbox, not a decision delay) -- oldest #${T.row.id} from ${T.row.from_id} (${me(T.ageMs)} ago), status ${T.row.status}`+r_(T.laterRelatedTraffic))}if(_.length>0){let T=_[0];h.push(`${_.length} unanswered -- no reply traffic from ${m.team} since the prompt, oldest #${T.row.id} from ${T.row.from_id} (${me(T.ageMs)} ago)`+r_(T.laterRelatedTraffic))}}if(p.length>0){let w=p.map(_=>`#${_.row.id}`).join(", ");h.push(`${p.length} likely answered in prose (reply traffic exists since the prompt), row(s) unclosed: needs queue answer ${w}`)}if(m.quiescedMembers!==void 0&&m.totalMembers!==void 0){let w=new Map;for(let T of m.quiescedMembers){let E=w.get(T.provider)??[];E.push(T.alias),w.set(T.provider,E)}let _=[...w.entries()].map(([T,E])=>`${T}: ${E.join(", ")}`).join("; ");h.push(`${m.quiescedMembers.length}/${m.totalMembers} members quiesced by a disabled provider (${_})`)}return` ${m.team}: ${h.join("; ")}`});r.push(`TEAMS OWING A DURABLE ANSWER (${l} owed, ${u} unclosed-but-answered) -- for the RECIPIENT, a prose/chat reply alone does not close these; for reading fleet health, reply traffic since the prompt means likely answered:
421
421
  ${d.join(`
422
422
  `)}`)}if(e.recentlyAnsweredForSender.length>0){let c=e.recentlyAnsweredForSender.map(l=>{let u=l.rows[0],d=u.answer.answer_text.trim().split(`
423
423
  `)[0].slice(0,140);return` ${l.team}: ${l.rows.length} answer(s) received, newest #${u.row.id} to ${u.row.to_id} (${me(u.ageMs)} ago) -- "${d}"`});r.push(`ANSWERS RECEIVED, NOT YET NOTICED (${e.recentlyAnsweredForSender.length}):
424
424
  ${c.join(`
425
425
  `)}`)}if(e.awaitingDecision.length>0&&r.push(`awaiting decision (${e.awaitingDecision.length}):
426
- ${e.awaitingDecision.map(Wl).join(`
426
+ ${e.awaitingDecision.map(Jl).join(`
427
427
  `)}`),e.awaitingReview.length>0){let c=e.awaitingReview.map(l=>` ${l.team}: #${l.task.id} ("${l.task.title}") -- untouched since ${he(l.task.updatedAt)}`);r.push(`awaiting meta-lead review (${e.awaitingReview.length}):
428
428
  ${c.join(`
429
429
  `)}`)}if(e.stalled.length>0){let c=new Map(e.stalledVerdicts.map(u=>[u.team,u])),l=e.stalled.map(u=>{let d=c.get(u);if(!d)return` ${u}: (not yet verified)`;let m=d.label==="genuinely_done"?` ${u}: verified done, tracker stale -- ${d.reason}`:` ${u}: ${d.label} -- ${d.reason}`;return d.selfReportedDone?`${m} (DISAGREES WITH team's own self-report: DONE since ${he(d.selfReportedDone.changedTs)})`:m});r.push(`stalled (${e.stalled.length}):
@@ -437,7 +437,7 @@ ${c.join(`
437
437
  `)}`)}if(e.flaggedEpics.length>0){let c=e.flaggedEpics.map(l=>` ${l.team}: #${l.entity.id} ("${l.entity.title}") -- ${l.entity.review_reason??"(no reason recorded)"}`);r.push(`epics needing review (${e.flaggedEpics.length}):
438
438
  ${c.join(`
439
439
  `)}`)}if(e.closedEpicsToReview.length>0&&r.push(`closed epics to review (${e.closedEpicsToReview.length}):
440
- ${e.closedEpicsToReview.map(Wl).join(`
440
+ ${e.closedEpicsToReview.map(Jl).join(`
441
441
  `)}`),e.uncommittedWork.length>0){let c=e.uncommittedWork.map(l=>` ${l.team}: ${l.dirtyCount} uncommitted change(s), ${l.todoCount} todo ${l.todoCount===1?"task":"tasks"} in this repo (e.g. #${l.exampleEntity.id} "${l.exampleEntity.title}")`);r.push(`produced output, not committed, not tracked (${e.uncommittedWork.length}):
442
442
  ${c.join(`
443
443
  `)}`)}if(e.teamfileLintWarnings.length>0){let c=e.teamfileLintWarnings.map(l=>` ${l.team}:
@@ -456,7 +456,7 @@ ${c.join(`
456
456
  ${c.join(`
457
457
  `)}`)}if(e.unseededTeams.length>0){let c=e.unseededTeams.map(l=>` ${l.team} (${l.repoPath}) -- seed it (\`lctl seed\`), not a nudge or state set`);r.push(`UNSEEDED (${e.unseededTeams.length}) -- no sessionid on any _MEMBER_ line, nothing can ever reach these:
458
458
  ${c.join(`
459
- `)}`)}if(e.stuckProcessing.length>0){let c=e.stuckProcessing.slice(0,sI),l=c.map(m=>` #${m.queueId} ${m.fromId} -> ${m.toId} -- processing for ${me(m.ageMs)}, no answer`+(m.constituentCount>1?` (${m.constituentCount} merged into this one)`:"")),u=e.stuckProcessing.length-c.length,d=u>0?`
459
+ `)}`)}if(e.stuckProcessing.length>0){let c=e.stuckProcessing.slice(0,mL),l=c.map(m=>` #${m.queueId} ${m.fromId} -> ${m.toId} -- processing for ${me(m.ageMs)}, no answer`+(m.constituentCount>1?` (${m.constituentCount} merged into this one)`:"")),u=e.stuckProcessing.length-c.length,d=u>0?`
460
460
  ...and ${u} more (use --json for the full list)`:"";r.push(`stuck processing (${e.stuckProcessing.length}):
461
461
  ${l.join(`
462
462
  `)}${d}`)}if(e.maintainerStale.length>0){let c=e.maintainerStale.map(l=>` ${l.team}: ${l.reason}`);r.push(`maintainer stale (${e.maintainerStale.length}):
@@ -465,109 +465,109 @@ ${c.join(`
465
465
  ${e.inbox.map(c=>` #${c.id} from ${c.from_id}`).join(`
466
466
  `)}`);let n=r.length===0?"all clear -- nothing needs attention":r.join(`
467
467
 
468
- `),o=Hs(e.memory),s=o===null?n:`${n}
468
+ `),o=Vs(e.memory),s=o===null?n:`${n}
469
469
 
470
470
  ${o}`;if(e.activeGhAccount===null||e.activeGhAccount.matchesPolicy)return s;let i=e.activeGhAccount.hostsFileChangedAt!==null?` (hosts.yml last changed ${e.activeGhAccount.hostsFileChangedAt})`:"";return`${`!!! ACTIVE GH ACCOUNT POLICY MISMATCH: "${e.activeGhAccount.account}" is active on this machine -- every future github.com push authenticates as this account, for every repo.${i} !!!`}
471
471
 
472
- ${s}`}async function Xg(e,t,r,n={}){let o={db:{path:"",db:e,close:()=>{}},teamsConfPath:"",teams:[...t]},s=await Zi(o,{maintainer:r,...n.config!==void 0?{config:n.config}:{},...n.nowMs!==void 0?{nowMs:n.nowMs}:{},...n.awaitingReviewThresholdMs!==void 0?{awaitingReviewThresholdMs:n.awaitingReviewThresholdMs}:{},...n.maintainerStaleThresholdMs!==void 0?{maintainerStaleThresholdMs:n.maintainerStaleThresholdMs}:{},...n.fetchReportImpl!==void 0?{fetchReportImpl:n.fetchReportImpl}:{},...n.heavyLockImpl!==void 0?{heavyLockImpl:n.heavyLockImpl}:{},...n.findNeverTrackFilesImpl!==void 0?{findNeverTrackFilesImpl:n.findNeverTrackFilesImpl}:{},...n.findSecretBearingTeamfilesImpl!==void 0?{findSecretBearingTeamfilesImpl:n.findSecretBearingTeamfilesImpl}:{},...n.checkRepoGitIdentityImpl!==void 0?{checkRepoGitIdentityImpl:n.checkRepoGitIdentityImpl}:{},...n.checkActiveGhAccountImpl!==void 0?{checkActiveGhAccountImpl:n.checkActiveGhAccountImpl}:{},...n.resolveMemberProviderImpl!==void 0?{resolveMemberProviderImpl:n.resolveMemberProviderImpl}:{},...n.lintTeamfileWarningsImpl!==void 0?{lintTeamfileWarningsImpl:n.lintTeamfileWarningsImpl}:{}}),i=(n.readMemoryAvailabilityImpl??To)(),a=s.blocked.length===0&&s.awaitingDecision.length===0&&s.awaitingReview.length===0&&s.stalled.length===0&&s.hungHolders.length===0&&s.flaggedEpics.length===0&&s.closedEpicsToReview.length===0&&(s.inbox===null||s.inbox.length===0)&&s.operatorPrompts.length===0&&s.operatorEscalations.length===0&&s.uncommittedWork.length===0&&s.expiredHolds.length===0&&s.neverTrackFiles.length===0&&s.secretBearingTeamfiles.length===0&&s.gitIdentityMismatches.length===0&&(s.activeGhAccount===null||s.activeGhAccount.matchesPolicy)&&!s.providerDisableReadFailed&&s.quiescedByProviderDisable.length===0&&s.blockedOnUnresolved.length===0&&s.staleAutoScanPause===null&&s.persistentDispatchFailures.every(u=>u.kind!=="continuous")&&s.parkedTeamsWithOwedPrompts.length===0&&s.rateLimitPolicyHealth===null,c=Hs(i),l=c===null?zo(s):`${zo(s)}
472
+ ${s}`}async function n_(e,t,r,n={}){let o={db:{path:"",db:e,close:()=>{}},teamsConfPath:"",teams:[...t]},s=await ra(o,{maintainer:r,...n.config!==void 0?{config:n.config}:{},...n.nowMs!==void 0?{nowMs:n.nowMs}:{},...n.awaitingReviewThresholdMs!==void 0?{awaitingReviewThresholdMs:n.awaitingReviewThresholdMs}:{},...n.maintainerStaleThresholdMs!==void 0?{maintainerStaleThresholdMs:n.maintainerStaleThresholdMs}:{},...n.fetchReportImpl!==void 0?{fetchReportImpl:n.fetchReportImpl}:{},...n.heavyLockImpl!==void 0?{heavyLockImpl:n.heavyLockImpl}:{},...n.findNeverTrackFilesImpl!==void 0?{findNeverTrackFilesImpl:n.findNeverTrackFilesImpl}:{},...n.findSecretBearingTeamfilesImpl!==void 0?{findSecretBearingTeamfilesImpl:n.findSecretBearingTeamfilesImpl}:{},...n.checkRepoGitIdentityImpl!==void 0?{checkRepoGitIdentityImpl:n.checkRepoGitIdentityImpl}:{},...n.checkActiveGhAccountImpl!==void 0?{checkActiveGhAccountImpl:n.checkActiveGhAccountImpl}:{},...n.resolveMemberProviderImpl!==void 0?{resolveMemberProviderImpl:n.resolveMemberProviderImpl}:{},...n.lintTeamfileWarningsImpl!==void 0?{lintTeamfileWarningsImpl:n.lintTeamfileWarningsImpl}:{}}),i=(n.readMemoryAvailabilityImpl??So)(),a=s.blocked.length===0&&s.awaitingDecision.length===0&&s.awaitingReview.length===0&&s.stalled.length===0&&s.hungHolders.length===0&&s.flaggedEpics.length===0&&s.closedEpicsToReview.length===0&&(s.inbox===null||s.inbox.length===0)&&s.operatorPrompts.length===0&&s.operatorEscalations.length===0&&s.uncommittedWork.length===0&&s.expiredHolds.length===0&&s.neverTrackFiles.length===0&&s.secretBearingTeamfiles.length===0&&s.gitIdentityMismatches.length===0&&(s.activeGhAccount===null||s.activeGhAccount.matchesPolicy)&&!s.providerDisableReadFailed&&s.quiescedByProviderDisable.length===0&&s.blockedOnUnresolved.length===0&&s.staleAutoScanPause===null&&s.persistentDispatchFailures.every(u=>u.kind!=="continuous")&&s.parkedTeamsWithOwedPrompts.length===0&&s.rateLimitPolicyHealth===null,c=Vs(i),l=c===null?Zo(s):`${Zo(s)}
473
473
 
474
- ${c}`;return{attention:s,memory:i,isEmpty:a,rendered:l}}var hI=18e5,gI={watch:{first:!1,active:[],wentIdle:[],newlyActive:[],wake:!1,why:"nochange"},stalled:[],maintainerWoken:!1,autoContinued:[],surfacedUnknown:[],surfacedBlocked:[],surfacedDoneConsistency:[],surfacedUnresolvableTeamfiles:[],surfacedFault:[],surfacedClosedEpics:[],escalated:[],autoRedelivered:[],woken:[],firedCronJobs:[],rateLimitCollected:null,rateLimitPolicyEvaluations:[]};function Zg(e){let t=e.fetchReport??Ae,r=e.readHeavyLockStatusImpl??lt,n=e.heavyLockStatusPath??Fn(),o=e.heavyLockPath??qn(),s=e.maintainerWakeImpl??pg,i=e.autoContinueImpl??mg,a=e.surfaceUnknownImpl??xg,c=e.surfaceBlockedImpl??gg,l=e.surfaceDoneConsistencyImpl??Sg,u=e.surfaceUnresolvableTeamfilesImpl??_g,d=e.surfaceFaultImpl??Ag,m=e.surfaceClosedEpicsImpl??yg,f=e.escalateImpl??Ih,p=e.autoRedeliverImpl??Lh,h=e.wakeImpl??Ch,w=e.evaluateCronJobsImpl??vh,_=e.miniplayerVerifyImpl??Kp,E=e.hungHolderCheckImpl??Mp,T=e.epicReviewImpl??Gp,v=e.orphanReconcilerImpl??Hp,S=e.hangProbeCollectImpl??Wp,N=e.rateLimitCollectImpl??Ph,x=e.rateLimitPolicyImpl??qh,I=e.assembleWakeReportImpl??Xg,k=e.existsSyncImpl??mI,B=e.statSyncImpl??pI,C=e.config??pe,g=e.escalation??xl,y=e.autoRedeliver??Rl,R=e.wake??Nl,P=e.intervalMs??hI,J=null,ee=!1;async function oe(){if(ee)return gI;ee=!0;try{let V=e.getTeams(),se=V.filter(H),$;try{$=await t(),Rh($,new Date().toISOString())}catch(G){throw Nh(G instanceof Error?G.message:String(G),new Date().toISOString()),G}let O=Date.now(),A=r(n,o,void 0,G=>{e.onError?.(G)}),q=Os(e.db,se,$),{stalled:M,continueEligible:Z}=await Lf(e.db,se,$,A,C,O);if(e.miniplayerVerify)try{await _(e.db,M,se,e.miniplayerVerify)}catch(G){e.onError?.(G)}let W=new Set(M);for(let G of se)!W.has(G.name)&&ie(e.db,G.name)?.miniplayer_verdict_label&&Wd(e.db,G.name);if(e.hungHolderCheck)try{let G=e.maintainerWake?.sessionAlivePath!==void 0||e.maintainerWake?.activityFreshnessMs!==void 0?{sessionAliveExemptTeamName:e.maintainerWake.teamName,sessionAliveExemptPath:e.maintainerWake.sessionAlivePath,sessionAliveFreshnessMs:e.maintainerWake.sessionAliveFreshnessMs,activityFreshnessMs:e.maintainerWake.activityFreshnessMs}:{};await E(e.db,se,{...G,...e.hungHolderCheck})}catch(G){e.onError?.(G)}if(e.orphanReconciler)try{let G=e.maintainerWake?.sessionAlivePath!==void 0||e.maintainerWake?.activityFreshnessMs!==void 0?{sessionAliveExemptTeamName:e.maintainerWake.teamName,sessionAliveExemptPath:e.maintainerWake.sessionAlivePath,sessionAliveFreshnessMs:e.maintainerWake.sessionAliveFreshnessMs,activityFreshnessMs:e.maintainerWake.activityFreshnessMs}:{};await v(e.db,V,$,{...G,...e.orphanReconciler})}catch(G){e.onError?.(G)}if(e.hangProbeCollect)try{S(e.db,e.hangProbeCollect)}catch(G){e.onError?.(G)}if(e.autoNudgeRedirectReview)try{let G=e.findDueAutoNudgeReviewsImpl??Ap,we=new Map(se.map(et=>[et.name,et.repoPath])),st=new Map(se.map(et=>[et.name,et])),Ze=await G(e.db,we,O),ft=e.buildReviewMessageImpl??kp,Ve=e.resetShiftImpl??$p,mn=e.enqueueImpl??_e,gr=e.checkProviderDisabledImpl??rt,or=e.resolveMemberProviderImpl??jt;for(let et of Ze)try{let _r=we.get(et.team);if(_r===void 0)continue;let po=st.get(et.team),ys=po===void 0?null:or(po,po.leadAlias);if(ys!==null&&gr(e.db,ys,O).disabled)continue;let Ra=await ft(et,_r);mn(e.db,V,et.team,Ra,{from:"autopilot"}),await Ve(e.db,et.team,_r,new Date(O).toISOString())}catch(_r){e.onError?.(_r)}}catch(G){e.onError?.(G)}if(e.epicReview)try{await T(e.db,V,e.epicReview)}catch(G){e.onError?.(G)}let ae=!1;if(e.maintainerWake)try{let G={cooldownMs:C.cooldownMs,...e.maintainerWake};if(G.sessionAlivePath!==void 0){let we=Cn(G.sessionAlivePath,G.sessionAliveFreshnessMs,G.activityFreshnessMs!==void 0?ie(e.db,G.teamName)?.last_cli_activity_ts??null:null,G.activityFreshnessMs,{existsSyncImpl:k,statSyncImpl:B,nowMs:O}),st,Ze;try{let Ve=await I(e.db,V,G.teamName,{nowMs:O,config:C,fetchReportImpl:async()=>$,heavyLockImpl:()=>A,...G.maintainerStaleThresholdMs!==void 0?{maintainerStaleThresholdMs:G.maintainerStaleThresholdMs}:{}});st=Ve.rendered,Ze=Ve.isEmpty}catch(Ve){e.onError?.(Ve),st="wake-report assembly failed this tick -- waking conservatively; check server logs for the error.",Ze=!1}let ft=Ve=>`${fI(Ve,"utf8")}
474
+ ${c}`;return{attention:s,memory:i,isEmpty:a,rendered:l}}var bL=18e5,SL={watch:{first:!1,active:[],wentIdle:[],newlyActive:[],wake:!1,why:"nochange"},stalled:[],maintainerWoken:!1,autoContinued:[],surfacedUnknown:[],surfacedBlocked:[],surfacedDoneConsistency:[],surfacedUnresolvableTeamfiles:[],surfacedFault:[],surfacedClosedEpics:[],escalated:[],autoRedelivered:[],woken:[],firedCronJobs:[],rateLimitCollected:null,rateLimitPolicyEvaluations:[]};function o_(e){let t=e.fetchReport??Ae,r=e.readHeavyLockStatusImpl??lt,n=e.heavyLockStatusPath??jn(),o=e.heavyLockPath??Hn(),s=e.maintainerWakeImpl??yg,i=e.autoContinueImpl??_g,a=e.surfaceUnknownImpl??Cg,c=e.surfaceBlockedImpl??Tg,l=e.surfaceDoneConsistencyImpl??xg,u=e.surfaceUnresolvableTeamfilesImpl??bg,d=e.surfaceFaultImpl??Ng,m=e.surfaceClosedEpicsImpl??vg,f=e.escalateImpl??Mh,p=e.autoRedeliverImpl??Ph,h=e.wakeImpl??Uh,w=e.evaluateCronJobsImpl??kh,_=e.miniplayerVerifyImpl??Qp,T=e.hungHolderCheckImpl??Fp,E=e.epicReviewImpl??Kp,v=e.orphanReconcilerImpl??Gp,S=e.hangProbeCollectImpl??Jp,N=e.rateLimitCollectImpl??Hh,$=e.rateLimitPolicyImpl??Gh,L=e.assembleWakeReportImpl??n_,R=e.existsSyncImpl??yL,H=e.statSyncImpl??TL,C=e.config??pe,g=e.escalation??Ll,y=e.autoRedeliver??Il,x=e.wake??Cl,P=e.intervalMs??bL,J=null,ee=!1;async function oe(){if(ee)return SL;ee=!0;try{let V=e.getTeams(),se=V.filter(B),k;try{k=await t(),Oh(k,new Date().toISOString())}catch(G){throw Dh(G instanceof Error?G.message:String(G),new Date().toISOString()),G}let O=Date.now(),A=r(n,o,void 0,G=>{e.onError?.(G)}),q=Us(e.db,se,k),{stalled:M,continueEligible:Z}=await Df(e.db,se,k,A,C,O);if(e.miniplayerVerify)try{await _(e.db,M,se,e.miniplayerVerify)}catch(G){e.onError?.(G)}let W=new Set(M);for(let G of se)!W.has(G.name)&&ie(e.db,G.name)?.miniplayer_verdict_label&&Jd(e.db,G.name);if(e.hungHolderCheck)try{let G=e.maintainerWake?.sessionAlivePath!==void 0||e.maintainerWake?.activityFreshnessMs!==void 0?{sessionAliveExemptTeamName:e.maintainerWake.teamName,sessionAliveExemptPath:e.maintainerWake.sessionAlivePath,sessionAliveFreshnessMs:e.maintainerWake.sessionAliveFreshnessMs,activityFreshnessMs:e.maintainerWake.activityFreshnessMs}:{};await T(e.db,se,{...G,...e.hungHolderCheck})}catch(G){e.onError?.(G)}if(e.orphanReconciler)try{let G=e.maintainerWake?.sessionAlivePath!==void 0||e.maintainerWake?.activityFreshnessMs!==void 0?{sessionAliveExemptTeamName:e.maintainerWake.teamName,sessionAliveExemptPath:e.maintainerWake.sessionAlivePath,sessionAliveFreshnessMs:e.maintainerWake.sessionAliveFreshnessMs,activityFreshnessMs:e.maintainerWake.activityFreshnessMs}:{};await v(e.db,V,k,{...G,...e.orphanReconciler})}catch(G){e.onError?.(G)}if(e.hangProbeCollect)try{S(e.db,e.hangProbeCollect)}catch(G){e.onError?.(G)}if(e.autoNudgeRedirectReview)try{let G=e.findDueAutoNudgeReviewsImpl??xp,we=new Map(se.map(et=>[et.name,et.repoPath])),st=new Map(se.map(et=>[et.name,et])),Ze=await G(e.db,we,O),ft=e.buildReviewMessageImpl??Np,Ve=e.resetShiftImpl??Rp,mn=e.enqueueImpl??_e,_r=e.checkProviderDisabledImpl??rt,or=e.resolveMemberProviderImpl??jt;for(let et of Ze)try{let wr=we.get(et.team);if(wr===void 0)continue;let go=st.get(et.team),Ss=go===void 0?null:or(go,go.leadAlias);if(Ss!==null&&_r(e.db,Ss,O).disabled)continue;let Ia=await ft(et,wr);mn(e.db,V,et.team,Ia,{from:"autopilot"}),await Ve(e.db,et.team,wr,new Date(O).toISOString())}catch(wr){e.onError?.(wr)}}catch(G){e.onError?.(G)}if(e.epicReview)try{await E(e.db,V,e.epicReview)}catch(G){e.onError?.(G)}let ae=!1;if(e.maintainerWake)try{let G={cooldownMs:C.cooldownMs,...e.maintainerWake};if(G.sessionAlivePath!==void 0){let we=Cn(G.sessionAlivePath,G.sessionAliveFreshnessMs,G.activityFreshnessMs!==void 0?ie(e.db,G.teamName)?.last_cli_activity_ts??null:null,G.activityFreshnessMs,{existsSyncImpl:R,statSyncImpl:H,nowMs:O}),st,Ze;try{let Ve=await L(e.db,V,G.teamName,{nowMs:O,config:C,fetchReportImpl:async()=>k,heavyLockImpl:()=>A,...G.maintainerStaleThresholdMs!==void 0?{maintainerStaleThresholdMs:G.maintainerStaleThresholdMs}:{}});st=Ve.rendered,Ze=Ve.isEmpty}catch(Ve){e.onError?.(Ve),st="wake-report assembly failed this tick -- waking conservatively; check server logs for the error.",Ze=!1}let ft=Ve=>`${EL(Ve,"utf8")}
475
475
 
476
476
  ---
477
- ${st}`;ae=s(e.db,se,$,G,ft,O,we?void 0:!Ze)}else ae=s(e.db,se,$,G,void 0,O)}catch(G){e.onError?.(G)}let Ee=[];if(e.autoContinue&&Ir(e.db)===null)try{Ee=await i(e.db,se,$,{config:C,...e.autoContinue,nowMs:O,stalledTeamNames:Z,heavyLockStatusPath:n,heavyLockPath:o,readHeavyLockStatusImpl:r})}catch(G){e.onError?.(G)}let ne=[];if(e.maintainerWake)try{ne=await a(e.db,M,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let D=[];if(e.maintainerWake)try{D=await c(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let j=[];if(e.maintainerWake)try{j=await l(e.db,se,e.maintainerWake.teamName,V,C)}catch(G){e.onError?.(G)}let Y=[];if(e.maintainerWake)try{Y=await d(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let K=[];if(e.maintainerWake)try{K=await m(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let re=[];if(e.maintainerWake)try{re=await u(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let te=[];try{te=await w(e.db,V,O,{onJobError:(G,we)=>e.onError?.(we)})}catch(G){e.onError?.(G)}let ue=[];try{ue=await f(e.db,se,g,O)}catch(G){e.onError?.(G)}let $e=[];try{$e=p(e.db,se,y,O)}catch(G){e.onError?.(G)}let be=[];try{be=h(e.db,se,$,R,O)}catch(G){e.onError?.(G)}let z=null,Te=[],Ge=e.rateLimitPolicy??e.rateLimitAutomation,je=e.rateLimitCollect??Ge;if(je!==void 0){let G=Date.now();try{z=await N(e.db,{nowMs:G,...je})}catch(we){e.onError?.(we)}try{Te=x(e.db,{nowMs:G,...Ge,dryRun:Ge===void 0})}catch(we){e.onError?.(we)}}let Ct={watch:q,stalled:M,maintainerWoken:ae,autoContinued:Ee,surfacedUnknown:ne,surfacedBlocked:D,surfacedDoneConsistency:j,surfacedUnresolvableTeamfiles:re,surfacedFault:Y,surfacedClosedEpics:K,escalated:ue,autoRedelivered:$e,woken:be,firedCronJobs:te,rateLimitCollected:z,rateLimitPolicyEvaluations:Te};return e.onTick?.(Ct),Ct}catch(V){throw e.onError?.(V),V}finally{ee=!1}}return{start(){J||(J=setInterval(()=>{oe().catch(()=>{})},P),J.unref())},stop(){J&&(clearInterval(J),J=null)},runTickNow:oe,isRunning:()=>J!==null,isTicking:()=>ee}}import{closeSync as _I,linkSync as wI,openSync as yI,readdirSync as EI,readFileSync as ta,readlinkSync as TI,realpathSync as bI,renameSync as e_,unlinkSync as Jl,writeSync as SI}from"node:fs";import{dirname as vI,join as AI}from"node:path";var Hn=class extends Error{holder;lockPath;constructor(t,r){super(`site lock held by "${t.ownerLabel}" (pid ${t.pid}, started ${t.startedAt}) at ${r} -- only one process (standalone \`lmauto serve\` or \`lmt site start\`) may run lmauto's scheduler against this DB at a time`),this.holder=t,this.lockPath=r,this.name="SiteLockHeldError"}};function Yo(e){return e===":memory:"?null:`${e}.lock`}function o_(e){let t=Qo(e);return t.kind==="held"?t.identity:null}function t_(e){let t;try{t=ta(e,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"free"}:{kind:"unknown"}}let r=Za(t);if(!r)return{kind:"unknown"};let n={...r,bootId:r.bootId??null};return Vl(n)?{kind:"held",identity:n}:{kind:"free"}}function $I(e,t){let r;try{r=bI(t)}catch{return!1}let n;try{n=EI(`/proc/${e}/fd`)}catch{return!1}for(let o of n)try{if(TI(`/proc/${e}/fd/${o}`)===r)return!0}catch{}return!1}function Qo(e){let t=Yo(e);if(t===null)return{kind:"free"};let r=t_(t);if(r.kind==="held")return r;let n=AI(vI(e),"site.lock");if(n===t)return r;let o=t_(n);return o.kind==="held"&&$I(o.identity.pid,e)?o:r}function ea(e){try{let t=Za(ta(e,"utf8"));return t?{...t,bootId:t.bootId??null}:null}catch{return null}}function s_(){try{let e=ta("/proc/sys/kernel/random/boot_id","utf8").trim();return ec(e)?e:null}catch{return null}}function i_(e){try{let t=ta(`/proc/${e}/stat`,"utf8"),o=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(o===void 0)return null;let s=Number(o);return Number.isFinite(s)?s:null}catch{return null}}function Vl(e){let t;try{process.kill(e.pid,0),t=!0}catch(n){t=n.code==="EPERM"}if(!t)return!1;if(e.bootId!==null){let n=s_();if(n!==null&&n!==e.bootId)return!1}if(e.pidStartTicks===null)return!0;let r=i_(e.pid);return r===null?!0:r===e.pidStartTicks}function r_(e,t){let r=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,n=yI(r,"wx");try{SI(n,JSON.stringify(t))}finally{_I(n)}try{return wI(r,e),!0}catch(o){if(o.code!=="EEXIST")throw o;return!1}finally{Jl(r)}}function ra(e,t){let r={pid:process.pid,ownerLabel:t,startedAt:new Date().toISOString(),pidStartTicks:i_(process.pid),bootId:s_()};if(r_(e,r))return n_(e,r);let n=ea(e);if(n!==null&&Vl(n))throw new Hn(n,e);let o=`${e}.reclaim.${process.pid}.${Math.random().toString(36).slice(2)}`,s=!1;try{e_(e,o);let a=ea(o);n===null&&a===null||n!==null&&a!==null&&a.pid===n.pid&&a.startedAt===n.startedAt?(Jl(o),s=!0):e_(o,e)}catch{}if(s&&r_(e,r))return n_(e,r);let i=ea(e);throw i!==null&&Vl(i)?new Hn(i,e):new Error(`failed to acquire site lock at ${e} (lost a reclaim race)`)}function n_(e,t){let r=!1;return{release(){if(!r){r=!0;try{let n=ea(e);n!==null&&n.pid===t.pid&&n.startedAt===t.startedAt&&Jl(e)}catch{}}}}}import{closeSync as Kl,existsSync as kI,fstatSync as xI,mkdirSync as RI,openSync as a_,readFileSync as c_,renameSync as NI,unlinkSync as II,writeSync as LI}from"node:fs";import{dirname as l_,join as CI}from"node:path";import{createHash as OI,randomBytes as DI}from"node:crypto";var MI=32;function Bn(e){return e===":memory:"?null:CI(l_(e),"localweb-passcode")}function PI(){return DI(MI).toString("base64url")}function zl(e,t){let r=l_(e);kI(r)||RI(r,{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,o;try{o=a_(n,"wx",384);let s=Buffer.from(t,"utf8"),i=0;for(;i<s.length;){let a=LI(o,s,i,s.length-i);if(a<=0)throw new Error("passcode file write made no progress");i+=a}Kl(o),o=void 0,NI(n,e)}catch(s){if(o!==void 0)try{Kl(o)}catch{}try{II(n)}catch{}throw s}}function u_(e){let t;try{t=a_(e,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=xI(t,{bigint:!0}),n=c_(t,"utf8"),o=OI("sha256").update(`${r.dev}:${r.ino}:${r.ctimeNs}:${r.mtimeNs}:${r.size}:`).update(n,"utf8").digest("base64url");return{passcode:n,generation:o}}finally{Kl(t)}}function d_(e){try{return c_(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function na(e){let t=PI();return zl(e,t),t}import{randomUUID as UI}from"node:crypto";function Yl(e){return`remote:${e.from.team?`${e.from.site}:${e.from.team}:${e.from.alias}`:`${e.from.site}:${e.from.alias}`}`}function m_(e,t,r){let n=t.find(o=>o.name===r.to.team);if(!n)throw new Error(`no local team registered for remote envelope's to.team "${r.to.team}"`);if(!H(n))throw new Error(`remote envelope addressed to "${r.to.team}", which is itself a remote (channel=lmmail) team -- not locally dispatchable`);_e(e,t,n.name,r.payload,{from:Yl(r),dedupeKey:r.msgId})}var FI=new Set(["dispatched","queued","failed"]);function qI(e){let t;try{t=JSON.parse(e)}catch{return!1}if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t.state;return typeof r=="string"&&FI.has(r)}var jI="reply-surfaced:";function HI(e,t,r,n){let o=r.inReplyTo;if(!o)throw new Error("recordReplyOrAck: envelope has no in_reply_to");let s=Zm(e,o);if(!s)return"orphan";if(qI(r.payload))return ef(e,o,n),"acked";tf(e,o,n);let i=t.find(a=>H(a)&&a.name===s.from_alias);if(i)try{_e(e,t,i.name,r.payload,{from:Yl(r),dedupeKey:`${jI}${r.msgId}`})}catch(a){process.stderr.write(`[mail] failed to surface reply to ${i.name}'s inbox (in_reply_to ${o}): ${a instanceof Error?a.message:String(a)}
478
- `)}return"replied"}function BI(e,t,r,n,o){let s=e.now??(()=>new Date().toISOString()),i={v:1,msgId:UI(),to:t,from:{site:e.localSiteId,team:"",alias:"lmauto"},sentAt:s(),payload:JSON.stringify({state:n,...o?{note:o}:{}}),inReplyTo:r},a=zr(t.site),c=new TextEncoder().encode(Eo(i));e.client.sendMessage({mailbox:a,subject:`lmauto ack ${i.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:c}}).catch(l=>{process.stderr.write(`[mail] failed to send ack to mailbox ${a} (in_reply_to ${r}): ${l instanceof Error?l.message:String(l)}
479
- `)})}function f_(e,t,r,n){if(r.inReplyTo){HI(e,t,r,(n.now??(()=>new Date().toISOString()))());return}let o;try{m_(e,t,r)}catch(i){o=i}let s=n.now??(()=>new Date().toISOString());if(Ym(e,r.msgId,s())){let i=o?(o instanceof Error?o.message:String(o)).slice(0,500):void 0;BI(n,r.from,r.msgId,o?"failed":"dispatched",i)}if(o)throw o}var __=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,WI=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,GI="text/plain; charset=utf-8",Ql="exec",w_="exec-result";var VI="exec-result";var JI=`
477
+ ${st}`;ae=s(e.db,se,k,G,ft,O,we?void 0:!Ze)}else ae=s(e.db,se,k,G,void 0,O)}catch(G){e.onError?.(G)}let Ee=[];if(e.autoContinue&&Lr(e.db)===null)try{Ee=await i(e.db,se,k,{config:C,...e.autoContinue,nowMs:O,stalledTeamNames:Z,heavyLockStatusPath:n,heavyLockPath:o,readHeavyLockStatusImpl:r})}catch(G){e.onError?.(G)}let ne=[];if(e.maintainerWake)try{ne=await a(e.db,M,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let D=[];if(e.maintainerWake)try{D=await c(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let j=[];if(e.maintainerWake)try{j=await l(e.db,se,e.maintainerWake.teamName,V,C)}catch(G){e.onError?.(G)}let Y=[];if(e.maintainerWake)try{Y=await d(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let K=[];if(e.maintainerWake)try{K=await m(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let re=[];if(e.maintainerWake)try{re=await u(e.db,se,e.maintainerWake.teamName,V,C,O)}catch(G){e.onError?.(G)}let te=[];try{te=await w(e.db,V,O,{onJobError:(G,we)=>e.onError?.(we)})}catch(G){e.onError?.(G)}let ue=[];try{ue=await f(e.db,se,g,O)}catch(G){e.onError?.(G)}let ke=[];try{ke=p(e.db,se,y,O)}catch(G){e.onError?.(G)}let be=[];try{be=h(e.db,se,k,x,O)}catch(G){e.onError?.(G)}let z=null,Te=[],Ge=e.rateLimitPolicy??e.rateLimitAutomation,je=e.rateLimitCollect??Ge;if(je!==void 0){let G=Date.now();try{z=await N(e.db,{nowMs:G,...je})}catch(we){e.onError?.(we)}try{Te=$(e.db,{nowMs:G,...Ge,dryRun:Ge===void 0})}catch(we){e.onError?.(we)}}let Ct={watch:q,stalled:M,maintainerWoken:ae,autoContinued:Ee,surfacedUnknown:ne,surfacedBlocked:D,surfacedDoneConsistency:j,surfacedUnresolvableTeamfiles:re,surfacedFault:Y,surfacedClosedEpics:K,escalated:ue,autoRedelivered:ke,woken:be,firedCronJobs:te,rateLimitCollected:z,rateLimitPolicyEvaluations:Te};return e.onTick?.(Ct),Ct}catch(V){throw e.onError?.(V),V}finally{ee=!1}}return{start(){J||(J=setInterval(()=>{oe().catch(()=>{})},P),J.unref())},stop(){J&&(clearInterval(J),J=null)},runTickNow:oe,isRunning:()=>J!==null,isTicking:()=>ee}}import{closeSync as vL,linkSync as AL,openSync as kL,readdirSync as $L,readFileSync as oa,readlinkSync as xL,realpathSync as RL,renameSync as s_,unlinkSync as Yl,writeSync as NL}from"node:fs";import{dirname as LL,join as IL}from"node:path";var Wn=class extends Error{holder;lockPath;constructor(t,r){super(`site lock held by "${t.ownerLabel}" (pid ${t.pid}, started ${t.startedAt}) at ${r} -- only one process (standalone \`lmauto serve\` or \`lmt site start\`) may run lmauto's scheduler against this DB at a time`),this.holder=t,this.lockPath=r,this.name="SiteLockHeldError"}};function es(e){return e===":memory:"?null:`${e}.lock`}function l_(e){let t=ts(e);return t.kind==="held"?t.identity:null}function i_(e){let t;try{t=oa(e,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"free"}:{kind:"unknown"}}let r=rc(t);if(!r)return{kind:"unknown"};let n={...r,bootId:r.bootId??null};return zl(n)?{kind:"held",identity:n}:{kind:"free"}}function CL(e,t){let r;try{r=RL(t)}catch{return!1}let n;try{n=$L(`/proc/${e}/fd`)}catch{return!1}for(let o of n)try{if(xL(`/proc/${e}/fd/${o}`)===r)return!0}catch{}return!1}function ts(e){let t=es(e);if(t===null)return{kind:"free"};let r=i_(t);if(r.kind==="held")return r;let n=IL(LL(e),"site.lock");if(n===t)return r;let o=i_(n);return o.kind==="held"&&CL(o.identity.pid,e)?o:r}function na(e){try{let t=rc(oa(e,"utf8"));return t?{...t,bootId:t.bootId??null}:null}catch{return null}}function u_(){try{let e=oa("/proc/sys/kernel/random/boot_id","utf8").trim();return nc(e)?e:null}catch{return null}}function d_(e){try{let t=oa(`/proc/${e}/stat`,"utf8"),o=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[19];if(o===void 0)return null;let s=Number(o);return Number.isFinite(s)?s:null}catch{return null}}function zl(e){let t;try{process.kill(e.pid,0),t=!0}catch(n){t=n.code==="EPERM"}if(!t)return!1;if(e.bootId!==null){let n=u_();if(n!==null&&n!==e.bootId)return!1}if(e.pidStartTicks===null)return!0;let r=d_(e.pid);return r===null?!0:r===e.pidStartTicks}function a_(e,t){let r=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,n=kL(r,"wx");try{NL(n,JSON.stringify(t))}finally{vL(n)}try{return AL(r,e),!0}catch(o){if(o.code!=="EEXIST")throw o;return!1}finally{Yl(r)}}function sa(e,t){let r={pid:process.pid,ownerLabel:t,startedAt:new Date().toISOString(),pidStartTicks:d_(process.pid),bootId:u_()};if(a_(e,r))return c_(e,r);let n=na(e);if(n!==null&&zl(n))throw new Wn(n,e);let o=`${e}.reclaim.${process.pid}.${Math.random().toString(36).slice(2)}`,s=!1;try{s_(e,o);let a=na(o);n===null&&a===null||n!==null&&a!==null&&a.pid===n.pid&&a.startedAt===n.startedAt?(Yl(o),s=!0):s_(o,e)}catch{}if(s&&a_(e,r))return c_(e,r);let i=na(e);throw i!==null&&zl(i)?new Wn(i,e):new Error(`failed to acquire site lock at ${e} (lost a reclaim race)`)}function c_(e,t){let r=!1;return{release(){if(!r){r=!0;try{let n=na(e);n!==null&&n.pid===t.pid&&n.startedAt===t.startedAt&&Yl(e)}catch{}}}}}import{closeSync as Ql,existsSync as OL,fstatSync as DL,mkdirSync as ML,openSync as m_,readFileSync as f_,renameSync as PL,unlinkSync as UL,writeSync as FL}from"node:fs";import{dirname as p_,join as qL}from"node:path";import{createHash as jL,randomBytes as HL}from"node:crypto";var BL=32;function Gn(e){return e===":memory:"?null:qL(p_(e),"localweb-passcode")}function WL(){return HL(BL).toString("base64url")}function Xl(e,t){let r=p_(e);OL(r)||ML(r,{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,o;try{o=m_(n,"wx",384);let s=Buffer.from(t,"utf8"),i=0;for(;i<s.length;){let a=FL(o,s,i,s.length-i);if(a<=0)throw new Error("passcode file write made no progress");i+=a}Ql(o),o=void 0,PL(n,e)}catch(s){if(o!==void 0)try{Ql(o)}catch{}try{UL(n)}catch{}throw s}}function h_(e){let t;try{t=m_(e,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=DL(t,{bigint:!0}),n=f_(t,"utf8"),o=jL("sha256").update(`${r.dev}:${r.ino}:${r.ctimeNs}:${r.mtimeNs}:${r.size}:`).update(n,"utf8").digest("base64url");return{passcode:n,generation:o}}finally{Ql(t)}}function g_(e){try{return f_(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function ia(e){let t=WL();return Xl(e,t),t}import{randomUUID as GL}from"node:crypto";function Zl(e){return`remote:${e.from.team?`${e.from.site}:${e.from.team}:${e.from.alias}`:`${e.from.site}:${e.from.alias}`}`}function __(e,t,r){let n=t.find(o=>o.name===r.to.team);if(!n)throw new Error(`no local team registered for remote envelope's to.team "${r.to.team}"`);if(!B(n))throw new Error(`remote envelope addressed to "${r.to.team}", which is itself a remote (channel=lmmail) team -- not locally dispatchable`);_e(e,t,n.name,r.payload,{from:Zl(r),dedupeKey:r.msgId})}var VL=new Set(["dispatched","queued","failed"]);function JL(e){let t;try{t=JSON.parse(e)}catch{return!1}if(typeof t!="object"||t===null||Array.isArray(t))return!1;let r=t.state;return typeof r=="string"&&VL.has(r)}var KL="reply-surfaced:";function zL(e,t,r,n){let o=r.inReplyTo;if(!o)throw new Error("recordReplyOrAck: envelope has no in_reply_to");let s=rf(e,o);if(!s)return"orphan";if(JL(r.payload))return nf(e,o,n),"acked";of(e,o,n);let i=t.find(a=>B(a)&&a.name===s.from_alias);if(i)try{_e(e,t,i.name,r.payload,{from:Zl(r),dedupeKey:`${KL}${r.msgId}`})}catch(a){process.stderr.write(`[mail] failed to surface reply to ${i.name}'s inbox (in_reply_to ${o}): ${a instanceof Error?a.message:String(a)}
478
+ `)}return"replied"}function YL(e,t,r,n,o){let s=e.now??(()=>new Date().toISOString()),i={v:1,msgId:GL(),to:t,from:{site:e.localSiteId,team:"",alias:"lmauto"},sentAt:s(),payload:JSON.stringify({state:n,...o?{note:o}:{}}),inReplyTo:r},a=zr(t.site),c=new TextEncoder().encode(bo(i));e.client.sendMessage({mailbox:a,subject:`lmauto ack ${i.msgId}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:c}}).catch(l=>{process.stderr.write(`[mail] failed to send ack to mailbox ${a} (in_reply_to ${r}): ${l instanceof Error?l.message:String(l)}
479
+ `)})}function w_(e,t,r,n){if(r.inReplyTo){zL(e,t,r,(n.now??(()=>new Date().toISOString()))());return}let o;try{__(e,t,r)}catch(i){o=i}let s=n.now??(()=>new Date().toISOString());if(Zm(e,r.msgId,s())){let i=o?(o instanceof Error?o.message:String(o)).slice(0,500):void 0;YL(n,r.from,r.msgId,o?"failed":"dispatched",i)}if(o)throw o}var b_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,QL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,XL="text/plain; charset=utf-8",eu="exec",S_="exec-result";var ZL="exec-result";var eI=`
480
480
  ... [lmexec output truncated; middle elided, see attachment] ...
481
- `;function y_(e){return Xl(S_(e))}function E_(e){return T_(S_(e))}function Xl(e){let t=v_(e),r=A_(t.type,"type",Ql),n=$_(t.id,"id"),o=eu(t.command,"command"),s=XI(t.timeout_s,"timeout_s"),i=QI(t.reply_to,"reply_to"),a=zI(t.from,"from");return{v:1,type:r,id:n,command:o,timeout_s:s,reply_to:i,...a===void 0?{}:{from:a}}}function T_(e){let t=v_(e),r=KI(t.v),n=A_(t.type,"type",w_),o=$_(t.id,"id"),s=eL(t.exit_code,"exit_code"),i=h_(t.stdout,"stdout"),a=h_(t.stderr,"stderr"),c=ZI(t.duration_ms,"duration_ms"),l=g_(t.timed_out,"timed_out"),u=g_(t.truncated,"truncated");if(l&&s!==null)throw new Error("invalid exec result: exit_code must be null when timed_out is true");if(!l&&s===null)throw new Error("invalid exec result: exit_code must be a number when timed_out is false");let d={type:n,id:o,exit_code:s,stdout:i,stderr:a,duration_ms:c,timed_out:l,truncated:u};if(r===1)return{v:r,...d};let m=YI(t.sender_trust),f=eu(t.sender,"sender");return{v:r,...d,sender_trust:m,sender:f}}function Zl(e){if(!__.test(e))throw new Error(`invalid exec id: ${e}`);return`${VI} ${e}`}function p_(e,t,r){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),o=r?.capBytes??49152,s=r?.marker??JI;if(!Number.isInteger(o)||o<1)throw new Error("inline cap must be a positive integer");if(n.byteLength<=o)return{inline:n.toString("utf8"),truncated:!1};let i=Buffer.byteLength(s,"utf8");if(i>=o)throw new Error("elision marker must be smaller than the inline cap");let a=n.toString("utf8"),c=o-i,l=Math.ceil(c/2),u=Math.floor(c/2);return{inline:`${tL(a,l)}${s}${rL(a,u)}`,truncated:!0,attachment:{name:e==="stdout"?"stdout.txt":"stderr.txt",content_type:GI,data:n}}}function b_(e,t){let r=p_("stdout",e.stdout,t),n=p_("stderr",e.stderr,t),o=T_({v:2,type:w_,id:e.id,exit_code:e.exit_code,stdout:r.inline,stderr:n.inline,duration_ms:e.duration_ms,timed_out:e.timed_out,truncated:r.truncated||n.truncated,sender_trust:e.sender_trust,sender:e.sender});return{subject:Zl(e.id),envelope:o,attachments:[r.attachment,n.attachment].filter(s=>s!==void 0)}}function S_(e){try{return JSON.parse(e)}catch(t){throw new Error(`invalid JSON: ${nL(t)}`)}}function v_(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("expected object");return e}function A_(e,t,r){if(e!==r)throw new Error(`invalid ${t}: expected ${r}`);return r}function KI(e){if(e===void 0||e===1)return 1;if(e===2)return 2;throw new Error("invalid v: expected 1 or 2")}function $_(e,t){if(typeof e!="string"||!__.test(e))throw new Error(`invalid ${t}: expected UUID v4`);return e}function eu(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`invalid ${t}: expected non-empty string`);return e}function zI(e,t){if(e!==void 0)return eu(e,t)}function YI(e){if(e==="admin"||e==="registered"||e==="anonymous")return e;throw new Error("invalid sender_trust: expected admin, registered, or anonymous")}function QI(e,t){if(typeof e!="string"||e.includes("/")||e.includes("\\")||e.includes("..")||e.endsWith(".")||/[\u0000-\u001f\u007f]/.test(e)||!WI.test(e))throw new Error(`invalid ${t}: expected mailbox name`);return e}function h_(e,t){if(typeof e!="string")throw new Error(`invalid ${t}: expected string`);return e}function XI(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<1)throw new Error(`invalid ${t}: expected positive integer`);return e}function ZI(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer`);return e}function eL(e,t){if(e===null)return null;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer or null`);return e}function g_(e,t){if(typeof e!="boolean")throw new Error(`invalid ${t}: expected boolean`);return e}function tL(e,t){if(t<=0||e.length===0)return"";let r=0,n="";for(let o of e){let s=Buffer.byteLength(o,"utf8");if(r+s>t)break;n+=o,r+=s}return n}function rL(e,t){if(t<=0||e.length===0)return"";let r=0,n=[],o=Array.from(e);for(let s=o.length-1;s>=0;s-=1){let i=o[s],a=Buffer.byteLength(i,"utf8");if(r+a>t)break;n.push(i),r+=a}return n.reverse().join("")}function nL(e){return e instanceof Error&&e.message?e.message:String(e)}var oL=/[;&|`$<>(){}\\]/,k_=/[\x00-\x1f\x7f]/;function R_(e){let t=[],r=0,n=e.length;for(;r<n;){for(;r<n&&e[r]===" ";)r+=1;if(r>=n)break;let o;if(e[r]==='"'||e[r]==="'"){let s=e[r];r+=1,o="";let i=r;for(;;){for(;r<n&&e[r]!==s;){if(k_.test(e[r])||s==="'"&&e[r]==="\\")return null;r+=1}if(r>=n)return null;if(o+=e.slice(i,r),s==="'"&&e[r+1]==="\\"&&e[r+2]==="'"&&e[r+3]==="'"){o+="'",r+=4,i=r;continue}r+=1;break}if(r<n&&e[r]!==" ")return null}else{let s=r;for(;r<n&&e[r]!==" ";){if(k_.test(e[r])||oL.test(e[r]))return null;r+=1}if(o=e.slice(s,r),o.includes('"')||o.includes("'"))return null}t.push(o)}return t.length>0?t:null}function tu(e){if(!e.includes("--json"))return"requires --json when run via exec (plain-text output has no machine-readable contract)"}function sL(e){return e.includes("--watch")?"tail --watch is a long-running stream, not a fit for a single bounded exec call":e.includes("--lines")?tu(e):"tail requires --lines N when run via exec (unbounded --max-bytes/no-limit output is not allowed)"}var iL=[{prefix:["lmbee","status"]},{prefix:["lmbee","teams"]},{prefix:["lmbee","queue","list"]},{prefix:["lmbee","queue","get"]},{prefix:["lmbee","queue","inbox"]},{prefix:["lmbee","history"]},{prefix:["lmbee","state","list"]},{prefix:["lmbee","state","get"]},{prefix:["lmbee","state","active"]},{prefix:["lmbee","source","list"]},{prefix:["lmctl","health"],validate:tu},{prefix:["lmctl","running"],validate:tu},{prefix:["lmctl","tail"],validate:sL}],aL=[{prefix:["lmbee","enqueue"]},{prefix:["lmbee","send"]},{prefix:["lmbee","nudge"]},{prefix:["lmbee","state","set"]},{prefix:["lmbee","queue","deliver"]},{prefix:["lmbee","queue","retrieve"]},{prefix:["lmbee","queue","gc"]},{prefix:["lmbee","source","add"]},{prefix:["lmbee","source","remove"]}];function cL(e,t){return e.length<t.prefix.length?!1:t.prefix.every((r,n)=>e[n]===r)}function x_(e,t){return t.find(r=>cL(e,r))}function N_(e,t){let r=x_(e,iL);if(r){let o=r.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:{allowed:!0}}let n=x_(e,aL);if(n){let o=n.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:t!=="admin"?{allowed:!1,code:"insufficient_trust",message:`write command requires the operator (admin) trust tier; sender is ${t}`}:{allowed:!0}}return{allowed:!1,code:"command_not_allowed",message:`command is not exec-able from the web: ${e.join(" ")}`}}import{spawn as I_}from"node:child_process";var lL=5e3,uL="/bin/sh";function L_(e){if(!Number.isInteger(e.timeoutMs)||e.timeoutMs<1)throw new Error("timeoutMs must be a positive integer");let t=e.killGraceMs??lL;if(!Number.isInteger(t)||t<0)throw new Error("killGraceMs must be a non-negative integer");return{killGraceMs:t,now:e.now??Date.now}}function C_(e,t,r,n){return new Promise((o,s)=>{let i=n(),a=[],c=[],l=!1,u=!1,d,m,f=h=>{u||(u=!0,d&&clearTimeout(d),m&&clearTimeout(m),o(h))},p=h=>{u||(u=!0,d&&clearTimeout(d),m&&clearTimeout(m),s(h))};e.stdout.on("data",h=>{a.push(Buffer.isBuffer(h)?h:Buffer.from(h))}),e.stderr.on("data",h=>{c.push(Buffer.isBuffer(h)?h:Buffer.from(h))}),e.on("error",h=>{p(h)}),e.on("close",h=>{f({exit_code:l?null:typeof h=="number"?h:null,stdout:Buffer.concat(a),stderr:Buffer.concat(c),duration_ms:Math.max(0,Math.round(n()-i)),timed_out:l})}),d=setTimeout(()=>{l=!0,ru(e.pid,"SIGTERM"),r>0?m=setTimeout(()=>{ru(e.pid,"SIGKILL")},r):ru(e.pid,"SIGKILL")},t)})}async function O_(e,t){if(e.trim().length===0)throw new Error("command must be non-empty");let{killGraceMs:r,now:n}=L_(t),o=t.shellPath??uL,s=I_(o,["-c",e],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return C_(s,t.timeoutMs,r,n)}async function D_(e,t){if(e.length===0)throw new Error("argv must be non-empty");let{killGraceMs:r,now:n}=L_(t),o=I_(e[0],e.slice(1),{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return C_(o,t.timeoutMs,r,n)}function ru(e,t){if(e)try{process.kill(-e,t)}catch(r){if(!dL(r))throw r}}function dL(e){return!!e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH"}var M_=1e3,fL=6e4,pL=20,hL=1e3;async function U_(e,t){let r=t.runCommand??O_,n=t.runCommandArgv??D_,o=t.sleep??_L,s=t.pollNow??Date.now,i=t.now??(()=>new Date),a=t.stderr??(d=>process.stderr.write(`${d}
482
- `)),c=t.shouldStop??(()=>!1),l=M_,u=!1;for(kt(a,i,"info","daemon_started",{mailbox:e.mailbox}),e.allowAnonymous&&kt(a,i,"warn","anonymous_execution_enabled",{mailbox:e.mailbox,warning:"REMOTE SHELL OPEN TO EVERY AUTHENTICATED LMMAIL USER"});!c();)try{let d=s(),m=await t.client.listMessages(e.mailbox,{status:"unread",after:0,...e.once?{}:{wait_s:pL}}),f=Math.max(0,s()-d);for(let p of m.messages){if(c())break;let h=gL(e,p.sender);if(h==="anonymous"&&!e.allowAnonymous){await t.client.getMessageMetadata(e.mailbox,p.seq),kt(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"anonymous_not_allowed"});continue}let w=await t.client.getMessage(e.mailbox,p.seq),_=Buffer.from(await t.client.download(w.body.download_url)).toString("utf8"),E;try{E=y_(_)}catch(x){kt(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"malformed_request",error:nu(x)});continue}let T=e.execAllowlist?R_(E.command):void 0,v=e.execAllowlist?T?N_(T,h):{allowed:!1,code:"malformed_command",message:"command could not be safely tokenized into arguments"}:{allowed:!0};if(!v.allowed){kt(a,i,"warn","command_rejected",{id:E.id,sender:p.sender,sender_trust:h,...E.from===void 0?{}:{asserted_from:E.from},code:v.code,seq:p.seq}),await P_(t.client,E.reply_to,{id:E.id,exit_code:126,stdout:"",stderr:JSON.stringify({error:{code:v.code,message:v.message}}),duration_ms:0,timed_out:!1,sender_trust:h,sender:p.sender});continue}kt(a,i,"info","command_started",{id:E.id,sender:p.sender,sender_trust:h,...E.from===void 0?{}:{asserted_from:E.from},seq:p.seq});let S;try{S=T?await n(T,{timeoutMs:Math.min(E.timeout_s,e.timeoutCapSeconds)*1e3}):await r(E.command,{timeoutMs:Math.min(E.timeout_s,e.timeoutCapSeconds)*1e3})}catch(x){kt(a,i,"error","command_failed",{id:E.id,sender:p.sender,sender_trust:h,...E.from===void 0?{}:{asserted_from:E.from},error:nu(x)});continue}let N=await P_(t.client,E.reply_to,{id:E.id,...S,sender_trust:h,sender:p.sender});kt(a,i,"info","command_finished",{id:E.id,sender:p.sender,sender_trust:h,...E.from===void 0?{}:{asserted_from:E.from},duration_ms:S.duration_ms,exit_code:S.exit_code,timed_out:S.timed_out,truncated:N.envelope.truncated})}if(l=M_,e.once||c())break;m.messages.length===0&&f<hL&&(u||(kt(a,i,"warn","long_poll_unsupported",{elapsed_ms:f,fallback_interval_ms:e.pollIntervalMs}),u=!0),await o(e.pollIntervalMs))}catch(d){if(kt(a,i,"error","api_error",{error:nu(d),retry_ms:l}),c())break;await o(l),l=Math.min(l*2,fL)}kt(a,i,"info","daemon_stopped",{mailbox:e.mailbox})}function gL(e,t){return e.adminUsers.has(t)?"admin":e.allowUsers.has(t)?"registered":"anonymous"}async function P_(e,t,r){let n=b_(r);return await e.sendMessage({mailbox:t,subject:n.subject,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(n.envelope),"utf8")},attachments:n.attachments.map(o=>({name:o.name,contentType:o.content_type,bytes:o.data}))}),n}function kt(e,t,r,n,o){e(JSON.stringify({ts:t().toISOString(),level:r,event:n,...o}))}function _L(e){return new Promise(t=>setTimeout(t,e))}function nu(e){return e instanceof Error?e.message:String(e)}var wL=5e3,yL=300;async function F_(e,t){await e.createMailbox(t,{tolerate409:!0})}function q_(e){let t=!1,r=!1,n=Promise.resolve(),o=e.stderr??(c=>process.stderr.write(`${c}
483
- `)),s=e.runDaemonLoopImpl??U_,i={mailbox:e.mailbox,allowUsers:e.allowUsers,adminUsers:e.adminUsers,allowAnonymous:e.allowAnonymous,apiUrl:"",pollIntervalMs:e.pollIntervalMs??wL,timeoutCapSeconds:e.timeoutCapSeconds??yL,once:!1,execAllowlist:!0},a={client:e.client,shouldStop:()=>t,stderr:o};return{start(){r||t||(r=!0,n=s(i,a).catch(c=>{o(`[exec-worker] unexpected top-level failure, worker stopped: ${c instanceof Error?c.message:String(c)}`)}))},stop(){t=!0},isRunning:()=>r&&!t,whenIdle:()=>n}}var EL=64*1024;function j_(e){return{v:1,msgId:e.msg_id,to:{site:e.to_site,team:e.to_team,alias:e.to_alias},from:{site:e.from_site,team:e.from_team,alias:e.from_alias},sentAt:e.sent_at,payload:e.payload}}async function ou(e,t,r,n,o,s){if(r.to.site!==t.localSiteId){Tn(e,r.msgId,`${Yr}addressed to a different site: ${r.to.site}`,o()),s.rejected++;return}if(!t.allowlist.includes(n)){Tn(e,r.msgId,`sender not allowlisted: ${n}`,o()),s.rejected++;return}try{await t.dispatch(r,n),Vm(e,r.msgId,o()),s.dispatched++}catch(i){Tn(e,r.msgId,i instanceof Error?i.message:String(i),o()),s.failed++}}async function H_(e,t,r,n){let o=n.now??(()=>new Date().toISOString()),s=n.maxBodyBytes??EL,i={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};for(let d of Wm(e))i.recovered++,await ou(e,n,j_(d),d.sender_user_id,o,i);let a=n.retryPolicy??dc;for(let d of qs(e,o(),a))zm(e,d.msg_id)&&(i.retriedFailed++,await ou(e,n,j_(d),d.sender_user_id,o,i));let c=Gm(e)??0,{messages:l}=await t.listMessages(r,{after:c});i.listed=l.length;let u=[...l].sort((d,m)=>d.seq-m.seq);for(let d of u){let m;try{m=await t.getMessage(r,d.seq)}catch{i.stoppedEarly=!0;break}if(m.body.size>s){i.stoppedEarly=!0;break}let f;try{f=await t.download(m.body.download_url)}catch{i.stoppedEarly=!0;break}let p;try{p=Hm(Buffer.from(f).toString("utf8"))}catch{i.stoppedEarly=!0;break}let h=o(),w=Bm(e,{msgId:p.msgId,seq:d.seq,to:p.to,from:p.from,senderUserId:m.sender,sentAt:p.sentAt,payload:p.payload},h);if(w!=="duplicate"){if(w==="conflict"){i.rejected++;continue}i.recorded++,await ou(e,n,p,m.sender,o,i)}}return i}async function B_(e,t){await e.createMailbox(t,{tolerate409:!0})}var TL=6e4,bL={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};function W_(e){let t=e.intervalMs??TL,r=null,n=!1;async function o(){if(n)return bL;n=!0;try{let s=await H_(e.db,e.client,e.mailbox,e.worker);return e.onPoll?.(s),s}catch(s){throw e.onError?.(s),s}finally{n=!1}}return{start(){r||(r=setInterval(()=>{o().catch(()=>{})},t),r.unref())},stop(){r&&(clearInterval(r),r=null)},pollNow:o,isRunning:()=>r!==null,isPolling:()=>n}}var SL=5e3;function G_(e){let t=e.intervalMs??SL,r=e.fetchReport??Ae,n=e.deliverImpl??Er,o=null,s=!1;async function i(){if(s)return 0;s=!0;try{let a=e.getTeams(),c=await r(),l=n(e.db,{teams:a,report:c,...e.remoteMail?{remoteMail:e.remoteMail}:{},...e.minMemoryPercent!==void 0?{minMemoryPercent:e.minMemoryPercent}:{}});return e.onDeliver?.(l),l}catch(a){throw e.onError?.(a),a}finally{s=!1}}return{start(){o||(o=setInterval(()=>{i().catch(()=>{})},t),o.unref())},stop(){o&&(clearInterval(o),o=null)},deliverNow:i,isRunning:()=>o!==null,isDelivering:()=>s}}import{isAbsolute as V_,resolve as J_}from"node:path";import{randomUUID as vL}from"node:crypto";function AL(e){return`'${e.replaceAll("'","'\\''")}'`}async function K_(e,t,r,n){if(!V_(n.db)||J_(n.db)!==J_(t))throw new Error("db must select the running daemon database");let o=n.conversationId?.trim()||vL();if(n.localScope.trim()==="")throw new Error("local_scope is required");if(!V_(n.script))throw new Error("script must be an absolute path");if(!n.args.every(c=>typeof c=="string"))throw new Error("args must be strings");let s=[process.env.LMSCRIPT_BIN||"lmscript",n.script,n.db,n.localScope,o,...n.args].map(AL).join(" "),i=Pn(e,{title:`on-demand conversation ${o}`,scheduleExpr:"0 0 31 2 *",actionKind:"script",actionPayload:s,enabled:!0}),a=await Ho(e,i.id,r,{runTimeoutMs:null,waitForCompletion:!1});if(Ci(e,i.id,!1),a.kind!=="fired"||a.runId===void 0)throw new Error(`on-demand launch was ${a.kind}`);return{conversationid:o,job_id:i.id,run_id:a.runId}}import{readFileSync as BO}from"node:fs";var $L=10*6e4,kL=60*6e4;function z_(e,t,r={},n=Date.now()){let o=r.ackDeadlineMs??$L,s=r.replyThresholdMs??kL,i=[];for(let a of t){let c=js(e,{site:a.peerSite,team:a.name,alias:a.alias});if(!c)continue;let l=Date.parse(c.sent_ts);if(c.state==="sent"){n-l>=o&&i.push(a.name);continue}c.state!=="replied"&&n-l>=s&&i.push(a.name)}return i}var xL=[/^\S+'s turn has finished and exited; resubmit/i,/^resubmit .*lmctl chat/i];function RL(e){let t=e.split(/\r?\n/).filter(n=>n.trim().length>0).filter(n=>!xL.some(o=>o.test(n.trim()))),r=(t[t.length-1]??"").trim();return r==="BLOCKED"?"BLOCKED":r==="DONE"?"DONE":null}function Y_(e){if(e.trim()==="")return{status:"NO-OUTPUT",wake:"env"};let t=RL(e);return t==="BLOCKED"?{status:"BLOCKED",wake:"blocked"}:t==="DONE"?{status:"DONE",wake:null}:{status:"IDLE",wake:null}}function Wn(e){switch(e.kind){case"ok":return Y_(e.replyText);case"stalled":{let t=Y_(e.replyText);return t.status==="BLOCKED"||t.status==="DONE"?t:{status:"NO-OUTPUT",wake:"env"}}case"busy":return{status:"RUNNING(busy)",wake:null};case"timeout":case"no-signal":return{status:"NO-OUTPUT",wake:"env"};case"error":return{status:"ENV-ERROR",wake:"env"}}}var Gn=Ut(xt(),1);function ke(e,t){return{error:{code:e,message:t}}}var ow=1e4;function iu(e,t,r){let n=20;if(r!==void 0){let s=typeof r=="number"?r:r.trim()===""?NaN:Number(r);if(!Number.isSafeInteger(s)||s<0||s>ow)return ke("invalid_limit",`invalid limit "${r}" -- must be an integer from 0 to ${ow}`);n=s}return{events:t?e.db.db.prepare("SELECT * FROM events WHERE team = ? ORDER BY id DESC LIMIT ?").all(t,n):e.db.db.prepare("SELECT * FROM events ORDER BY id DESC LIMIT ?").all(n)}}function sw(e,t,r,n={}){let o=iu(e,t,r);return n.json?JSON.stringify(o):"error"in o?o.error.message:(0,Gn.formatTable)([["ID","TS","TEAM","STATUS","NOTE"],...o.events.map(s=>[String(s.id),he(s.ts),(0,Gn.escapeCell)(s.team),(0,Gn.escapeCell)(s.status),(0,Gn.escapeCell)(s.note??"")])])}var iw=Ut(xt(),1);function au(e){let t=e.db.db,r=Km(t),n=mc(t),o=n.filter(c=>c.failure_reason?.startsWith(Yr)).length,s=n.length-o,i=qs(t,new Date().toISOString()).length,a=Xm(t);return{counts:r,retryEligibleCount:s,permanentCount:o,dueNowCount:i,deliveryErrorCount:a}}function aw(e,t={}){let r=au(e);if(t.json)return JSON.stringify(r);let n=[["persisted (awaiting dispatch)",String(r.counts.persisted)],["dispatched",String(r.counts.dispatched)],["replied",String(r.counts.replied)],["failed -- retry-eligible (backoff pending)",String(r.retryEligibleCount)],["failed -- permanent (never retried)",String(r.permanentCount)]],o=(0,iw.formatTable)([["STATE","COUNT"],...n]),s=r.deliveryErrorCount>0?`
481
+ `;function v_(e){return tu(x_(e))}function A_(e){return k_(x_(e))}function tu(e){let t=R_(e),r=N_(t.type,"type",eu),n=L_(t.id,"id"),o=nu(t.command,"command"),s=sI(t.timeout_s,"timeout_s"),i=oI(t.reply_to,"reply_to"),a=rI(t.from,"from");return{v:1,type:r,id:n,command:o,timeout_s:s,reply_to:i,...a===void 0?{}:{from:a}}}function k_(e){let t=R_(e),r=tI(t.v),n=N_(t.type,"type",S_),o=L_(t.id,"id"),s=aI(t.exit_code,"exit_code"),i=E_(t.stdout,"stdout"),a=E_(t.stderr,"stderr"),c=iI(t.duration_ms,"duration_ms"),l=T_(t.timed_out,"timed_out"),u=T_(t.truncated,"truncated");if(l&&s!==null)throw new Error("invalid exec result: exit_code must be null when timed_out is true");if(!l&&s===null)throw new Error("invalid exec result: exit_code must be a number when timed_out is false");let d={type:n,id:o,exit_code:s,stdout:i,stderr:a,duration_ms:c,timed_out:l,truncated:u};if(r===1)return{v:r,...d};let m=nI(t.sender_trust),f=nu(t.sender,"sender");return{v:r,...d,sender_trust:m,sender:f}}function ru(e){if(!b_.test(e))throw new Error(`invalid exec id: ${e}`);return`${ZL} ${e}`}function y_(e,t,r){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),o=r?.capBytes??49152,s=r?.marker??eI;if(!Number.isInteger(o)||o<1)throw new Error("inline cap must be a positive integer");if(n.byteLength<=o)return{inline:n.toString("utf8"),truncated:!1};let i=Buffer.byteLength(s,"utf8");if(i>=o)throw new Error("elision marker must be smaller than the inline cap");let a=n.toString("utf8"),c=o-i,l=Math.ceil(c/2),u=Math.floor(c/2);return{inline:`${cI(a,l)}${s}${lI(a,u)}`,truncated:!0,attachment:{name:e==="stdout"?"stdout.txt":"stderr.txt",content_type:XL,data:n}}}function $_(e,t){let r=y_("stdout",e.stdout,t),n=y_("stderr",e.stderr,t),o=k_({v:2,type:S_,id:e.id,exit_code:e.exit_code,stdout:r.inline,stderr:n.inline,duration_ms:e.duration_ms,timed_out:e.timed_out,truncated:r.truncated||n.truncated,sender_trust:e.sender_trust,sender:e.sender});return{subject:ru(e.id),envelope:o,attachments:[r.attachment,n.attachment].filter(s=>s!==void 0)}}function x_(e){try{return JSON.parse(e)}catch(t){throw new Error(`invalid JSON: ${uI(t)}`)}}function R_(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("expected object");return e}function N_(e,t,r){if(e!==r)throw new Error(`invalid ${t}: expected ${r}`);return r}function tI(e){if(e===void 0||e===1)return 1;if(e===2)return 2;throw new Error("invalid v: expected 1 or 2")}function L_(e,t){if(typeof e!="string"||!b_.test(e))throw new Error(`invalid ${t}: expected UUID v4`);return e}function nu(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`invalid ${t}: expected non-empty string`);return e}function rI(e,t){if(e!==void 0)return nu(e,t)}function nI(e){if(e==="admin"||e==="registered"||e==="anonymous")return e;throw new Error("invalid sender_trust: expected admin, registered, or anonymous")}function oI(e,t){if(typeof e!="string"||e.includes("/")||e.includes("\\")||e.includes("..")||e.endsWith(".")||/[\u0000-\u001f\u007f]/.test(e)||!QL.test(e))throw new Error(`invalid ${t}: expected mailbox name`);return e}function E_(e,t){if(typeof e!="string")throw new Error(`invalid ${t}: expected string`);return e}function sI(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<1)throw new Error(`invalid ${t}: expected positive integer`);return e}function iI(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer`);return e}function aI(e,t){if(e===null)return null;if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer or null`);return e}function T_(e,t){if(typeof e!="boolean")throw new Error(`invalid ${t}: expected boolean`);return e}function cI(e,t){if(t<=0||e.length===0)return"";let r=0,n="";for(let o of e){let s=Buffer.byteLength(o,"utf8");if(r+s>t)break;n+=o,r+=s}return n}function lI(e,t){if(t<=0||e.length===0)return"";let r=0,n=[],o=Array.from(e);for(let s=o.length-1;s>=0;s-=1){let i=o[s],a=Buffer.byteLength(i,"utf8");if(r+a>t)break;n.push(i),r+=a}return n.reverse().join("")}function uI(e){return e instanceof Error&&e.message?e.message:String(e)}var dI=/[;&|`$<>(){}\\]/,I_=/[\x00-\x1f\x7f]/;function O_(e){let t=[],r=0,n=e.length;for(;r<n;){for(;r<n&&e[r]===" ";)r+=1;if(r>=n)break;let o;if(e[r]==='"'||e[r]==="'"){let s=e[r];r+=1,o="";let i=r;for(;;){for(;r<n&&e[r]!==s;){if(I_.test(e[r])||s==="'"&&e[r]==="\\")return null;r+=1}if(r>=n)return null;if(o+=e.slice(i,r),s==="'"&&e[r+1]==="\\"&&e[r+2]==="'"&&e[r+3]==="'"){o+="'",r+=4,i=r;continue}r+=1;break}if(r<n&&e[r]!==" ")return null}else{let s=r;for(;r<n&&e[r]!==" ";){if(I_.test(e[r])||dI.test(e[r]))return null;r+=1}if(o=e.slice(s,r),o.includes('"')||o.includes("'"))return null}t.push(o)}return t.length>0?t:null}function ou(e){if(!e.includes("--json"))return"requires --json when run via exec (plain-text output has no machine-readable contract)"}function mI(e){return e.includes("--watch")?"tail --watch is a long-running stream, not a fit for a single bounded exec call":e.includes("--lines")?ou(e):"tail requires --lines N when run via exec (unbounded --max-bytes/no-limit output is not allowed)"}var fI=[{prefix:["lmbee","status"]},{prefix:["lmbee","teams"]},{prefix:["lmbee","queue","list"]},{prefix:["lmbee","queue","get"]},{prefix:["lmbee","queue","inbox"]},{prefix:["lmbee","history"]},{prefix:["lmbee","state","list"]},{prefix:["lmbee","state","get"]},{prefix:["lmbee","state","active"]},{prefix:["lmbee","source","list"]},{prefix:["lmctl","health"],validate:ou},{prefix:["lmctl","running"],validate:ou},{prefix:["lmctl","tail"],validate:mI}],pI=[{prefix:["lmbee","enqueue"]},{prefix:["lmbee","send"]},{prefix:["lmbee","nudge"]},{prefix:["lmbee","state","set"]},{prefix:["lmbee","queue","deliver"]},{prefix:["lmbee","queue","retrieve"]},{prefix:["lmbee","queue","gc"]},{prefix:["lmbee","source","add"]},{prefix:["lmbee","source","remove"]}];function hI(e,t){return e.length<t.prefix.length?!1:t.prefix.every((r,n)=>e[n]===r)}function C_(e,t){return t.find(r=>hI(e,r))}function D_(e,t){let r=C_(e,fI);if(r){let o=r.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:{allowed:!0}}let n=C_(e,pI);if(n){let o=n.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:t!=="admin"?{allowed:!1,code:"insufficient_trust",message:`write command requires the operator (admin) trust tier; sender is ${t}`}:{allowed:!0}}return{allowed:!1,code:"command_not_allowed",message:`command is not exec-able from the web: ${e.join(" ")}`}}import{spawn as M_}from"node:child_process";var gI=5e3,_I="/bin/sh";function P_(e){if(!Number.isInteger(e.timeoutMs)||e.timeoutMs<1)throw new Error("timeoutMs must be a positive integer");let t=e.killGraceMs??gI;if(!Number.isInteger(t)||t<0)throw new Error("killGraceMs must be a non-negative integer");return{killGraceMs:t,now:e.now??Date.now}}function U_(e,t,r,n){return new Promise((o,s)=>{let i=n(),a=[],c=[],l=!1,u=!1,d,m,f=h=>{u||(u=!0,d&&clearTimeout(d),m&&clearTimeout(m),o(h))},p=h=>{u||(u=!0,d&&clearTimeout(d),m&&clearTimeout(m),s(h))};e.stdout.on("data",h=>{a.push(Buffer.isBuffer(h)?h:Buffer.from(h))}),e.stderr.on("data",h=>{c.push(Buffer.isBuffer(h)?h:Buffer.from(h))}),e.on("error",h=>{p(h)}),e.on("close",h=>{f({exit_code:l?null:typeof h=="number"?h:null,stdout:Buffer.concat(a),stderr:Buffer.concat(c),duration_ms:Math.max(0,Math.round(n()-i)),timed_out:l})}),d=setTimeout(()=>{l=!0,su(e.pid,"SIGTERM"),r>0?m=setTimeout(()=>{su(e.pid,"SIGKILL")},r):su(e.pid,"SIGKILL")},t)})}async function F_(e,t){if(e.trim().length===0)throw new Error("command must be non-empty");let{killGraceMs:r,now:n}=P_(t),o=t.shellPath??_I,s=M_(o,["-c",e],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return U_(s,t.timeoutMs,r,n)}async function q_(e,t){if(e.length===0)throw new Error("argv must be non-empty");let{killGraceMs:r,now:n}=P_(t),o=M_(e[0],e.slice(1),{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return U_(o,t.timeoutMs,r,n)}function su(e,t){if(e)try{process.kill(-e,t)}catch(r){if(!wI(r))throw r}}function wI(e){return!!e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH"}var j_=1e3,EI=6e4,TI=20,bI=1e3;async function B_(e,t){let r=t.runCommand??F_,n=t.runCommandArgv??q_,o=t.sleep??vI,s=t.pollNow??Date.now,i=t.now??(()=>new Date),a=t.stderr??(d=>process.stderr.write(`${d}
482
+ `)),c=t.shouldStop??(()=>!1),l=j_,u=!1;for($t(a,i,"info","daemon_started",{mailbox:e.mailbox}),e.allowAnonymous&&$t(a,i,"warn","anonymous_execution_enabled",{mailbox:e.mailbox,warning:"REMOTE SHELL OPEN TO EVERY AUTHENTICATED LMMAIL USER"});!c();)try{let d=s(),m=await t.client.listMessages(e.mailbox,{status:"unread",after:0,...e.once?{}:{wait_s:TI}}),f=Math.max(0,s()-d);for(let p of m.messages){if(c())break;let h=SI(e,p.sender);if(h==="anonymous"&&!e.allowAnonymous){await t.client.getMessageMetadata(e.mailbox,p.seq),$t(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"anonymous_not_allowed"});continue}let w=await t.client.getMessage(e.mailbox,p.seq),_=Buffer.from(await t.client.download(w.body.download_url)).toString("utf8"),T;try{T=v_(_)}catch($){$t(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"malformed_request",error:iu($)});continue}let E=e.execAllowlist?O_(T.command):void 0,v=e.execAllowlist?E?D_(E,h):{allowed:!1,code:"malformed_command",message:"command could not be safely tokenized into arguments"}:{allowed:!0};if(!v.allowed){$t(a,i,"warn","command_rejected",{id:T.id,sender:p.sender,sender_trust:h,...T.from===void 0?{}:{asserted_from:T.from},code:v.code,seq:p.seq}),await H_(t.client,T.reply_to,{id:T.id,exit_code:126,stdout:"",stderr:JSON.stringify({error:{code:v.code,message:v.message}}),duration_ms:0,timed_out:!1,sender_trust:h,sender:p.sender});continue}$t(a,i,"info","command_started",{id:T.id,sender:p.sender,sender_trust:h,...T.from===void 0?{}:{asserted_from:T.from},seq:p.seq});let S;try{S=E?await n(E,{timeoutMs:Math.min(T.timeout_s,e.timeoutCapSeconds)*1e3}):await r(T.command,{timeoutMs:Math.min(T.timeout_s,e.timeoutCapSeconds)*1e3})}catch($){$t(a,i,"error","command_failed",{id:T.id,sender:p.sender,sender_trust:h,...T.from===void 0?{}:{asserted_from:T.from},error:iu($)});continue}let N=await H_(t.client,T.reply_to,{id:T.id,...S,sender_trust:h,sender:p.sender});$t(a,i,"info","command_finished",{id:T.id,sender:p.sender,sender_trust:h,...T.from===void 0?{}:{asserted_from:T.from},duration_ms:S.duration_ms,exit_code:S.exit_code,timed_out:S.timed_out,truncated:N.envelope.truncated})}if(l=j_,e.once||c())break;m.messages.length===0&&f<bI&&(u||($t(a,i,"warn","long_poll_unsupported",{elapsed_ms:f,fallback_interval_ms:e.pollIntervalMs}),u=!0),await o(e.pollIntervalMs))}catch(d){if($t(a,i,"error","api_error",{error:iu(d),retry_ms:l}),c())break;await o(l),l=Math.min(l*2,EI)}$t(a,i,"info","daemon_stopped",{mailbox:e.mailbox})}function SI(e,t){return e.adminUsers.has(t)?"admin":e.allowUsers.has(t)?"registered":"anonymous"}async function H_(e,t,r){let n=$_(r);return await e.sendMessage({mailbox:t,subject:n.subject,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(n.envelope),"utf8")},attachments:n.attachments.map(o=>({name:o.name,contentType:o.content_type,bytes:o.data}))}),n}function $t(e,t,r,n,o){e(JSON.stringify({ts:t().toISOString(),level:r,event:n,...o}))}function vI(e){return new Promise(t=>setTimeout(t,e))}function iu(e){return e instanceof Error?e.message:String(e)}var AI=5e3,kI=300;async function W_(e,t){await e.createMailbox(t,{tolerate409:!0})}function G_(e){let t=!1,r=!1,n=Promise.resolve(),o=e.stderr??(c=>process.stderr.write(`${c}
483
+ `)),s=e.runDaemonLoopImpl??B_,i={mailbox:e.mailbox,allowUsers:e.allowUsers,adminUsers:e.adminUsers,allowAnonymous:e.allowAnonymous,apiUrl:"",pollIntervalMs:e.pollIntervalMs??AI,timeoutCapSeconds:e.timeoutCapSeconds??kI,once:!1,execAllowlist:!0},a={client:e.client,shouldStop:()=>t,stderr:o};return{start(){r||t||(r=!0,n=s(i,a).catch(c=>{o(`[exec-worker] unexpected top-level failure, worker stopped: ${c instanceof Error?c.message:String(c)}`)}))},stop(){t=!0},isRunning:()=>r&&!t,whenIdle:()=>n}}var $I=64*1024;function V_(e){return{v:1,msgId:e.msg_id,to:{site:e.to_site,team:e.to_team,alias:e.to_alias},from:{site:e.from_site,team:e.from_team,alias:e.from_alias},sentAt:e.sent_at,payload:e.payload}}async function au(e,t,r,n,o,s){if(r.to.site!==t.localSiteId){Tn(e,r.msgId,`${Yr}addressed to a different site: ${r.to.site}`,o()),s.rejected++;return}if(!t.allowlist.includes(n)){Tn(e,r.msgId,`sender not allowlisted: ${n}`,o()),s.rejected++;return}try{await t.dispatch(r,n),zm(e,r.msgId,o()),s.dispatched++}catch(i){Tn(e,r.msgId,i instanceof Error?i.message:String(i),o()),s.failed++}}async function J_(e,t,r,n){let o=n.now??(()=>new Date().toISOString()),s=n.maxBodyBytes??$I,i={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};for(let d of Jm(e))i.recovered++,await au(e,n,V_(d),d.sender_user_id,o,i);let a=n.retryPolicy??pc;for(let d of Ws(e,o(),a))Xm(e,d.msg_id)&&(i.retriedFailed++,await au(e,n,V_(d),d.sender_user_id,o,i));let c=Km(e)??0,{messages:l}=await t.listMessages(r,{after:c});i.listed=l.length;let u=[...l].sort((d,m)=>d.seq-m.seq);for(let d of u){let m;try{m=await t.getMessage(r,d.seq)}catch{i.stoppedEarly=!0;break}if(m.body.size>s){i.stoppedEarly=!0;break}let f;try{f=await t.download(m.body.download_url)}catch{i.stoppedEarly=!0;break}let p;try{p=Gm(Buffer.from(f).toString("utf8"))}catch{i.stoppedEarly=!0;break}let h=o(),w=Vm(e,{msgId:p.msgId,seq:d.seq,to:p.to,from:p.from,senderUserId:m.sender,sentAt:p.sentAt,payload:p.payload},h);if(w!=="duplicate"){if(w==="conflict"){i.rejected++;continue}i.recorded++,await au(e,n,p,m.sender,o,i)}}return i}async function K_(e,t){await e.createMailbox(t,{tolerate409:!0})}var xI=6e4,RI={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};function z_(e){let t=e.intervalMs??xI,r=null,n=!1;async function o(){if(n)return RI;n=!0;try{let s=await J_(e.db,e.client,e.mailbox,e.worker);return e.onPoll?.(s),s}catch(s){throw e.onError?.(s),s}finally{n=!1}}return{start(){r||(r=setInterval(()=>{o().catch(()=>{})},t),r.unref())},stop(){r&&(clearInterval(r),r=null)},pollNow:o,isRunning:()=>r!==null,isPolling:()=>n}}var NI=5e3;function Y_(e){let t=e.intervalMs??NI,r=e.fetchReport??Ae,n=e.deliverImpl??Tr,o=null,s=!1;async function i(){if(s)return 0;s=!0;try{let a=e.getTeams(),c=await r(),l=n(e.db,{teams:a,report:c,...e.remoteMail?{remoteMail:e.remoteMail}:{},...e.minMemoryPercent!==void 0?{minMemoryPercent:e.minMemoryPercent}:{}});return e.onDeliver?.(l),l}catch(a){throw e.onError?.(a),a}finally{s=!1}}return{start(){o||(o=setInterval(()=>{i().catch(()=>{})},t),o.unref())},stop(){o&&(clearInterval(o),o=null)},deliverNow:i,isRunning:()=>o!==null,isDelivering:()=>s}}import{isAbsolute as Q_,resolve as X_}from"node:path";import{randomUUID as LI}from"node:crypto";function II(e){return`'${e.replaceAll("'","'\\''")}'`}async function Z_(e,t,r,n){if(!Q_(n.db)||X_(n.db)!==X_(t))throw new Error("db must select the running daemon database");let o=n.conversationId?.trim()||LI();if(n.localScope.trim()==="")throw new Error("local_scope is required");if(!Q_(n.script))throw new Error("script must be an absolute path");if(!n.args.every(c=>typeof c=="string"))throw new Error("args must be strings");let s=[process.env.LMSCRIPT_BIN||"lmscript",n.script,n.db,n.localScope,o,...n.args].map(II).join(" "),i=Fn(e,{title:`on-demand conversation ${o}`,scheduleExpr:"0 0 31 2 *",actionKind:"script",actionPayload:s,enabled:!0}),a=await Vo(e,i.id,r,{runTimeoutMs:null,waitForCompletion:!1});if(Mi(e,i.id,!1),a.kind!=="fired"||a.runId===void 0)throw new Error(`on-demand launch was ${a.kind}`);return{conversationid:o,job_id:i.id,run_id:a.runId}}import{readFileSync as YO}from"node:fs";var CI=10*6e4,OI=60*6e4;function ew(e,t,r={},n=Date.now()){let o=r.ackDeadlineMs??CI,s=r.replyThresholdMs??OI,i=[];for(let a of t){let c=Gs(e,{site:a.peerSite,team:a.name,alias:a.alias});if(!c)continue;let l=Date.parse(c.sent_ts);if(c.state==="sent"){n-l>=o&&i.push(a.name);continue}c.state!=="replied"&&n-l>=s&&i.push(a.name)}return i}var DI=[/^\S+'s turn has finished and exited; resubmit/i,/^resubmit .*lmctl chat/i];function MI(e){let t=e.split(/\r?\n/).filter(n=>n.trim().length>0).filter(n=>!DI.some(o=>o.test(n.trim()))),r=(t[t.length-1]??"").trim();return r==="BLOCKED"?"BLOCKED":r==="DONE"?"DONE":null}function tw(e){if(e.trim()==="")return{status:"NO-OUTPUT",wake:"env"};let t=MI(e);return t==="BLOCKED"?{status:"BLOCKED",wake:"blocked"}:t==="DONE"?{status:"DONE",wake:null}:{status:"IDLE",wake:null}}function Vn(e){switch(e.kind){case"ok":return tw(e.replyText);case"stalled":{let t=tw(e.replyText);return t.status==="BLOCKED"||t.status==="DONE"?t:{status:"NO-OUTPUT",wake:"env"}}case"busy":return{status:"RUNNING(busy)",wake:null};case"timeout":case"no-signal":return{status:"NO-OUTPUT",wake:"env"};case"error":return{status:"ENV-ERROR",wake:"env"}}}var Jn=Ut(xt(),1);function $e(e,t){return{error:{code:e,message:t}}}var lw=1e4;function lu(e,t,r){let n=20;if(r!==void 0){let s=typeof r=="number"?r:r.trim()===""?NaN:Number(r);if(!Number.isSafeInteger(s)||s<0||s>lw)return $e("invalid_limit",`invalid limit "${r}" -- must be an integer from 0 to ${lw}`);n=s}return{events:t?e.db.db.prepare("SELECT * FROM events WHERE team = ? ORDER BY id DESC LIMIT ?").all(t,n):e.db.db.prepare("SELECT * FROM events ORDER BY id DESC LIMIT ?").all(n)}}function uw(e,t,r,n={}){let o=lu(e,t,r);return n.json?JSON.stringify(o):"error"in o?o.error.message:(0,Jn.formatTable)([["ID","TS","TEAM","STATUS","NOTE"],...o.events.map(s=>[String(s.id),he(s.ts),(0,Jn.escapeCell)(s.team),(0,Jn.escapeCell)(s.status),(0,Jn.escapeCell)(s.note??"")])])}var dw=Ut(xt(),1);function uu(e){let t=e.db.db,r=Qm(t),n=hc(t),o=n.filter(c=>c.failure_reason?.startsWith(Yr)).length,s=n.length-o,i=Ws(t,new Date().toISOString()).length,a=tf(t);return{counts:r,retryEligibleCount:s,permanentCount:o,dueNowCount:i,deliveryErrorCount:a}}function mw(e,t={}){let r=uu(e);if(t.json)return JSON.stringify(r);let n=[["persisted (awaiting dispatch)",String(r.counts.persisted)],["dispatched",String(r.counts.dispatched)],["replied",String(r.counts.replied)],["failed -- retry-eligible (backoff pending)",String(r.retryEligibleCount)],["failed -- permanent (never retried)",String(r.permanentCount)]],o=(0,dw.formatTable)([["STATE","COUNT"],...n]),s=r.deliveryErrorCount>0?`
484
484
  ${r.deliveryErrorCount} row(s) with a recorded delivery error (invocation failed to spawn -- see delivery_error)`:"";return`${o}
485
- ${r.dueNowCount} failed row(s) due for retry now${s}`}import{closeSync as sC,existsSync as iC,openSync as aC,readFileSync as _u,readSync as cC,realpathSync as lC,statSync as uC}from"node:fs";var GL="member_health:";function cu(e,t){return`${GL}${e}:${t}`}function cw(e,t,r,n){let o={kind:n.kind,observedAt:n.nowIso??new Date().toISOString(),remedy:n.remedy};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(cu(t,r),JSON.stringify(o))}function Xo(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(cu(t,r));if(n===void 0)return null;try{let o=JSON.parse(n.v);return o.kind!=="evicted"||typeof o.observedAt!="string"||typeof o.remedy!="string"?null:{kind:"evicted",observedAt:o.observedAt,remedy:o.remedy}}catch{return null}}function lw(e,t,r){e.prepare("DELETE FROM kv WHERE k = ?").run(cu(t,r))}function uw(e,t){let r=t.title.trim();if(r.length===0)throw new Error("prompt: task title must not be blank");let n=new Date().toISOString(),o=e.prepare("INSERT INTO prompt_tasks(title, description, created_at) VALUES (?, ?, ?)").run(r,t.description??"",n);return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(o.lastInsertRowid)}function Zo(e,t){return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(t)??null}function dw(e,t){let r=t.prompt.trim();if(r.length===0)throw new Error("prompt: prompt must not be blank");let n=new Date().toISOString(),o=e.prepare("INSERT INTO task_prompts(task_id, from_id, to_id, prompt, created_at) VALUES (?, ?, ?, ?, ?)").run(t.taskId,t.fromId,t.toId,r,n);return e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(o.lastInsertRowid)}function mw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE task_id = ? ORDER BY id ASC").all(t)}function fw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id ASC").all(t)}function pw(e,t){return e.transaction(n=>{let o=e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id").all(n);if(o.length===0)return o;let s=new Date().toISOString(),i=e.prepare("UPDATE task_prompts SET retrieved_ts = ? WHERE id = ? AND retrieved_ts IS NULL");for(let a of o)i.run(s,a.id),a.retrieved_ts=s;return o})(t)}function hw(e,t){return e.prepare("SELECT task_id FROM task_prompts WHERE from_id = ? OR to_id = ? ORDER BY id DESC LIMIT 1").get(t,t)?.task_id??null}function gw(e,t){let r=e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(t.promptId);if(r===void 0)throw new Error(`prompt: prompt #${t.promptId} does not exist`);if(Zo(e,t.toTaskId)===null)throw new Error(`prompt: --task ${t.toTaskId} does not refer to an existing prompt task`);return e.transaction(()=>{e.prepare("INSERT INTO prompt_task_reassignments(prompt_id, from_task_id, to_task_id, reassigned_by, reassigned_at) VALUES (?, ?, ?, ?, ?)").run(t.promptId,r.task_id,t.toTaskId,t.reassignedBy,new Date().toISOString()),e.prepare("UPDATE task_prompts SET task_id = ? WHERE id = ?").run(t.toTaskId,t.promptId)}).immediate(),e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(t.promptId)}function _w(e,t){return e.prepare("SELECT * FROM prompt_task_reassignments WHERE prompt_id = ? ORDER BY id ASC").all(t)}function ww(e,t){return e.prepare(`SELECT task_id, MAX(created_at) AS last_message_at, COUNT(*) AS message_count
485
+ ${r.dueNowCount} failed row(s) due for retry now${s}`}import{closeSync as mC,existsSync as fC,openSync as pC,readFileSync as Eu,readSync as hC,realpathSync as gC,statSync as _C}from"node:fs";var XI="member_health:";function du(e,t){return`${XI}${e}:${t}`}function fw(e,t,r,n){let o={kind:n.kind,observedAt:n.nowIso??new Date().toISOString(),remedy:n.remedy};e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(du(t,r),JSON.stringify(o))}function rs(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(du(t,r));if(n===void 0)return null;try{let o=JSON.parse(n.v);return o.kind!=="evicted"||typeof o.observedAt!="string"||typeof o.remedy!="string"?null:{kind:"evicted",observedAt:o.observedAt,remedy:o.remedy}}catch{return null}}function pw(e,t,r){e.prepare("DELETE FROM kv WHERE k = ?").run(du(t,r))}function hw(e,t){let r=t.title.trim();if(r.length===0)throw new Error("prompt: task title must not be blank");let n=new Date().toISOString(),o=e.prepare("INSERT INTO prompt_tasks(title, description, created_at) VALUES (?, ?, ?)").run(r,t.description??"",n);return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(o.lastInsertRowid)}function ns(e,t){return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(t)??null}function gw(e,t){let r=t.prompt.trim();if(r.length===0)throw new Error("prompt: prompt must not be blank");let n=new Date().toISOString(),o=e.prepare("INSERT INTO task_prompts(task_id, from_id, to_id, prompt, created_at) VALUES (?, ?, ?, ?, ?)").run(t.taskId,t.fromId,t.toId,r,n);return e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(o.lastInsertRowid)}function _w(e,t){return e.prepare("SELECT * FROM task_prompts WHERE task_id = ? ORDER BY id ASC").all(t)}function ww(e,t){return e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id ASC").all(t)}function yw(e,t){return e.transaction(n=>{let o=e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id").all(n);if(o.length===0)return o;let s=new Date().toISOString(),i=e.prepare("UPDATE task_prompts SET retrieved_ts = ? WHERE id = ? AND retrieved_ts IS NULL");for(let a of o)i.run(s,a.id),a.retrieved_ts=s;return o})(t)}function Ew(e,t){return e.prepare("SELECT task_id FROM task_prompts WHERE from_id = ? OR to_id = ? ORDER BY id DESC LIMIT 1").get(t,t)?.task_id??null}function Tw(e,t){let r=e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(t.promptId);if(r===void 0)throw new Error(`prompt: prompt #${t.promptId} does not exist`);if(ns(e,t.toTaskId)===null)throw new Error(`prompt: --task ${t.toTaskId} does not refer to an existing prompt task`);return e.transaction(()=>{e.prepare("INSERT INTO prompt_task_reassignments(prompt_id, from_task_id, to_task_id, reassigned_by, reassigned_at) VALUES (?, ?, ?, ?, ?)").run(t.promptId,r.task_id,t.toTaskId,t.reassignedBy,new Date().toISOString()),e.prepare("UPDATE task_prompts SET task_id = ? WHERE id = ?").run(t.toTaskId,t.promptId)}).immediate(),e.prepare("SELECT * FROM task_prompts WHERE id = ?").get(t.promptId)}function bw(e,t){return e.prepare("SELECT * FROM prompt_task_reassignments WHERE prompt_id = ? ORDER BY id ASC").all(t)}function Sw(e,t){return e.prepare(`SELECT task_id, MAX(created_at) AS last_message_at, COUNT(*) AS message_count
486
486
  FROM task_prompts
487
487
  WHERE task_id IS NOT NULL AND (from_id = ? OR to_id = ?)
488
488
  GROUP BY task_id
489
- ORDER BY last_message_at DESC`).all(t,t).map(n=>{let o=Zo(e,n.task_id);if(o===null)throw new Error(`prompt: task #${n.task_id} referenced by task_prompts but missing from prompt_tasks`);return{task:o,lastPromptAt:n.last_message_at,promptCount:n.message_count}})}import{readFileSync as VL}from"node:fs";function JL(e,t){return t?e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NULL AND to_id = ? ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NULL ORDER BY id").all()}function KL(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('sent', 'retrieved') ORDER BY id").all(t.to_id),n=wc(t);for(let o of r){let s;try{s=VL(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function lu(e,t){return JL(e,t).map(r=>({row:r,verifiedTarget:KL(e,r)}))}function yw(e,t){let r=lu(e,t),n=e.prepare("UPDATE queue SET merged_into_id = ? WHERE id = ?"),o=0,s=[];for(let{row:i,verifiedTarget:a}of r)a?(n.run(a.id,i.id),o++):s.push(i);return{repaired:o,unverified:s}}function Ew(e,t){let r=t?e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NOT NULL AND expects_response = 1 AND to_id = ? ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NOT NULL AND expects_response = 1 ORDER BY id").all(),n=[];for(let o of r){let s=e.prepare("SELECT * FROM queue WHERE id = ?").get(o.merged_into_id);s===void 0||s.expects_response||n.push({row:o,canonical:s})}return n}var uu="operator";function zL(e){if(e===uu)throw new Error(`logical_names: "${uu}" is reserved for the real operator entity (epic #162's #164) -- never a re-routable logical name`)}function Tw(e,t,r,n,o=new Date().toISOString()){zL(t),e.prepare(`INSERT INTO logical_names(name, teamfile_path, alias, updated_at) VALUES (?, ?, ?, ?)
490
- ON CONFLICT(name) DO UPDATE SET teamfile_path = excluded.teamfile_path, alias = excluded.alias, updated_at = excluded.updated_at`).run(t,r,n,o)}function sa(e,t){return t===uu?null:e.prepare("SELECT teamfile_path AS teamfilePath, alias FROM logical_names WHERE name = ?").get(t)??null}function bw(e){return e.prepare("SELECT name, teamfile_path AS teamfilePath, alias, updated_at AS updatedAt FROM logical_names ORDER BY name").all()}function Sw(e,t){e.prepare("DELETE FROM logical_names WHERE name = ?").run(t)}function es(e,t,r){let n=sa(e,r);if(n===null)return null;for(let o of t){if(!H(o))continue;let s;try{s=Q(o)}catch{continue}if(s===n.teamfilePath)return{team:o.name,alias:n.alias}}return null}import{existsSync as YL,mkdirSync as QL,readFileSync as XL,renameSync as ZL,writeFileSync as eC}from"node:fs";import{homedir as tC}from"node:os";import{dirname as rC,join as vw}from"node:path";function du(e){let{row:t,answer:r}=e;return t.retracted_ts!==null?"RETRACTED":t.merged_into_id!==null?`MERGED->#${t.merged_into_id}`:r!==null?"ANSWERED":t.retrieved_ts!==null?"READ, no answer":t.status==="sent"?"NEVER RECEIVED":t.status.toUpperCase()}function mu(e,t,r){let n=`
489
+ ORDER BY last_message_at DESC`).all(t,t).map(n=>{let o=ns(e,n.task_id);if(o===null)throw new Error(`prompt: task #${n.task_id} referenced by task_prompts but missing from prompt_tasks`);return{task:o,lastPromptAt:n.last_message_at,promptCount:n.message_count}})}import{readFileSync as ZI}from"node:fs";function eC(e,t){return t?e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NULL AND to_id = ? ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NULL ORDER BY id").all()}function tC(e,t){let r=e.prepare("SELECT * FROM queue WHERE to_id = ? AND status IN ('sent', 'retrieved') ORDER BY id").all(t.to_id),n=Tc(t);for(let o of r){let s;try{s=ZI(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function mu(e,t){return eC(e,t).map(r=>({row:r,verifiedTarget:tC(e,r)}))}function vw(e,t){let r=mu(e,t),n=e.prepare("UPDATE queue SET merged_into_id = ? WHERE id = ?"),o=0,s=[];for(let{row:i,verifiedTarget:a}of r)a?(n.run(a.id,i.id),o++):s.push(i);return{repaired:o,unverified:s}}function Aw(e,t){let r=t?e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NOT NULL AND expects_response = 1 AND to_id = ? ORDER BY id").all(t):e.prepare("SELECT * FROM queue WHERE status = 'merged' AND merged_into_id IS NOT NULL AND expects_response = 1 ORDER BY id").all(),n=[];for(let o of r){let s=e.prepare("SELECT * FROM queue WHERE id = ?").get(o.merged_into_id);s===void 0||s.expects_response||n.push({row:o,canonical:s})}return n}var fu="operator";function rC(e){if(e===fu)throw new Error(`logical_names: "${fu}" is reserved for the real operator entity (epic #162's #164) -- never a re-routable logical name`)}function kw(e,t,r,n,o=new Date().toISOString()){rC(t),e.prepare(`INSERT INTO logical_names(name, teamfile_path, alias, updated_at) VALUES (?, ?, ?, ?)
490
+ ON CONFLICT(name) DO UPDATE SET teamfile_path = excluded.teamfile_path, alias = excluded.alias, updated_at = excluded.updated_at`).run(t,r,n,o)}function ca(e,t){return t===fu?null:e.prepare("SELECT teamfile_path AS teamfilePath, alias FROM logical_names WHERE name = ?").get(t)??null}function $w(e){return e.prepare("SELECT name, teamfile_path AS teamfilePath, alias, updated_at AS updatedAt FROM logical_names ORDER BY name").all()}function xw(e,t){e.prepare("DELETE FROM logical_names WHERE name = ?").run(t)}function os(e,t,r){let n=ca(e,r);if(n===null)return null;for(let o of t){if(!B(o))continue;let s;try{s=Q(o)}catch{continue}if(s===n.teamfilePath)return{team:o.name,alias:n.alias}}return null}import{existsSync as nC,mkdirSync as oC,readFileSync as sC,renameSync as iC,writeFileSync as aC}from"node:fs";import{homedir as cC}from"node:os";import{dirname as lC,join as Rw}from"node:path";function pu(e){let{row:t,answer:r}=e;return t.retracted_ts!==null?"RETRACTED":t.merged_into_id!==null?`MERGED->#${t.merged_into_id}`:r!==null?"ANSWERED":t.retrieved_ts!==null?"READ, no answer":t.status==="sent"?"NEVER RECEIVED":t.status.toUpperCase()}function hu(e,t,r){let n=`
491
491
  SELECT q.*, r.id AS ans_id, r.answered_at AS ans_answered_at, r.answer_text AS ans_text,
492
492
  (SELECT COUNT(*) FROM answers s WHERE s.prompt_queue_id = q.id AND s.superseded_at IS NOT NULL) AS ans_superseded
493
493
  FROM queue q
494
494
  LEFT JOIN answers r ON r.prompt_queue_id = q.id AND r.superseded_at IS NULL
495
495
  WHERE q.from_id = ?
496
- `,o=[t];return r&&r.length>0&&(n+=` AND q.id IN (${r.map(()=>"?").join(",")})`,o.push(...r)),n+=" ORDER BY q.id DESC",e.prepare(n).all(...o).map(i=>({row:i,answer:i.ans_id===null?null:{id:i.ans_id,answeredAt:i.ans_answered_at,text:i.ans_text,supersededCount:i.ans_superseded}}))}function Aw(e){return e.filter(t=>t.answer===null&&t.row.retracted_ts===null&&t.row.merged_into_id===null)}function $w(e,t){let r=t??process.env.LMBEE_SENDER_PULL_SEEN_DIR??vw(tC(),".lmbee","sender-pull-seen");return vw(r,`${e}.json`)}function fu(e){try{let t=JSON.parse(XL(e,"utf8"));return new Map(Object.entries(t).map(([r,n])=>[Number(r),n]))}catch{return new Map}}function kw(e,t){let r=rC(e);YL(r)||QL(r,{recursive:!0});let n={};for(let[s,i]of t)n[String(s)]=i;let o=`${e}.tmp`;eC(o,JSON.stringify(n,null,1)),ZL(o,e)}var nC=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],pu=nC.join(", ");function oC(e,t){return e.prepare(`SELECT ${pu} FROM team_progress WHERE team = ?`).get(t)??null}function xw(e,t){let r=e-Date.parse(t);return Number.isFinite(r)?r:null}function Rw(e,t,r){function n(f,p){return t?e.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ? AND to_id = ?`).all(f,t):e.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ?`).all(f)}function o(f){let p=new Map;for(let h of f){let w=p.get(h.to_id);w?w.push(h.ts):p.set(h.to_id,[h.ts])}return p}let s=f=>{let p=f.reduce((h,w)=>h===null||w!==null&&w<h?w:h,null);return p===null?null:xw(r,p)},i=f=>{let p=f.filter(w=>w!==null);if(p.length===0)return 0;let h=s(p);return h===null||!f.includes(null)?h:Math.max(0,h)},a=o(n("pending","created_ts")),c=o(n("escalating","escalation_claimed_ts")),l=f=>({escalationAttemptCount:f?.escalation_attempt_count??0,lastEscalationAttemptTs:f?.last_escalation_attempt_ts??null,quotaExhaustedLastSeenAgeMs:f?.quota_exhausted_last_seen_ts?xw(r,f.quota_exhausted_last_seen_ts):null,quotaExhaustedMessage:f?.quota_exhausted_message??null}),u=new Set([...a.keys(),...c.keys()]),d=[...u].map(f=>{let p=a.get(f)??[],h=c.get(f)??[];return{toId:f,pendingCount:p.length,oldestPendingAgeMs:p.length>0?s(p):null,escalatingCount:h.length,oldestEscalatingAgeMs:h.length>0?i(h):null,...l(oC(e,f))}}),m=t?e.prepare(`SELECT ${pu} FROM team_progress WHERE team = ? AND escalation_attempt_count > 0`).all(t):e.prepare(`SELECT ${pu} FROM team_progress WHERE escalation_attempt_count > 0`).all();for(let f of m)u.has(f.team)||d.push({toId:f.team,pendingCount:0,oldestPendingAgeMs:null,escalatingCount:0,oldestEscalatingAgeMs:null,...l(f)});return d.sort((f,p)=>(p.oldestPendingAgeMs??-1)-(f.oldestPendingAgeMs??-1)),d}var Kt=Ut(xt(),1);var dC=[".md",".txt",".json",".log",".yaml",".yml",".csv",".html",".htm",".xml"];function mC(e){if(/\s/.test(e)||!(e.startsWith("/")||e.startsWith("./")||dC.some(r=>e.toLowerCase().endsWith(r))))return!1;try{return iC(e)}catch{return!1}}function fC(e,t){return new Error(`${e}: prompt body looks like a file path that exists on disk: "${t}"
496
+ `,o=[t];return r&&r.length>0&&(n+=` AND q.id IN (${r.map(()=>"?").join(",")})`,o.push(...r)),n+=" ORDER BY q.id DESC",e.prepare(n).all(...o).map(i=>({row:i,answer:i.ans_id===null?null:{id:i.ans_id,answeredAt:i.ans_answered_at,text:i.ans_text,supersededCount:i.ans_superseded}}))}function Nw(e){return e.filter(t=>t.answer===null&&t.row.retracted_ts===null&&t.row.merged_into_id===null)}function Lw(e,t){let r=t??process.env.LMBEE_SENDER_PULL_SEEN_DIR??Rw(cC(),".lmbee","sender-pull-seen");return Rw(r,`${e}.json`)}function gu(e){try{let t=JSON.parse(sC(e,"utf8"));return new Map(Object.entries(t).map(([r,n])=>[Number(r),n]))}catch{return new Map}}function Iw(e,t){let r=lC(e);nC(r)||oC(r,{recursive:!0});let n={};for(let[s,i]of t)n[String(s)]=i;let o=`${e}.tmp`;aC(o,JSON.stringify(n,null,1)),iC(o,e)}var uC=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],_u=uC.join(", ");function dC(e,t){return e.prepare(`SELECT ${_u} FROM team_progress WHERE team = ?`).get(t)??null}function Cw(e,t){let r=e-Date.parse(t);return Number.isFinite(r)?r:null}function Ow(e,t,r){function n(f,p){return t?e.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ? AND to_id = ?`).all(f,t):e.prepare(`SELECT to_id, ${p} AS ts FROM queue WHERE status = ?`).all(f)}function o(f){let p=new Map;for(let h of f){let w=p.get(h.to_id);w?w.push(h.ts):p.set(h.to_id,[h.ts])}return p}let s=f=>{let p=f.reduce((h,w)=>h===null||w!==null&&w<h?w:h,null);return p===null?null:Cw(r,p)},i=f=>{let p=f.filter(w=>w!==null);if(p.length===0)return 0;let h=s(p);return h===null||!f.includes(null)?h:Math.max(0,h)},a=o(n("pending","created_ts")),c=o(n("escalating","escalation_claimed_ts")),l=f=>({escalationAttemptCount:f?.escalation_attempt_count??0,lastEscalationAttemptTs:f?.last_escalation_attempt_ts??null,quotaExhaustedLastSeenAgeMs:f?.quota_exhausted_last_seen_ts?Cw(r,f.quota_exhausted_last_seen_ts):null,quotaExhaustedMessage:f?.quota_exhausted_message??null}),u=new Set([...a.keys(),...c.keys()]),d=[...u].map(f=>{let p=a.get(f)??[],h=c.get(f)??[];return{toId:f,pendingCount:p.length,oldestPendingAgeMs:p.length>0?s(p):null,escalatingCount:h.length,oldestEscalatingAgeMs:h.length>0?i(h):null,...l(dC(e,f))}}),m=t?e.prepare(`SELECT ${_u} FROM team_progress WHERE team = ? AND escalation_attempt_count > 0`).all(t):e.prepare(`SELECT ${_u} FROM team_progress WHERE escalation_attempt_count > 0`).all();for(let f of m)u.has(f.team)||d.push({toId:f.team,pendingCount:0,oldestPendingAgeMs:null,escalatingCount:0,oldestEscalatingAgeMs:null,...l(f)});return d.sort((f,p)=>(p.oldestPendingAgeMs??-1)-(f.oldestPendingAgeMs??-1)),d}var Kt=Ut(xt(),1);var wC=[".md",".txt",".json",".log",".yaml",".yml",".csv",".html",".htm",".xml"];function yC(e){if(/\s/.test(e)||!(e.startsWith("/")||e.startsWith("./")||wC.some(r=>e.toLowerCase().endsWith(r))))return!1;try{return fC(e)}catch{return!1}}function EC(e,t){return new Error(`${e}: prompt body looks like a file path that exists on disk: "${t}"
497
497
  Did you mean @${t} ?
498
- Pass --literal if you really meant to send the path as text.`)}function Cr(e,t,r){if(t.startsWith("@"))return _u(t.slice(1),"utf8");if(!r&&mC(t))throw fC(e,t);return t}async function Cw(e,t,r,n){let{baseId:o,alias:s}=Qr(t);if(o!=="operator"&&!e.teams.some(T=>T.name===o)){let T=es(e.db.db,e.teams,o);T!==null&&(o=T.team,s=s??T.alias,t=s!==null?`${o}:${s}`:o)}let i=`pending; the cron will deliver it -- or run: queue deliver ${o}`,a=e.teams.find(T=>T.name===o);if(a&&H(a)){let T=s??a.leadAlias,v=Vr(a);if(v.length>0&&!v.some(S=>S.alias===T))throw new Error(`enqueue: "${T}" is not a configured member of team "${o}" -- actual members: ${v.map(S=>S.alias).join(", ")}`)}if(n.inReplyTo!==void 0&&yr(e.db.db,n.inReplyTo)===null)throw new Error(`enqueue: --in-reply-to ${n.inReplyTo} does not refer to an existing queue prompt`);let c=n.isInteractiveTerminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0),l=n.from==="operator"&&c,u=Cr("enqueue",r,n.literal),d=_e(e.db.db,e.teams,t,u,{from:n.from,...n.expectsResponse!==void 0?{expectsResponse:n.expectsResponse}:{},...n.inReplyTo!==void 0?{inReplyTo:n.inReplyTo}:{},...l?{operatorPriority:!0}:{}}),f=(n.readSiteLockStateImpl??Qo)(e.db.path),p=f.kind==="free"?"warning: no lmbee daemon appears to be running against this database -- queue delivery, mail polling, and anti-churn nudging are all offline; this prompt will sit undelivered until `lmbee serve` is started (or deliver it manually with `queue deliver`).\n":f.kind==="unknown"?`warning: could not confirm whether an lmbee daemon is running against this database (the site lock could not be read) -- this is not evidence it is down.
499
- `:"",h=a&&H(a)?pC(e,a,s??a.leadAlias,t):"",_=(n.inReplyTo===void 0?yr(e.db.db,d):null)?.expects_response===1&&!hC(u)?`warning: expects-response is set but this prompt does not look like it is asking a question (no "?") -- consider --expects-response false if this is informational.
500
- `:"",E=p+h+_;if(a&&H(a))try{let v=await(n.fetchReport??Ae)();if(Fe(a,v))return`${E}queued#${d} -> ${t} (pending; ${o} is presence-gated right now -- it won't push-deliver until that interactive session ends. ${o} can pull it early with \`queue retrieve ${o}\`, or you can check back later with \`queue deliver ${o}\`)`}catch{}return`${E}queued#${d} -> ${t} (${i})`}function pC(e,t,r,n){let o;try{o=Q(t)}catch{return""}let s=jt(t,r),i=s!==null?rt(e.db.db,s):null,a=Xo(e.db.db,o,r);if((i===null||!i.disabled)&&a===null)return"";let c=[];if(i!==null&&i.disabled){let m=i.config?.expiresAt?`disabled until ${i.config.expiresAt}`:"disabled indefinitely";c.push(`${n} is on ${s}, ${m}`)}a!==null&&c.push(`${n} was last observed evicted at ${a.observedAt} -- remedy: ${a.remedy}`);let l=m=>m.alias===r||m.provider===null||rt(e.db.db,m.provider).disabled?!1:Xo(e.db.db,o,m.alias)===null,u=Vr(t).filter(l).map(m=>m.alias),d=u.length>0?`live seats on this team: ${u.join(", ")}`:"no other known-live seats on this team";return`warning: ${c.join("; ")}; ${d}.
501
- `}function hC(e){return e.includes("?")}function wu(e,t){return{queue:hc(e.db.db,t)}}function Ow(e,t,r={}){if(r.json)return JSON.stringify(wu(e,t));let n=hc(e.db.db,t).map(o=>[String(o.id),(0,Kt.escapeCell)(o.from_id),(0,Kt.escapeCell)(o.to_id),(0,Kt.escapeCell)(o.status),he(o.created_ts),o.sent_ts!==null?he(o.sent_ts):o.retrieved_ts!==null?he(o.retrieved_ts):"-"]);return(0,Kt.formatTable)([["ID","FROM","TO","STATUS","CREATED","SENT/RETRIEVED"],...n])}function Vn(e,t){return yr(e.db.db,t)}function Dw(e,t,r={}){let n=Vn(e,t);return r.json?JSON.stringify(n?{queue:n}:ke("queue_not_found",`no queue entry ${t}`)):n?`queue#${n.id} ${n.from_id} -> ${n.to_id} [${n.status}] prompt=${n.prompt_file} created ${n.created_ts} sent ${n.sent_ts??"-"} retrieved ${n.retrieved_ts??"-"}`:`no queue entry ${t}`}var hu=64*1024;function Nw(e){if(e===null)return null;let t=Buffer.byteLength(e.answer_text,"utf8");if(t<=hu)return{...e,byteLength:t,totalBytes:t,truncated:!1};let r=Buffer.from(e.answer_text,"utf8").subarray(0,hu).toString("utf8");for(;Buffer.byteLength(r,"utf8")>hu;)r=r.slice(0,-1);return{...e,answer_text:r,byteLength:Buffer.byteLength(r,"utf8"),totalBytes:t,truncated:!0}}function ts(e,t){let r=yr(e.db.db,t);if(r===null)return null;let n=Ce(e.db.db,t),o=Qh(e.db.db,t).map(s=>Nw(s)).filter(s=>s!==null);return{id:r.id,createdAt:r.created_ts,answer:Nw(n),answerHistory:o,mergedInto:r.status==="merged"?Ml(e.db.db,r)?.id??null:null,...vt(r,n)}}function Mw(e,t,r={}){let n=ts(e,t);if(r.json)return JSON.stringify(n?{state:n}:ke("queue_not_found",`no queue entry ${t}`));if(n===null)return`no queue entry ${t}`;let o;if(n.answerHistory.length>1){let i=n.answerHistory.map(a=>{let c=a.superseded_at!==null?`superseded ${a.superseded_at}`:"current";return` answered ${a.answered_at} (${c}): ${a.answer_text}${a.truncated?` \u2026 [truncated, ${a.totalBytes} bytes total]`:""}`});o=`
498
+ Pass --literal if you really meant to send the path as text.`)}function Cr(e,t,r){if(t.startsWith("@"))return Eu(t.slice(1),"utf8");if(!r&&yC(t))throw EC(e,t);return t}async function Uw(e,t,r,n){let{baseId:o,alias:s}=Qr(t);if(o!=="operator"&&!e.teams.some(E=>E.name===o)){let E=os(e.db.db,e.teams,o);E!==null&&(o=E.team,s=s??E.alias,t=s!==null?`${o}:${s}`:o)}let i=`pending; the cron will deliver it -- or run: queue deliver ${o}`,a=e.teams.find(E=>E.name===o);if(a&&B(a)){let E=s??a.leadAlias,v=Vr(a);if(v.length>0&&!v.some(S=>S.alias===E))throw new Error(`enqueue: "${E}" is not a configured member of team "${o}" -- actual members: ${v.map(S=>S.alias).join(", ")}`)}if(n.inReplyTo!==void 0&&Er(e.db.db,n.inReplyTo)===null)throw new Error(`enqueue: --in-reply-to ${n.inReplyTo} does not refer to an existing queue prompt`);let c=n.isInteractiveTerminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0),l=n.from==="operator"&&c,u=Cr("enqueue",r,n.literal),d=_e(e.db.db,e.teams,t,u,{from:n.from,...n.expectsResponse!==void 0?{expectsResponse:n.expectsResponse}:{},...n.inReplyTo!==void 0?{inReplyTo:n.inReplyTo}:{},...l?{operatorPriority:!0}:{}}),f=(n.readSiteLockStateImpl??ts)(e.db.path),p=f.kind==="free"?"warning: no lmbee daemon appears to be running against this database -- queue delivery, mail polling, and anti-churn nudging are all offline; this prompt will sit undelivered until `lmbee serve` is started (or deliver it manually with `queue deliver`).\n":f.kind==="unknown"?`warning: could not confirm whether an lmbee daemon is running against this database (the site lock could not be read) -- this is not evidence it is down.
499
+ `:"",h=a&&B(a)?TC(e,a,s??a.leadAlias,t):"",_=(n.inReplyTo===void 0?Er(e.db.db,d):null)?.expects_response===1&&!bC(u)?`warning: expects-response is set but this prompt does not look like it is asking a question (no "?") -- consider --expects-response false if this is informational.
500
+ `:"",T=p+h+_;if(a&&B(a))try{let v=await(n.fetchReport??Ae)();if(Fe(a,v))return`${T}queued#${d} -> ${t} (pending; ${o} is presence-gated right now -- it won't push-deliver until that interactive session ends. ${o} can pull it early with \`queue retrieve ${o}\`, or you can check back later with \`queue deliver ${o}\`)`}catch{}return`${T}queued#${d} -> ${t} (${i})`}function TC(e,t,r,n){let o;try{o=Q(t)}catch{return""}let s=jt(t,r),i=s!==null?rt(e.db.db,s):null,a=rs(e.db.db,o,r);if((i===null||!i.disabled)&&a===null)return"";let c=[];if(i!==null&&i.disabled){let m=i.config?.expiresAt?`disabled until ${i.config.expiresAt}`:"disabled indefinitely";c.push(`${n} is on ${s}, ${m}`)}a!==null&&c.push(`${n} was last observed evicted at ${a.observedAt} -- remedy: ${a.remedy}`);let l=m=>m.alias===r||m.provider===null||rt(e.db.db,m.provider).disabled?!1:rs(e.db.db,o,m.alias)===null,u=Vr(t).filter(l).map(m=>m.alias),d=u.length>0?`live seats on this team: ${u.join(", ")}`:"no other known-live seats on this team";return`warning: ${c.join("; ")}; ${d}.
501
+ `}function bC(e){return e.includes("?")}function Tu(e,t){return{queue:wc(e.db.db,t)}}function Fw(e,t,r={}){if(r.json)return JSON.stringify(Tu(e,t));let n=wc(e.db.db,t).map(o=>[String(o.id),(0,Kt.escapeCell)(o.from_id),(0,Kt.escapeCell)(o.to_id),(0,Kt.escapeCell)(o.status),he(o.created_ts),o.sent_ts!==null?he(o.sent_ts):o.retrieved_ts!==null?he(o.retrieved_ts):"-"]);return(0,Kt.formatTable)([["ID","FROM","TO","STATUS","CREATED","SENT/RETRIEVED"],...n])}function Kn(e,t){return Er(e.db.db,t)}function qw(e,t,r={}){let n=Kn(e,t);return r.json?JSON.stringify(n?{queue:n}:$e("queue_not_found",`no queue entry ${t}`)):n?`queue#${n.id} ${n.from_id} -> ${n.to_id} [${n.status}] prompt=${n.prompt_file} created ${n.created_ts} sent ${n.sent_ts??"-"} retrieved ${n.retrieved_ts??"-"}`:`no queue entry ${t}`}var wu=64*1024;function Dw(e){if(e===null)return null;let t=Buffer.byteLength(e.answer_text,"utf8");if(t<=wu)return{...e,byteLength:t,totalBytes:t,truncated:!1};let r=Buffer.from(e.answer_text,"utf8").subarray(0,wu).toString("utf8");for(;Buffer.byteLength(r,"utf8")>wu;)r=r.slice(0,-1);return{...e,answer_text:r,byteLength:Buffer.byteLength(r,"utf8"),totalBytes:t,truncated:!0}}function ss(e,t){let r=Er(e.db.db,t);if(r===null)return null;let n=Ce(e.db.db,t),o=rg(e.db.db,t).map(s=>Dw(s)).filter(s=>s!==null);return{id:r.id,createdAt:r.created_ts,answer:Dw(n),answerHistory:o,mergedInto:r.status==="merged"?Fl(e.db.db,r)?.id??null:null,...vt(r,n)}}function jw(e,t,r={}){let n=ss(e,t);if(r.json)return JSON.stringify(n?{state:n}:$e("queue_not_found",`no queue entry ${t}`));if(n===null)return`no queue entry ${t}`;let o;if(n.answerHistory.length>1){let i=n.answerHistory.map(a=>{let c=a.superseded_at!==null?`superseded ${a.superseded_at}`:"current";return` answered ${a.answered_at} (${c}): ${a.answer_text}${a.truncated?` \u2026 [truncated, ${a.totalBytes} bytes total]`:""}`});o=`
502
502
  answer history (${i.length} answers, amended ${i.length-1}x):
503
503
  ${i.join(`
504
504
  `)}`}else o=n.answer?`
505
- answer: ${n.answer.answer_text}${n.answer.truncated?` \u2026 [truncated, ${n.answer.totalBytes} bytes total]`:""}`:"";let s=n.mergedInto!==null?` -> #${n.mergedInto}`:"";return`queue#${n.id} [${n.lifecycle}/${n.lifecycleBasis}${s}] created ${n.createdAt} pulled ${n.pulledAt??"-"}${o}`}function Pw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=es(e.db.db,e.teams,r),a=i!==null?i.team:r;try{let c=o.amend?ag(e.db.db,t,a,s):sn(e.db.db,t,a,s);return{output:o.json?JSON.stringify({answer:c}):o.amend?`amended queue#${t} (answer#${c.id}, recorded ${c.answered_at}, superseding a prior answer)`:`answered queue#${t} (answer#${c.id}, recorded ${c.answered_at})`,exitCode:0}}catch(c){if(c instanceof L)return{output:o.json?JSON.stringify(ke(c.code,c.message)):`${c.code}: ${c.message}`,exitCode:c.exitCode};throw c}}function Uw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=es(e.db.db,e.teams,r),a=i!==null?i.team:r,c=t.map(m=>{try{let f=sn(e.db.db,m,a,s);return{id:m,ok:!0,answerId:f.id,answeredAt:f.answered_at}}catch(f){if(f instanceof L)return{id:m,ok:!1,code:f.code,message:f.message};throw f}}),u=c.filter(m=>!m.ok).length>0?1:0;return o.json?{output:JSON.stringify({outcomes:c}),exitCode:u}:{output:c.map(m=>m.ok?`answered queue#${m.id} (answer#${m.answerId}, recorded ${m.answeredAt})`:`queue#${m.id}: ${m.code}: ${m.message}`).join(`
506
- `),exitCode:u}}function Fw(e,t,r,n,o={}){let s=Cr("queue resolve",n,o.literal);try{let i=o.amend?cg(e.db.db,t,r,s):ig(e.db.db,t,r,s);return{output:o.json?JSON.stringify({answer:i}):o.amend?`amended resolution for queue#${t} as proxy for operator (answer#${i.id}, recorded ${i.answered_at}, superseding a prior resolution)`:`resolved queue#${t} as proxy for operator (answer#${i.id}, recorded ${i.answered_at})`,exitCode:0}}catch(i){if(i instanceof L)return{output:o.json?JSON.stringify(ke(i.code,i.message)):`${i.code}: ${i.message}`,exitCode:i.exitCode};throw i}}function qw(e,t,r,n,o={}){try{let s=tg(e.db.db,t,r,n,{noNotice:o.noNotice});return o.json?{output:JSON.stringify(s),exitCode:0}:{output:s.kind==="deleted"?`deleted queue#${t} (never retrieved): ${s.reason}`:s.kind==="retracted-with-notice"?`retracted queue#${t}: ${s.row.retracted_reason} -- fresh notice sent as queue#${s.noticeId} (was already retrieved, unanswered)`:`retracted queue#${t}: ${s.row.retracted_reason}${o.noNotice?" -- no notice sent (--no-notice)":""}`,exitCode:0}}catch(s){if(s instanceof L)return{output:o.json?JSON.stringify(ke(s.code,s.message)):`${s.code}: ${s.message}`,exitCode:s.exitCode};throw s}}function jw(e,t,r={}){let n=Date.now(),o=rg(e.db.db,t,n);if(r.json)return{output:JSON.stringify({candidates:o}),exitCode:0};if(o.length===0)return{output:`${t}: no redelivery candidates (nothing dispatched-but-unconfirmed)`,exitCode:0};let s=o.map(i=>` #${i.row.id} from ${i.row.from_id}, sent ${me(i.ageMs)} ago -- \`lmbee queue redeliver ${i.row.id} --reason "<why>"\``);return{output:`${t}: ${o.length} redelivery candidate(s) (dispatched, never confirmed -- a refreshed session has no record of these):
505
+ answer: ${n.answer.answer_text}${n.answer.truncated?` \u2026 [truncated, ${n.answer.totalBytes} bytes total]`:""}`:"";let s=n.mergedInto!==null?` -> #${n.mergedInto}`:"";return`queue#${n.id} [${n.lifecycle}/${n.lifecycleBasis}${s}] created ${n.createdAt} pulled ${n.pulledAt??"-"}${o}`}function Hw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=os(e.db.db,e.teams,r),a=i!==null?i.team:r;try{let c=o.amend?mg(e.db.db,t,a,s):sn(e.db.db,t,a,s);return{output:o.json?JSON.stringify({answer:c}):o.amend?`amended queue#${t} (answer#${c.id}, recorded ${c.answered_at}, superseding a prior answer)`:`answered queue#${t} (answer#${c.id}, recorded ${c.answered_at})`,exitCode:0}}catch(c){if(c instanceof I)return{output:o.json?JSON.stringify($e(c.code,c.message)):`${c.code}: ${c.message}`,exitCode:c.exitCode};throw c}}function Bw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=os(e.db.db,e.teams,r),a=i!==null?i.team:r,c=t.map(m=>{try{let f=sn(e.db.db,m,a,s);return{id:m,ok:!0,answerId:f.id,answeredAt:f.answered_at}}catch(f){if(f instanceof I)return{id:m,ok:!1,code:f.code,message:f.message};throw f}}),u=c.filter(m=>!m.ok).length>0?1:0;return o.json?{output:JSON.stringify({outcomes:c}),exitCode:u}:{output:c.map(m=>m.ok?`answered queue#${m.id} (answer#${m.answerId}, recorded ${m.answeredAt})`:`queue#${m.id}: ${m.code}: ${m.message}`).join(`
506
+ `),exitCode:u}}function Ww(e,t,r,n,o={}){let s=Cr("queue resolve",n,o.literal);try{let i=o.amend?fg(e.db.db,t,r,s):dg(e.db.db,t,r,s);return{output:o.json?JSON.stringify({answer:i}):o.amend?`amended resolution for queue#${t} as proxy for operator (answer#${i.id}, recorded ${i.answered_at}, superseding a prior resolution)`:`resolved queue#${t} as proxy for operator (answer#${i.id}, recorded ${i.answered_at})`,exitCode:0}}catch(i){if(i instanceof I)return{output:o.json?JSON.stringify($e(i.code,i.message)):`${i.code}: ${i.message}`,exitCode:i.exitCode};throw i}}function Gw(e,t,r,n,o={}){try{let s=ig(e.db.db,t,r,n,{noNotice:o.noNotice});return o.json?{output:JSON.stringify(s),exitCode:0}:{output:s.kind==="deleted"?`deleted queue#${t} (never retrieved): ${s.reason}`:s.kind==="retracted-with-notice"?`retracted queue#${t}: ${s.row.retracted_reason} -- fresh notice sent as queue#${s.noticeId} (was already retrieved, unanswered)`:`retracted queue#${t}: ${s.row.retracted_reason}${o.noNotice?" -- no notice sent (--no-notice)":""}`,exitCode:0}}catch(s){if(s instanceof I)return{output:o.json?JSON.stringify($e(s.code,s.message)):`${s.code}: ${s.message}`,exitCode:s.exitCode};throw s}}function Vw(e,t,r={}){let n=Date.now(),o=ag(e.db.db,t,n);if(r.json)return{output:JSON.stringify({candidates:o}),exitCode:0};if(o.length===0)return{output:`${t}: no redelivery candidates (nothing dispatched-but-unconfirmed)`,exitCode:0};let s=o.map(i=>` #${i.row.id} from ${i.row.from_id}, sent ${me(i.ageMs)} ago -- \`lmbee queue redeliver ${i.row.id} --reason "<why>"\``);return{output:`${t}: ${o.length} redelivery candidate(s) (dispatched, never confirmed -- a refreshed session has no record of these):
507
507
  ${s.join(`
508
- `)}`,exitCode:0}}function Hw(e,t,r,n={}){try{let o=ng(e.db.db,t,r);return{output:n.json?JSON.stringify({row:o}):`requeued queue#${t} for redelivery (status: ${o.status})`,exitCode:0}}catch(o){if(o instanceof L)return{output:n.json?JSON.stringify(ke(o.code,o.message)):`${o.code}: ${o.message}`,exitCode:o.exitCode};throw o}}function Bw(e,t,r,n={}){let o=new Date().toISOString();return Om(e.db.db,t,r??null,o),{output:n.json?JSON.stringify({team:t,pausedAt:o,reason:r??null}):`${t}: queue delivery paused${r?` (${r})`:""} -- manual lctl chat/nudge/enqueue unaffected; \`lmbee queue resume ${t}\` to lift`,exitCode:0}}function Ww(e,t,r={}){let n=Dm(e.db.db,t);return{output:r.json?JSON.stringify({team:t,wasPaused:n}):n?`${t}: queue delivery resumed`:`${t}: queue delivery was not paused`,exitCode:0}}function Gw(e,t,r={}){if(t!==void 0){let s=Lm(e.db.db,t);return r.json?{output:JSON.stringify({team:t,paused:s!==null,state:s}),exitCode:0}:s===null?{output:`${t}: queue delivery is not paused`,exitCode:0}:{output:`${t}: queue delivery PAUSED since ${s.pausedAt}${s.reason?` (${s.reason})`:""}`,exitCode:0}}let n=Cm(e.db.db);if(r.json)return{output:JSON.stringify({paused:n}),exitCode:0};if(n.length===0)return{output:"no teams have queue delivery paused",exitCode:0};let o=n.map(s=>` ${s.team}: paused since ${s.pausedAt}${s.reason?` (${s.reason})`:""}`);return{output:`queue delivery paused (${n.length}):
508
+ `)}`,exitCode:0}}function Jw(e,t,r,n={}){try{let o=cg(e.db.db,t,r);return{output:n.json?JSON.stringify({row:o}):`requeued queue#${t} for redelivery (status: ${o.status})`,exitCode:0}}catch(o){if(o instanceof I)return{output:n.json?JSON.stringify($e(o.code,o.message)):`${o.code}: ${o.message}`,exitCode:o.exitCode};throw o}}function Kw(e,t,r,n={}){let o=new Date().toISOString();return Pm(e.db.db,t,r??null,o),{output:n.json?JSON.stringify({team:t,pausedAt:o,reason:r??null}):`${t}: queue delivery paused${r?` (${r})`:""} -- manual lctl chat/nudge/enqueue unaffected; \`lmbee queue resume ${t}\` to lift`,exitCode:0}}function zw(e,t,r={}){let n=Um(e.db.db,t);return{output:r.json?JSON.stringify({team:t,wasPaused:n}):n?`${t}: queue delivery resumed`:`${t}: queue delivery was not paused`,exitCode:0}}function Yw(e,t,r={}){if(t!==void 0){let s=Dm(e.db.db,t);return r.json?{output:JSON.stringify({team:t,paused:s!==null,state:s}),exitCode:0}:s===null?{output:`${t}: queue delivery is not paused`,exitCode:0}:{output:`${t}: queue delivery PAUSED since ${s.pausedAt}${s.reason?` (${s.reason})`:""}`,exitCode:0}}let n=Mm(e.db.db);if(r.json)return{output:JSON.stringify({paused:n}),exitCode:0};if(n.length===0)return{output:"no teams have queue delivery paused",exitCode:0};let o=n.map(s=>` ${s.team}: paused since ${s.pausedAt}${s.reason?` (${s.reason})`:""}`);return{output:`queue delivery paused (${n.length}):
509
509
  ${o.join(`
510
- `)}`,exitCode:0}}function ia(e,t={}){let{rows:r,meta:n}=_c(e.db.db,t);return{rows:r.map(o=>({...o,...vt(o,Ce(e.db.db,o.id))})),meta:n}}function yu(e,t={}){return _c(e.db.db,t)}var gu=32*1024;function Or(e,t){let r=yr(e.db.db,t);if(!r)return null;let n=new Date().toISOString(),o=u=>({id:t,status:u,text:null,byteLength:null,truncated:!1,sourceModifiedAt:null,fetchedAt:n}),s=u=>u.code==="ENOENT",i;try{i=lC(r.prompt_file)}catch(u){return o(s(u)?"missing":"unreadable")}let a,c;try{let u=uC(i);if(!u.isFile())return o("unreadable");a=u.size,c=u.mtime.toISOString()}catch(u){return o(s(u)?"missing":"unreadable")}let l;try{l=aC(i,"r")}catch{return o("unreadable")}try{let u=Buffer.alloc(gu),d=cC(l,u,0,gu,0);return{id:t,status:"available",text:u.subarray(0,d).toString("utf8"),byteLength:d,truncated:a>gu,sourceModifiedAt:c,fetchedAt:n}}catch{return o("unreadable")}finally{sC(l)}}async function Vw(e,t,r={}){let o=await(r.fetchReport??Ae)();return`queue deliver: dispatched ${Er(e.db.db,{teams:e.teams,teamName:t,report:o})} pending prompt(s)`}function Jw(e,t,r={}){let n=Vs(e.db.db,t,r.id),o=r.id===void 0?pw(e.db.db,t):[];if(n.length===0&&o.length===0)return`queue retrieve ${t}: nothing pending`;let s=n.map(c=>{let l;try{l=_u(c.prompt_file,"utf8")}catch{l="(could not read prompt file)"}return`#${c.id} from ${c.from_id} (${c.created_ts}):
510
+ `)}`,exitCode:0}}function la(e,t={}){let{rows:r,meta:n}=Ec(e.db.db,t);return{rows:r.map(o=>({...o,...vt(o,Ce(e.db.db,o.id))})),meta:n}}function bu(e,t={}){return Ec(e.db.db,t)}var yu=32*1024;function Or(e,t){let r=Er(e.db.db,t);if(!r)return null;let n=new Date().toISOString(),o=u=>({id:t,status:u,text:null,byteLength:null,truncated:!1,sourceModifiedAt:null,fetchedAt:n}),s=u=>u.code==="ENOENT",i;try{i=gC(r.prompt_file)}catch(u){return o(s(u)?"missing":"unreadable")}let a,c;try{let u=_C(i);if(!u.isFile())return o("unreadable");a=u.size,c=u.mtime.toISOString()}catch(u){return o(s(u)?"missing":"unreadable")}let l;try{l=pC(i,"r")}catch{return o("unreadable")}try{let u=Buffer.alloc(yu),d=hC(l,u,0,yu,0);return{id:t,status:"available",text:u.subarray(0,d).toString("utf8"),byteLength:d,truncated:a>yu,sourceModifiedAt:c,fetchedAt:n}}catch{return o("unreadable")}finally{mC(l)}}async function Qw(e,t,r={}){let o=await(r.fetchReport??Ae)();return`queue deliver: dispatched ${Tr(e.db.db,{teams:e.teams,teamName:t,report:o})} pending prompt(s)`}function Xw(e,t,r={}){let n=Ys(e.db.db,t,r.id),o=r.id===void 0?yw(e.db.db,t):[];if(n.length===0&&o.length===0)return`queue retrieve ${t}: nothing pending`;let s=n.map(c=>{let l;try{l=Eu(c.prompt_file,"utf8")}catch{l="(could not read prompt file)"}return`#${c.id} from ${c.from_id} (${c.created_ts}):
511
511
  ${l}`}),i=o.map(c=>`[task-prompt] #${c.id} from ${c.from_id} (${c.created_at}):
512
512
  ${c.prompt}`),a=n.length+o.length;return`queue retrieve ${t}${r.id===void 0?"":` #${r.id}`}: ${a} prompt(s)
513
513
 
514
514
  ${[...s,...i].join(`
515
515
 
516
- `)}`}function gC(e,t){if(t==="operator"||e.teams.some(n=>n.name===t))return t;let r=es(e.db.db,e.teams,t);if(r!==null)return r.team;throw new Error(`queue inbox: "${t}" is not a registered team, "operator", or a resolvable logical name`)}function Eu(e,t){let r=gC(e,t),n=[...Xh(e.db.db,r),...Gs(e.db.db,r)];n.sort((s,i)=>s.id-i.id);let o=fw(e.db.db,r);return{pending:n,taskPrompts:o}}function Kw(e,t,r={}){let n=Eu(e,t),o=r.promptsOnly===!0?n.pending.filter(a=>a.in_reply_to===null):n.pending;if(r.json)return JSON.stringify({pending:o,taskPrompts:n.taskPrompts});let s=o.length+n.taskPrompts.length;if(s===0)return`queue inbox ${t}: nothing pending (queue or task prompts)`;let i=o.map(a=>{let c=a.in_reply_to!==null?`PROMPT -> #${a.in_reply_to}`:"PROMPT";if(a.status==="merged"){let d=Ml(e.db.db,a),m=d!==null?` -> #${d.id}`:"";return{ts:a.created_ts,text:`[queue] #${a.id} from ${a.from_id} (${he(a.created_ts)}) ${c} status=merged${m} prompt=${a.prompt_file}`}}let l=vt(a,Ce(e.db.db,a.id)),u=l.lifecycle==="queued"?"Queued":l.lifecycle==="processing"?"Processing":"Finished";return{ts:a.created_ts,text:`[queue] #${a.id} from ${a.from_id} (${he(a.created_ts)}) ${c} status=${u} prompt=${a.prompt_file}`}});for(let a of n.taskPrompts){let c=a.task_id!==null?`task #${a.task_id}`:"no task";i.push({ts:a.created_at,text:`[task-prompt] #${a.id} from ${a.from_id} (${he(a.created_at)}) ${c}: ${a.prompt}`})}return i.sort((a,c)=>a.ts.localeCompare(c.ts)),`queue inbox ${t}: ${s} pending (${o.length} queue, ${n.taskPrompts.length} task prompts)
516
+ `)}`}function SC(e,t){if(t==="operator"||e.teams.some(n=>n.name===t))return t;let r=os(e.db.db,e.teams,t);if(r!==null)return r.team;throw new Error(`queue inbox: "${t}" is not a registered team, "operator", or a resolvable logical name`)}function Su(e,t){let r=SC(e,t),n=[...ng(e.db.db,r),...zs(e.db.db,r)];n.sort((s,i)=>s.id-i.id);let o=ww(e.db.db,r);return{pending:n,taskPrompts:o}}function Zw(e,t,r={}){let n=Su(e,t),o=r.promptsOnly===!0?n.pending.filter(a=>a.in_reply_to===null):n.pending;if(r.json)return JSON.stringify({pending:o,taskPrompts:n.taskPrompts});let s=o.length+n.taskPrompts.length;if(s===0)return`queue inbox ${t}: nothing pending (queue or task prompts)`;let i=o.map(a=>{let c=a.in_reply_to!==null?`PROMPT -> #${a.in_reply_to}`:"PROMPT";if(a.status==="merged"){let d=Fl(e.db.db,a),m=d!==null?` -> #${d.id}`:"";return{ts:a.created_ts,text:`[queue] #${a.id} from ${a.from_id} (${he(a.created_ts)}) ${c} status=merged${m} prompt=${a.prompt_file}`}}let l=vt(a,Ce(e.db.db,a.id)),u=l.lifecycle==="queued"?"Queued":l.lifecycle==="processing"?"Processing":"Finished";return{ts:a.created_ts,text:`[queue] #${a.id} from ${a.from_id} (${he(a.created_ts)}) ${c} status=${u} prompt=${a.prompt_file}`}});for(let a of n.taskPrompts){let c=a.task_id!==null?`task #${a.task_id}`:"no task";i.push({ts:a.created_at,text:`[task-prompt] #${a.id} from ${a.from_id} (${he(a.created_at)}) ${c}: ${a.prompt}`})}return i.sort((a,c)=>a.ts.localeCompare(c.ts)),`queue inbox ${t}: ${s} pending (${o.length} queue, ${n.taskPrompts.length} task prompts)
517
517
  ${i.map(a=>a.text).join(`
518
- `)}`}function zw(e,t,r={}){let n=on(e.db.db,t,Date.now(),e.teams.map(s=>s.name));if(r.idsOnly)return n.map(s=>s.row.id).join(",");if(r.json)return JSON.stringify({owed:n});if(n.length===0)return`${t}: nothing owed`;let o=n.map(s=>` #${s.row.id} from ${s.row.from_id}, ${me(s.ageMs)} ago${s.hasReplyTrafficSince?" (likely answered in prose, row still open)":""}`);return`${t}: ${n.length} owed answer(s):
518
+ `)}`}function ey(e,t,r={}){let n=on(e.db.db,t,Date.now(),e.teams.map(s=>s.name));if(r.idsOnly)return n.map(s=>s.row.id).join(",");if(r.json)return JSON.stringify({owed:n});if(n.length===0)return`${t}: nothing owed`;let o=n.map(s=>` #${s.row.id} from ${s.row.from_id}, ${me(s.ageMs)} ago${s.hasReplyTrafficSince?" (likely answered in prose, row still open)":""}`);return`${t}: ${n.length} owed answer(s):
519
519
  ${o.join(`
520
- `)}`}function Yw(e,t,r={}){let n=on(e.db.db,t,Date.now()).filter(s=>s.hasReplyTrafficSince);if(r.idsOnly)return n.map(s=>s.row.id).join(",");if(r.json)return JSON.stringify({likelyAnswered:n});if(n.length===0)return`${t}: nothing likely-answered-but-unclosed`;let o=n.map(s=>` #${s.row.id} from ${s.row.from_id}, ${me(s.ageMs)} ago`);return`${t}: ${n.length} row(s) with reply traffic since the prompt, unclosed -- reply traffic is not proof of an answer, review before closing:
520
+ `)}`}function ty(e,t,r={}){let n=on(e.db.db,t,Date.now()).filter(s=>s.hasReplyTrafficSince);if(r.idsOnly)return n.map(s=>s.row.id).join(",");if(r.json)return JSON.stringify({likelyAnswered:n});if(n.length===0)return`${t}: nothing likely-answered-but-unclosed`;let o=n.map(s=>` #${s.row.id} from ${s.row.from_id}, ${me(s.ageMs)} ago`);return`${t}: ${n.length} row(s) with reply traffic since the prompt, unclosed -- reply traffic is not proof of an answer, review before closing:
521
521
  ${o.join(`
522
522
  `)}
523
- close with: queue answer ${n.map(s=>s.row.id).join(",")} <text|@file> --from ${t}`}function Iw(e){if(!e)return"";let t=Date.now()-Date.parse(e);if(!Number.isFinite(t))return"";let r=Math.floor(t/6e4);if(r<60)return`${r}m`;let n=Math.floor(t/36e5);return n<24?`${n}h`:`${Math.floor(t/864e5)}d`}var Lw=600;function Qw(e,t,r={}){let n=r.seenPath??$w(t);if(r.mark!==void 0){let c=fu(n),l=Array.isArray(r.mark)?r.mark:mu(e.db.db,t).filter(d=>d.answer!==null&&!c.has(d.row.id)).map(d=>d.row.id),u=new Date().toISOString();for(let d of l)c.set(d,u);return kw(n,c),`marked ${l.length} pulled`}let o=fu(n),s=r.ids!==void 0&&r.ids.length>0,i=mu(e.db.db,t,r.ids);if(!s&&!r.all&&(i=r.open?Aw(i):i.filter(c=>c.answer!==null&&!o.has(c.row.id))),r.json)return JSON.stringify(i.map(c=>({id:c.row.id,to:c.row.to_id,alias:c.row.to_alias,state:du(c),answeredAt:c.answer?.answeredAt??null,superseded:c.answer?.supersededCount??0,pulled:o.has(c.row.id),answer:c.answer?.text??null})));if(i.length===0)return`queue pull(${t}): nothing to pull`;let a=[];for(let c of i){let l=`#${c.row.id} -> ${c.row.to_id} ${du(c)}`;if(c.answer!==null?(l+=` answered ${Iw(c.answer.answeredAt)} ago`,c.answer.supersededCount>0&&(l+=` (${c.answer.supersededCount} superseded)`),o.has(c.row.id)&&(l+=" [already pulled]")):(c.row.sent_ts??c.row.created_ts)&&(l+=` sent ${Iw(c.row.sent_ts??c.row.created_ts)} ago`),a.push(l),c.answer!==null&&c.answer.text){let u=c.answer.text.trim();!r.full&&u.length>Lw&&(u=`${u.slice(0,Lw)}
523
+ close with: queue answer ${n.map(s=>s.row.id).join(",")} <text|@file> --from ${t}`}function Mw(e){if(!e)return"";let t=Date.now()-Date.parse(e);if(!Number.isFinite(t))return"";let r=Math.floor(t/6e4);if(r<60)return`${r}m`;let n=Math.floor(t/36e5);return n<24?`${n}h`:`${Math.floor(t/864e5)}d`}var Pw=600;function ry(e,t,r={}){let n=r.seenPath??Lw(t);if(r.mark!==void 0){let c=gu(n),l=Array.isArray(r.mark)?r.mark:hu(e.db.db,t).filter(d=>d.answer!==null&&!c.has(d.row.id)).map(d=>d.row.id),u=new Date().toISOString();for(let d of l)c.set(d,u);return Iw(n,c),`marked ${l.length} pulled`}let o=gu(n),s=r.ids!==void 0&&r.ids.length>0,i=hu(e.db.db,t,r.ids);if(!s&&!r.all&&(i=r.open?Nw(i):i.filter(c=>c.answer!==null&&!o.has(c.row.id))),r.json)return JSON.stringify(i.map(c=>({id:c.row.id,to:c.row.to_id,alias:c.row.to_alias,state:pu(c),answeredAt:c.answer?.answeredAt??null,superseded:c.answer?.supersededCount??0,pulled:o.has(c.row.id),answer:c.answer?.text??null})));if(i.length===0)return`queue pull(${t}): nothing to pull`;let a=[];for(let c of i){let l=`#${c.row.id} -> ${c.row.to_id} ${pu(c)}`;if(c.answer!==null?(l+=` answered ${Mw(c.answer.answeredAt)} ago`,c.answer.supersededCount>0&&(l+=` (${c.answer.supersededCount} superseded)`),o.has(c.row.id)&&(l+=" [already pulled]")):(c.row.sent_ts??c.row.created_ts)&&(l+=` sent ${Mw(c.row.sent_ts??c.row.created_ts)} ago`),a.push(l),c.answer!==null&&c.answer.text){let u=c.answer.text.trim();!r.full&&u.length>Pw&&(u=`${u.slice(0,Pw)}
524
524
  ... (--full for the rest)`),a.push(u.split(`
525
525
  `).map(d=>` ${d}`).join(`
526
526
  `)),a.push("")}}return!s&&!r.all&&!r.open&&a.push(`-- ${i.length} unpulled answer(s). \`--mark\` to clear, \`--full\` for whole text.`),a.join(`
527
- `).replace(/\n+$/,"")}function Tu(e,t,r=Date.now()){return{stats:Rw(e.db.db,t,r)}}function _C(e){let t=e/36e5;return t<24?`${Math.round(t)}h ago`:`${Math.round(t/24)}d ago`}function Xw(e,t,r={}){let n=Tu(e,t);if(r.json)return JSON.stringify(n);if(n.stats.length===0)return t?`queue stats ${t}: nothing pending`:"queue stats: nothing pending anywhere";let o=n.stats.map(s=>[(0,Kt.escapeCell)(s.toId),String(s.pendingCount),s.oldestPendingAgeMs!==null?me(s.oldestPendingAgeMs):"-",String(s.escalatingCount),s.oldestEscalatingAgeMs!==null?me(s.oldestEscalatingAgeMs):"-",String(s.escalationAttemptCount),s.lastEscalationAttemptTs!==null?he(s.lastEscalationAttemptTs):"-",s.quotaExhaustedLastSeenAgeMs!==null?_C(s.quotaExhaustedLastSeenAgeMs):"-"]);return(0,Kt.formatTable)([["TO","PENDING","OLDEST AGE","ESCALATING","ESCALATING AGE","ESCALATION ATTEMPTS","LAST ESCALATION","QUOTA EXHAUSTED"],...o])}function Zw(e,t){let r=(t??7)*24*60*6e4;return`queue gc: removed ${df(e.db.db,{retentionMs:r})} prompt file(s) older than ${t??7} day(s)`}function wC(e,t,r){let n=Ew(e.db.db,t);if(r)return JSON.stringify(n.map(({row:s,canonical:i})=>({id:s.id,from:s.from_id,to:s.to_id,created_ts:s.created_ts,merged_into_id:i.id})));if(n.length===0)return`queue doctor${t?` ${t}`:""} --swallowed: no expects_response rows silently absorbed by a false-canonical merge`;let o=[`queue doctor${t?` ${t}`:""} --swallowed: ${n.length} expects_response row(s) folded into a canonical that itself reads as "nothing owed" -- REPORT ONLY, triage each before repairing anything:`,""];for(let{row:s,canonical:i}of n){let a="(prompt file unreadable)";try{a=_u(s.prompt_file,"utf8").split(`
527
+ `).replace(/\n+$/,"")}function vu(e,t,r=Date.now()){return{stats:Ow(e.db.db,t,r)}}function vC(e){let t=e/36e5;return t<24?`${Math.round(t)}h ago`:`${Math.round(t/24)}d ago`}function ny(e,t,r={}){let n=vu(e,t);if(r.json)return JSON.stringify(n);if(n.stats.length===0)return t?`queue stats ${t}: nothing pending`:"queue stats: nothing pending anywhere";let o=n.stats.map(s=>[(0,Kt.escapeCell)(s.toId),String(s.pendingCount),s.oldestPendingAgeMs!==null?me(s.oldestPendingAgeMs):"-",String(s.escalatingCount),s.oldestEscalatingAgeMs!==null?me(s.oldestEscalatingAgeMs):"-",String(s.escalationAttemptCount),s.lastEscalationAttemptTs!==null?he(s.lastEscalationAttemptTs):"-",s.quotaExhaustedLastSeenAgeMs!==null?vC(s.quotaExhaustedLastSeenAgeMs):"-"]);return(0,Kt.formatTable)([["TO","PENDING","OLDEST AGE","ESCALATING","ESCALATING AGE","ESCALATION ATTEMPTS","LAST ESCALATION","QUOTA EXHAUSTED"],...o])}function oy(e,t){let r=(t??7)*24*60*6e4;return`queue gc: removed ${pf(e.db.db,{retentionMs:r})} prompt file(s) older than ${t??7} day(s)`}function AC(e,t,r){let n=Aw(e.db.db,t);if(r)return JSON.stringify(n.map(({row:s,canonical:i})=>({id:s.id,from:s.from_id,to:s.to_id,created_ts:s.created_ts,merged_into_id:i.id})));if(n.length===0)return`queue doctor${t?` ${t}`:""} --swallowed: no expects_response rows silently absorbed by a false-canonical merge`;let o=[`queue doctor${t?` ${t}`:""} --swallowed: ${n.length} expects_response row(s) folded into a canonical that itself reads as "nothing owed" -- REPORT ONLY, triage each before repairing anything:`,""];for(let{row:s,canonical:i}of n){let a="(prompt file unreadable)";try{a=Eu(s.prompt_file,"utf8").split(`
528
528
  `)[0]??""}catch{}o.push(` #${s.id} from ${s.from_id} to ${s.to_id}, ${he(s.created_ts)} -- merged into #${i.id}: "${a}"`)}return o.join(`
529
- `)}function ey(e,t,r={}){if(r.swallowed===!0)return wC(e,t,r.json);if(r.repair===!0){let l=yw(e.db.db,t);if(r.json)return JSON.stringify({repaired:l.repaired,unverified:l.unverified.map(d=>d.id)});let u=[`queue doctor${t?` ${t}`:""}: repaired ${l.repaired} row(s) with a verified merge target`];return l.unverified.length>0&&(u.push(`${l.unverified.length} row(s) could NOT be verified (left untouched, original content still in their own prompt_file):`),u.push(...l.unverified.map(d=>` #${d.id} from ${d.from_id} to ${d.to_id} (${d.created_ts}) prompt=${d.prompt_file}`))),u.join(`
530
- `)}let n=lu(e.db.db,t);if(r.json)return JSON.stringify(n.map(({row:l,verifiedTarget:u})=>({id:l.id,from:l.from_id,to:l.to_id,created_ts:l.created_ts,verifiedTarget:u?.id??null})));if(n.length===0)return`queue doctor${t?` ${t}`:""}: no orphan-merged rows (status='merged' AND merged_into_id IS NULL)`;let o=n.filter(l=>l.verifiedTarget!==null),s=n.filter(l=>l.verifiedTarget===null),i=new Map;for(let{row:l,verifiedTarget:u}of n){let d=i.get(l.to_id)??{verified:0,unverified:0};u!==null?d.verified++:d.unverified++,i.set(l.to_id,d)}let a=[...i.entries()].sort((l,u)=>u[1].unverified-l[1].unverified||u[1].verified-l[1].verified),c=[`queue doctor${t?` ${t}`:""}: ${n.length} orphan-merged row(s) -- ${o.length} verified delivered (run --repair to record), ${s.length} genuine unknown(s)`,...(0,Kt.formatTable)([["RECIPIENT","VERIFIED","UNVERIFIED"],...a.map(([l,u])=>[(0,Kt.escapeCell)(l),String(u.verified),String(u.unverified)])]).split(`
529
+ `)}function sy(e,t,r={}){if(r.swallowed===!0)return AC(e,t,r.json);if(r.repair===!0){let l=vw(e.db.db,t);if(r.json)return JSON.stringify({repaired:l.repaired,unverified:l.unverified.map(d=>d.id)});let u=[`queue doctor${t?` ${t}`:""}: repaired ${l.repaired} row(s) with a verified merge target`];return l.unverified.length>0&&(u.push(`${l.unverified.length} row(s) could NOT be verified (left untouched, original content still in their own prompt_file):`),u.push(...l.unverified.map(d=>` #${d.id} from ${d.from_id} to ${d.to_id} (${d.created_ts}) prompt=${d.prompt_file}`))),u.join(`
530
+ `)}let n=mu(e.db.db,t);if(r.json)return JSON.stringify(n.map(({row:l,verifiedTarget:u})=>({id:l.id,from:l.from_id,to:l.to_id,created_ts:l.created_ts,verifiedTarget:u?.id??null})));if(n.length===0)return`queue doctor${t?` ${t}`:""}: no orphan-merged rows (status='merged' AND merged_into_id IS NULL)`;let o=n.filter(l=>l.verifiedTarget!==null),s=n.filter(l=>l.verifiedTarget===null),i=new Map;for(let{row:l,verifiedTarget:u}of n){let d=i.get(l.to_id)??{verified:0,unverified:0};u!==null?d.verified++:d.unverified++,i.set(l.to_id,d)}let a=[...i.entries()].sort((l,u)=>u[1].unverified-l[1].unverified||u[1].verified-l[1].verified),c=[`queue doctor${t?` ${t}`:""}: ${n.length} orphan-merged row(s) -- ${o.length} verified delivered (run --repair to record), ${s.length} genuine unknown(s)`,...(0,Kt.formatTable)([["RECIPIENT","VERIFIED","UNVERIFIED"],...a.map(([l,u])=>[(0,Kt.escapeCell)(l),String(u.verified),String(u.unverified)])]).split(`
531
531
  `)];return s.length>0&&(c.push("","Unverified rows (no delivered target found anywhere; original content still in their own prompt_file):"),c.push(...s.map(({row:l})=>` #${l.id} from ${l.from_id} to ${l.to_id} (${l.created_ts}) prompt=${l.prompt_file}`))),c.join(`
532
- `)}import{readFileSync as yC,statSync as EC}from"node:fs";var Jn=Ut(xt(),1);function aa(e,t,r){let n;try{n=EC(t)}catch{return{output:`error: source not found: ${t}`,ok:!1}}if(!n.isFile())return{output:`error: source must be a regular file (a teams.conf-style TSV or a teams.md), not a directory: ${t}`,ok:!1};let o=t.toLowerCase(),s=o.endsWith(".md");if(!s&&!o.endsWith(".conf"))return{output:`error: source must end in .conf or .md: ${t}`,ok:!1};let i;try{i=yC(t,"utf8")}catch(l){return{output:`error: could not read source ${t}: ${l instanceof Error?l.message:String(l)}`,ok:!1}}let a=s?rc(i):yo(i);if(a.length===0)return{output:`error: source parsed to zero teams, not registered: ${t}`,ok:!1};Is(e.db.db,t,r??null);let c=a.map(l=>l.name).join(", ");return{output:`source added: ${t} (${a.length} team${a.length===1?"":"s"}: ${c})`,ok:!0}}function bu(e){return{defaultTeamsConfPath:e.teamsConfPath,sources:nc(e.db.db)}}function ty(e,t={}){let r=bu(e);if(t.json)return JSON.stringify(r);let n=["-",(0,Jn.escapeCell)(r.defaultTeamsConfPath),"(default, always scanned)"],o=r.sources.map(s=>[String(s.id),(0,Jn.escapeCell)(s.path),(0,Jn.escapeCell)(s.label??"")]);return(0,Jn.formatTable)([["ID","PATH","LABEL"],n,...o])}function ry(e,t){return Ls(e.db.db,t),`source removed: ${t}`}import{execFile as TC}from"node:child_process";import{promisify as bC}from"node:util";var Kn=Ut(xt(),1);var SC=bC(TC);function ny(e,t){return{team:t,state:Ue(e.db.db,t),progress:ie(e.db.db,t),last_nudged:Nc(e.db.db,t)}}function Su(e){let t=e.teams.map(n=>ny(e,n.name)),r=Cs(e.db.db)??[];return{teams:t,active:r}}function vu(e,t){return{team:ny(e,t)}}var vC=new Set(["DONE"]);function oy(e,t={}){let r=Su(e),n=t.nonDone?r.teams.filter(i=>!vC.has(i.state?.status??"")):r.teams;if(t.json)return JSON.stringify({...r,teams:n});let o=n.map(i=>[(0,Kn.escapeCell)(i.team),(0,Kn.escapeCell)(i.state?.status??"?"),i.state?.changed_ts?he(i.state.changed_ts):"-",i.state?.last_ts?he(i.state.last_ts):"-",(0,Kn.escapeCell)(i.progress?.progress_status??"?"),i.progress?.confirmed_done_ts?"yes":"-"]);return`${(0,Kn.formatTable)([["TEAM","STATUS(self-report)","CHANGED","LAST","PROGRESS","CONFIRMED-DONE"],...o])}
533
- active: ${r.active.length?r.active.join(","):"(none)"}`}function sy(e,t,r={}){let{team:n}=vu(e,t);if(r.json)return JSON.stringify({team:n});let o=n.state?`self-report: ${n.state.status} (changed ${n.state.changed_ts}, last ${n.state.last_ts})`:"self-report: (no state)",s=`progress: ${n.progress?.progress_status??"(never scanned)"}`+(n.progress?.confirmed_done_ts?` -- MAINTAINER-CONFIRMED DONE at ${n.progress.confirmed_done_ts}`:"");return`${t}: ${o}
534
- ${s}`}function iy(e,t,r,n,o=Date.now()){return ir(e.db.db,t,r,o),tt(e.db.db,t,r,o,{note:n||"manual state set"}),`state set ${t} -> ${r}`}function ay(e,t,r,n=Date.now()){let o=new Date(n).toISOString();return Ha(e.db.db,t,o),tt(e.db.db,t,"confirmed-done",n,{note:r||"maintainer confirmed done"}),`${t}: confirmed done at ${o} -- stalled-flagging and auto-nudge suppressed until new work or \`state reopen ${t}\``}async function cy(e,t,r,n=Date.now(),o=SC){let s=ie(e.db.db,t)?.confirmed_done_ts!=null;Ha(e.db.db,t,null),tt(e.db.db,t,"reopened",n,{note:r||"maintainer reopened"});let i=s?`${t}: reopened -- confirmed-done cleared`:`${t}: reopened -- was not confirmed-done, nothing to clear`,a=e.teams.find(c=>c.name===t);if(a===void 0||!H(a))return i;try{let c=await Jo(Q(a),a.leadAlias,o);if(!c.sessionResolves){let l=c.provider?` (provider=${c.provider})`:"";return`${i}
535
- WARNING: ${a.leadAlias}'s own session does not resolve -- session not found${l}. Reopening alone will NOT make this team reachable; run \`lmctl refresh ${t}.lmctl ${a.leadAlias}\` first.`}}catch{}return i}function Au(e){return{active:Cs(e.db.db)??[]}}function ly(e,t={}){let r=Au(e);return t.json?JSON.stringify(r):`active: ${r.active.length?r.active.join(","):"(none)"}`}var zn=Ut(xt(),1);function AC(e,t){return H(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead(reclaimable)":"Idle":"remote -- delivery only"}async function $u(e,t={}){let r=null;t.live&&(r=await(t.fetchReport??Ae)());let n=e.teams.map(u=>{let d=Ue(e.db.db,u.name),m=lf(e.db.db,u.name).length,f={team:u.name,status:d?.status??null,changedTs:d?.changed_ts??null,pending:m};return t.live&&r&&(f.live=AC(u,r)),f}),s=await(t.checkActiveGhAccountImpl??Xi)(),i=s!==null&&!s.matchesPolicy?s:null,c=(t.readSiteLockStateImpl??Qo)(e.db.path),l=c.kind==="held"?{running:!0,pid:c.identity.pid,ownerLabel:c.identity.ownerLabel,startedAt:c.identity.startedAt,unconfirmed:!1}:{running:!1,pid:null,ownerLabel:null,startedAt:null,unconfirmed:c.kind==="unknown"};return{live:t.live===!0,teams:n,ghAccountMismatch:i,daemon:l}}async function uy(e,t={}){let r=await $u(e,t);if(t.json)return JSON.stringify(r);let n=r.live?["TEAM","LAST-STATUS","CHANGED","PENDING","LIVE"]:["TEAM","LAST-STATUS","CHANGED","PENDING"],o=r.teams.map(a=>{let c=[(0,zn.escapeCell)(a.team),(0,zn.escapeCell)(a.status??"?"),a.changedTs===null?"-":he(a.changedTs),String(a.pending)];return r.live?[...c,(0,zn.escapeCell)(a.live??"")]:c}),s=(0,zn.formatTable)([n,...o]),i=[];return i.push(r.daemon.unconfirmed?"!!! DAEMON STATE COULD NOT BE CONFIRMED -- the site lock could not be read (a transient error, or a race with a concurrent lock operation). This is NOT evidence the daemon is down -- do not act on it as if it were; re-run status, or check `systemctl --user status lmbee.service`. !!!":r.daemon.running?`daemon: running (pid ${r.daemon.pid}, ${r.daemon.ownerLabel}, started ${r.daemon.startedAt})`:"!!! DAEMON NOT RUNNING -- queue delivery, mail polling, and anti-churn nudging are all OFFLINE. A prompt accepted by `enqueue` will sit undelivered until `lmbee serve` is started. !!!"),r.ghAccountMismatch!==null&&i.push(`!!! GH ACCOUNT POLICY MISMATCH: "${r.ghAccountMismatch.account}" is the active account on this machine -- policy requires "${Bl}". DO NOT PUSH until this is switched back. !!!`),i.push(s),i.join(`
532
+ `)}import{readFileSync as kC,statSync as $C}from"node:fs";var zn=Ut(xt(),1);function ua(e,t,r){let n;try{n=$C(t)}catch{return{output:`error: source not found: ${t}`,ok:!1}}if(!n.isFile())return{output:`error: source must be a regular file (a teams.conf-style TSV or a teams.md), not a directory: ${t}`,ok:!1};let o=t.toLowerCase(),s=o.endsWith(".md");if(!s&&!o.endsWith(".conf"))return{output:`error: source must end in .conf or .md: ${t}`,ok:!1};let i;try{i=kC(t,"utf8")}catch(l){return{output:`error: could not read source ${t}: ${l instanceof Error?l.message:String(l)}`,ok:!1}}let a=s?sc(i):To(i);if(a.length===0)return{output:`error: source parsed to zero teams, not registered: ${t}`,ok:!1};Ds(e.db.db,t,r??null);let c=a.map(l=>l.name).join(", ");return{output:`source added: ${t} (${a.length} team${a.length===1?"":"s"}: ${c})`,ok:!0}}function Au(e){return{defaultTeamsConfPath:e.teamsConfPath,sources:ic(e.db.db)}}function iy(e,t={}){let r=Au(e);if(t.json)return JSON.stringify(r);let n=["-",(0,zn.escapeCell)(r.defaultTeamsConfPath),"(default, always scanned)"],o=r.sources.map(s=>[String(s.id),(0,zn.escapeCell)(s.path),(0,zn.escapeCell)(s.label??"")]);return(0,zn.formatTable)([["ID","PATH","LABEL"],n,...o])}function ay(e,t){return Ms(e.db.db,t),`source removed: ${t}`}import{execFile as xC}from"node:child_process";import{promisify as RC}from"node:util";var Yn=Ut(xt(),1);var NC=RC(xC);function cy(e,t){return{team:t,state:Ue(e.db.db,t),progress:ie(e.db.db,t),last_nudged:Cc(e.db.db,t)}}function ku(e){let t=e.teams.map(n=>cy(e,n.name)),r=Ps(e.db.db)??[];return{teams:t,active:r}}function $u(e,t){return{team:cy(e,t)}}var LC=new Set(["DONE"]);function ly(e,t={}){let r=ku(e),n=t.nonDone?r.teams.filter(i=>!LC.has(i.state?.status??"")):r.teams;if(t.json)return JSON.stringify({...r,teams:n});let o=n.map(i=>[(0,Yn.escapeCell)(i.team),(0,Yn.escapeCell)(i.state?.status??"?"),i.state?.changed_ts?he(i.state.changed_ts):"-",i.state?.last_ts?he(i.state.last_ts):"-",(0,Yn.escapeCell)(i.progress?.progress_status??"?"),i.progress?.confirmed_done_ts?"yes":"-"]);return`${(0,Yn.formatTable)([["TEAM","STATUS(self-report)","CHANGED","LAST","PROGRESS","CONFIRMED-DONE"],...o])}
533
+ active: ${r.active.length?r.active.join(","):"(none)"}`}function uy(e,t,r={}){let{team:n}=$u(e,t);if(r.json)return JSON.stringify({team:n});let o=n.state?`self-report: ${n.state.status} (changed ${n.state.changed_ts}, last ${n.state.last_ts})`:"self-report: (no state)",s=`progress: ${n.progress?.progress_status??"(never scanned)"}`+(n.progress?.confirmed_done_ts?` -- MAINTAINER-CONFIRMED DONE at ${n.progress.confirmed_done_ts}`:"");return`${t}: ${o}
534
+ ${s}`}function dy(e,t,r,n,o=Date.now()){return ir(e.db.db,t,r,o),tt(e.db.db,t,r,o,{note:n||"manual state set"}),`state set ${t} -> ${r}`}function my(e,t,r,n=Date.now()){let o=new Date(n).toISOString();return Ga(e.db.db,t,o),tt(e.db.db,t,"confirmed-done",n,{note:r||"maintainer confirmed done"}),`${t}: confirmed done at ${o} -- stalled-flagging and auto-nudge suppressed until new work or \`state reopen ${t}\``}async function fy(e,t,r,n=Date.now(),o=NC){let s=ie(e.db.db,t)?.confirmed_done_ts!=null;Ga(e.db.db,t,null),tt(e.db.db,t,"reopened",n,{note:r||"maintainer reopened"});let i=s?`${t}: reopened -- confirmed-done cleared`:`${t}: reopened -- was not confirmed-done, nothing to clear`,a=e.teams.find(c=>c.name===t);if(a===void 0||!B(a))return i;try{let c=await Qo(Q(a),a.leadAlias,o);if(!c.sessionResolves){let l=c.provider?` (provider=${c.provider})`:"";return`${i}
535
+ WARNING: ${a.leadAlias}'s own session does not resolve -- session not found${l}. Reopening alone will NOT make this team reachable; run \`lmctl refresh ${t}.lmctl ${a.leadAlias}\` first.`}}catch{}return i}function xu(e){return{active:Ps(e.db.db)??[]}}function py(e,t={}){let r=xu(e);return t.json?JSON.stringify(r):`active: ${r.active.length?r.active.join(","):"(none)"}`}var Qn=Ut(xt(),1);function IC(e,t){return B(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead(reclaimable)":"Idle":"remote -- delivery only"}async function Ru(e,t={}){let r=null;t.live&&(r=await(t.fetchReport??Ae)());let n=e.teams.map(u=>{let d=Ue(e.db.db,u.name),m=mf(e.db.db,u.name).length,f={team:u.name,status:d?.status??null,changedTs:d?.changed_ts??null,pending:m};return t.live&&r&&(f.live=IC(u,r)),f}),s=await(t.checkActiveGhAccountImpl??ta)(),i=s!==null&&!s.matchesPolicy?s:null,c=(t.readSiteLockStateImpl??ts)(e.db.path),l=c.kind==="held"?{running:!0,pid:c.identity.pid,ownerLabel:c.identity.ownerLabel,startedAt:c.identity.startedAt,unconfirmed:!1}:{running:!1,pid:null,ownerLabel:null,startedAt:null,unconfirmed:c.kind==="unknown"};return{live:t.live===!0,teams:n,ghAccountMismatch:i,daemon:l}}async function hy(e,t={}){let r=await Ru(e,t);if(t.json)return JSON.stringify(r);let n=r.live?["TEAM","LAST-STATUS","CHANGED","PENDING","LIVE"]:["TEAM","LAST-STATUS","CHANGED","PENDING"],o=r.teams.map(a=>{let c=[(0,Qn.escapeCell)(a.team),(0,Qn.escapeCell)(a.status??"?"),a.changedTs===null?"-":he(a.changedTs),String(a.pending)];return r.live?[...c,(0,Qn.escapeCell)(a.live??"")]:c}),s=(0,Qn.formatTable)([n,...o]),i=[];return i.push(r.daemon.unconfirmed?"!!! DAEMON STATE COULD NOT BE CONFIRMED -- the site lock could not be read (a transient error, or a race with a concurrent lock operation). This is NOT evidence the daemon is down -- do not act on it as if it were; re-run status, or check `systemctl --user status lmbee.service`. !!!":r.daemon.running?`daemon: running (pid ${r.daemon.pid}, ${r.daemon.ownerLabel}, started ${r.daemon.startedAt})`:"!!! DAEMON NOT RUNNING -- queue delivery, mail polling, and anti-churn nudging are all OFFLINE. A prompt accepted by `enqueue` will sit undelivered until `lmbee serve` is started. !!!"),r.ghAccountMismatch!==null&&i.push(`!!! GH ACCOUNT POLICY MISMATCH: "${r.ghAccountMismatch.account}" is the active account on this machine -- policy requires "${Vl}". DO NOT PUSH until this is switched back. !!!`),i.push(s),i.join(`
536
536
 
537
- `)}var Dr=Ut(xt(),1);function ku(e){return{teams:e.teams}}function dy(e,t={}){if(t.json)return JSON.stringify(ku(e));let r=e.teams.map(n=>H(n)?[(0,Dr.escapeCell)(n.name),(0,Dr.escapeCell)(n.leadAlias),(0,Dr.escapeCell)(n.promptName),(0,Dr.escapeCell)(n.description)]:[(0,Dr.escapeCell)(n.name),"(remote)","--","--"]);return(0,Dr.formatTable)([["TEAM","LEAD","PROMPT","WHAT-IT-DOES"],...r])}function $C(e){let t=e.LMCTL_AUTH_URL?.trim()||e.LMCTL_AUTH_BASE_URL?.trim();return t?t.replace(/\/+$/,""):void 0}async function xu(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.validateAppkeyImpl??vd,o=$C(t),s;try{s=r({env:t})}catch(a){return{data:ke("no_appkey",a instanceof Error?a.message:String(a)),exitCode:3}}let i;try{i=await n(s.appkey,{env:t,...o!==void 0?{authBaseUrl:o}:{}})}catch(a){return{data:ke("auth_unreachable",`could not validate appkey: ${a instanceof Error?a.message:String(a)}`),exitCode:4}}return i.valid?{data:{userId:i.userId,label:i.label,appkeySource:s.source},exitCode:0}:{data:ke("invalid_appkey",`appkey is invalid (source: ${s.source})`),exitCode:3}}async function my(e={}){let{data:t,exitCode:r}=await xu(e);return e.json?{output:JSON.stringify(t),exitCode:r}:"error"in t?{output:t.error.message,exitCode:r}:{output:`user_id: ${t.userId}
537
+ `)}var Dr=Ut(xt(),1);function Nu(e){return{teams:e.teams}}function gy(e,t={}){if(t.json)return JSON.stringify(Nu(e));let r=e.teams.map(n=>B(n)?[(0,Dr.escapeCell)(n.name),(0,Dr.escapeCell)(n.leadAlias),(0,Dr.escapeCell)(n.promptName),(0,Dr.escapeCell)(n.description)]:[(0,Dr.escapeCell)(n.name),"(remote)","--","--"]);return(0,Dr.formatTable)([["TEAM","LEAD","PROMPT","WHAT-IT-DOES"],...r])}function CC(e){let t=e.LMCTL_AUTH_URL?.trim()||e.LMCTL_AUTH_BASE_URL?.trim();return t?t.replace(/\/+$/,""):void 0}async function Lu(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.validateAppkeyImpl??$d,o=CC(t),s;try{s=r({env:t})}catch(a){return{data:$e("no_appkey",a instanceof Error?a.message:String(a)),exitCode:3}}let i;try{i=await n(s.appkey,{env:t,...o!==void 0?{authBaseUrl:o}:{}})}catch(a){return{data:$e("auth_unreachable",`could not validate appkey: ${a instanceof Error?a.message:String(a)}`),exitCode:4}}return i.valid?{data:{userId:i.userId,label:i.label,appkeySource:s.source},exitCode:0}:{data:$e("invalid_appkey",`appkey is invalid (source: ${s.source})`),exitCode:3}}async function _y(e={}){let{data:t,exitCode:r}=await Lu(e);return e.json?{output:JSON.stringify(t),exitCode:r}:"error"in t?{output:t.error.message,exitCode:r}:{output:`user_id: ${t.userId}
538
538
  label: ${t.label}
539
- appkey source: ${t.appkeySource}`,exitCode:r}}import{execFile as kC}from"node:child_process";import{promisify as xC}from"node:util";var RC=xC(kC);async function fy(e,t=3e4){let r=e.trim().split(/\s+/).filter(Boolean),{stdout:n}=await RC("lmctl",["status",...r,"--json"],{timeout:t}),o;try{o=JSON.parse(n)}catch(s){throw new Error(`unexpected \`lmctl status --json\` output (not valid JSON): ${s instanceof Error?s.message:String(s)}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error("unexpected `lmctl status --json` shape: expected a JSON object");return o}import{execFile as NC}from"node:child_process";import{existsSync as IC}from"node:fs";import{promisify as LC}from"node:util";var CC=LC(NC),ca=class extends Error{constructor(){super("LMBI_SUBSCRIPTION_CLI is not set -- point it at lmbi's own reviewed subscription-report-cli.js (see the lmbi subscription contract for the current staged path) before running this command."),this.name="SubscriptionCliNotConfiguredError"}};async function Ru(e){let t=e.cliPath??process.env.LMBI_SUBSCRIPTION_CLI;if(t===void 0||t==="")throw new ca;let r=e.execFileImpl??CC,{stdout:n}=await r("node",[t,e.configPath,"--json"],{timeout:e.timeoutMs??3e4});return JSON.parse(n)}async function py(e={}){let t=e.configPath??process.env.LMBI_SUBSCRIPTION_CONFIG_PATH;if(t===void 0||t===""||!IC(t))return{status:200,body:{needs_configuration:!0}};try{return{status:200,body:await Ru({configPath:t,cliPath:e.cliPath,execFileImpl:e.execFileImpl})}}catch(r){return r instanceof ca?{status:500,body:{error:r.message}}:{status:502,body:{error:r instanceof Error?r.message:String(r)}}}}import{createHash as yy,randomBytes as MC,timingSafeEqual as PC}from"node:crypto";var hy=e=>{let t=e.env.server?e.env.server:e.env,r=t.incoming.socket.remoteAddress,n=t.incoming.socket.remotePort,o=t.incoming.socket.remoteFamily;return{remote:{address:r,port:n,addressType:o==="IPv4"?"IPv4":o==="IPv6"?"IPv6":void 0}}};import{createHash as gy}from"node:crypto";import{basename as OC}from"node:path";function b(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}var _y="body{font:1rem/1.45 system-ui,sans-serif;margin:1rem;color:#111;background:#fff}main,header,footer{max-width:90rem}h1{font-size:1.5rem;margin:.7rem 0}h2{font-size:1.2rem;margin:1rem 0 .4rem}p{margin:.5rem 0}a{color:#0645ad;overflow-wrap:anywhere}table{border-collapse:collapse;width:100%;min-width:44rem}th,td{text-align:left;vertical-align:top;padding:.35rem .5rem;border:1px solid #bbb;overflow-wrap:anywhere}caption{text-align:left;font-weight:bold}.table-scroll,section{max-width:100%;overflow-x:auto}form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:end;margin:.7rem 0}label{display:flex;flex-direction:column;max-width:100%}input,select,textarea,button{font:inherit;max-width:100%;box-sizing:border-box}textarea{flex:1 1 100%}pre{white-space:pre-wrap;overflow-wrap:anywhere}details,li,dd{overflow-wrap:anywhere}dd{margin-left:1rem}article{border-top:1px solid #bbb;padding:.5rem 0}.warning{border-left:3px solid #754b00;padding-left:.5rem}footer{margin-top:2rem}.status-chip{display:inline-block;padding:.15rem .55rem;border-radius:1rem;border:1px solid transparent;font-size:.85rem;font-weight:600;line-height:1.4}.status-queued{background:#dbeafe;color:#1e3a8a;border-color:#93c5fd}.status-replied{background:#dcfce7;color:#14532d;border-color:#86efac}.status-processing{background:#fef3c7;color:#78350f;border-color:#fcd34d}.status-muted{background:#f3f4f6;color:#374151;border-color:#d1d5db}@media(max-width:500px){body{margin:.75rem}th,td{padding:.25rem}}",DC=`default-src 'none'; style-src 'sha256-${gy("sha256").update(_y).digest("base64")}'; form-action 'self'`;function Re(e,t){return`<a href="${b(e)}">${b(t)}</a>`}function Yn(e,t,r){return t.length?`<div class="table-scroll" role="region" aria-label="${b(r)}" tabindex="0"><table><caption>${b(r)}</caption><thead><tr>${e.map(n=>`<th scope="col">${b(n)}</th>`).join("")}</tr></thead><tbody>${t.map(n=>`<tr>${n.map(o=>`<td>${o}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`:"<p>No matching records.</p>"}function fe(e){return`<time datetime="${b(e)}" title="${b(e)}">${b(he(e))}</time>`}function Oe(e,t,r=200){return e.header("Cache-Control","no-store"),e.header("X-Content-Type-Options","nosniff"),e.html(t,r)}function ve(e,t,r,n={},o=[],s=!1){let i=r.replace(/\/$/,""),a=s&&i!=="",c=DC+`; base-uri '${a?"self":"none"}'`+(o.length?`; script-src ${o.map(d=>`'sha256-${gy("sha256").update(d).digest("base64")}'`).join(" ")}; connect-src 'self'`:""),l=Object.entries(n).map(([d,m])=>` ${d}="${b(m)}"`).join(""),u=[[i||"/","Home"],[`${i}/tasks`,"Tasks"],[`${i}/running`,"Running"],[`${i}/cron`,"Cron"],[`${i}/comm/math`,"Prompts"],[`${i}/operator`,"Operator"]];return`<!doctype html><html lang="en"><head><meta charset="utf-8">
539
+ appkey source: ${t.appkeySource}`,exitCode:r}}import{execFile as OC}from"node:child_process";import{promisify as DC}from"node:util";var MC=DC(OC);async function wy(e,t=3e4){let r=e.trim().split(/\s+/).filter(Boolean),{stdout:n}=await MC("lmctl",["status",...r,"--json"],{timeout:t}),o;try{o=JSON.parse(n)}catch(s){throw new Error(`unexpected \`lmctl status --json\` output (not valid JSON): ${s instanceof Error?s.message:String(s)}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error("unexpected `lmctl status --json` shape: expected a JSON object");return o}import{execFile as PC}from"node:child_process";import{existsSync as UC}from"node:fs";import{promisify as FC}from"node:util";var qC=FC(PC),da=class extends Error{constructor(){super("LMBI_SUBSCRIPTION_CLI is not set -- point it at lmbi's own reviewed subscription-report-cli.js (see the lmbi subscription contract for the current staged path) before running this command."),this.name="SubscriptionCliNotConfiguredError"}};async function Iu(e){let t=e.cliPath??process.env.LMBI_SUBSCRIPTION_CLI;if(t===void 0||t==="")throw new da;let r=e.execFileImpl??qC,{stdout:n}=await r("node",[t,e.configPath,"--json"],{timeout:e.timeoutMs??3e4});return JSON.parse(n)}async function yy(e={}){let t=e.configPath??process.env.LMBI_SUBSCRIPTION_CONFIG_PATH;if(t===void 0||t===""||!UC(t))return{status:200,body:{needs_configuration:!0}};try{return{status:200,body:await Iu({configPath:t,cliPath:e.cliPath,execFileImpl:e.execFileImpl})}}catch(r){return r instanceof da?{status:500,body:{error:r.message}}:{status:502,body:{error:r instanceof Error?r.message:String(r)}}}}import{createHash as vy,randomBytes as BC,timingSafeEqual as WC}from"node:crypto";var Ey=e=>{let t=e.env.server?e.env.server:e.env,r=t.incoming.socket.remoteAddress,n=t.incoming.socket.remotePort,o=t.incoming.socket.remoteFamily;return{remote:{address:r,port:n,addressType:o==="IPv4"?"IPv4":o==="IPv6"?"IPv6":void 0}}};import{createHash as Ty}from"node:crypto";import{basename as jC}from"node:path";function b(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}var by="body{font:1rem/1.45 system-ui,sans-serif;margin:1rem;color:#111;background:#fff}main,header,footer{max-width:90rem}h1{font-size:1.5rem;margin:.7rem 0}h2{font-size:1.2rem;margin:1rem 0 .4rem}p{margin:.5rem 0}a{color:#0645ad;overflow-wrap:anywhere}table{border-collapse:collapse;width:100%;min-width:44rem}th,td{text-align:left;vertical-align:top;padding:.35rem .5rem;border:1px solid #bbb;overflow-wrap:anywhere}caption{text-align:left;font-weight:bold}.table-scroll,section{max-width:100%;overflow-x:auto}form{display:flex;flex-wrap:wrap;gap:.5rem;align-items:end;margin:.7rem 0}label{display:flex;flex-direction:column;max-width:100%}input,select,textarea,button{font:inherit;max-width:100%;box-sizing:border-box}textarea{flex:1 1 100%}pre{white-space:pre-wrap;overflow-wrap:anywhere}details,li,dd{overflow-wrap:anywhere}dd{margin-left:1rem}article{border-top:1px solid #bbb;padding:.5rem 0}.warning{border-left:3px solid #754b00;padding-left:.5rem}footer{margin-top:2rem}.status-chip{display:inline-block;padding:.15rem .55rem;border-radius:1rem;border:1px solid transparent;font-size:.85rem;font-weight:600;line-height:1.4}.status-queued{background:#dbeafe;color:#1e3a8a;border-color:#93c5fd}.status-replied{background:#dcfce7;color:#14532d;border-color:#86efac}.status-processing{background:#fef3c7;color:#78350f;border-color:#fcd34d}.status-muted{background:#f3f4f6;color:#374151;border-color:#d1d5db}@media(max-width:500px){body{margin:.75rem}th,td{padding:.25rem}}",HC=`default-src 'none'; style-src 'sha256-${Ty("sha256").update(by).digest("base64")}'; form-action 'self'`;function Re(e,t){return`<a href="${b(e)}">${b(t)}</a>`}function Xn(e,t,r){return t.length?`<div class="table-scroll" role="region" aria-label="${b(r)}" tabindex="0"><table><caption>${b(r)}</caption><thead><tr>${e.map(n=>`<th scope="col">${b(n)}</th>`).join("")}</tr></thead><tbody>${t.map(n=>`<tr>${n.map(o=>`<td>${o}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`:"<p>No matching records.</p>"}function fe(e){return`<time datetime="${b(e)}" title="${b(e)}">${b(he(e))}</time>`}function Oe(e,t,r=200){return e.header("Cache-Control","no-store"),e.header("X-Content-Type-Options","nosniff"),e.html(t,r)}function ve(e,t,r,n={},o=[],s=!1){let i=r.replace(/\/$/,""),a=s&&i!=="",c=HC+`; base-uri '${a?"self":"none"}'`+(o.length?`; script-src ${o.map(d=>`'sha256-${Ty("sha256").update(d).digest("base64")}'`).join(" ")}; connect-src 'self'`:""),l=Object.entries(n).map(([d,m])=>` ${d}="${b(m)}"`).join(""),u=[[i||"/","Home"],[`${i}/tasks`,"Tasks"],[`${i}/running`,"Running"],[`${i}/cron`,"Cron"],[`${i}/comm/math`,"Prompts"],[`${i}/operator`,"Operator"]];return`<!doctype html><html lang="en"><head><meta charset="utf-8">
540
540
  <meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="${b(c)}"><title>${b(e)} \u2014 lmauto</title>
541
541
  ${a?`<base href="${b(i)}/" />`:""}
542
- <style>${_y}</style></head><body><a href="#main">Skip to content</a><header><p>Local operations / lmauto</p><nav aria-label="Main">${u.map(([d,m])=>Re(d,m)).join(" | ")}</nav></header><main${l} id="main"><h1>${b(e)}</h1>${t}</main><footer><p>Times are relative to this page load. Refresh for current data.</p></footer></body></html>`}function Mr(e){let t=new Map;for(let r of e)if(H(r))try{t.set(Q(r),r.name)}catch{}return t}function wy(e,t,r){function n(s,i=!0){if(s===null)return"\u2014";let a=gn(s);if(!a)return b(s);let{teamfilePath:c,alias:l}=a,u=`${OC(c)}:${l}`,d=t.get(c);if(i&&d)return`<a href="${b(`${r}/sessions/${encodeURIComponent(d)}/${encodeURIComponent(l)}`)}" title="${b(s)}">${b(u)}</a>`;let m=i?`${s} \u2014 Not in the current local team registry -- no session page available`:s;return`<span title="${b(m)}">${b(u)}</span>`}function o(s,i,a){return`<section><h2>${s}</h2><table><thead><tr>${i.map(c=>`<th scope="col">${c}</th>`).join("")}</tr></thead><tbody>${a.length?a.map(c=>`<tr>${c.map(l=>`<td>${l}</td>`).join("")}</tr>`).join(""):`<tr><td colspan="${i.length}">No ${s.toLowerCase()} invocations.</td></tr>`}</tbody></table></section>`}return"<p>Running shows work still in progress. Dead means its process stopped abnormally while work was still in progress; session data remains intact and may be resumed. Idle means the invocation finished, successfully or with a recorded error; an Idle error status describes that finished result, not an ongoing crash. A target is &lt;teamfile&gt;.lmctl:&lt;role&gt;: the team\u2019s configuration file and the member role executing, such as Lead or Coder. From names what started the invocation: another member\u2019s identity, or operator for a person acting directly, not through an agent. Only targets whose team can be resolved in the current local registry link to a session page; other targets remain unlinked. Full identities are available in the labels\u2019 tooltips.</p>"+o("Running",["Target","From","Started","Running for"],e.running.map(s=>[n(s.target),n(s.from_identity,!1),b(s.started_human),b(s.running_for_human)]))+o("Dead",["Target","From","Started","Stale for"],e.dead.map(s=>[n(s.target),n(s.from_identity,!1),b(s.started_human),b(s.stale_for_human)]))+o("Idle",["Target","From","Status","Ended","Idle for","Ran for"],e.idle.map(s=>[n(s.target),n(s.from_identity,!1),b(s.status),b(he(s.ended_at)),b(me(s.idle_ms)),b(s.ran_human)]))}var la="localweb_session",UC=8*1024,FC=1024,qC=30*24*60*60,jC=10,HC=6e4,BC=6e4,WC=1024;function $y(e,t){let r=GC(t.mountPath),n=`${r}/login`||"/login",o=`${r}/`||"/",s=r||"/",i=t.allowedOrigins,a=new Map,c=new Map,l=t.remoteKey??ZC,u,d=()=>{let m;try{m=t.readAuthority()}catch{m=null}return!m||!m.passcode||!m.generation?(a.clear(),u=void 0,null):(u!==void 0&&m.generation!==u&&a.clear(),u=m.generation,m)};e.use("*",async(m,f)=>{m.header("Cache-Control","no-store");let p=VC(m.req.path,r);if(m.req.method==="GET"&&(p==="/healthz"||p==="/login")||m.req.method==="POST"&&p==="/login"){await f();return}let h=m.req.header("origin");if(h!==void 0&&!i.includes(h))return m.json({error:"origin not allowed"},403);let w=d();if(w===null)return rs(m,p,n,r,"unavailable");let _=m.req.header("authorization");if(_!==void 0){let T=l(m),v=Date.now();if(Sy(c,T,v))return rs(m,p,n,r,"locked_out");let S=_.startsWith("Bearer ")?_.slice(7):"";if(!by(S,w.passcode))return vy(c,T,v),rs(m,p,n,r);Ay(c,T),await f();return}let E=Ty(m.req.header("cookie"));if(E===null||a.get(E)!==w.generation)return rs(m,p,n,r,E===null?"missing":"expired");if(YC(m.req.method)&&!Ey(m.req.url,m.req.header("host"),h,i))return rs(m,p,n,r);await f()}),e.get("/healthz",m=>m.json({ok:!0})),e.get("/login",m=>m.html(JC(Ry(m,n,r),r))),e.post("/login",async m=>{if(!Ey(m.req.url,m.req.header("host"),m.req.header("origin"),i))return Nu(m,n,r);let f=l(m),p=Date.now();if(Sy(c,f,p))return KC(m,r);let h=d();if(h===null)return Nu(m,n,r);let w=await zC(m.req.raw).catch(()=>null);if(w===null||!by(w,h.passcode))return vy(c,f,p),Nu(m,n,r);Ay(c,f),a.size>=FC&&a.delete(a.keys().next().value);let _=MC(32).toString("base64url");return a.set(_,h.generation),m.header("Set-Cookie",QC(_,s,new URL(m.req.url).protocol==="https:")),m.redirect(xy(m,r)??o,303)}),e.post("/logout",m=>{let f=Ty(m.req.header("cookie"));return f!==null&&a.delete(f),m.header("Set-Cookie",XC(s,new URL(m.req.url).protocol==="https:")),m.redirect(n,303)})}function GC(e=""){if(e===""||e==="/")return"";let t=e.endsWith("/")?e.slice(0,-1):e;if(!/^\/[A-Za-z0-9_./~-]+$/.test(t)||t.startsWith("//"))throw new Error("Invalid mount path");return t}function VC(e,t){return t&&(e===t||e.startsWith(`${t}/`))?e.slice(t.length)||"/":e}function rs(e,t,r,n,o="required"){let s=o==="locked_out"?429:401;if(t==="/api"||t.startsWith("/api/"))return e.json({error:o==="locked_out"?"too many failed attempts":"unauthorized"},s);let i={unavailable:"Authentication is not currently available.",missing:"You are not logged in yet.",expired:"Your session expired. Log in again to continue.",required:"Authentication required.",locked_out:"Too many failed attempts from this source. Try again shortly."}[o],a=e.req.method==="GET"?ky(`${n}${t}${new URL(e.req.url).search}`,n):null,c=a===null?r:`${r}?next=${encodeURIComponent(a)}`,l=o==="locked_out"?`<p>${i}</p>`:`<p>${i}</p><p><a href="${b(c)}">Log in</a></p>`;return e.html(ve("Authentication required",l,n),s)}function JC(e,t){return ve("LocalWeb login",`<form method="post" action="${b(e)}"><label>Passcode<input type="password" name="passcode" autocomplete="current-password" required></label><button type="submit">Log in</button></form>`,t)}function Nu(e,t,r){return e.html(ve("Login failed",`<p>Invalid credentials.</p><a href="${b(Ry(e,t,r))}">Try again</a>`,r),401)}function KC(e,t){return e.html(ve("Login failed","<p>Too many failed attempts from this source. Try again shortly.</p>",t),429)}function ky(e,t){if(!e||e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f]/.test(e))return null;let r="http://localweb.invalid";try{let n=new URL(e,r),o=decodeURIComponent(n.pathname);if(n.origin!==r||o.includes("//")||/[\\\x00-\x1f\x7f]/.test(o))return null;let s=new URL(o,r),i=a=>!t||a===t||a.startsWith(`${t}/`);return s.origin!==r||s.pathname.includes("//")||!i(n.pathname)||!i(s.pathname)?null:`${n.pathname}${n.search}${n.hash}`}catch{return null}}function xy(e,t){let r=new URL(e.req.url).searchParams.getAll("next");return r.length===1?ky(r[0],t):null}function Ry(e,t,r){let n=xy(e,r);return n===null?t:`${t}?next=${encodeURIComponent(n)}`}async function zC(e){if(!e.headers.get("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new Error("invalid form");let t=e.body?.getReader();if(!t)throw new Error("missing form");let r=[],n=0;for(;;){let{done:s,value:i}=await t.read();if(s)break;if(n+=i.byteLength,n>UC)throw await t.cancel(),new Error("form too large");r.push(i)}let o=new URLSearchParams(Buffer.concat(r).toString("utf8"));if(o.getAll("passcode").length!==1||[...o.keys()].some(s=>s!=="passcode"))throw new Error("invalid form");return o.get("passcode")??""}function Ey(e,t,r,n){if(r===void 0||!n.includes(r))return!1;let o=new URL(e),s=t??o.host;return r===`${o.protocol}//${s}`&&n.includes(`${o.protocol}//${o.host}`)}function YC(e){return e!=="GET"&&e!=="HEAD"&&e!=="OPTIONS"}function Ty(e){let t=(e??"").split(";").map(r=>r.trim()).filter(r=>r.startsWith(`${la}=`)).map(r=>r.slice(la.length+1));return t.length===1&&/^[A-Za-z0-9_-]{43}$/.test(t[0])?t[0]:null}function QC(e,t,r){return`${la}=${e}; Path=${t}; HttpOnly; SameSite=Strict; Max-Age=${qC}${r?"; Secure":""}`}function XC(e,t){return`${la}=; Path=${e}; HttpOnly; SameSite=Strict; Max-Age=0${t?"; Secure":""}`}function by(e,t){let r=yy("sha256").update(e,"utf8").digest(),n=yy("sha256").update(t,"utf8").digest();return PC(r,n)}function ZC(e){try{return hy(e).remote.address??"unknown"}catch{return"unknown"}}function Sy(e,t,r){let n=e.get(t);return n!==void 0&&r<n.lockedUntilMs}function vy(e,t,r){let n=e.get(t);if(n===void 0||r-n.windowStartMs>HC){e.size>=WC&&e.delete(e.keys().next().value),e.set(t,{count:1,windowStartMs:r,lockedUntilMs:0});return}n.count+=1,n.count>=jC&&(n.lockedUntilMs=r+BC)}function Ay(e,t){e.delete(t)}import{createHash as eO}from"node:crypto";var Ny=64*1024,tO=new Set(["math"]);function rO(e,t){return eO("sha256").update(e,"utf8").update("\0","utf8").update(t,"utf8").digest("hex")}function ua(e,t,r){let n=r.to?.trim(),o=r.prompt??"",s=r.dedupeKey?.trim();if(!n)throw new L("INVALID_ARGUMENT","to is required",2);if(!s)throw new L("INVALID_ARGUMENT","dedupeKey is required",2);if(o.trim().length===0)throw new L("INVALID_ARGUMENT","prompt is required",2);if(Buffer.byteLength(o,"utf8")>Ny)throw new L("INVALID_ARGUMENT",`prompt exceeds the ${Ny}-byte comm-flow cap`,2);if(!tO.has(n))throw new L("INVALID_ARGUMENT",`"${n}" is not a comm-flow-enabled target`,2);let i=t.find(l=>l.name===n);if(i===void 0||!H(i))throw new L("INVALID_ARGUMENT",`"${n}" is not a registered local team`,2);let a=rO(n,o);return e.transaction(()=>{let l=e.prepare("SELECT id, admission_fingerprint FROM queue WHERE dedupe_key = ?").get(s);if(l){if(l.admission_fingerprint===a)return{queueId:l.id,replayed:!0};throw new L("CONFLICT",`dedupeKey "${s}" was already used for a different prompt`,4)}let u=_e(e,t,n,o,{from:"operator",dedupeKey:s});return e.prepare("UPDATE queue SET admission_fingerprint = ? WHERE id = ?").run(a,u),{queueId:u,replayed:!1}}).immediate()}import{existsSync as nO,readFileSync as oO}from"node:fs";import{dirname as Ly,join as Iu}from"node:path";import{fileURLToPath as Cy}from"node:url";var sO=Iu(Ly(Cy(import.meta.url)),"public"),iO={"/legacy":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/index.html":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/app.js":{file:"app.js",contentType:"text/javascript; charset=utf-8"},"/legacy/styles.css":{file:"styles.css",contentType:"text/css; charset=utf-8"}},aO=Iu(Ly(Cy(import.meta.url)),"vendor-webui"),cO={"/":{file:"index.html",contentType:"text/html; charset=utf-8"},"/index.html":{file:"index.html",contentType:"text/html; charset=utf-8"},"/local.js":{file:"local.js",contentType:"text/javascript; charset=utf-8"},"/styles.css":{file:"styles.css",contentType:"text/css; charset=utf-8"}};function lO(e){return e.endsWith("/")?e.slice(0,-1):e}function uO(e,t){let r=e.replace(/<head[^>]*>/i,n=>`${n}
543
- <base href="${t}" />`);if(r===e)throw new Error("injectBaseHref: no <head> tag found in index.html -- cannot inject <base href>");return r}function Iy(e,t,r,n){for(let o of Object.keys(r))e.get(o,s=>{let i=r[o];if(!i)return s.notFound();let a=Iu(t,i.file);if(!nO(a))return s.notFound();let c=oO(a);return n!==void 0&&i.contentType.startsWith("text/html")&&(c=uO(c.toString("utf8"),n)),s.body(c,200,{"content-type":i.contentType})})}function Oy(e,t={}){let r=lO(t.mountPath??""),n=t.webDistDir??aO;Iy(e,n,cO,r!==""?`${r}/`:void 0),Iy(e,sO,iO,`${r}/legacy/`)}import{createHash as Ou,createHmac as gO,randomBytes as Lu,timingSafeEqual as _O}from"node:crypto";import{basename as wO}from"node:path";import{existsSync as dO}from"node:fs";import{homedir as mO}from"node:os";import{join as fO}from"node:path";function pO(e){return e||(process.env.LMTEAM_DB_PATH?process.env.LMTEAM_DB_PATH:fO(mO(),".lmteam","lmteam.db"))}function da(e){let t=pO(e);if(!dO(t))throw new Error(`lmteam database not found at ${t} -- set LMTEAM_DB_PATH or check the path`);return new ht(t,{readonly:!0,fileMustExist:!0})}function Dy(e,t={}){let r=t.status??"stands",n=t.affects?e.prepare(`SELECT d.* FROM decisions d JOIN decision_affects a ON a.decision_id = d.id
544
- WHERE a.target = ? AND d.status = ? ORDER BY d.decided_at DESC`).all(t.affects,r):e.prepare("SELECT * FROM decisions WHERE status = ? ORDER BY decided_at DESC").all(r),o=e.prepare("SELECT target FROM decision_affects WHERE decision_id = ? ORDER BY target");return n.map(s=>({...s,affects:o.all(s.id).map(i=>i.target)}))}function My(e){return e.prepare("SELECT * FROM asks WHERE status = 'open' ORDER BY raised_at ASC").all()}function Py(e,t){return e.prepare("SELECT * FROM asks WHERE id = ?").get(t)??null}function Uy(e){return e.prepare("SELECT * FROM blocked WHERE status = 'open' ORDER BY raised_at ASC").all()}function hO(){let e=!1,t=0,r=new Set,n=A=>!e&&!document.hidden&&A===t,o=A=>document.getElementById(A),s=(A,q)=>{let M=o(A);M&&(M.textContent=q)},i=(A,q="")=>{let M=document.createElement(A);return M.textContent=q,M},a=A=>A!==null&&typeof A=="object"&&!Array.isArray(A),c=A=>Number.isSafeInteger(A)&&Number(A)>0,l=A=>typeof A=="string"&&Number.isFinite(Date.parse(A)),u=A=>A===null||l(A);async function d(A,q,M,Z){r.add(M);let W,ae,Ee=new Promise((j,Y)=>{W=()=>{ae?.cancel().catch(()=>{}),Y(new Error("Request cancelled or timed out"))},M.signal.addEventListener("abort",W,{once:!0})}),ne=setTimeout(()=>M.abort(),15e3),D=async()=>{M.signal.throwIfAborted();let j=await fetch(A,{method:Z===void 0?"GET":"POST",signal:M.signal,credentials:"same-origin",cache:"no-store",redirect:"error",headers:{Accept:q==="json"?"application/json":"text/html",...Z===void 0?{}:{"Content-Type":"application/x-www-form-urlencoded"}},...Z===void 0?{}:{body:Z}});if(M.signal.throwIfAborted(),j.status!==200||j.redirected||!j.headers.get("content-type")?.includes(q==="json"?"application/json":"text/html")){let ue;if(q==="html"&&!j.redirected&&j.headers.get("content-type")?.includes("text/html")){let be=await j.text().catch(()=>""),z=/<h1>[^<]*<\/h1>\s*<p>([^<]*)<\/p>/.exec(be);z&&z[1]&&(ue=z[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"))}else j.body?.cancel().catch(()=>{});let $e=new Error(ue??"Unexpected server response");throw $e.status=j.status,$e}let Y=j.body?.getReader();if(ae=Y,!Y)throw new Error("Missing response body");let K=new TextDecoder,re=0,te="";try{for(;;){let ue=await Y.read();if(M.signal.throwIfAborted(),ue.done)break;if(re+=ue.value.byteLength,re>(q==="json"?262144:2e6))throw new Error("Response exceeds safety limit");te+=K.decode(ue.value,{stream:!0})}return te+K.decode()}catch(ue){throw Y.cancel().catch(()=>{}),ue}};try{return await Promise.race([D(),Ee])}finally{clearTimeout(ne),M.signal.removeEventListener("abort",W),r.delete(M)}}function m(A,q){if(!a(A)||A.id!==q||!l(A.createdAt)||!u(A.pulledAt)||!u(A.answeredAt))throw new Error("Invalid queue state");let M=A.lifecycle,Z=A.lifecycleBasis,W=A.answer;if(!(M==="queued"?Z==="dispatched":M==="processing"?Z==="confirmed"||Z==="dispatched":M==="finished"&&["answer","merged","informational"].includes(String(Z))))throw new Error("Invalid lifecycle evidence");if(Z==="answer"){if(!a(W)||!c(W.id)||W.prompt_queue_id!==q||typeof W.answer_text!="string"||!l(W.answered_at)||W.answered_at!==A.answeredAt||!l(W.created_at)||typeof W.truncated!="boolean")throw new Error("Invalid correlated answer");let Ee=new TextEncoder().encode(W.answer_text).length;if(!Number.isSafeInteger(W.byteLength)||W.byteLength!==Ee||Ee>65536||!Number.isSafeInteger(W.totalBytes)||Number(W.totalBytes)<Ee||(W.truncated?Number(W.totalBytes)<=Ee:W.totalBytes!==Ee))throw new Error("Invalid response coverage")}else if(W!==null||A.answeredAt!==null)throw new Error("Unexpected answer");if(M==="queued"&&A.pulledAt!==null)throw new Error("Unexpected handling time");return A}let f=o("comm-state"),p=Number(f?.dataset.queueId),h=f?.dataset.mount??"",w,_=null,E=0,T=f?.dataset.lifecycle==="finished";function v(){if(clearTimeout(w),!(!f||!c(p)||e||document.hidden||T||_)){if(E>=60){s("comm-poll-notice","Automatic checks paused after 60 reads. Use Refresh state to check again.");return}w=setTimeout(()=>void S(),Math.min(1e3*1.5**E,1e4))}}async function S(){if(!f||_||e||document.hidden||T||E>=60)return;let A=new AbortController,q=t;_=A,E++;try{let M=await d(`${h}/api/queue/${p}/state`,"json",A);if(!n(q))return;let Z=m(JSON.parse(M),p),W=Z.lifecycleBasis,ae=Z.answer,Ee=Z.lifecycle==="queued"?"Queued":Z.lifecycle==="processing"?"Processing":W==="merged"?"Combined":W==="informational"?"Informational":"Replied",ne=Z.lifecycle==="queued"?"Queued \u2014 waiting for handling":Z.lifecycle==="processing"?W==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed":W==="merged"?"Finished \u2014 combined with another prompt":W==="informational"?"Finished \u2014 informational, no answer expected":"Finished \u2014 answer recorded",D=W==="merged"?"No separate answer: prompt combined into another prompt.":"No answer expected: this was an informational send.",j=f.dataset.sender??"sender not recorded",Y=f.dataset.recipient??"inbox not recorded",K=ae?`Answer recorded in the ${Y} inbox for prompt #${p} from ${j}.`:Z.lifecycle==="finished"?D:`No answer recorded for prompt #${p} from ${j} to ${Y}.`,re=i("span",Ee);re.className=`status-chip status-${Z.lifecycle==="finished"?ae?"replied":"muted":Z.lifecycle}`,re.title=ne,f.replaceChildren(re,i("span",` \xB7 ${ne}`)),f.dataset.lifecycle=Z.lifecycle,f.dataset.lifecycleBasis=W,s("comm-receipt-summary",ae?"An answer is recorded below.":Z.lifecycle==="finished"?D:"No answer recorded yet."),s("comm-response-status",K),s("comm-response-none",!ae&&Z.lifecycle!=="finished"?"No correlated answer recorded yet. Refresh to check again.":""),s("comm-response-meta",ae?`Recorded ${ae.answered_at} \xB7 answer #${ae.id} to prompt #${ae.prompt_queue_id}`:""),s("comm-response",ae?.answer_text??"");let te=o("comm-response");te&&(te.hidden=!ae),s("comm-response-truncation",ae?ae.truncated?`Truncated: ${ae.byteLength} of ${ae.totalBytes} bytes. No continuation endpoint is available.`:`${ae.byteLength} bytes returned.`:""),s("comm-reply-time",ae?.answered_at??"not recorded"),s("comm-handling-observation",`Latest handling evidence: ${Z.pulledAt??"not recorded"}${Z.pulledAt?W==="confirmed"?" (picked up)":W==="dispatched"?" (delivery attempted)":" (transport or pickup time)":""}`),s("comm-poll-notice",`State checked ${new Date().toISOString()}.`),T=Z.lifecycle==="finished"}catch(M){n(q)&&s("comm-poll-notice",`State unavailable; displayed records may be stale. ${M instanceof Error?M.message:String(M)}. Use Refresh state.`)}finally{_===A&&(_=null),v()}}let N=o("comm-composer-container"),x=o("comm-draft-form"),I=null,k=!1,B=!1,C=!1,g=null,y=null,R=A=>Array.from(A.querySelectorAll("input, textarea")),P=(A,q)=>{let M=R(A).filter(Z=>Z.name===q);if(M.length!==1)throw new Error("Invalid review fields");return M[0]};function J(A,q){let M=R(A).map(Z=>({input:Z,value:Z.value}));g=A,y=A.querySelector('button[type="submit"]'),A.addEventListener("submit",Z=>{if(B||e||document.hidden){Z.preventDefault();return}for(let W of M)W.input.value=W.value;B=!0,C=!0,q&&(q.disabled=!0),y&&(y.disabled=!0),s("comm-send-status","Submitting through the browser. If the outcome is uncertain, return here and retry this same confirmation.")})}let ee=o("comm-confirm-form");if(ee&&J(ee,o("comm-edit-button")),x?.addEventListener("submit",A=>{C&&A.preventDefault()}),N&&x&&o("compose")){let A=Array.from(N.childNodes),q=x.querySelector('textarea[name="prompt"]'),M=x.querySelector('button[type="submit"]');x.addEventListener("submit",async Z=>{if(!q||(Z.preventDefault(),I||C||e||document.hidden))return;let W=q.value.replace(/\r\n?/g,`
542
+ <style>${by}</style></head><body><a href="#main">Skip to content</a><header><p>Local operations / lmauto</p><nav aria-label="Main">${u.map(([d,m])=>Re(d,m)).join(" | ")}</nav></header><main${l} id="main"><h1>${b(e)}</h1>${t}</main><footer><p>Times are relative to this page load. Refresh for current data.</p></footer></body></html>`}function Mr(e){let t=new Map;for(let r of e)if(B(r))try{t.set(Q(r),r.name)}catch{}return t}function Sy(e,t,r){function n(s,i=!0){if(s===null)return"\u2014";let a=gn(s);if(!a)return b(s);let{teamfilePath:c,alias:l}=a,u=`${jC(c)}:${l}`,d=t.get(c);if(i&&d)return`<a href="${b(`${r}/sessions/${encodeURIComponent(d)}/${encodeURIComponent(l)}`)}" title="${b(s)}">${b(u)}</a>`;let m=i?`${s} \u2014 Not in the current local team registry -- no session page available`:s;return`<span title="${b(m)}">${b(u)}</span>`}function o(s,i,a){return`<section><h2>${s}</h2><table><thead><tr>${i.map(c=>`<th scope="col">${c}</th>`).join("")}</tr></thead><tbody>${a.length?a.map(c=>`<tr>${c.map(l=>`<td>${l}</td>`).join("")}</tr>`).join(""):`<tr><td colspan="${i.length}">No ${s.toLowerCase()} invocations.</td></tr>`}</tbody></table></section>`}return"<p>Running shows work still in progress. Dead means its process stopped abnormally while work was still in progress; session data remains intact and may be resumed. Idle means the invocation finished, successfully or with a recorded error; an Idle error status describes that finished result, not an ongoing crash. A target is &lt;teamfile&gt;.lmctl:&lt;role&gt;: the team\u2019s configuration file and the member role executing, such as Lead or Coder. From names what started the invocation: another member\u2019s identity, or operator for a person acting directly, not through an agent. Only targets whose team can be resolved in the current local registry link to a session page; other targets remain unlinked. Full identities are available in the labels\u2019 tooltips.</p>"+o("Running",["Target","From","Started","Running for"],e.running.map(s=>[n(s.target),n(s.from_identity,!1),b(s.started_human),b(s.running_for_human)]))+o("Dead",["Target","From","Started","Stale for"],e.dead.map(s=>[n(s.target),n(s.from_identity,!1),b(s.started_human),b(s.stale_for_human)]))+o("Idle",["Target","From","Status","Ended","Idle for","Ran for"],e.idle.map(s=>[n(s.target),n(s.from_identity,!1),b(s.status),b(he(s.ended_at)),b(me(s.idle_ms)),b(s.ran_human)]))}var ma="localweb_session",GC=8*1024,VC=1024,JC=30*24*60*60,KC=10,zC=6e4,YC=6e4,QC=1024;function Ly(e,t){let r=XC(t.mountPath),n=`${r}/login`||"/login",o=`${r}/`||"/",s=r||"/",i=t.allowedOrigins,a=new Map,c=new Map,l=t.remoteKey??iO,u,d=()=>{let m;try{m=t.readAuthority()}catch{m=null}return!m||!m.passcode||!m.generation?(a.clear(),u=void 0,null):(u!==void 0&&m.generation!==u&&a.clear(),u=m.generation,m)};e.use("*",async(m,f)=>{m.header("Cache-Control","no-store");let p=ZC(m.req.path,r);if(m.req.method==="GET"&&(p==="/healthz"||p==="/login")||m.req.method==="POST"&&p==="/login"){await f();return}let h=m.req.header("origin");if(h!==void 0&&!i.includes(h))return m.json({error:"origin not allowed"},403);let w=d();if(w===null)return is(m,p,n,r,"unavailable");let _=m.req.header("authorization");if(_!==void 0){let E=l(m),v=Date.now();if(xy(c,E,v))return is(m,p,n,r,"locked_out");let S=_.startsWith("Bearer ")?_.slice(7):"";if(!$y(S,w.passcode))return Ry(c,E,v),is(m,p,n,r);Ny(c,E),await f();return}let T=ky(m.req.header("cookie"));if(T===null||a.get(T)!==w.generation)return is(m,p,n,r,T===null?"missing":"expired");if(nO(m.req.method)&&!Ay(m.req.url,m.req.header("host"),h,i))return is(m,p,n,r);await f()}),e.get("/healthz",m=>m.json({ok:!0})),e.get("/login",m=>m.html(eO(Oy(m,n,r),r))),e.post("/login",async m=>{if(!Ay(m.req.url,m.req.header("host"),m.req.header("origin"),i))return Cu(m,n,r);let f=l(m),p=Date.now();if(xy(c,f,p))return tO(m,r);let h=d();if(h===null)return Cu(m,n,r);let w=await rO(m.req.raw).catch(()=>null);if(w===null||!$y(w,h.passcode))return Ry(c,f,p),Cu(m,n,r);Ny(c,f),a.size>=VC&&a.delete(a.keys().next().value);let _=BC(32).toString("base64url");return a.set(_,h.generation),m.header("Set-Cookie",oO(_,s,new URL(m.req.url).protocol==="https:")),m.redirect(Cy(m,r)??o,303)}),e.post("/logout",m=>{let f=ky(m.req.header("cookie"));return f!==null&&a.delete(f),m.header("Set-Cookie",sO(s,new URL(m.req.url).protocol==="https:")),m.redirect(n,303)})}function XC(e=""){if(e===""||e==="/")return"";let t=e.endsWith("/")?e.slice(0,-1):e;if(!/^\/[A-Za-z0-9_./~-]+$/.test(t)||t.startsWith("//"))throw new Error("Invalid mount path");return t}function ZC(e,t){return t&&(e===t||e.startsWith(`${t}/`))?e.slice(t.length)||"/":e}function is(e,t,r,n,o="required"){let s=o==="locked_out"?429:401;if(t==="/api"||t.startsWith("/api/"))return e.json({error:o==="locked_out"?"too many failed attempts":"unauthorized"},s);let i={unavailable:"Authentication is not currently available.",missing:"You are not logged in yet.",expired:"Your session expired. Log in again to continue.",required:"Authentication required.",locked_out:"Too many failed attempts from this source. Try again shortly."}[o],a=e.req.method==="GET"?Iy(`${n}${t}${new URL(e.req.url).search}`,n):null,c=a===null?r:`${r}?next=${encodeURIComponent(a)}`,l=o==="locked_out"?`<p>${i}</p>`:`<p>${i}</p><p><a href="${b(c)}">Log in</a></p>`;return e.html(ve("Authentication required",l,n),s)}function eO(e,t){return ve("LocalWeb login",`<form method="post" action="${b(e)}"><label>Passcode<input type="password" name="passcode" autocomplete="current-password" required></label><button type="submit">Log in</button></form>`,t)}function Cu(e,t,r){return e.html(ve("Login failed",`<p>Invalid credentials.</p><a href="${b(Oy(e,t,r))}">Try again</a>`,r),401)}function tO(e,t){return e.html(ve("Login failed","<p>Too many failed attempts from this source. Try again shortly.</p>",t),429)}function Iy(e,t){if(!e||e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f]/.test(e))return null;let r="http://localweb.invalid";try{let n=new URL(e,r),o=decodeURIComponent(n.pathname);if(n.origin!==r||o.includes("//")||/[\\\x00-\x1f\x7f]/.test(o))return null;let s=new URL(o,r),i=a=>!t||a===t||a.startsWith(`${t}/`);return s.origin!==r||s.pathname.includes("//")||!i(n.pathname)||!i(s.pathname)?null:`${n.pathname}${n.search}${n.hash}`}catch{return null}}function Cy(e,t){let r=new URL(e.req.url).searchParams.getAll("next");return r.length===1?Iy(r[0],t):null}function Oy(e,t,r){let n=Cy(e,r);return n===null?t:`${t}?next=${encodeURIComponent(n)}`}async function rO(e){if(!e.headers.get("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new Error("invalid form");let t=e.body?.getReader();if(!t)throw new Error("missing form");let r=[],n=0;for(;;){let{done:s,value:i}=await t.read();if(s)break;if(n+=i.byteLength,n>GC)throw await t.cancel(),new Error("form too large");r.push(i)}let o=new URLSearchParams(Buffer.concat(r).toString("utf8"));if(o.getAll("passcode").length!==1||[...o.keys()].some(s=>s!=="passcode"))throw new Error("invalid form");return o.get("passcode")??""}function Ay(e,t,r,n){if(r===void 0||!n.includes(r))return!1;let o=new URL(e),s=t??o.host;return r===`${o.protocol}//${s}`&&n.includes(`${o.protocol}//${o.host}`)}function nO(e){return e!=="GET"&&e!=="HEAD"&&e!=="OPTIONS"}function ky(e){let t=(e??"").split(";").map(r=>r.trim()).filter(r=>r.startsWith(`${ma}=`)).map(r=>r.slice(ma.length+1));return t.length===1&&/^[A-Za-z0-9_-]{43}$/.test(t[0])?t[0]:null}function oO(e,t,r){return`${ma}=${e}; Path=${t}; HttpOnly; SameSite=Strict; Max-Age=${JC}${r?"; Secure":""}`}function sO(e,t){return`${ma}=; Path=${e}; HttpOnly; SameSite=Strict; Max-Age=0${t?"; Secure":""}`}function $y(e,t){let r=vy("sha256").update(e,"utf8").digest(),n=vy("sha256").update(t,"utf8").digest();return WC(r,n)}function iO(e){try{return Ey(e).remote.address??"unknown"}catch{return"unknown"}}function xy(e,t,r){let n=e.get(t);return n!==void 0&&r<n.lockedUntilMs}function Ry(e,t,r){let n=e.get(t);if(n===void 0||r-n.windowStartMs>zC){e.size>=QC&&e.delete(e.keys().next().value),e.set(t,{count:1,windowStartMs:r,lockedUntilMs:0});return}n.count+=1,n.count>=KC&&(n.lockedUntilMs=r+YC)}function Ny(e,t){e.delete(t)}import{createHash as aO}from"node:crypto";var Dy=64*1024,cO=new Set(["math"]);function lO(e,t){return aO("sha256").update(e,"utf8").update("\0","utf8").update(t,"utf8").digest("hex")}function fa(e,t,r){let n=r.to?.trim(),o=r.prompt??"",s=r.dedupeKey?.trim();if(!n)throw new I("INVALID_ARGUMENT","to is required",2);if(!s)throw new I("INVALID_ARGUMENT","dedupeKey is required",2);if(o.trim().length===0)throw new I("INVALID_ARGUMENT","prompt is required",2);if(Buffer.byteLength(o,"utf8")>Dy)throw new I("INVALID_ARGUMENT",`prompt exceeds the ${Dy}-byte comm-flow cap`,2);if(!cO.has(n))throw new I("INVALID_ARGUMENT",`"${n}" is not a comm-flow-enabled target`,2);let i=t.find(l=>l.name===n);if(i===void 0||!B(i))throw new I("INVALID_ARGUMENT",`"${n}" is not a registered local team`,2);let a=lO(n,o);return e.transaction(()=>{let l=e.prepare("SELECT id, admission_fingerprint FROM queue WHERE dedupe_key = ?").get(s);if(l){if(l.admission_fingerprint===a)return{queueId:l.id,replayed:!0};throw new I("CONFLICT",`dedupeKey "${s}" was already used for a different prompt`,4)}let u=_e(e,t,n,o,{from:"operator",dedupeKey:s});return e.prepare("UPDATE queue SET admission_fingerprint = ? WHERE id = ?").run(a,u),{queueId:u,replayed:!1}}).immediate()}import{existsSync as uO,readFileSync as dO}from"node:fs";import{dirname as Py,join as Ou}from"node:path";import{fileURLToPath as Uy}from"node:url";var mO=Ou(Py(Uy(import.meta.url)),"public"),fO={"/legacy":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/index.html":{file:"index.html",contentType:"text/html; charset=utf-8"},"/legacy/app.js":{file:"app.js",contentType:"text/javascript; charset=utf-8"},"/legacy/styles.css":{file:"styles.css",contentType:"text/css; charset=utf-8"}},pO=Ou(Py(Uy(import.meta.url)),"vendor-webui"),hO={"/":{file:"index.html",contentType:"text/html; charset=utf-8"},"/index.html":{file:"index.html",contentType:"text/html; charset=utf-8"},"/local.js":{file:"local.js",contentType:"text/javascript; charset=utf-8"},"/styles.css":{file:"styles.css",contentType:"text/css; charset=utf-8"}};function gO(e){return e.endsWith("/")?e.slice(0,-1):e}function _O(e,t){let r=e.replace(/<head[^>]*>/i,n=>`${n}
543
+ <base href="${t}" />`);if(r===e)throw new Error("injectBaseHref: no <head> tag found in index.html -- cannot inject <base href>");return r}function My(e,t,r,n){for(let o of Object.keys(r))e.get(o,s=>{let i=r[o];if(!i)return s.notFound();let a=Ou(t,i.file);if(!uO(a))return s.notFound();let c=dO(a);return n!==void 0&&i.contentType.startsWith("text/html")&&(c=_O(c.toString("utf8"),n)),s.body(c,200,{"content-type":i.contentType})})}function Fy(e,t={}){let r=gO(t.mountPath??""),n=t.webDistDir??pO;My(e,n,hO,r!==""?`${r}/`:void 0),My(e,mO,fO,`${r}/legacy/`)}import{createHash as Pu,createHmac as SO,randomBytes as Du,timingSafeEqual as vO}from"node:crypto";import{basename as AO}from"node:path";import{existsSync as wO}from"node:fs";import{homedir as yO}from"node:os";import{join as EO}from"node:path";function TO(e){return e||(process.env.LMTEAM_DB_PATH?process.env.LMTEAM_DB_PATH:EO(yO(),".lmteam","lmteam.db"))}function pa(e){let t=TO(e);if(!wO(t))throw new Error(`lmteam database not found at ${t} -- set LMTEAM_DB_PATH or check the path`);return new ht(t,{readonly:!0,fileMustExist:!0})}function qy(e,t={}){let r=t.status??"stands",n=t.affects?e.prepare(`SELECT d.* FROM decisions d JOIN decision_affects a ON a.decision_id = d.id
544
+ WHERE a.target = ? AND d.status = ? ORDER BY d.decided_at DESC`).all(t.affects,r):e.prepare("SELECT * FROM decisions WHERE status = ? ORDER BY decided_at DESC").all(r),o=e.prepare("SELECT target FROM decision_affects WHERE decision_id = ? ORDER BY target");return n.map(s=>({...s,affects:o.all(s.id).map(i=>i.target)}))}function jy(e){return e.prepare("SELECT * FROM asks WHERE status = 'open' ORDER BY raised_at ASC").all()}function Hy(e,t){return e.prepare("SELECT * FROM asks WHERE id = ?").get(t)??null}function By(e){return e.prepare("SELECT * FROM blocked WHERE status = 'open' ORDER BY raised_at ASC").all()}function bO(){let e=!1,t=0,r=new Set,n=A=>!e&&!document.hidden&&A===t,o=A=>document.getElementById(A),s=(A,q)=>{let M=o(A);M&&(M.textContent=q)},i=(A,q="")=>{let M=document.createElement(A);return M.textContent=q,M},a=A=>A!==null&&typeof A=="object"&&!Array.isArray(A),c=A=>Number.isSafeInteger(A)&&Number(A)>0,l=A=>typeof A=="string"&&Number.isFinite(Date.parse(A)),u=A=>A===null||l(A);async function d(A,q,M,Z){r.add(M);let W,ae,Ee=new Promise((j,Y)=>{W=()=>{ae?.cancel().catch(()=>{}),Y(new Error("Request cancelled or timed out"))},M.signal.addEventListener("abort",W,{once:!0})}),ne=setTimeout(()=>M.abort(),15e3),D=async()=>{M.signal.throwIfAborted();let j=await fetch(A,{method:Z===void 0?"GET":"POST",signal:M.signal,credentials:"same-origin",cache:"no-store",redirect:"error",headers:{Accept:q==="json"?"application/json":"text/html",...Z===void 0?{}:{"Content-Type":"application/x-www-form-urlencoded"}},...Z===void 0?{}:{body:Z}});if(M.signal.throwIfAborted(),j.status!==200||j.redirected||!j.headers.get("content-type")?.includes(q==="json"?"application/json":"text/html")){let ue;if(q==="html"&&!j.redirected&&j.headers.get("content-type")?.includes("text/html")){let be=await j.text().catch(()=>""),z=/<h1>[^<]*<\/h1>\s*<p>([^<]*)<\/p>/.exec(be);z&&z[1]&&(ue=z[1].replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'"))}else j.body?.cancel().catch(()=>{});let ke=new Error(ue??"Unexpected server response");throw ke.status=j.status,ke}let Y=j.body?.getReader();if(ae=Y,!Y)throw new Error("Missing response body");let K=new TextDecoder,re=0,te="";try{for(;;){let ue=await Y.read();if(M.signal.throwIfAborted(),ue.done)break;if(re+=ue.value.byteLength,re>(q==="json"?262144:2e6))throw new Error("Response exceeds safety limit");te+=K.decode(ue.value,{stream:!0})}return te+K.decode()}catch(ue){throw Y.cancel().catch(()=>{}),ue}};try{return await Promise.race([D(),Ee])}finally{clearTimeout(ne),M.signal.removeEventListener("abort",W),r.delete(M)}}function m(A,q){if(!a(A)||A.id!==q||!l(A.createdAt)||!u(A.pulledAt)||!u(A.answeredAt))throw new Error("Invalid queue state");let M=A.lifecycle,Z=A.lifecycleBasis,W=A.answer;if(!(M==="queued"?Z==="dispatched":M==="processing"?Z==="confirmed"||Z==="dispatched":M==="finished"&&["answer","merged","informational"].includes(String(Z))))throw new Error("Invalid lifecycle evidence");if(Z==="answer"){if(!a(W)||!c(W.id)||W.prompt_queue_id!==q||typeof W.answer_text!="string"||!l(W.answered_at)||W.answered_at!==A.answeredAt||!l(W.created_at)||typeof W.truncated!="boolean")throw new Error("Invalid correlated answer");let Ee=new TextEncoder().encode(W.answer_text).length;if(!Number.isSafeInteger(W.byteLength)||W.byteLength!==Ee||Ee>65536||!Number.isSafeInteger(W.totalBytes)||Number(W.totalBytes)<Ee||(W.truncated?Number(W.totalBytes)<=Ee:W.totalBytes!==Ee))throw new Error("Invalid response coverage")}else if(W!==null||A.answeredAt!==null)throw new Error("Unexpected answer");if(M==="queued"&&A.pulledAt!==null)throw new Error("Unexpected handling time");return A}let f=o("comm-state"),p=Number(f?.dataset.queueId),h=f?.dataset.mount??"",w,_=null,T=0,E=f?.dataset.lifecycle==="finished";function v(){if(clearTimeout(w),!(!f||!c(p)||e||document.hidden||E||_)){if(T>=60){s("comm-poll-notice","Automatic checks paused after 60 reads. Use Refresh state to check again.");return}w=setTimeout(()=>void S(),Math.min(1e3*1.5**T,1e4))}}async function S(){if(!f||_||e||document.hidden||E||T>=60)return;let A=new AbortController,q=t;_=A,T++;try{let M=await d(`${h}/api/queue/${p}/state`,"json",A);if(!n(q))return;let Z=m(JSON.parse(M),p),W=Z.lifecycleBasis,ae=Z.answer,Ee=Z.lifecycle==="queued"?"Queued":Z.lifecycle==="processing"?"Processing":W==="merged"?"Combined":W==="informational"?"Informational":"Replied",ne=Z.lifecycle==="queued"?"Queued \u2014 waiting for handling":Z.lifecycle==="processing"?W==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed":W==="merged"?"Finished \u2014 combined with another prompt":W==="informational"?"Finished \u2014 informational, no answer expected":"Finished \u2014 answer recorded",D=W==="merged"?"No separate answer: prompt combined into another prompt.":"No answer expected: this was an informational send.",j=f.dataset.sender??"sender not recorded",Y=f.dataset.recipient??"inbox not recorded",K=ae?`Answer recorded in the ${Y} inbox for prompt #${p} from ${j}.`:Z.lifecycle==="finished"?D:`No answer recorded for prompt #${p} from ${j} to ${Y}.`,re=i("span",Ee);re.className=`status-chip status-${Z.lifecycle==="finished"?ae?"replied":"muted":Z.lifecycle}`,re.title=ne,f.replaceChildren(re,i("span",` \xB7 ${ne}`)),f.dataset.lifecycle=Z.lifecycle,f.dataset.lifecycleBasis=W,s("comm-receipt-summary",ae?"An answer is recorded below.":Z.lifecycle==="finished"?D:"No answer recorded yet."),s("comm-response-status",K),s("comm-response-none",!ae&&Z.lifecycle!=="finished"?"No correlated answer recorded yet. Refresh to check again.":""),s("comm-response-meta",ae?`Recorded ${ae.answered_at} \xB7 answer #${ae.id} to prompt #${ae.prompt_queue_id}`:""),s("comm-response",ae?.answer_text??"");let te=o("comm-response");te&&(te.hidden=!ae),s("comm-response-truncation",ae?ae.truncated?`Truncated: ${ae.byteLength} of ${ae.totalBytes} bytes. No continuation endpoint is available.`:`${ae.byteLength} bytes returned.`:""),s("comm-reply-time",ae?.answered_at??"not recorded"),s("comm-handling-observation",`Latest handling evidence: ${Z.pulledAt??"not recorded"}${Z.pulledAt?W==="confirmed"?" (picked up)":W==="dispatched"?" (delivery attempted)":" (transport or pickup time)":""}`),s("comm-poll-notice",`State checked ${new Date().toISOString()}.`),E=Z.lifecycle==="finished"}catch(M){n(q)&&s("comm-poll-notice",`State unavailable; displayed records may be stale. ${M instanceof Error?M.message:String(M)}. Use Refresh state.`)}finally{_===A&&(_=null),v()}}let N=o("comm-composer-container"),$=o("comm-draft-form"),L=null,R=!1,H=!1,C=!1,g=null,y=null,x=A=>Array.from(A.querySelectorAll("input, textarea")),P=(A,q)=>{let M=x(A).filter(Z=>Z.name===q);if(M.length!==1)throw new Error("Invalid review fields");return M[0]};function J(A,q){let M=x(A).map(Z=>({input:Z,value:Z.value}));g=A,y=A.querySelector('button[type="submit"]'),A.addEventListener("submit",Z=>{if(H||e||document.hidden){Z.preventDefault();return}for(let W of M)W.input.value=W.value;H=!0,C=!0,q&&(q.disabled=!0),y&&(y.disabled=!0),s("comm-send-status","Submitting through the browser. If the outcome is uncertain, return here and retry this same confirmation.")})}let ee=o("comm-confirm-form");if(ee&&J(ee,o("comm-edit-button")),$?.addEventListener("submit",A=>{C&&A.preventDefault()}),N&&$&&o("compose")){let A=Array.from(N.childNodes),q=$.querySelector('textarea[name="prompt"]'),M=$.querySelector('button[type="submit"]');$.addEventListener("submit",async Z=>{if(!q||(Z.preventDefault(),L||C||e||document.hidden))return;let W=q.value.replace(/\r\n?/g,`
545
545
  `);if(!W.trim()||new TextEncoder().encode(W.replace(/\n/g,`\r
546
- `)).length>65536){s("comm-composer-notice","Enter a nonblank prompt of at most 64 KiB UTF-8.");return}let ae=t,Ee=new AbortController;I=Ee,k=!1,M&&(M.disabled=!0),s("comm-composer-notice","Reviewing prompt\u2026");try{let ne=new URL(x.action,window.location.href),D=o("compose")?.dataset.base;if(!D||ne.origin!==new URL(window.location.href).origin||ne.pathname!==`${D}/review`||ne.search||ne.hash)throw new Error("Unexpected review destination");let j=()=>{let G=new URLSearchParams;for(let we of R(x))we.name&&!we.disabled&&G.append(we.name,we.value.replace(/\r\n|\r|\n/g,`\r
547
- `));return G.toString()},Y;try{Y=await d(ne.href,"html",Ee,j())}catch(G){if((G instanceof Error?G.status:void 0)!==409||!n(ae))throw G;s("comm-composer-notice","Session renewing\u2026");let st=await d(window.location.href,"html",Ee);if(!n(ae))return;let Ze=new DOMParser().parseFromString(st,"text/html").getElementById("comm-draft-form"),ft="";try{Ze&&(ft=P(Ze,"csrf").value)}catch{}if(!ft)throw G;P(x,"csrf").value=ft,Y=await d(ne.href,"html",Ee,j())}if(!n(ae))return;let re=new DOMParser().parseFromString(Y,"text/html").getElementById("comm-confirm-form");if(!re)throw new Error("Review unavailable; use the native review form after reloading");let te=new URL(re.getAttribute("action")??"",ne.href),ue=P(re,"confirmation").value;if(re.method.toLowerCase()!=="post"||te.origin!==ne.origin||te.pathname!==`${D}/prompts`||te.search||te.hash||!ue||ue.length>4096||P(re,"prompt").value!==W)throw new Error("Review did not match the exact prompt");let $e=i("div");$e.id="comm-review-panel",$e.append(i("p","Review prompt to math:Lead"),i("pre",W));let be=document.createElement("form");be.id="comm-confirm-form",be.method="post",be.action=te.href;let z=document.createElement("input");z.type="hidden",z.name="confirmation",z.value=ue;let Te=document.createElement("textarea");Te.name="prompt",Te.hidden=!0,Te.value=W;let Ge=document.createElement("button");Ge.type="submit",Ge.id="comm-confirm-submit",Ge.textContent="Confirm and queue";let je=document.createElement("button");je.type="button",je.id="comm-edit-button",je.textContent="Edit prompt";let Ct=i("p");Ct.id="comm-send-status",Ct.setAttribute("role","status"),be.append(z,Te,Ge),$e.append(be,je,Ct),je.addEventListener("click",()=>{C||je.disabled||(q.value=W,N.replaceChildren(...A),g=null)}),J(be,je),N.replaceChildren($e)}catch(ne){n(ae)&&s("comm-composer-notice",`Review unavailable: ${ne instanceof Error?ne.message:String(ne)}. Draft retained; retry review or reload to renew the form. The native flow also works without JavaScript.`)}finally{I===Ee&&(I=null,M&&!e&&!document.hidden&&(M.disabled=!1),!e&&!document.hidden&&k&&s("comm-composer-notice","Review interrupted; draft retained. Review again when ready."))}})}function oe(){I&&(k=!0),t++,clearTimeout(w);for(let A of r)A.abort()}let V=()=>{if(!I&&!C){let A=x?.querySelector('button[type="submit"]');A&&(A.disabled=!1),k&&s("comm-composer-notice","Review interrupted; draft retained. Review again when ready.")}v()},se=()=>{document.hidden?oe():V()},$=()=>{e=!0,oe()},O=A=>{A.persisted&&(e=!1,g&&B&&(B=!1,y&&(y.disabled=!1,y.textContent="Retry this same confirmation"),s("comm-send-status","Outcome may be uncertain. Retry only this same confirmation, or check the inbox.")),V())};return document.addEventListener("visibilitychange",se),window.addEventListener("pagehide",$),window.addEventListener("pageshow",O),v(),()=>{$(),document.removeEventListener("visibilitychange",se),window.removeEventListener("pagehide",$),window.removeEventListener("pageshow",O)}}var ma=`(function () {
546
+ `)).length>65536){s("comm-composer-notice","Enter a nonblank prompt of at most 64 KiB UTF-8.");return}let ae=t,Ee=new AbortController;L=Ee,R=!1,M&&(M.disabled=!0),s("comm-composer-notice","Reviewing prompt\u2026");try{let ne=new URL($.action,window.location.href),D=o("compose")?.dataset.base;if(!D||ne.origin!==new URL(window.location.href).origin||ne.pathname!==`${D}/review`||ne.search||ne.hash)throw new Error("Unexpected review destination");let j=()=>{let G=new URLSearchParams;for(let we of x($))we.name&&!we.disabled&&G.append(we.name,we.value.replace(/\r\n|\r|\n/g,`\r
547
+ `));return G.toString()},Y;try{Y=await d(ne.href,"html",Ee,j())}catch(G){if((G instanceof Error?G.status:void 0)!==409||!n(ae))throw G;s("comm-composer-notice","Session renewing\u2026");let st=await d(window.location.href,"html",Ee);if(!n(ae))return;let Ze=new DOMParser().parseFromString(st,"text/html").getElementById("comm-draft-form"),ft="";try{Ze&&(ft=P(Ze,"csrf").value)}catch{}if(!ft)throw G;P($,"csrf").value=ft,Y=await d(ne.href,"html",Ee,j())}if(!n(ae))return;let re=new DOMParser().parseFromString(Y,"text/html").getElementById("comm-confirm-form");if(!re)throw new Error("Review unavailable; use the native review form after reloading");let te=new URL(re.getAttribute("action")??"",ne.href),ue=P(re,"confirmation").value;if(re.method.toLowerCase()!=="post"||te.origin!==ne.origin||te.pathname!==`${D}/prompts`||te.search||te.hash||!ue||ue.length>4096||P(re,"prompt").value!==W)throw new Error("Review did not match the exact prompt");let ke=i("div");ke.id="comm-review-panel",ke.append(i("p","Review prompt to math:Lead"),i("pre",W));let be=document.createElement("form");be.id="comm-confirm-form",be.method="post",be.action=te.href;let z=document.createElement("input");z.type="hidden",z.name="confirmation",z.value=ue;let Te=document.createElement("textarea");Te.name="prompt",Te.hidden=!0,Te.value=W;let Ge=document.createElement("button");Ge.type="submit",Ge.id="comm-confirm-submit",Ge.textContent="Confirm and queue";let je=document.createElement("button");je.type="button",je.id="comm-edit-button",je.textContent="Edit prompt";let Ct=i("p");Ct.id="comm-send-status",Ct.setAttribute("role","status"),be.append(z,Te,Ge),ke.append(be,je,Ct),je.addEventListener("click",()=>{C||je.disabled||(q.value=W,N.replaceChildren(...A),g=null)}),J(be,je),N.replaceChildren(ke)}catch(ne){n(ae)&&s("comm-composer-notice",`Review unavailable: ${ne instanceof Error?ne.message:String(ne)}. Draft retained; retry review or reload to renew the form. The native flow also works without JavaScript.`)}finally{L===Ee&&(L=null,M&&!e&&!document.hidden&&(M.disabled=!1),!e&&!document.hidden&&R&&s("comm-composer-notice","Review interrupted; draft retained. Review again when ready."))}})}function oe(){L&&(R=!0),t++,clearTimeout(w);for(let A of r)A.abort()}let V=()=>{if(!L&&!C){let A=$?.querySelector('button[type="submit"]');A&&(A.disabled=!1),R&&s("comm-composer-notice","Review interrupted; draft retained. Review again when ready.")}v()},se=()=>{document.hidden?oe():V()},k=()=>{e=!0,oe()},O=A=>{A.persisted&&(e=!1,g&&H&&(H=!1,y&&(y.disabled=!1,y.textContent="Retry this same confirmation"),s("comm-send-status","Outcome may be uncertain. Retry only this same confirmation, or check the inbox.")),V())};return document.addEventListener("visibilitychange",se),window.addEventListener("pagehide",k),window.addEventListener("pageshow",O),v(),()=>{k(),document.removeEventListener("visibilitychange",se),window.removeEventListener("pagehide",k),window.removeEventListener("pageshow",O)}}var ha=`(function () {
548
548
  function __name(value) { return value; }
549
- return (${hO.toString()})();
550
- })();`;var Fy=ve("","","").match(/<style>([\s\S]*?)<\/style>/),yO=Ou("sha256").update(Fy?Fy[1]:"").digest("base64"),EO=Ou("sha256").update(ma).digest("base64"),TO=`default-src 'none'; style-src 'sha256-${yO}'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; script-src 'sha256-${EO}'; connect-src 'self'`,Cu="lmbee_comm_browser",bO=64*1024,SO=256*1024,Qn=class extends Error{};function qy(e){let t=new tn,{context:r}=e,n=(e.mountPath??"").replace(/\/$/,"");if(n&&(!/^\/[A-Za-z0-9_./~-]+$/.test(n)||n.startsWith("//")))throw new Error("Invalid mount path");let o=`${n}/comm/math`,s=e.now??Date.now,i=Lu(32),a=new Map,c=$=>Ou("sha256").update($).digest("hex"),l=$=>gO("sha256",i).update($).digest("base64url"),u=$=>{let O=Buffer.from(JSON.stringify($)).toString("base64url");return`${O}.${l(O)}`};function d($){let O=$.split(".");if(O.length!==2||$.length>4096)throw new Error("Invalid confirmation. Review the prompt again.");let A=Buffer.from(l(O[0])),q=Buffer.from(O[1]);if(A.length!==q.length||!_O(A,q))throw new Error("Invalid confirmation. Review the prompt again.");return JSON.parse(Buffer.from(O[0],"base64url").toString("utf8"))}function m($,O=!1){let A=($.req.header("cookie")??"").split(";").map(M=>M.trim()).filter(M=>M.startsWith(`${Cu}=`));if(A.length===1)try{let M=d(A[0].slice(Cu.length+1));if(typeof M.browser=="string"&&/^[a-f0-9]{48}$/.test(M.browser))return M.browser}catch{}if(!O)throw new Error("Browser confirmation expired. Open the Math inbox and review again.");let q=Lu(24).toString("hex");return $.header("Set-Cookie",`${Cu}=${u({browser:q})}; Path=${o}; HttpOnly; SameSite=Strict${new URL($.req.url).protocol==="https:"?"; Secure":""}`),q}function f(){let $=r.teams.find(O=>O.name==="math");if(!$||!H($)||$.leadAlias!=="Lead")throw new Error("The local math Lead inbox is unavailable.");return`${Q($)}:Lead`}function p($){return $==="merged"||$==="informational"||$==="retracted"}function h($){return $.answeredAt?`<a href="${o}/prompts/${$.id}#comm-response">Answer to #${$.id}</a> \xB7 ${fe($.answeredAt)}`:$.lifecycleBasis==="merged"?"No separate answer (merged)":$.lifecycleBasis==="informational"?"No answer expected (informational)":$.lifecycleBasis==="retracted"?`No answer expected (retracted): ${b($.retracted_reason??"no reason recorded")}`:"No answer recorded"}function w($){for(let O of $.split(`
551
- `)){let A=O.trim();if(A)return A}return""}let _=80,E=2e3;function T($,O){return $.length>O?`${$.slice(0,O)}\u2026`:$}function v($){let O=w($);return O?T(O,_):"(empty prompt)"}function S($){return T($.trim(),E)}function N($){let O=Or(r,$),A=`Prompt #${$}`;return!O||O.status!=="available"||O.text===null?`<a href="${o}/prompts/${$}">${b(A)}</a>`:`<a href="${o}/prompts/${$}" title="${b(S(O.text))}">${b(v(O.text))}</a>`}function x($){return $.lifecycle==="queued"?"queued":$.lifecycle==="processing"?"processing":p($.lifecycleBasis)?"muted":"replied"}function I($){return $.lifecycle==="queued"?"Queued":$.lifecycle==="processing"?"Processing":$.lifecycleBasis==="merged"?"Combined":$.lifecycleBasis==="informational"?"Informational":$.lifecycleBasis==="retracted"?"Retracted":"Replied"}function k($){return`<span class="status-chip status-${x($)}" title="${b(B($))}">${b(I($))}</span>`}function B($){return $.lifecycle==="queued"?"Queued \u2014 waiting for handling":$.lifecycle==="finished"?$.lifecycleBasis==="merged"?"Finished \u2014 combined with another prompt":$.lifecycleBasis==="informational"?"Finished \u2014 informational, no answer expected":$.lifecycleBasis==="retracted"?"Finished \u2014 retracted, no answer expected":"Finished \u2014 answer recorded":$.lifecycleBasis==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed"}function C($){if($==="operator")return"Operator";let O=gn($);if(O){let q=r.teams.find(M=>{if(!H(M))return!1;try{return Q(M)===O.teamfilePath}catch{return!1}});return q?`<a href="${b(`${n}/sessions/${encodeURIComponent(q.name)}/${encodeURIComponent(O.alias)}`)}" title="${b($)}">${b(`${q.name}:${O.alias}`)}</a>`:`<span title="${b($)}">${b(`${wO(O.teamfilePath)}:${O.alias}`)}</span>`}let A=r.teams.find(q=>q.name===$);return A&&H(A)?`<a href="${b(`${n}/sessions/${encodeURIComponent(A.name)}/${encodeURIComponent(A.leadAlias)}`)}" title="${b(`Current configured lead for inbox ${$}`)}">${b(`${A.name}:${A.leadAlias}`)}</a>`:`${b($)}${A?" (remote inbox)":" (not in the current team list)"}`}function g(){let $=r.teams.find(O=>O.name==="math");if(!$||!H($))return'<section aria-label="Assigned work"><h2>Assigned work</h2><p>Math\u2019s current local actor is unavailable, so its assigned work cannot be resolved.</p></section>';try{let O=br(r.db.db,{owner:{team:Q($),alias:$.leadAlias},limit:5});return`<section aria-label="Assigned work"><h2>Assigned work</h2><p>Work owned by ${C("math")}. Open an item to follow its epic, parent task, or subtasks.</p>${O.rows.length?`<ul>${O.rows.map(A=>`<li><a href="${n}/tasks/${A.id}">${b(`${A.kind} #${A.id}: ${A.title}`)}</a> \u2014 ${b(A.status)}</li>`).join("")}</ul><p>Up to five assigned items shown.</p>`:"<p>No assigned work returned for this actor.</p>"}</section>`}catch{return'<section aria-label="Assigned work"><h2>Assigned work</h2><p>Current work ownership is unavailable. Prompt and answer records below remain readable.</p></section>'}}let y="<details><summary>About these records</summary><p>Actor links open each team\u2019s current configured lead; records identify inboxes and sender labels, not exact historical sessions. Assigned work is current ownership, not proof of execution or a prompt\u2019s topic. A delivery attempt does not confirm the inbox read a prompt. A recorded answer does not establish delivery back to the sender or task success.</p></details>";function R($,O,A,q=200){return $.html(ve(O,`${A}<script>${ma}</script>`,n,{},[ma]),q)}function P($,O="",A=""){return`<div id="comm-composer-container"><p id="comm-composer-notice">${b(A)}</p><form id="comm-draft-form" method="post" action="${o}/review"><input type="hidden" name="csrf" value="${b(u({browser:$,purpose:"review"}))}"><label for="prompt">Prompt for math Lead (maximum 64 KiB UTF-8)</label><textarea id="prompt" name="prompt" rows="8" required>
552
- ${b(O)}</textarea><button type="submit">Review prompt</button></form></div>`}function J($,O){return`<form method="post" action="${o}/prompts"><input type="hidden" name="confirmation" value="${b(O)}"><textarea name="prompt" hidden>
553
- ${b($)}</textarea><button type="submit">Retry this same confirmation</button></form>`}let ee=500;function oe($){let O=$.req.query("ask");if(O!==void 0&&/^[1-9]\d*$/.test(O)){try{let q=da(),M;try{M=Py(q,Number(O))}finally{q.close()}if(M){let Z=M.downstream?b(M.downstream):"Not recorded";return`<div id="comm-reply-context" aria-label="Replying to"><p><strong>Replying to ask:</strong> ${b(M.subject)}</p><p>${b(M.reason)}</p><p><strong>Downstream:</strong> ${Z}</p></div>`}}catch{}return""}let A=$.req.query("reply_to");if(A!==void 0&&/^[1-9]\d*$/.test(A)){let q=Vn(r,Number(A));if(q){let M=Or(r,q.id),Z=M?.status==="available"&&M.text!==null?T(M.text.trim(),ee):"(preview unavailable)";return`<div id="comm-reply-context" aria-label="Replying to"><p><strong>Replying to</strong> a prompt from ${C(q.from_id)}, ${fe(q.created_ts)}:</p><pre>${b(Z)}</pre></div>`}}return""}async function V($){if(!$.req.header("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new Error("Expected a browser form.");let O=$.req.raw.body?.getReader();if(!O)throw new Error("Missing form.");let A=0,q=[];for(;;){let{done:Z,value:W}=await O.read();if(Z)break;if(A+=W.byteLength,A>SO)throw await O.cancel(),new Error("Form exceeds the size limit.");q.push(W)}let M=new URLSearchParams(Buffer.concat(q).toString("utf8"));for(let Z of M.keys())if(M.getAll(Z).length!==1)throw new Error("Duplicate form field.");return M}function se($){let O=$.get("prompt")??"";if(!O.trim()||Buffer.byteLength(O)>bO)throw new Error("Enter a nonblank prompt of at most 64 KiB UTF-8.");return O}return t.use("/comm/math/*",async($,O)=>{$.header("Cache-Control","no-store"),$.header("Content-Security-Policy",TO),$.header("Referrer-Policy","same-origin"),$.header("X-Content-Type-Options","nosniff");let A=new URL($.req.url),q=`${A.protocol}//${$.req.header("host")??A.host}`,M=$.req.header("sec-fetch-site");if(!e.allowedOrigins.includes(q)||M&&M!=="same-origin"&&M!=="none"||$.req.header("origin")!==void 0&&$.req.header("origin")!==q||$.req.method==="POST"&&$.req.header("origin")!==q)return R($,"Request rejected","<p>Use this browser\u2019s local Math inbox page.</p>",403);await O()}),t.get("/comm/math",$=>{let O="<p>Sending is not enabled on this surface.</p>";if(e.enabled)try{f(),O=P(m($,!0))}catch(M){O=`<p>${b(M.message)}</p>`}let A=$.req.query("after");if(A!==void 0&&(!/^[1-9]\d*$/.test(A)||!Number.isSafeInteger(Number(A))))return R($,"Invalid page","<p>Invalid prompt cursor.</p>",400);let q=ia(r,{toId:"math",limit:20,...A?{after:Number(A)}:{}});return R($,"Math inbox",`<p>Prompts to ${C("math")} and the answers recorded against them. Select a prompt to follow the exchange; use assigned work to explore the tasks this actor owns.</p>${y}<p><a href="${o}">Refresh inbox</a> \xB7 <a href="#compose">Write a prompt</a> \xB7 <a href="${n}/sessions/math/Lead">Math session</a></p><section id="compose" aria-label="Write a prompt" data-mount="${b(n)}" data-base="${b(o)}"><h2>Write a prompt</h2><p>Start a new prompt to ${C("math")}. Review the exact text before queueing it.</p>${oe($)}${O}</section>${g()}<section id="history" aria-label="Prompts and answers"><h2>Incoming prompts and answers</h2><p>Only prompts addressed to Math appear here. <a href="${n}/sessions/math/Lead#comm-sequence">See incoming and outgoing exchanges</a> in the session timeline.</p><p>Newest 20 matching prompts first. Queued means waiting; processing records a pull or dispatch attempt; finished means an answer was recorded, an informational send expected no answer, or prompts from the same sender to the same recipient were combined to avoid separate deliveries. Finished for a combined prompt does not mean separate work was done, and no separate answer is expected. The combined prompt ID is not recorded, so no link is available.</p><table><thead><tr><th>Prompt</th><th>Actors</th><th>Handling</th><th>Queued</th><th>Answer</th></tr></thead><tbody>${q.rows.map(M=>`<tr data-queue-id="${M.id}"><td>${N(M.id)}</td><td>${C(M.from_id)} \u2192 ${C(M.to_id)}</td><td>${k(M)} \xB7 ${b(B(M))}</td><td>${fe(M.created_ts)}</td><td>${h(M)}</td></tr>`).join("")}</tbody></table><p>Task links for these prompts: not recorded.</p>${q.meta.next_cursor?`<a href="${o}?after=${q.meta.next_cursor}">Older prompts</a>`:""}</section>`)}),t.post("/comm/math/review",async $=>{if(!e.enabled)return R($,"Sending unavailable","<p>Sending is not enabled.</p>",403);let O="",A="";try{let q=await V($);O=q.get("prompt")??"";let M;try{M=m($)}catch(ae){throw new Qn(ae.message)}A=M;let Z;try{Z=d(q.get("csrf")??"")}catch(ae){throw new Qn(ae.message)}if(Z.browser!==M||Z.purpose!=="review")throw new Qn("Review form no longer matches this browser session. Reloading will renew it.");O=se(q);let W={browser:M,digest:c(O),target:f(),key:`localweb:${Lu(24).toString("hex")}`,expires:s()+3e5};return R($,"Review prompt to math",`<div id="comm-review-panel"><p>New prompt: Operator \u2192 ${C("math")}. Task link: none.</p><p>Queue one prompt for math to handle on its next pull. Processing may wait; the agent may use its existing file/network permissions.</p><p>Recipient: <a href="${b(`${n}/sessions/math/Lead`)}" title="${b(W.target)}">math:Lead</a></p><pre id="comm-review-preview">
549
+ return (${bO.toString()})();
550
+ })();`;var Wy=ve("","","").match(/<style>([\s\S]*?)<\/style>/),kO=Pu("sha256").update(Wy?Wy[1]:"").digest("base64"),$O=Pu("sha256").update(ha).digest("base64"),xO=`default-src 'none'; style-src 'sha256-${kO}'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; script-src 'sha256-${$O}'; connect-src 'self'`,Mu="lmbee_comm_browser",RO=64*1024,NO=256*1024,Zn=class extends Error{};function Gy(e){let t=new tn,{context:r}=e,n=(e.mountPath??"").replace(/\/$/,"");if(n&&(!/^\/[A-Za-z0-9_./~-]+$/.test(n)||n.startsWith("//")))throw new Error("Invalid mount path");let o=`${n}/comm/math`,s=e.now??Date.now,i=Du(32),a=new Map,c=k=>Pu("sha256").update(k).digest("hex"),l=k=>SO("sha256",i).update(k).digest("base64url"),u=k=>{let O=Buffer.from(JSON.stringify(k)).toString("base64url");return`${O}.${l(O)}`};function d(k){let O=k.split(".");if(O.length!==2||k.length>4096)throw new Error("Invalid confirmation. Review the prompt again.");let A=Buffer.from(l(O[0])),q=Buffer.from(O[1]);if(A.length!==q.length||!vO(A,q))throw new Error("Invalid confirmation. Review the prompt again.");return JSON.parse(Buffer.from(O[0],"base64url").toString("utf8"))}function m(k,O=!1){let A=(k.req.header("cookie")??"").split(";").map(M=>M.trim()).filter(M=>M.startsWith(`${Mu}=`));if(A.length===1)try{let M=d(A[0].slice(Mu.length+1));if(typeof M.browser=="string"&&/^[a-f0-9]{48}$/.test(M.browser))return M.browser}catch{}if(!O)throw new Error("Browser confirmation expired. Open the Math inbox and review again.");let q=Du(24).toString("hex");return k.header("Set-Cookie",`${Mu}=${u({browser:q})}; Path=${o}; HttpOnly; SameSite=Strict${new URL(k.req.url).protocol==="https:"?"; Secure":""}`),q}function f(){let k=r.teams.find(O=>O.name==="math");if(!k||!B(k)||k.leadAlias!=="Lead")throw new Error("The local math Lead inbox is unavailable.");return`${Q(k)}:Lead`}function p(k){return k==="merged"||k==="informational"||k==="retracted"}function h(k){return k.answeredAt?`<a href="${o}/prompts/${k.id}#comm-response">Answer to #${k.id}</a> \xB7 ${fe(k.answeredAt)}`:k.lifecycleBasis==="merged"?"No separate answer (merged)":k.lifecycleBasis==="informational"?"No answer expected (informational)":k.lifecycleBasis==="retracted"?`No answer expected (retracted): ${b(k.retracted_reason??"no reason recorded")}`:"No answer recorded"}function w(k){for(let O of k.split(`
551
+ `)){let A=O.trim();if(A)return A}return""}let _=80,T=2e3;function E(k,O){return k.length>O?`${k.slice(0,O)}\u2026`:k}function v(k){let O=w(k);return O?E(O,_):"(empty prompt)"}function S(k){return E(k.trim(),T)}function N(k){let O=Or(r,k),A=`Prompt #${k}`;return!O||O.status!=="available"||O.text===null?`<a href="${o}/prompts/${k}">${b(A)}</a>`:`<a href="${o}/prompts/${k}" title="${b(S(O.text))}">${b(v(O.text))}</a>`}function $(k){return k.lifecycle==="queued"?"queued":k.lifecycle==="processing"?"processing":p(k.lifecycleBasis)?"muted":"replied"}function L(k){return k.lifecycle==="queued"?"Queued":k.lifecycle==="processing"?"Processing":k.lifecycleBasis==="merged"?"Combined":k.lifecycleBasis==="informational"?"Informational":k.lifecycleBasis==="retracted"?"Retracted":"Replied"}function R(k){return`<span class="status-chip status-${$(k)}" title="${b(H(k))}">${b(L(k))}</span>`}function H(k){return k.lifecycle==="queued"?"Queued \u2014 waiting for handling":k.lifecycle==="finished"?k.lifecycleBasis==="merged"?"Finished \u2014 combined with another prompt":k.lifecycleBasis==="informational"?"Finished \u2014 informational, no answer expected":k.lifecycleBasis==="retracted"?"Finished \u2014 retracted, no answer expected":"Finished \u2014 answer recorded":k.lifecycleBasis==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed"}function C(k){if(k==="operator")return"Operator";let O=gn(k);if(O){let q=r.teams.find(M=>{if(!B(M))return!1;try{return Q(M)===O.teamfilePath}catch{return!1}});return q?`<a href="${b(`${n}/sessions/${encodeURIComponent(q.name)}/${encodeURIComponent(O.alias)}`)}" title="${b(k)}">${b(`${q.name}:${O.alias}`)}</a>`:`<span title="${b(k)}">${b(`${AO(O.teamfilePath)}:${O.alias}`)}</span>`}let A=r.teams.find(q=>q.name===k);return A&&B(A)?`<a href="${b(`${n}/sessions/${encodeURIComponent(A.name)}/${encodeURIComponent(A.leadAlias)}`)}" title="${b(`Current configured lead for inbox ${k}`)}">${b(`${A.name}:${A.leadAlias}`)}</a>`:`${b(k)}${A?" (remote inbox)":" (not in the current team list)"}`}function g(){let k=r.teams.find(O=>O.name==="math");if(!k||!B(k))return'<section aria-label="Assigned work"><h2>Assigned work</h2><p>Math\u2019s current local actor is unavailable, so its assigned work cannot be resolved.</p></section>';try{let O=Sr(r.db.db,{owner:{team:Q(k),alias:k.leadAlias},limit:5});return`<section aria-label="Assigned work"><h2>Assigned work</h2><p>Work owned by ${C("math")}. Open an item to follow its epic, parent task, or subtasks.</p>${O.rows.length?`<ul>${O.rows.map(A=>`<li><a href="${n}/tasks/${A.id}">${b(`${A.kind} #${A.id}: ${A.title}`)}</a> \u2014 ${b(A.status)}</li>`).join("")}</ul><p>Up to five assigned items shown.</p>`:"<p>No assigned work returned for this actor.</p>"}</section>`}catch{return'<section aria-label="Assigned work"><h2>Assigned work</h2><p>Current work ownership is unavailable. Prompt and answer records below remain readable.</p></section>'}}let y="<details><summary>About these records</summary><p>Actor links open each team\u2019s current configured lead; records identify inboxes and sender labels, not exact historical sessions. Assigned work is current ownership, not proof of execution or a prompt\u2019s topic. A delivery attempt does not confirm the inbox read a prompt. A recorded answer does not establish delivery back to the sender or task success.</p></details>";function x(k,O,A,q=200){return k.html(ve(O,`${A}<script>${ha}</script>`,n,{},[ha]),q)}function P(k,O="",A=""){return`<div id="comm-composer-container"><p id="comm-composer-notice">${b(A)}</p><form id="comm-draft-form" method="post" action="${o}/review"><input type="hidden" name="csrf" value="${b(u({browser:k,purpose:"review"}))}"><label for="prompt">Prompt for math Lead (maximum 64 KiB UTF-8)</label><textarea id="prompt" name="prompt" rows="8" required>
552
+ ${b(O)}</textarea><button type="submit">Review prompt</button></form></div>`}function J(k,O){return`<form method="post" action="${o}/prompts"><input type="hidden" name="confirmation" value="${b(O)}"><textarea name="prompt" hidden>
553
+ ${b(k)}</textarea><button type="submit">Retry this same confirmation</button></form>`}let ee=500;function oe(k){let O=k.req.query("ask");if(O!==void 0&&/^[1-9]\d*$/.test(O)){try{let q=pa(),M;try{M=Hy(q,Number(O))}finally{q.close()}if(M){let Z=M.downstream?b(M.downstream):"Not recorded";return`<div id="comm-reply-context" aria-label="Replying to"><p><strong>Replying to ask:</strong> ${b(M.subject)}</p><p>${b(M.reason)}</p><p><strong>Downstream:</strong> ${Z}</p></div>`}}catch{}return""}let A=k.req.query("reply_to");if(A!==void 0&&/^[1-9]\d*$/.test(A)){let q=Kn(r,Number(A));if(q){let M=Or(r,q.id),Z=M?.status==="available"&&M.text!==null?E(M.text.trim(),ee):"(preview unavailable)";return`<div id="comm-reply-context" aria-label="Replying to"><p><strong>Replying to</strong> a prompt from ${C(q.from_id)}, ${fe(q.created_ts)}:</p><pre>${b(Z)}</pre></div>`}}return""}async function V(k){if(!k.req.header("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new Error("Expected a browser form.");let O=k.req.raw.body?.getReader();if(!O)throw new Error("Missing form.");let A=0,q=[];for(;;){let{done:Z,value:W}=await O.read();if(Z)break;if(A+=W.byteLength,A>NO)throw await O.cancel(),new Error("Form exceeds the size limit.");q.push(W)}let M=new URLSearchParams(Buffer.concat(q).toString("utf8"));for(let Z of M.keys())if(M.getAll(Z).length!==1)throw new Error("Duplicate form field.");return M}function se(k){let O=k.get("prompt")??"";if(!O.trim()||Buffer.byteLength(O)>RO)throw new Error("Enter a nonblank prompt of at most 64 KiB UTF-8.");return O}return t.use("/comm/math/*",async(k,O)=>{k.header("Cache-Control","no-store"),k.header("Content-Security-Policy",xO),k.header("Referrer-Policy","same-origin"),k.header("X-Content-Type-Options","nosniff");let A=new URL(k.req.url),q=`${A.protocol}//${k.req.header("host")??A.host}`,M=k.req.header("sec-fetch-site");if(!e.allowedOrigins.includes(q)||M&&M!=="same-origin"&&M!=="none"||k.req.header("origin")!==void 0&&k.req.header("origin")!==q||k.req.method==="POST"&&k.req.header("origin")!==q)return x(k,"Request rejected","<p>Use this browser\u2019s local Math inbox page.</p>",403);await O()}),t.get("/comm/math",k=>{let O="<p>Sending is not enabled on this surface.</p>";if(e.enabled)try{f(),O=P(m(k,!0))}catch(M){O=`<p>${b(M.message)}</p>`}let A=k.req.query("after");if(A!==void 0&&(!/^[1-9]\d*$/.test(A)||!Number.isSafeInteger(Number(A))))return x(k,"Invalid page","<p>Invalid prompt cursor.</p>",400);let q=la(r,{toId:"math",limit:20,...A?{after:Number(A)}:{}});return x(k,"Math inbox",`<p>Prompts to ${C("math")} and the answers recorded against them. Select a prompt to follow the exchange; use assigned work to explore the tasks this actor owns.</p>${y}<p><a href="${o}">Refresh inbox</a> \xB7 <a href="#compose">Write a prompt</a> \xB7 <a href="${n}/sessions/math/Lead">Math session</a></p><section id="compose" aria-label="Write a prompt" data-mount="${b(n)}" data-base="${b(o)}"><h2>Write a prompt</h2><p>Start a new prompt to ${C("math")}. Review the exact text before queueing it.</p>${oe(k)}${O}</section>${g()}<section id="history" aria-label="Prompts and answers"><h2>Incoming prompts and answers</h2><p>Only prompts addressed to Math appear here. <a href="${n}/sessions/math/Lead#comm-sequence">See incoming and outgoing exchanges</a> in the session timeline.</p><p>Newest 20 matching prompts first. Queued means waiting; processing records a pull or dispatch attempt; finished means an answer was recorded, an informational send expected no answer, or prompts from the same sender to the same recipient were combined to avoid separate deliveries. Finished for a combined prompt does not mean separate work was done, and no separate answer is expected. The combined prompt ID is not recorded, so no link is available.</p><table><thead><tr><th>Prompt</th><th>Actors</th><th>Handling</th><th>Queued</th><th>Answer</th></tr></thead><tbody>${q.rows.map(M=>`<tr data-queue-id="${M.id}"><td>${N(M.id)}</td><td>${C(M.from_id)} \u2192 ${C(M.to_id)}</td><td>${R(M)} \xB7 ${b(H(M))}</td><td>${fe(M.created_ts)}</td><td>${h(M)}</td></tr>`).join("")}</tbody></table><p>Task links for these prompts: not recorded.</p>${q.meta.next_cursor?`<a href="${o}?after=${q.meta.next_cursor}">Older prompts</a>`:""}</section>`)}),t.post("/comm/math/review",async k=>{if(!e.enabled)return x(k,"Sending unavailable","<p>Sending is not enabled.</p>",403);let O="",A="";try{let q=await V(k);O=q.get("prompt")??"";let M;try{M=m(k)}catch(ae){throw new Zn(ae.message)}A=M;let Z;try{Z=d(q.get("csrf")??"")}catch(ae){throw new Zn(ae.message)}if(Z.browser!==M||Z.purpose!=="review")throw new Zn("Review form no longer matches this browser session. Reloading will renew it.");O=se(q);let W={browser:M,digest:c(O),target:f(),key:`localweb:${Du(24).toString("hex")}`,expires:s()+3e5};return x(k,"Review prompt to math",`<div id="comm-review-panel"><p>New prompt: Operator \u2192 ${C("math")}. Task link: none.</p><p>Queue one prompt for math to handle on its next pull. Processing may wait; the agent may use its existing file/network permissions.</p><p>Recipient: <a href="${b(`${n}/sessions/math/Lead`)}" title="${b(W.target)}">math:Lead</a></p><pre id="comm-review-preview">
554
554
  ${b(O)}</pre><form id="comm-confirm-form" method="post" action="${o}/prompts"><input type="hidden" name="confirmation" value="${b(u(W))}"><textarea name="prompt" hidden>
555
- ${b(O)}</textarea><button id="comm-confirm-submit" type="submit">Confirm and queue</button></form><button type="button" id="comm-edit-button">Edit prompt</button><p id="comm-send-status" role="status"></p><details><summary>Edit prompt</summary>${P(M,O)}</details><p>Confirmation expires in five minutes. If a submission result is uncertain, retry this same confirmation; do not create a new prompt.</p></div>`)}catch(q){let M=q instanceof Qn?409:400;return R($,"Review unavailable",`<p>${b(q.message)}</p>${A?P(A,O):`<pre>
556
- ${b(O)}</pre>`}<a href="${o}">Math inbox</a>`,M)}}),t.post("/comm/math/prompts",async $=>{if(!e.enabled)return R($,"Sending unavailable","<p>Sending is not enabled.</p>",403);let O="",A="",q=!1;try{let M=await V($);O=M.get("prompt")??"",A=M.get("confirmation")??"";let Z=m($);O=se(M);let W=d(A);if(W.browser!==Z||W.digest!==c(O)||!Number.isFinite(W.expires)||!/^localweb:[a-f0-9]{48}$/.test(W.key))throw new Error("Confirmation does not match this browser and prompt.");let ae=r.db.db.prepare("SELECT id, admission_fingerprint FROM queue WHERE dedupe_key = ?").get(W.key);if(ae){if(ae.admission_fingerprint!==c(`math\0${O}`))throw new Error("Confirmation conflicts with an existing admission.");return $.redirect(`${o}/prompts/${ae.id}`,303)}if(W.expires<s()||W.target!==f())throw new Error("Confirmation expired or changed. Check the inbox before reviewing again; a previous uncertain admission may already exist.");q=!0;let Ee=s()-6e4;for(let[j,Y]of a)Y.start<Ee&&a.delete(j);let ne=a.get(Z)??{start:s(),count:0};if(ne.count>=10)return R($,"Please wait",`<p>Ten prompts were queued this minute. Wait before retrying this unchanged confirmation.</p><pre>
557
- ${b(O)}</pre>${J(O,A)}`,429);let D=ua(r.db.db,r.teams,{to:"math",prompt:O,dedupeKey:W.key});return D.replayed||(ne.count++,a.set(Z,ne)),$.redirect(`${o}/prompts/${D.queueId}`,303)}catch(M){return R($,"Prompt not confirmed",`<p>${b(M.message)}</p><pre>
558
- ${b(O)}</pre>${q?J(O,A):""}<p>No new confirmation key was issued. For an uncertain result, retain the original confirmation and check the inbox before sending again. A server restart invalidates pending confirmations; known receipt URLs remain readable.</p><a href="${o}">Math inbox</a>`,400)}}),t.get("/comm/math/prompts/:id",$=>{let O=$.req.param("id"),A=Number(O);if(!/^[1-9]\d*$/.test(O)||!Number.isSafeInteger(A))return R($,"Not found","<p>Invalid prompt ID.</p>",404);let q=Vn(r,A);if(!q||q.to_id!=="math")return R($,"Not found","<p>No Math inbox prompt at this address.</p>",404);let M=ts(r,A),Z=Or(r,A),W=M.answer,ae=M.lifecycle==="finished"&&p(M.lifecycleBasis),Ee=b(q.retracted_reason??"no reason recorded"),ne=M.lifecycleBasis==="informational"?"This was an informational send; no answer is expected.":M.lifecycleBasis==="retracted"?`This prompt was retracted by its sender: ${Ee}. No answer is expected.`:"This prompt was combined into another prompt. The combined prompt ID is not recorded, so no link is available.",D=M.lifecycleBasis==="informational"?"No answer expected: this was an informational send.":M.lifecycleBasis==="retracted"?`No answer expected: this prompt was retracted. Reason: ${Ee}.`:"No separate answer: prompt combined into another prompt.";if(W&&W.prompt_queue_id!==A)return R($,"Answer unavailable","<p>Answer correlation mismatch.</p>",503);let j="";if(e.enabled)try{f(),j=`<section id="compose" aria-label="Write a prompt" data-mount="${b(n)}" data-base="${b(o)}"><h2>Write another prompt</h2><p>Start a new prompt to ${C("math")}. Review the exact text before queueing it.</p>${P(m($,!0))}</section>`}catch{}return R($,`Math prompt #${A}`,`<p>Prompt #${A}: ${C(q.from_id)} \u2192 ${C(q.to_id)}. <span id="comm-receipt-summary">${W?"An answer is recorded below.":ae?ne:"No answer recorded yet."}</span></p>${y}<p>Work: no task association is recorded for this prompt. <a href="#assigned-work">Browse Math\u2019s current assigned work</a>.</p><p id="comm-state" role="status" aria-live="polite" data-sender="${b(q.from_id)}" data-recipient="${b(q.to_id)}" data-queue-id="${A}" data-mount="${b(n)}" data-lifecycle="${M.lifecycle}" data-lifecycle-basis="${M.lifecycleBasis}">${k(M)} \xB7 ${b(B(M))}</p><p><a href="${o}/prompts/${A}">Refresh state</a> \xB7 <a href="${o}">Math inbox</a></p>${j}<section aria-label="Prompt and answer sequence"><h2>Prompt and answer sequence</h2><article data-queue-id="${A}" data-event="request"><h3>Prompt text</h3><p>${C(q.from_id)} \u2192 ${C(q.to_id)} \xB7 queued ${fe(M.createdAt)}</p><details><summary>Prompt times</summary><p id="comm-handling-observation">Delivery attempted ${q.sent_ts?fe(q.sent_ts):"not recorded"} \xB7 Picked up ${q.retrieved_ts?fe(q.retrieved_ts):"not recorded"} </p><p>Answer recorded <span id="comm-reply-time">${W?fe(W.answered_at):"not recorded"}</span></p></details>${Z?.status==="available"?`<pre>
555
+ ${b(O)}</textarea><button id="comm-confirm-submit" type="submit">Confirm and queue</button></form><button type="button" id="comm-edit-button">Edit prompt</button><p id="comm-send-status" role="status"></p><details><summary>Edit prompt</summary>${P(M,O)}</details><p>Confirmation expires in five minutes. If a submission result is uncertain, retry this same confirmation; do not create a new prompt.</p></div>`)}catch(q){let M=q instanceof Zn?409:400;return x(k,"Review unavailable",`<p>${b(q.message)}</p>${A?P(A,O):`<pre>
556
+ ${b(O)}</pre>`}<a href="${o}">Math inbox</a>`,M)}}),t.post("/comm/math/prompts",async k=>{if(!e.enabled)return x(k,"Sending unavailable","<p>Sending is not enabled.</p>",403);let O="",A="",q=!1;try{let M=await V(k);O=M.get("prompt")??"",A=M.get("confirmation")??"";let Z=m(k);O=se(M);let W=d(A);if(W.browser!==Z||W.digest!==c(O)||!Number.isFinite(W.expires)||!/^localweb:[a-f0-9]{48}$/.test(W.key))throw new Error("Confirmation does not match this browser and prompt.");let ae=r.db.db.prepare("SELECT id, admission_fingerprint FROM queue WHERE dedupe_key = ?").get(W.key);if(ae){if(ae.admission_fingerprint!==c(`math\0${O}`))throw new Error("Confirmation conflicts with an existing admission.");return k.redirect(`${o}/prompts/${ae.id}`,303)}if(W.expires<s()||W.target!==f())throw new Error("Confirmation expired or changed. Check the inbox before reviewing again; a previous uncertain admission may already exist.");q=!0;let Ee=s()-6e4;for(let[j,Y]of a)Y.start<Ee&&a.delete(j);let ne=a.get(Z)??{start:s(),count:0};if(ne.count>=10)return x(k,"Please wait",`<p>Ten prompts were queued this minute. Wait before retrying this unchanged confirmation.</p><pre>
557
+ ${b(O)}</pre>${J(O,A)}`,429);let D=fa(r.db.db,r.teams,{to:"math",prompt:O,dedupeKey:W.key});return D.replayed||(ne.count++,a.set(Z,ne)),k.redirect(`${o}/prompts/${D.queueId}`,303)}catch(M){return x(k,"Prompt not confirmed",`<p>${b(M.message)}</p><pre>
558
+ ${b(O)}</pre>${q?J(O,A):""}<p>No new confirmation key was issued. For an uncertain result, retain the original confirmation and check the inbox before sending again. A server restart invalidates pending confirmations; known receipt URLs remain readable.</p><a href="${o}">Math inbox</a>`,400)}}),t.get("/comm/math/prompts/:id",k=>{let O=k.req.param("id"),A=Number(O);if(!/^[1-9]\d*$/.test(O)||!Number.isSafeInteger(A))return x(k,"Not found","<p>Invalid prompt ID.</p>",404);let q=Kn(r,A);if(!q||q.to_id!=="math")return x(k,"Not found","<p>No Math inbox prompt at this address.</p>",404);let M=ss(r,A),Z=Or(r,A),W=M.answer,ae=M.lifecycle==="finished"&&p(M.lifecycleBasis),Ee=b(q.retracted_reason??"no reason recorded"),ne=M.lifecycleBasis==="informational"?"This was an informational send; no answer is expected.":M.lifecycleBasis==="retracted"?`This prompt was retracted by its sender: ${Ee}. No answer is expected.`:"This prompt was combined into another prompt. The combined prompt ID is not recorded, so no link is available.",D=M.lifecycleBasis==="informational"?"No answer expected: this was an informational send.":M.lifecycleBasis==="retracted"?`No answer expected: this prompt was retracted. Reason: ${Ee}.`:"No separate answer: prompt combined into another prompt.";if(W&&W.prompt_queue_id!==A)return x(k,"Answer unavailable","<p>Answer correlation mismatch.</p>",503);let j="";if(e.enabled)try{f(),j=`<section id="compose" aria-label="Write a prompt" data-mount="${b(n)}" data-base="${b(o)}"><h2>Write another prompt</h2><p>Start a new prompt to ${C("math")}. Review the exact text before queueing it.</p>${P(m(k,!0))}</section>`}catch{}return x(k,`Math prompt #${A}`,`<p>Prompt #${A}: ${C(q.from_id)} \u2192 ${C(q.to_id)}. <span id="comm-receipt-summary">${W?"An answer is recorded below.":ae?ne:"No answer recorded yet."}</span></p>${y}<p>Work: no task association is recorded for this prompt. <a href="#assigned-work">Browse Math\u2019s current assigned work</a>.</p><p id="comm-state" role="status" aria-live="polite" data-sender="${b(q.from_id)}" data-recipient="${b(q.to_id)}" data-queue-id="${A}" data-mount="${b(n)}" data-lifecycle="${M.lifecycle}" data-lifecycle-basis="${M.lifecycleBasis}">${R(M)} \xB7 ${b(H(M))}</p><p><a href="${o}/prompts/${A}">Refresh state</a> \xB7 <a href="${o}">Math inbox</a></p>${j}<section aria-label="Prompt and answer sequence"><h2>Prompt and answer sequence</h2><article data-queue-id="${A}" data-event="request"><h3>Prompt text</h3><p>${C(q.from_id)} \u2192 ${C(q.to_id)} \xB7 queued ${fe(M.createdAt)}</p><details><summary>Prompt times</summary><p id="comm-handling-observation">Delivery attempted ${q.sent_ts?fe(q.sent_ts):"not recorded"} \xB7 Picked up ${q.retrieved_ts?fe(q.retrieved_ts):"not recorded"} </p><p>Answer recorded <span id="comm-reply-time">${W?fe(W.answered_at):"not recorded"}</span></p></details>${Z?.status==="available"?`<pre>
559
559
  ${b(Z.text)}</pre><p>${Z.truncated?"Preview truncated.":"Saved prompt text; availability may change."}</p>`:"<p>Prompt preview unavailable.</p>"}</article><article data-queue-id="${A}" data-event="response"><h3>Answer</h3><p id="comm-poll-notice" role="status" aria-live="polite">Live updates while this page is visible.</p><p id="comm-response-status">${ae?D:`${W?"Answer recorded":"Waiting for an answer"} in the ${C(q.to_id)} inbox for prompt #${A} from ${C(q.from_id)}.`}</p>${W?`<p id="comm-response-meta">Recorded ${fe(W.answered_at)} \xB7 answer #${W.id} to prompt #${W.prompt_queue_id}</p><pre id="comm-response">
560
- ${b(W.answer_text)}</pre><p id="comm-response-truncation">${W.truncated?`Truncated: ${W.byteLength} of ${W.totalBytes} bytes. No continuation endpoint is available.`:`${W.byteLength} bytes returned.`}</p>`:`<p id="comm-response-meta"></p><pre id="comm-response" hidden></pre><p id="comm-response-truncation"></p><p id="comm-response-none">${ae?"":"No correlated answer recorded yet. Refresh to check again."}</p>`}</article></section><div id="assigned-work">${g()}</div>`)}),t}import{basename as vO}from"node:path";var Du=50,AO=e=>e.trim().toLowerCase().replace(/[\s_]+/g,"-"),Mu=e=>["blocked","error","on-hold","rate-limited"].includes(AO(e));function Gy(e){if(!/^[1-9]\d*$/.test(e)||!Number.isSafeInteger(Number(e)))throw new L("INVALID_ARGUMENT","Invalid positive integer ID");return Number(e)}function $O(e){let t={},r=new Set(["q","project","status","kind","team","attention","sort","page"]);for(let[n,o]of new URL(e).searchParams){if(!r.has(n)||Object.hasOwn(t,n)||o.length>256||/[\x00-\x1f\x7f]/.test(o))throw new L("INVALID_ARGUMENT","Invalid or duplicate task filter");t[n]=o}if(t.page&&Gy(t.page)>Ne)throw new L("INVALID_ARGUMENT","Page exceeds safety limit");if(t.attention&&t.attention!=="1")throw new L("INVALID_ARGUMENT","attention must be 1");if(t.sort&&!["id","updated"].includes(t.sort))throw new L("INVALID_ARGUMENT","Unknown task sort");if(t.kind&&!["epic","task","subtask"].includes(t.kind))throw new L("INVALID_ARGUMENT","Unknown task kind");return t}function jy(e,t){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==""));return e+(r.size?`?${r}`:"")}function kO(e,t,r,n){let o=e.filter(f=>(!t.q||`${f.id} ${f.title} ${f.description} ${f.requirements} ${f.acceptance_criteria}`.toLowerCase().includes(t.q.toLowerCase()))&&(!t.attention||Mu(f.status))&&(!n||f.owner_team_path===n));o.sort(t.sort==="updated"?(f,p)=>Date.parse(p.updated_at)-Date.parse(f.updated_at)||f.id-p.id:(f,p)=>f.id-p.id);let s=Number(t.page||1),i=o.slice((s-1)*Du,s*Du),a=new Map(e.map(f=>[f.id,f])),c=f=>{if(f===null)return;let p=a.get(f)??r(f);return a.set(f,p),p},l=new Map(i.map(f=>[f.id,{...f,context:!1}]));for(let f of i){let p=c(f.parent_id),h=new Set([f.id]);for(;p&&!h.has(p.id);)h.add(p.id),l.has(p.id)||l.set(p.id,{...p,context:!0}),p=c(p.parent_id)}let u=new Map;for(let f of l.values()){let p=f.parent_id!==null&&l.has(f.parent_id)?f.parent_id:null,h=u.get(p)??[];h.push(f),u.set(p,h)}let d=[],m=f=>{for(let p of u.get(f)??[])d.push(p),m(p.id)};return m(null),{rows:d,total:o.length,pageNumber:s,more:o.length>s*Du,byId:a}}function Xn(e,t){return Re(`${t}/tasks/${e.id}`,`#${e.id} ${e.title}`)}function Vy(e,t,r){if(e.owner_team_path===null)return"Unassigned";let n=`${vO(e.owner_team_path)}:${e.owner_alias}`,o=`${e.owner_team_path}:${e.owner_alias}`,s=t.get(e.owner_team_path);return s&&e.owner_alias?`<a href="${b(`${r}/sessions/${encodeURIComponent(s)}/${encodeURIComponent(e.owner_alias)}`)}" title="${b(o)}">${b(n)}</a>`:`<span title="${b(o)}">${b(n)}</span>`}function Jy(e){if(e.blocked_on!==null){let t=e.blocked_on==="operator"?"Operator":e.blocked_on;return`<span class="status-chip status-processing" title="blocked_on names who this task is waiting on; independent of the recorded status text">Blocked on ${b(t)}</span>`}if(e.hold_until!==null){let t=Date.parse(e.hold_until)<=Date.now(),r=e.hold_reason?` \u2014 ${b(e.hold_reason)}`:"";return t?`<span class="status-chip status-processing" title="Hold expired ${b(e.hold_until)}; not auto-cleared, needs the owning team to resolve it">Hold expired, evidence due${r}</span>`:`<span class="status-chip status-muted">On hold until ${fe(e.hold_until)}${r}</span>`}return"\u2014"}function Hy(e,t,r,n,o="Task ledger"){return Yn(["Task / hierarchy","Project","Recorded status","Blocked / hold","Recorded owner","Updated","Presentation"],e.map(s=>{let i=[],a=s.parent_id===null?void 0:t.get(s.parent_id),c=new Set([s.id]);for(;a&&!c.has(a.id);)c.add(a.id),i.unshift(a),a=a.parent_id===null?void 0:t.get(a.parent_id);let l=i.map(u=>Xn(u,r)).join(" / ");return[`${l?`${l}<br>`:""}${Xn(s,r)}${s.context?" <strong>(ancestor context)</strong>":""}<br>${b(s.kind)}`,b(s.project),b(s.status),Jy(s),Vy(s,n,r),fe(s.updated_at),s.kind==="epic"?"Not applicable":s.delivered_ts?`First presented ${fe(s.delivered_ts)}`:"Not recorded"]}),o)}function By(e,t,r){let n=["q","project","status"].map(i=>`<label>${{q:"Search",project:"Project",status:"Exact recorded status"}[i]}<input name="${i}" value="${b(e[i]??"")}" maxlength="256"></label>`).join(""),o=(i,a,c)=>`<label>${a}<select name="${i}">${c.map(([l,u])=>`<option value="${b(l)}"${e[i]===l?" selected":""}>${b(u)}</option>`).join("")}</select></label>`,s=[["",`All teams (${t.length} own work in this scope)`],...t.map(i=>[i,i])];return`<form method="get" action="${b(r)}/tasks">${n}${o("kind","Kind",[["","All kinds"],["epic","Epic"],["task","Task"],["subtask","Subtask"]])}${o("team","Owning team",s)}${o("sort","Sort",[["id","ID"],["updated","Updated"]])}<label>Attention only<input type="checkbox" name="attention" value="1"${e.attention?" checked":""}></label><button>Filter tasks</button> ${Re(`${r}/tasks`,"Clear filters")}</form>`}function Wy(e){return`<p>${e.total} entities in this scope: ${e.by_kind.epic??0} epics, ${e.by_kind.task??0} tasks, ${e.by_kind.subtask??0} subtasks.</p>`}function Ky(e,t,r=""){let n=r.replace(/\/$/,""),o=(i,a,c,l=200)=>Oe(i,ve(a,c,n,{"data-page":"tasks"}),l),s=(i,a)=>{let c=a instanceof L?a.code==="NOT_FOUND"?404:a.code==="DB_BUSY"?503:a.code==="STORAGE_ERROR"?500:a.code==="CONFLICT"?409:400:500;return o(i,"Tasks unavailable",`<p>${b(a instanceof Error?a.message:String(a))}</p>${Re(`${n}/tasks`,"Task ledger")}`,c)};e.get("/tasks",i=>{try{let a=$O(i.req.url),c;if(a.team){let p=t.teams.find(h=>h.name===a.team&&H(h));if(!p||!H(p))throw new L("INVALID_ARGUMENT","Unknown local owning team");c=Q(p)}let l=br(t.db.db,{...a.project?{project:a.project}:{},...a.kind?{kind:a.kind}:{},...a.status?{status:a.status}:{},limit:Ne}),u=Mr(t.teams),d=[...new Set(l.rows.map(p=>p.owner_team_path).filter(p=>p!==null).map(p=>u.get(p)).filter(p=>p!==void 0))].sort();if(l.meta.next_cursor!==null)return o(i,"Tasks",'<p class="warning">This scope exceeds 10,000 entities. Choose a project, kind, or status to narrow it; an incomplete board is not shown.</p>'+By(a,d,n),503);let m=kO(l.rows,a,p=>Sr(t.db.db,p),c),f=`<nav aria-label="Task pages">${m.pageNumber>1?Re(jy(`${n}/tasks`,{...a,page:String(m.pageNumber-1)}),"Previous page"):""} ${m.more?Re(jy(`${n}/tasks`,{...a,page:String(m.pageNumber+1)}),"Next page"):""}</nav>`;return o(i,"Tasks",'<p data-testid="page-intro">Epics group tasks, and tasks can contain subtasks; follow a title to read its details and children. Status and owner are recorded values; Updated means content activity; Attention means blocked, error, on-hold, or rate-limited; First presentation means when the item was first shown to an agent to work on, not completion. Blocked / hold is separate from the recorded status text: it shows when a task is structurally waiting on a specific team or operator, or deliberately parked until a date, even while its own status reads as ordinary active work.</p>'+Wy({total:l.rows.length,by_kind:l.rows.reduce((p,h)=>(p[h.kind]=(p[h.kind]??0)+1,p),{})})+By(a,d,n)+`<p>${m.total} matching entities. Page ${m.pageNumber}, up to 50 matches plus labeled ancestor context; presentation does not mean completion.</p>`+f+Hy(m.rows,m.byId,n,u)+f)}catch(a){return s(i,a)}}),e.get("/tasks/:id",i=>{try{let a=Gy(i.req.param("id")),c=Sr(t.db.db,a),l=vr(t.db.db,a),u=[],d=c.parent_id,m=new Set([a]);for(;d!==null&&!m.has(d);){m.add(d);let S=Sr(t.db.db,d);u.unshift(S),d=S.parent_id}let f=Mr(t.teams),p=new Map([...u,c,...l.children].map(S=>[S.id,S])),h=S=>S.length?`<ul>${S.map(N=>`<li>${Xn(N,n)} \u2014 ${b(N.status)}</li>`).join("")}</ul>`:"<p>None recorded.</p>",w=`<nav aria-label="Breadcrumb">${Re(`${n}/tasks`,"Task ledger")} / ${u.map(S=>Re(`${n}/tasks/${S.id}`,`#${S.id} ${S.title} (status: ${S.status})`)).join(" / ")}${u.length?" / ":""}<span aria-current="page">#${c.id} ${b(c.title)}</span></nav>`,_=u.at(-1),E=u.find(S=>S.kind==="epic"),v=`<p data-testid="work-context">${c.kind==="epic"?"This is an epic with no parent.":c.kind==="task"?E?`This is a task in epic ${Xn(E,n)}.`:"This is a task with no parent epic.":`This is a subtask${_?` of task ${Xn(_,n)}`:""}${E?`, part of epic ${Xn(E,n)}.`:"; no parent epic is recorded."}`}</p><p data-testid="page-intro">This page describes one work item and its recorded status and owner. Follow the breadcrumb to its parent or epic, or a child title to drill down; Updated records content activity, not completion.</p>`+w+`<p>Kind: ${b(c.kind)}; project: ${b(c.project)}; recorded status: <strong>${b(c.status)}</strong>.</p><p>Recorded owner: ${Vy(c,f,n)}.</p><p>Blocked / hold: ${Jy(c)}</p>`+["description","requirements","acceptance_criteria"].map(S=>`<h2>${{description:"Description",requirements:"Requirements",acceptance_criteria:"Acceptance criteria"}[S]}</h2><pre>${b(c[S]||"Not supplied")}</pre>`).join("")+Wy(Ar(t.db.db,{id:a}))+"<h2>Children</h2>"+Hy(l.children,p,n,f,"Immediate children")+"<h2>Depends on</h2>"+h(c.dependencies.outgoing)+"<h2>Required by</h2>"+h(c.dependencies.incoming)+`<h2>Times</h2><p>Created ${fe(c.created_at)}; updated ${fe(c.updated_at)}.</p><p>First presentation: ${c.kind==="epic"?"Not applicable":c.delivered_ts?fe(c.delivered_ts):"Not recorded"}. Presentation does not mean completion.</p>`;return o(i,`Task #${c.id}: ${c.title}`,v)}catch(a){return s(i,a)}})}import{basename as xO}from"node:path";var zy=50,Yy='<p data-testid="page-intro">A cron job is work scheduled to run automatically; this page reviews its saved configuration and recorded results. An unresolved escalated run is waiting for a person to help, while execution uncertain means the process has not been confirmed stopped.</p>',RO={ok:"OK (last-fire bookkeeping)",error:"Error",skipped_overlap:"Skipped: earlier execution still guarded",skipped_stale:"Skipped: scheduled window too old",reconciled:"Process gone; outcome unknown",blocked_escalation:"Skipped: unresolved escalation at last check"},nt=e=>e===null?"Not recorded":fe(e),Qe=e=>e===null?"Not configured":b(e),Qy=e=>e.last_fire_status===null?"Not recorded":`${b(RO[e.last_fire_status]??e.last_fire_status)} <small>(${b(e.last_fire_status)})</small>`;function Xy(e){let t=e.req.queries("after");if(t===void 0)return 0;let r=t[0]??"";if(t.length!==1||!/^(0|[1-9]\d*)$/.test(r)||!Number.isSafeInteger(Number(r)))throw new U("INVALID_ARGUMENT","after must be a nonnegative integer");return Number(r)}function Zy(e,t,r){if(e.session_teamfile===null||e.session_alias===null)return"Not configured";let n=`${e.session_teamfile}:${e.session_alias}`,o=`${xO(e.session_teamfile)}:${e.session_alias}`,s=t.get(e.session_teamfile);return s?`<a href="${b(`${r}/sessions/${encodeURIComponent(s)}/${encodeURIComponent(e.session_alias)}`)}" title="${b(n)}">${b(o)}</a>`:`<span title="${b(n)}">${b(o)}</span> (not in the current local registry)`}function eE(e,t){let r=[];return(e.last_fire_status==="error"||e.last_fire_error)&&r.push("Recorded fire error"),e.last_fire_status==="blocked_escalation"&&r.push("Last check blocked by escalation"),e.last_fire_status==="reconciled"&&r.push("Previous execution outcome unknown"),t?.status==="escalated"&&t.escalation_resolved_at===null&&r.push(`Run #${t.id}: escalated \u2014 waiting for a person`),t?.execution_state==="uncertain"&&r.push(`Run #${t.id}: execution uncertain`),t?.status==="failed"&&r.push(`Run #${t.id}: failed; execution still guarded`),r}function Pu(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function NO(e){if(e===null)return"<p>No artifacts recorded.</p>";try{let t=JSON.parse(e);if(Array.isArray(t)&&t.every(r=>typeof r=="string"))return t.length?`<ul>${t.map(r=>`<li>${b(r)}</li>`).join("")}</ul>`:"<p>No artifacts recorded.</p>"}catch{}return`<pre>${b(e)}</pre>`}function IO(e){let t=e.status==="escalated",r=t&&e.escalation_resolved_at===null,n=e.status==="failed"||r||e.execution_state==="uncertain",o=`${e.status}${t?r?" \u2014 waiting for a person":" \u2014 escalation resolved":""}`,s=t||e.escalation_reason!==null||e.escalation_resolved_at!==null?"<h4>Escalation</h4>"+Pu([["Reason",Qe(e.escalation_reason)],["Requested action",Qe(e.escalation_action)],["Owner",Qe(e.escalation_owner)],["Resolved at",nt(e.escalation_resolved_at)],["Resolution",Qe(e.escalation_resolution)],["Resolved by",Qe(e.escalation_resolution_actor)],["Resolution note",Qe(e.escalation_resolution_note)]]):"";return`<article id="run-${e.id}"${n?' class="warning"':""}><h3>Run #${e.id}: ${b(o)}</h3>`+Pu([["Execution state",b(e.execution_state)],["Trigger",b(e.trigger_kind)],["Created",nt(e.created_at)],["Started",nt(e.started_at)],["Finished",nt(e.finished_at)],["Result reported",nt(e.reported_at)],["Last updated",nt(e.updated_at)],["Execution reference",Qe(e.execution_identity)],["Process ID",Qe(e.pid)],["Execution uncertainty reason",Qe(e.execution_uncertain_reason)],["Execution confirmed gone",nt(e.execution_gone_at)],["Confirmation note",Qe(e.execution_confirmation_note)]])+`<h4>Summary</h4><pre>${b(e.summary??"No summary recorded.")}</pre><h4>Artifacts (recorded paths or references)</h4>`+NO(e.artifacts)+s+"</article>"}function tE(e,t,r=""){let n=r.replace(/\/$/,""),o=(a,c,l,u=200)=>Oe(a,ve(c,l,n),u),s=(a,c)=>{let l=c instanceof U?c.code==="NOT_FOUND"?404:c.code==="DB_BUSY"?503:c.code==="INVALID_ARGUMENT"?400:500:500;return o(a,"Cron review unavailable",`<p>${b(c instanceof Error?c.message:String(c))}</p>${Re(`${n}/cron`,"Cron jobs")}`,l)},i=(a,c,l)=>`<nav aria-label="Cron pages">${c?Re(a,"First page"):""} ${l!==null?Re(`${a}?after=${l}`,"Next page"):""}</nav>`;e.get("/cron",a=>{try{let c=Xy(a),l=Li(t.db.db,{limit:zy,after:c}),u=Mr(t.teams),d=l.rows.map(f=>({job:f,flags:eE(f,Rr(t.db.db,f.id))})),m=(f,p)=>Yn(["Job","Schedule / timezone","Action kind","Enabled","Last fire status","Last fired","Scheduler last looked at","Last fire error","Session"],f.map(({job:h,flags:w})=>[Re(`${n}/cron/${h.id}`,`#${h.id} ${h.title}`)+(w.length?`<p class="warning"><strong>${w.map(b).join("<br>")}</strong></p>`:""),`<code>${b(h.schedule_expr)}</code><br>${b(h.timezone??"Host-local timezone")}`,b(h.action_kind),h.enabled?"Enabled":"Disabled",Qy(h),nt(h.last_fired_ts),nt(h.last_checked_ts),h.last_fire_error===null?"None recorded":`<pre>${b(h.last_fire_error)}</pre>`,Zy(h,u,n)]),p);return o(a,"Cron jobs",Yy+"<p>Saved jobs, up to 50 per page in ID order. Times below are stored scheduler records; OK is not proof of successful AI work. A retained error can predate a later skipped check.</p><h2>Failures and review flags</h2>"+m(d.filter(f=>f.flags.length>0),"Jobs with review flags on this page")+"<h2>Other jobs</h2>"+m(d.filter(f=>f.flags.length===0),"Other jobs on this page")+i(`${n}/cron`,c,l.meta.next_cursor))}catch(c){return s(a,c)}}),e.get("/cron/:id",a=>{try{let c=a.req.param("id");if(!/^[1-9]\d*$/.test(c)||!Number.isSafeInteger(Number(c)))throw new U("INVALID_ARGUMENT","Invalid positive job ID");let l=Xy(a),u=Ie(t.db.db,Number(c)),d=ki(t.db.db,{jobId:u.id,limit:zy,after:l}),m=Rr(t.db.db,u.id),f=eE(u,m),p=Pu([["Title",b(u.title)],["Schedule expression",`<code>${b(u.schedule_expr)}</code>`],["Timezone",b(u.timezone??"Host-local timezone")],["Action kind",b(u.action_kind)],["Enabled",u.enabled?"Enabled":"Disabled"],["Provider",Qe(u.provider)],["Model",Qe(u.model)],["Working directory",Qe(u.working_directory)],["Escalation owner",Qe(u.escalation_owner)],["Session",Zy(u,Mr(t.teams),n)],["Session teamfile",Qe(u.session_teamfile)],["Session alias",Qe(u.session_alias)],["Session seeded at",nt(u.session_seeded_at)],["Session generation",b(u.session_generation)],["Scheduler last looked at",nt(u.last_checked_ts)],["Last fired",nt(u.last_fired_ts)],["Last fire status",Qy(u)],["Last fire error",u.last_fire_error===null?"None recorded":`<pre>${b(u.last_fire_error)}</pre>`],["Recorded execution since",nt(u.running_since_ts)],["Recorded systemd unit",Qe(u.running_systemd_unit)],["Created",nt(u.created_at)],["Updated",nt(u.updated_at)],["Revision",b(u.revision)]]),h=m?`<p>${Re(`${n}/cron/${u.id}?after=${m.id-1}#run-${m.id}`,`Inspect guarded run #${m.id}`)} \u2014 ${b(m.status)}, execution ${b(m.execution_state)}.</p>`:"",w=l?"<p>No more run records after this cursor.</p>":"<p>No run history recorded. Command or script jobs may have last-fire records without run history; an empty history is not itself an error.</p>";return o(a,`Cron job #${u.id}: ${u.title}`,Yy+`<p>${Re(`${n}/cron`,"All cron jobs")}</p>`+(f.length?`<p class="warning"><strong>${f.map(b).join("<br>")}</strong></p>`:"")+h+"<h2>Configuration</h2>"+p+`<h3>Action payload (command, script, prompt, or enqueue data)</h3><pre>${b(u.action_payload)}</pre><h2>Run history</h2><p>Up to 50 recorded runs, oldest ID first. Outcome and process state are separate: active is recorded as active, uncertain is not confirmed stopped, and gone is confirmed stopped.</p>`+(d.rows.length?d.rows.map(IO).join(""):w)+i(`${n}/cron/${u.id}`,l,d.next_cursor))}catch(c){return s(a,c)}})}function LO(e,t){return t===null&&e.retracted_ts===null&&(e.status==="pending"||e.status==="escalating"||e.status==="sent"||e.status==="retrieved")}var nE=64*1024;async function CO(e){if(!e.req.header("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new L("INVALID_ARGUMENT","Expected a browser form.");let t=e.req.raw.body?.getReader();if(!t)throw new L("INVALID_ARGUMENT","Missing form.");let r=0,n=[];for(;;){let{done:i,value:a}=await t.read();if(i)break;if(r+=a.byteLength,r>nE)throw await t.cancel(),new L("INVALID_ARGUMENT","Form exceeds the size limit.");n.push(a)}let s=new URLSearchParams(Buffer.concat(n).toString("utf8")).getAll("answer");if(s.length!==1)throw new L("INVALID_ARGUMENT","Missing or duplicate answer field.");return s[0]}function oE(e,t){let r=[t.from_id,t.to_id,t.escalation_only,t.to_alias],o=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...r,t.id).id??Number.MAX_SAFE_INTEGER;return e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ?").all(...r,t.id,o)}function sE(e,t){let r=[];t.retracted_ts!==null&&t.retracted_reason&&r.push(t.retracted_reason);let n=oE(e,t);for(let o of n)o.retracted_ts!==null&&o.retracted_reason&&r.push(o.retracted_reason);return r}function Uu(e,t=Date.now()){return Go(e,t).map(n=>{let o=n.row,s=nn(e,o),i=Wo(e,o),a=n.ageMs>=Ko||s>=2&&o.sent_ts===null,c=sE(e,o);return{row:o,constituentCount:s,retractedCount:i,urgent:a,retractedReasons:c}})}function iE(e){return e===1?"1 of 1":`${e} merged into this one`}function OO(e){return e==="merged"||e==="informational"||e==="retracted"}function DO(e){return e.lifecycle==="queued"?"queued":e.lifecycle==="processing"?"processing":OO(e.lifecycleBasis)?"muted":"replied"}function MO(e){return e.lifecycle==="queued"?"Queued":e.lifecycle==="processing"?"Processing":e.lifecycleBasis==="merged"?"Combined":e.lifecycleBasis==="informational"?"Informational":e.lifecycleBasis==="retracted"?"Retracted":"Replied"}function aE(e){return`<span class="status-chip status-${DO(e)}" title="${b(Fu(e))}">${b(MO(e))}</span>`}function Fu(e){return e.lifecycle==="queued"?"Queued \u2014 waiting for handling":e.lifecycle==="processing"?e.lifecycleBasis==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed":e.lifecycle==="finished"?e.lifecycleBasis==="retracted"?"Finished \u2014 retracted":e.lifecycleBasis==="merged"?"Finished \u2014 combined with another prompt":e.lifecycleBasis==="informational"?"Finished \u2014 informational, no answer expected":"Finished \u2014 answer recorded":`${e.lifecycle} (${e.lifecycleBasis})`}function PO(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function UO(e){return e.length===0?"<p>No standing decisions recorded.</p>":e.map(t=>{let r=t.would_change_it?`<p><strong>Would change this:</strong> ${b(t.would_change_it)}</p>`:"<p><strong>Would change this:</strong> Not recorded.</p>",n=t.affects.length>0?t.affects.map(b).join(", "):"Not recorded";return`<article aria-label="Decision #${t.id}"><h3>${b(t.subject)}</h3><p>${b(t.decision)}</p>${r}<details><summary>Reasoning</summary><p>${b(t.reasoning)}</p></details><p>Decided by ${b(t.decided_by)}, ${fe(t.decided_at)}. Affects: ${n}.</p></article>`}).join("")}function FO(e){return e.length===0?"<p>Nothing blocking math right now.</p>":e.map(t=>`<article aria-label="Blocked #${t.id}"><h3>!!! ${b(t.title)}</h3><p>Category: ${b(t.category)}.</p>${t.detail?`<p>${b(t.detail)}</p>`:""}<p>Raised by ${b(t.raised_by)}, ${fe(t.raised_at)}.</p></article>`).join("")}function qO(e,t){return e.length===0?"<p>No open judgment calls for the operator.</p>":e.map(r=>{let n=r.downstream?`<p><strong>Downstream:</strong> ${b(r.downstream)}</p>`:"<p><strong>Downstream:</strong> Not recorded.</p>";return`<article aria-label="Ask #${r.id}"><h3>${b(r.subject)}</h3><p>${b(r.reason)}</p>${n}<p>Status: Open. Raised by ${b(r.raised_by)}, ${fe(r.raised_at)}.</p><p><a href="${b(t)}/comm/math?ask=${r.id}#compose">Discuss this with math</a></p></article>`}).join("")}function rE(e,t,r,n){if(e.length===0)return`<p>No ${t.toLowerCase()}.</p>`;let o=["Prompt","From","Age","Constituents","Retractions","Lifecycle"],s=e.map(i=>{let a=i.row,c=Ce(n,a.id),l=vt(a,c),u=`<a href="${b(r)}/operator/${a.id}">#${a.id}</a>`,d=b(a.from_id),m=fe(a.created_ts),f=iE(i.constituentCount),p=i.retractedCount>0?`${i.retractedCount} retracted${i.retractedReasons.length>0?`: ${i.retractedReasons.map(w=>`\u201C${b(w)}\u201D`).join("; ")}`:""}`:"\u2014",h=`${aE(l)} \xB7 ${b(Fu(l))}`;return[u,d,m,f,p,h]});return Yn(o,s,t)}function cE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/operator",o=>{try{let s=Uu(t.db.db,Date.now()),i=s.filter(w=>w.urgent),a=s.filter(w=>!w.urgent),c='<p data-testid="page-intro">What needs the operator, what math has already decided for them to review, and a way to reach math directly. Blocked means math is technically incapable of proceeding (re-auth, billing, account identity) -- rare and urgent. Escalations are requests a team sent that genuinely need a decision, shown whether or not anyone is currently monitoring them; urgent means waiting over four hours, or never delivered despite repeated sends. Constituents counts how many separate escalations were folded into one message; Retractions counts how many of those the sender has since withdrawn, with their stated reason. Asks are judgment calls only the operator can make, routine, not urgent -- problem statement, then what it affects downstream, then who raised it. Decisions are rulings math has already made, for review, not approval.</p>',l=`<section class="warning" aria-label="Urgent escalations"><h2>Urgent escalations</h2>${rE(i,"Urgent escalations",n,t.db.db)}</section>`,u=`<section aria-label="Routine escalations"><h2>Routine escalations</h2>${rE(a,"Routine escalations",n,t.db.db)}</section>`,d=`<section aria-label="Send a message"><h2>Send a message</h2><p>Start a new request to math. This reuses the same queue and composer as <a href="${b(n)}/comm/math">the Math inbox</a> -- one write path, not a second one.</p><p><a href="${b(n)}/comm/math#compose">Write a message to math</a></p></section>`,m,f,p;try{let w=da(),_,E,T;try{_=Uy(w),E=My(w),T=Dy(w)}finally{w.close()}m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${FO(_)}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${qO(E,n)}</section>`,p=`<section aria-label="Decisions"><h2>Decisions</h2><p>Rulings math has already made, in force now (superseded and reversed decisions are excluded). Nothing here waits on you -- read, and ping math if you disagree.</p>${UO(T)}</section>`}catch(w){let _=`<p class="warning">lmteam data unavailable: ${b(w instanceof Error?w.message:String(w))}</p>`;m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${_}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${_}</section>`,p=`<section aria-label="Decisions"><h2>Decisions</h2>${_}</section>`}let h=`${c}${m}${l}${f}${d}${u}${p}`;return Oe(o,ve("Operator inbox",h,n,{"data-page":"operator"},[],!0))}catch(s){return Oe(o,ve("Operator inbox unavailable",`<p>${b(s instanceof Error?s.message:String(s))}</p>`,n,{},[],!0),500)}}),e.get("/operator/:id",o=>{let s=o.req.param("id"),i=Number(s);if(!s||!/^[1-9]\d*$/.test(s)||!Number.isSafeInteger(i))return Oe(o,ve("Invalid escalation ID",`<p>Invalid escalation ID.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),400);try{let a=yr(t.db.db,i);if(!a||a.to_id!=="operator")return Oe(o,ve("Not found",`<p>No operator escalation at this address.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),404);let c=Or(t,i),l=Ce(t.db.db,i),u=vt(a,l),d=nn(t.db.db,a),m=Wo(t.db.db,a),f=sE(t.db.db,a),p=[["From",b(a.from_id)],["To",b(a.to_id)],["Queued",fe(a.created_ts)],["Lifecycle",`${aE(u)} \xB7 ${b(Fu(u))}`],["Constituents",b(iE(d))],["Delivery attempted",a.sent_ts?fe(a.sent_ts):"not recorded"],["Picked up",a.retrieved_ts?fe(a.retrieved_ts):"not recorded"],["Subject",a.subject_id?b(a.subject_id):"none"]];m>0&&p.push(["Retractions",`${m} retracted${f.length>0?`: ${f.map(v=>`\u201C${b(v)}\u201D`).join("; ")}`:""}`]),a.retracted_ts!==null&&(p.push(["Retracted at",fe(a.retracted_ts)]),p.push(["Retraction reason",b(a.retracted_reason??"(none)")]));let h="";c?.status==="available"?h=`<pre>${b(c.text)}</pre><p>${c.truncated?`Preview truncated (${c.byteLength} bytes).`:`Full content (${c.byteLength} bytes).`}</p>`:h=`<p>Prompt preview unavailable (${b(c?.status??"missing")}).</p>`;let w="";l?w=`<section><h2>Answer</h2><p>Recorded ${fe(l.answered_at)}</p><pre>${b(l.answer_text)}</pre></section>`:LO(a,l)&&(w=`<section aria-label="Answer"><h2>Answer</h2><form method="post" action="${b(n)}/operator/${i}/answer"><label for="answer">Answer text</label><textarea id="answer" name="answer" rows="8" maxlength="${nE}" required></textarea><button>Send answer</button></form></section>`);let _=oE(t.db.db,a),E="";_.length>0&&(E=`<section><h3>Merged constituents (${_.length})</h3><p>Additional escalations folded into this message:</p><ul>${_.map(v=>`<li><a href="${b(n)}/operator/${v.id}">#${v.id}</a> from ${b(v.from_id)} (queued ${fe(v.created_ts)})${v.retracted_ts?` \u2014 <strong>Retracted</strong>: \u201C${b(v.retracted_reason)}\u201D`:""}</li>`).join("")}</ul></section>`);let T=`<p><a href="${b(n)}/operator">Operator inbox</a></p>
560
+ ${b(W.answer_text)}</pre><p id="comm-response-truncation">${W.truncated?`Truncated: ${W.byteLength} of ${W.totalBytes} bytes. No continuation endpoint is available.`:`${W.byteLength} bytes returned.`}</p>`:`<p id="comm-response-meta"></p><pre id="comm-response" hidden></pre><p id="comm-response-truncation"></p><p id="comm-response-none">${ae?"":"No correlated answer recorded yet. Refresh to check again."}</p>`}</article></section><div id="assigned-work">${g()}</div>`)}),t}import{basename as LO}from"node:path";var Uu=50,IO=e=>e.trim().toLowerCase().replace(/[\s_]+/g,"-"),Fu=e=>["blocked","error","on-hold","rate-limited"].includes(IO(e));function Yy(e){if(!/^[1-9]\d*$/.test(e)||!Number.isSafeInteger(Number(e)))throw new I("INVALID_ARGUMENT","Invalid positive integer ID");return Number(e)}function CO(e){let t={},r=new Set(["q","project","status","kind","team","attention","sort","page"]);for(let[n,o]of new URL(e).searchParams){if(!r.has(n)||Object.hasOwn(t,n)||o.length>256||/[\x00-\x1f\x7f]/.test(o))throw new I("INVALID_ARGUMENT","Invalid or duplicate task filter");t[n]=o}if(t.page&&Yy(t.page)>Ne)throw new I("INVALID_ARGUMENT","Page exceeds safety limit");if(t.attention&&t.attention!=="1")throw new I("INVALID_ARGUMENT","attention must be 1");if(t.sort&&!["id","updated"].includes(t.sort))throw new I("INVALID_ARGUMENT","Unknown task sort");if(t.kind&&!["epic","task","subtask"].includes(t.kind))throw new I("INVALID_ARGUMENT","Unknown task kind");return t}function Vy(e,t){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==""));return e+(r.size?`?${r}`:"")}function OO(e,t,r,n){let o=e.filter(f=>(!t.q||`${f.id} ${f.title} ${f.description} ${f.requirements} ${f.acceptance_criteria}`.toLowerCase().includes(t.q.toLowerCase()))&&(!t.attention||Fu(f.status))&&(!n||f.owner_team_path===n));o.sort(t.sort==="updated"?(f,p)=>Date.parse(p.updated_at)-Date.parse(f.updated_at)||f.id-p.id:(f,p)=>f.id-p.id);let s=Number(t.page||1),i=o.slice((s-1)*Uu,s*Uu),a=new Map(e.map(f=>[f.id,f])),c=f=>{if(f===null)return;let p=a.get(f)??r(f);return a.set(f,p),p},l=new Map(i.map(f=>[f.id,{...f,context:!1}]));for(let f of i){let p=c(f.parent_id),h=new Set([f.id]);for(;p&&!h.has(p.id);)h.add(p.id),l.has(p.id)||l.set(p.id,{...p,context:!0}),p=c(p.parent_id)}let u=new Map;for(let f of l.values()){let p=f.parent_id!==null&&l.has(f.parent_id)?f.parent_id:null,h=u.get(p)??[];h.push(f),u.set(p,h)}let d=[],m=f=>{for(let p of u.get(f)??[])d.push(p),m(p.id)};return m(null),{rows:d,total:o.length,pageNumber:s,more:o.length>s*Uu,byId:a}}function eo(e,t){return Re(`${t}/tasks/${e.id}`,`#${e.id} ${e.title}`)}function Qy(e,t,r){if(e.owner_team_path===null)return"Unassigned";let n=`${LO(e.owner_team_path)}:${e.owner_alias}`,o=`${e.owner_team_path}:${e.owner_alias}`,s=t.get(e.owner_team_path);return s&&e.owner_alias?`<a href="${b(`${r}/sessions/${encodeURIComponent(s)}/${encodeURIComponent(e.owner_alias)}`)}" title="${b(o)}">${b(n)}</a>`:`<span title="${b(o)}">${b(n)}</span>`}function Xy(e){if(e.blocked_on!==null){let t=e.blocked_on==="operator"?"Operator":e.blocked_on;return`<span class="status-chip status-processing" title="blocked_on names who this task is waiting on; independent of the recorded status text">Blocked on ${b(t)}</span>`}if(e.hold_until!==null){let t=Date.parse(e.hold_until)<=Date.now(),r=e.hold_reason?` \u2014 ${b(e.hold_reason)}`:"";return t?`<span class="status-chip status-processing" title="Hold expired ${b(e.hold_until)}; not auto-cleared, needs the owning team to resolve it">Hold expired, evidence due${r}</span>`:`<span class="status-chip status-muted">On hold until ${fe(e.hold_until)}${r}</span>`}return"\u2014"}function Jy(e,t,r,n,o="Task ledger"){return Xn(["Task / hierarchy","Project","Recorded status","Blocked / hold","Recorded owner","Updated","Presentation"],e.map(s=>{let i=[],a=s.parent_id===null?void 0:t.get(s.parent_id),c=new Set([s.id]);for(;a&&!c.has(a.id);)c.add(a.id),i.unshift(a),a=a.parent_id===null?void 0:t.get(a.parent_id);let l=i.map(u=>eo(u,r)).join(" / ");return[`${l?`${l}<br>`:""}${eo(s,r)}${s.context?" <strong>(ancestor context)</strong>":""}<br>${b(s.kind)}`,b(s.project),b(s.status),Xy(s),Qy(s,n,r),fe(s.updated_at),s.kind==="epic"?"Not applicable":s.delivered_ts?`First presented ${fe(s.delivered_ts)}`:"Not recorded"]}),o)}function Ky(e,t,r){let n=["q","project","status"].map(i=>`<label>${{q:"Search",project:"Project",status:"Exact recorded status"}[i]}<input name="${i}" value="${b(e[i]??"")}" maxlength="256"></label>`).join(""),o=(i,a,c)=>`<label>${a}<select name="${i}">${c.map(([l,u])=>`<option value="${b(l)}"${e[i]===l?" selected":""}>${b(u)}</option>`).join("")}</select></label>`,s=[["",`All teams (${t.length} own work in this scope)`],...t.map(i=>[i,i])];return`<form method="get" action="${b(r)}/tasks">${n}${o("kind","Kind",[["","All kinds"],["epic","Epic"],["task","Task"],["subtask","Subtask"]])}${o("team","Owning team",s)}${o("sort","Sort",[["id","ID"],["updated","Updated"]])}<label>Attention only<input type="checkbox" name="attention" value="1"${e.attention?" checked":""}></label><button>Filter tasks</button> ${Re(`${r}/tasks`,"Clear filters")}</form>`}function zy(e){return`<p>${e.total} entities in this scope: ${e.by_kind.epic??0} epics, ${e.by_kind.task??0} tasks, ${e.by_kind.subtask??0} subtasks.</p>`}function Zy(e,t,r=""){let n=r.replace(/\/$/,""),o=(i,a,c,l=200)=>Oe(i,ve(a,c,n,{"data-page":"tasks"}),l),s=(i,a)=>{let c=a instanceof I?a.code==="NOT_FOUND"?404:a.code==="DB_BUSY"?503:a.code==="STORAGE_ERROR"?500:a.code==="CONFLICT"?409:400:500;return o(i,"Tasks unavailable",`<p>${b(a instanceof Error?a.message:String(a))}</p>${Re(`${n}/tasks`,"Task ledger")}`,c)};e.get("/tasks",i=>{try{let a=CO(i.req.url),c;if(a.team){let p=t.teams.find(h=>h.name===a.team&&B(h));if(!p||!B(p))throw new I("INVALID_ARGUMENT","Unknown local owning team");c=Q(p)}let l=Sr(t.db.db,{...a.project?{project:a.project}:{},...a.kind?{kind:a.kind}:{},...a.status?{status:a.status}:{},limit:Ne}),u=Mr(t.teams),d=[...new Set(l.rows.map(p=>p.owner_team_path).filter(p=>p!==null).map(p=>u.get(p)).filter(p=>p!==void 0))].sort();if(l.meta.next_cursor!==null)return o(i,"Tasks",'<p class="warning">This scope exceeds 10,000 entities. Choose a project, kind, or status to narrow it; an incomplete board is not shown.</p>'+Ky(a,d,n),503);let m=OO(l.rows,a,p=>vr(t.db.db,p),c),f=`<nav aria-label="Task pages">${m.pageNumber>1?Re(Vy(`${n}/tasks`,{...a,page:String(m.pageNumber-1)}),"Previous page"):""} ${m.more?Re(Vy(`${n}/tasks`,{...a,page:String(m.pageNumber+1)}),"Next page"):""}</nav>`;return o(i,"Tasks",'<p data-testid="page-intro">Epics group tasks, and tasks can contain subtasks; follow a title to read its details and children. Status and owner are recorded values; Updated means content activity; Attention means blocked, error, on-hold, or rate-limited; First presentation means when the item was first shown to an agent to work on, not completion. Blocked / hold is separate from the recorded status text: it shows when a task is structurally waiting on a specific team or operator, or deliberately parked until a date, even while its own status reads as ordinary active work.</p>'+zy({total:l.rows.length,by_kind:l.rows.reduce((p,h)=>(p[h.kind]=(p[h.kind]??0)+1,p),{})})+Ky(a,d,n)+`<p>${m.total} matching entities. Page ${m.pageNumber}, up to 50 matches plus labeled ancestor context; presentation does not mean completion.</p>`+f+Jy(m.rows,m.byId,n,u)+f)}catch(a){return s(i,a)}}),e.get("/tasks/:id",i=>{try{let a=Yy(i.req.param("id")),c=vr(t.db.db,a),l=Ar(t.db.db,a),u=[],d=c.parent_id,m=new Set([a]);for(;d!==null&&!m.has(d);){m.add(d);let S=vr(t.db.db,d);u.unshift(S),d=S.parent_id}let f=Mr(t.teams),p=new Map([...u,c,...l.children].map(S=>[S.id,S])),h=S=>S.length?`<ul>${S.map(N=>`<li>${eo(N,n)} \u2014 ${b(N.status)}</li>`).join("")}</ul>`:"<p>None recorded.</p>",w=`<nav aria-label="Breadcrumb">${Re(`${n}/tasks`,"Task ledger")} / ${u.map(S=>Re(`${n}/tasks/${S.id}`,`#${S.id} ${S.title} (status: ${S.status})`)).join(" / ")}${u.length?" / ":""}<span aria-current="page">#${c.id} ${b(c.title)}</span></nav>`,_=u.at(-1),T=u.find(S=>S.kind==="epic"),v=`<p data-testid="work-context">${c.kind==="epic"?"This is an epic with no parent.":c.kind==="task"?T?`This is a task in epic ${eo(T,n)}.`:"This is a task with no parent epic.":`This is a subtask${_?` of task ${eo(_,n)}`:""}${T?`, part of epic ${eo(T,n)}.`:"; no parent epic is recorded."}`}</p><p data-testid="page-intro">This page describes one work item and its recorded status and owner. Follow the breadcrumb to its parent or epic, or a child title to drill down; Updated records content activity, not completion.</p>`+w+`<p>Kind: ${b(c.kind)}; project: ${b(c.project)}; recorded status: <strong>${b(c.status)}</strong>.</p><p>Recorded owner: ${Qy(c,f,n)}.</p><p>Blocked / hold: ${Xy(c)}</p>`+["description","requirements","acceptance_criteria"].map(S=>`<h2>${{description:"Description",requirements:"Requirements",acceptance_criteria:"Acceptance criteria"}[S]}</h2><pre>${b(c[S]||"Not supplied")}</pre>`).join("")+zy(kr(t.db.db,{id:a}))+"<h2>Children</h2>"+Jy(l.children,p,n,f,"Immediate children")+"<h2>Depends on</h2>"+h(c.dependencies.outgoing)+"<h2>Required by</h2>"+h(c.dependencies.incoming)+`<h2>Times</h2><p>Created ${fe(c.created_at)}; updated ${fe(c.updated_at)}.</p><p>First presentation: ${c.kind==="epic"?"Not applicable":c.delivered_ts?fe(c.delivered_ts):"Not recorded"}. Presentation does not mean completion.</p>`;return o(i,`Task #${c.id}: ${c.title}`,v)}catch(a){return s(i,a)}})}import{basename as DO}from"node:path";var eE=50,tE='<p data-testid="page-intro">A cron job is work scheduled to run automatically; this page reviews its saved configuration and recorded results. An unresolved escalated run is waiting for a person to help, while execution uncertain means the process has not been confirmed stopped.</p>',MO={ok:"OK (last-fire bookkeeping)",error:"Error",skipped_overlap:"Skipped: earlier execution still guarded",skipped_stale:"Skipped: scheduled window too old",reconciled:"Process gone; outcome unknown",blocked_escalation:"Skipped: unresolved escalation at last check"},nt=e=>e===null?"Not recorded":fe(e),Qe=e=>e===null?"Not configured":b(e),rE=e=>e.last_fire_status===null?"Not recorded":`${b(MO[e.last_fire_status]??e.last_fire_status)} <small>(${b(e.last_fire_status)})</small>`;function nE(e){let t=e.req.queries("after");if(t===void 0)return 0;let r=t[0]??"";if(t.length!==1||!/^(0|[1-9]\d*)$/.test(r)||!Number.isSafeInteger(Number(r)))throw new U("INVALID_ARGUMENT","after must be a nonnegative integer");return Number(r)}function oE(e,t,r){if(e.session_teamfile===null||e.session_alias===null)return"Not configured";let n=`${e.session_teamfile}:${e.session_alias}`,o=`${DO(e.session_teamfile)}:${e.session_alias}`,s=t.get(e.session_teamfile);return s?`<a href="${b(`${r}/sessions/${encodeURIComponent(s)}/${encodeURIComponent(e.session_alias)}`)}" title="${b(n)}">${b(o)}</a>`:`<span title="${b(n)}">${b(o)}</span> (not in the current local registry)`}function sE(e,t){let r=[];return(e.last_fire_status==="error"||e.last_fire_error)&&r.push("Recorded fire error"),e.last_fire_status==="blocked_escalation"&&r.push("Last check blocked by escalation"),e.last_fire_status==="reconciled"&&r.push("Previous execution outcome unknown"),t?.status==="escalated"&&t.escalation_resolved_at===null&&r.push(`Run #${t.id}: escalated \u2014 waiting for a person`),t?.execution_state==="uncertain"&&r.push(`Run #${t.id}: execution uncertain`),t?.status==="failed"&&r.push(`Run #${t.id}: failed; execution still guarded`),r}function qu(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function PO(e){if(e===null)return"<p>No artifacts recorded.</p>";try{let t=JSON.parse(e);if(Array.isArray(t)&&t.every(r=>typeof r=="string"))return t.length?`<ul>${t.map(r=>`<li>${b(r)}</li>`).join("")}</ul>`:"<p>No artifacts recorded.</p>"}catch{}return`<pre>${b(e)}</pre>`}function UO(e){let t=e.status==="escalated",r=t&&e.escalation_resolved_at===null,n=e.status==="failed"||r||e.execution_state==="uncertain",o=`${e.status}${t?r?" \u2014 waiting for a person":" \u2014 escalation resolved":""}`,s=t||e.escalation_reason!==null||e.escalation_resolved_at!==null?"<h4>Escalation</h4>"+qu([["Reason",Qe(e.escalation_reason)],["Requested action",Qe(e.escalation_action)],["Owner",Qe(e.escalation_owner)],["Resolved at",nt(e.escalation_resolved_at)],["Resolution",Qe(e.escalation_resolution)],["Resolved by",Qe(e.escalation_resolution_actor)],["Resolution note",Qe(e.escalation_resolution_note)]]):"";return`<article id="run-${e.id}"${n?' class="warning"':""}><h3>Run #${e.id}: ${b(o)}</h3>`+qu([["Execution state",b(e.execution_state)],["Trigger",b(e.trigger_kind)],["Created",nt(e.created_at)],["Started",nt(e.started_at)],["Finished",nt(e.finished_at)],["Result reported",nt(e.reported_at)],["Last updated",nt(e.updated_at)],["Execution reference",Qe(e.execution_identity)],["Process ID",Qe(e.pid)],["Execution uncertainty reason",Qe(e.execution_uncertain_reason)],["Execution confirmed gone",nt(e.execution_gone_at)],["Confirmation note",Qe(e.execution_confirmation_note)]])+`<h4>Summary</h4><pre>${b(e.summary??"No summary recorded.")}</pre><h4>Artifacts (recorded paths or references)</h4>`+PO(e.artifacts)+s+"</article>"}function iE(e,t,r=""){let n=r.replace(/\/$/,""),o=(a,c,l,u=200)=>Oe(a,ve(c,l,n),u),s=(a,c)=>{let l=c instanceof U?c.code==="NOT_FOUND"?404:c.code==="DB_BUSY"?503:c.code==="INVALID_ARGUMENT"?400:500:500;return o(a,"Cron review unavailable",`<p>${b(c instanceof Error?c.message:String(c))}</p>${Re(`${n}/cron`,"Cron jobs")}`,l)},i=(a,c,l)=>`<nav aria-label="Cron pages">${c?Re(a,"First page"):""} ${l!==null?Re(`${a}?after=${l}`,"Next page"):""}</nav>`;e.get("/cron",a=>{try{let c=nE(a),l=Di(t.db.db,{limit:eE,after:c}),u=Mr(t.teams),d=l.rows.map(f=>({job:f,flags:sE(f,lr(t.db.db,f.id))})),m=(f,p)=>Xn(["Job","Schedule / timezone","Action kind","Enabled","Last fire status","Last fired","Scheduler last looked at","Last fire error","Session"],f.map(({job:h,flags:w})=>[Re(`${n}/cron/${h.id}`,`#${h.id} ${h.title}`)+(w.length?`<p class="warning"><strong>${w.map(b).join("<br>")}</strong></p>`:""),`<code>${b(h.schedule_expr)}</code><br>${b(h.timezone??"Host-local timezone")}`,b(h.action_kind),h.enabled?"Enabled":"Disabled",rE(h),nt(h.last_fired_ts),nt(h.last_checked_ts),h.last_fire_error===null?"None recorded":`<pre>${b(h.last_fire_error)}</pre>`,oE(h,u,n)]),p);return o(a,"Cron jobs",tE+"<p>Saved jobs, up to 50 per page in ID order. Times below are stored scheduler records; OK is not proof of successful AI work. A retained error can predate a later skipped check.</p><h2>Failures and review flags</h2>"+m(d.filter(f=>f.flags.length>0),"Jobs with review flags on this page")+"<h2>Other jobs</h2>"+m(d.filter(f=>f.flags.length===0),"Other jobs on this page")+i(`${n}/cron`,c,l.meta.next_cursor))}catch(c){return s(a,c)}}),e.get("/cron/:id",a=>{try{let c=a.req.param("id");if(!/^[1-9]\d*$/.test(c)||!Number.isSafeInteger(Number(c)))throw new U("INVALID_ARGUMENT","Invalid positive job ID");let l=nE(a),u=Le(t.db.db,Number(c)),d=Ni(t.db.db,{jobId:u.id,limit:eE,after:l}),m=lr(t.db.db,u.id),f=sE(u,m),p=qu([["Title",b(u.title)],["Schedule expression",`<code>${b(u.schedule_expr)}</code>`],["Timezone",b(u.timezone??"Host-local timezone")],["Action kind",b(u.action_kind)],["Enabled",u.enabled?"Enabled":"Disabled"],["Provider",Qe(u.provider)],["Model",Qe(u.model)],["Working directory",Qe(u.working_directory)],["Escalation owner",Qe(u.escalation_owner)],["Session",oE(u,Mr(t.teams),n)],["Session teamfile",Qe(u.session_teamfile)],["Session alias",Qe(u.session_alias)],["Session seeded at",nt(u.session_seeded_at)],["Session generation",b(u.session_generation)],["Scheduler last looked at",nt(u.last_checked_ts)],["Last fired",nt(u.last_fired_ts)],["Last fire status",rE(u)],["Last fire error",u.last_fire_error===null?"None recorded":`<pre>${b(u.last_fire_error)}</pre>`],["Recorded execution since",nt(u.running_since_ts)],["Recorded systemd unit",Qe(u.running_systemd_unit)],["Created",nt(u.created_at)],["Updated",nt(u.updated_at)],["Revision",b(u.revision)]]),h=m?`<p>${Re(`${n}/cron/${u.id}?after=${m.id-1}#run-${m.id}`,`Inspect guarded run #${m.id}`)} \u2014 ${b(m.status)}, execution ${b(m.execution_state)}.</p>`:"",w=l?"<p>No more run records after this cursor.</p>":"<p>No run history recorded. Command or script jobs may have last-fire records without run history; an empty history is not itself an error.</p>";return o(a,`Cron job #${u.id}: ${u.title}`,tE+`<p>${Re(`${n}/cron`,"All cron jobs")}</p>`+(f.length?`<p class="warning"><strong>${f.map(b).join("<br>")}</strong></p>`:"")+h+"<h2>Configuration</h2>"+p+`<h3>Action payload (command, script, prompt, or enqueue data)</h3><pre>${b(u.action_payload)}</pre><h2>Run history</h2><p>Up to 50 recorded runs, oldest ID first. Outcome and process state are separate: active is recorded as active, uncertain is not confirmed stopped, and gone is confirmed stopped.</p>`+(d.rows.length?d.rows.map(UO).join(""):w)+i(`${n}/cron/${u.id}`,l,d.next_cursor))}catch(c){return s(a,c)}})}function FO(e,t){return t===null&&e.retracted_ts===null&&(e.status==="pending"||e.status==="escalating"||e.status==="sent"||e.status==="retrieved")}var cE=64*1024;async function qO(e){if(!e.req.header("content-type")?.toLowerCase().startsWith("application/x-www-form-urlencoded"))throw new I("INVALID_ARGUMENT","Expected a browser form.");let t=e.req.raw.body?.getReader();if(!t)throw new I("INVALID_ARGUMENT","Missing form.");let r=0,n=[];for(;;){let{done:i,value:a}=await t.read();if(i)break;if(r+=a.byteLength,r>cE)throw await t.cancel(),new I("INVALID_ARGUMENT","Form exceeds the size limit.");n.push(a)}let s=new URLSearchParams(Buffer.concat(n).toString("utf8")).getAll("answer");if(s.length!==1)throw new I("INVALID_ARGUMENT","Missing or duplicate answer field.");return s[0]}function lE(e,t){let r=[t.from_id,t.to_id,t.escalation_only,t.to_alias],o=e.prepare("SELECT MIN(id) AS id FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND id > ? AND status != 'merged'").get(...r,t.id).id??Number.MAX_SAFE_INTEGER;return e.prepare("SELECT * FROM queue WHERE from_id = ? AND to_id = ? AND escalation_only = ? AND to_alias IS ? AND status = 'merged' AND id > ? AND id < ?").all(...r,t.id,o)}function uE(e,t){let r=[];t.retracted_ts!==null&&t.retracted_reason&&r.push(t.retracted_reason);let n=lE(e,t);for(let o of n)o.retracted_ts!==null&&o.retracted_reason&&r.push(o.retracted_reason);return r}function ju(e,t=Date.now()){return zo(e,t).map(n=>{let o=n.row,s=nn(e,o),i=Ko(e,o),a=n.ageMs>=Xo||s>=2&&o.sent_ts===null,c=uE(e,o);return{row:o,constituentCount:s,retractedCount:i,urgent:a,retractedReasons:c}})}function dE(e){return e===1?"1 of 1":`${e} merged into this one`}function jO(e){return e==="merged"||e==="informational"||e==="retracted"}function HO(e){return e.lifecycle==="queued"?"queued":e.lifecycle==="processing"?"processing":jO(e.lifecycleBasis)?"muted":"replied"}function BO(e){return e.lifecycle==="queued"?"Queued":e.lifecycle==="processing"?"Processing":e.lifecycleBasis==="merged"?"Combined":e.lifecycleBasis==="informational"?"Informational":e.lifecycleBasis==="retracted"?"Retracted":"Replied"}function mE(e){return`<span class="status-chip status-${HO(e)}" title="${b(Hu(e))}">${b(BO(e))}</span>`}function Hu(e){return e.lifecycle==="queued"?"Queued \u2014 waiting for handling":e.lifecycle==="processing"?e.lifecycleBasis==="confirmed"?"Processing \u2014 picked up by inbox":"Processing \u2014 delivery attempted; read not confirmed":e.lifecycle==="finished"?e.lifecycleBasis==="retracted"?"Finished \u2014 retracted":e.lifecycleBasis==="merged"?"Finished \u2014 combined with another prompt":e.lifecycleBasis==="informational"?"Finished \u2014 informational, no answer expected":"Finished \u2014 answer recorded":`${e.lifecycle} (${e.lifecycleBasis})`}function WO(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function GO(e){return e.length===0?"<p>No standing decisions recorded.</p>":e.map(t=>{let r=t.would_change_it?`<p><strong>Would change this:</strong> ${b(t.would_change_it)}</p>`:"<p><strong>Would change this:</strong> Not recorded.</p>",n=t.affects.length>0?t.affects.map(b).join(", "):"Not recorded";return`<article aria-label="Decision #${t.id}"><h3>${b(t.subject)}</h3><p>${b(t.decision)}</p>${r}<details><summary>Reasoning</summary><p>${b(t.reasoning)}</p></details><p>Decided by ${b(t.decided_by)}, ${fe(t.decided_at)}. Affects: ${n}.</p></article>`}).join("")}function VO(e){return e.length===0?"<p>Nothing blocking math right now.</p>":e.map(t=>`<article aria-label="Blocked #${t.id}"><h3>!!! ${b(t.title)}</h3><p>Category: ${b(t.category)}.</p>${t.detail?`<p>${b(t.detail)}</p>`:""}<p>Raised by ${b(t.raised_by)}, ${fe(t.raised_at)}.</p></article>`).join("")}function JO(e,t){return e.length===0?"<p>No open judgment calls for the operator.</p>":e.map(r=>{let n=r.downstream?`<p><strong>Downstream:</strong> ${b(r.downstream)}</p>`:"<p><strong>Downstream:</strong> Not recorded.</p>";return`<article aria-label="Ask #${r.id}"><h3>${b(r.subject)}</h3><p>${b(r.reason)}</p>${n}<p>Status: Open. Raised by ${b(r.raised_by)}, ${fe(r.raised_at)}.</p><p><a href="${b(t)}/comm/math?ask=${r.id}#compose">Discuss this with math</a></p></article>`}).join("")}function aE(e,t,r,n){if(e.length===0)return`<p>No ${t.toLowerCase()}.</p>`;let o=["Prompt","From","Age","Constituents","Retractions","Lifecycle"],s=e.map(i=>{let a=i.row,c=Ce(n,a.id),l=vt(a,c),u=`<a href="${b(r)}/operator/${a.id}">#${a.id}</a>`,d=b(a.from_id),m=fe(a.created_ts),f=dE(i.constituentCount),p=i.retractedCount>0?`${i.retractedCount} retracted${i.retractedReasons.length>0?`: ${i.retractedReasons.map(w=>`\u201C${b(w)}\u201D`).join("; ")}`:""}`:"\u2014",h=`${mE(l)} \xB7 ${b(Hu(l))}`;return[u,d,m,f,p,h]});return Xn(o,s,t)}function fE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/operator",o=>{try{let s=ju(t.db.db,Date.now()),i=s.filter(w=>w.urgent),a=s.filter(w=>!w.urgent),c='<p data-testid="page-intro">What needs the operator, what math has already decided for them to review, and a way to reach math directly. Blocked means math is technically incapable of proceeding (re-auth, billing, account identity) -- rare and urgent. Escalations are requests a team sent that genuinely need a decision, shown whether or not anyone is currently monitoring them; urgent means waiting over four hours, or never delivered despite repeated sends. Constituents counts how many separate escalations were folded into one message; Retractions counts how many of those the sender has since withdrawn, with their stated reason. Asks are judgment calls only the operator can make, routine, not urgent -- problem statement, then what it affects downstream, then who raised it. Decisions are rulings math has already made, for review, not approval.</p>',l=`<section class="warning" aria-label="Urgent escalations"><h2>Urgent escalations</h2>${aE(i,"Urgent escalations",n,t.db.db)}</section>`,u=`<section aria-label="Routine escalations"><h2>Routine escalations</h2>${aE(a,"Routine escalations",n,t.db.db)}</section>`,d=`<section aria-label="Send a message"><h2>Send a message</h2><p>Start a new request to math. This reuses the same queue and composer as <a href="${b(n)}/comm/math">the Math inbox</a> -- one write path, not a second one.</p><p><a href="${b(n)}/comm/math#compose">Write a message to math</a></p></section>`,m,f,p;try{let w=pa(),_,T,E;try{_=By(w),T=jy(w),E=qy(w)}finally{w.close()}m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${VO(_)}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${JO(T,n)}</section>`,p=`<section aria-label="Decisions"><h2>Decisions</h2><p>Rulings math has already made, in force now (superseded and reversed decisions are excluded). Nothing here waits on you -- read, and ping math if you disagree.</p>${GO(E)}</section>`}catch(w){let _=`<p class="warning">lmteam data unavailable: ${b(w instanceof Error?w.message:String(w))}</p>`;m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${_}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${_}</section>`,p=`<section aria-label="Decisions"><h2>Decisions</h2>${_}</section>`}let h=`${c}${m}${l}${f}${d}${u}${p}`;return Oe(o,ve("Operator inbox",h,n,{"data-page":"operator"},[],!0))}catch(s){return Oe(o,ve("Operator inbox unavailable",`<p>${b(s instanceof Error?s.message:String(s))}</p>`,n,{},[],!0),500)}}),e.get("/operator/:id",o=>{let s=o.req.param("id"),i=Number(s);if(!s||!/^[1-9]\d*$/.test(s)||!Number.isSafeInteger(i))return Oe(o,ve("Invalid escalation ID",`<p>Invalid escalation ID.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),400);try{let a=Er(t.db.db,i);if(!a||a.to_id!=="operator")return Oe(o,ve("Not found",`<p>No operator escalation at this address.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),404);let c=Or(t,i),l=Ce(t.db.db,i),u=vt(a,l),d=nn(t.db.db,a),m=Ko(t.db.db,a),f=uE(t.db.db,a),p=[["From",b(a.from_id)],["To",b(a.to_id)],["Queued",fe(a.created_ts)],["Lifecycle",`${mE(u)} \xB7 ${b(Hu(u))}`],["Constituents",b(dE(d))],["Delivery attempted",a.sent_ts?fe(a.sent_ts):"not recorded"],["Picked up",a.retrieved_ts?fe(a.retrieved_ts):"not recorded"],["Subject",a.subject_id?b(a.subject_id):"none"]];m>0&&p.push(["Retractions",`${m} retracted${f.length>0?`: ${f.map(v=>`\u201C${b(v)}\u201D`).join("; ")}`:""}`]),a.retracted_ts!==null&&(p.push(["Retracted at",fe(a.retracted_ts)]),p.push(["Retraction reason",b(a.retracted_reason??"(none)")]));let h="";c?.status==="available"?h=`<pre>${b(c.text)}</pre><p>${c.truncated?`Preview truncated (${c.byteLength} bytes).`:`Full content (${c.byteLength} bytes).`}</p>`:h=`<p>Prompt preview unavailable (${b(c?.status??"missing")}).</p>`;let w="";l?w=`<section><h2>Answer</h2><p>Recorded ${fe(l.answered_at)}</p><pre>${b(l.answer_text)}</pre></section>`:FO(a,l)&&(w=`<section aria-label="Answer"><h2>Answer</h2><form method="post" action="${b(n)}/operator/${i}/answer"><label for="answer">Answer text</label><textarea id="answer" name="answer" rows="8" maxlength="${cE}" required></textarea><button>Send answer</button></form></section>`);let _=lE(t.db.db,a),T="";_.length>0&&(T=`<section><h3>Merged constituents (${_.length})</h3><p>Additional escalations folded into this message:</p><ul>${_.map(v=>`<li><a href="${b(n)}/operator/${v.id}">#${v.id}</a> from ${b(v.from_id)} (queued ${fe(v.created_ts)})${v.retracted_ts?` \u2014 <strong>Retracted</strong>: \u201C${b(v.retracted_reason)}\u201D`:""}</li>`).join("")}</ul></section>`);let E=`<p><a href="${b(n)}/operator">Operator inbox</a></p>
561
561
  <p data-testid="page-intro">One escalation addressed to the operator. Constituents counts how many separate escalations were folded into this message; Retractions, if shown, counts how many of those the sender has since withdrawn, with their stated reason.</p>
562
- <section aria-label="Escalation metadata"><h2>Metadata</h2>${PO(p)}</section>
562
+ <section aria-label="Escalation metadata"><h2>Metadata</h2>${WO(p)}</section>
563
563
  <article aria-label="Prompt content"><h2>Prompt content</h2>${h}</article>
564
564
  ${w}
565
- ${E}`;return Oe(o,ve(`Operator escalation #${i}`,T,n,{"data-page":"operator-detail"},[],!0))}catch(a){return Oe(o,ve("Operator escalation unavailable",`<p>${b(a instanceof Error?a.message:String(a))}</p>`,n,{},[],!0),500)}}),e.post("/operator/:id/answer",async o=>{let s=o.req.param("id"),i=Number(s);if(!s||!/^[1-9]\d*$/.test(s)||!Number.isSafeInteger(i))return Oe(o,ve("Invalid escalation ID",`<p>Invalid escalation ID.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),400);try{let a=await CO(o);return sn(t.db.db,i,"operator",a),o.redirect(`${n}/operator/${i}`,303)}catch(a){let c=a instanceof L?a.code==="NOT_FOUND"?404:a.code==="CONFLICT"?409:400:500;return Oe(o,ve("Answer not recorded",`<p>${b(a instanceof Error?a.message:String(a))}</p><p><a href="${b(n)}/operator/${i}">Back to escalation #${i}</a></p>`,n,{},[],!0),c)}})}function lE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/",o=>{try{let s=new Date().toISOString(),i=Ar(t.db.db),a=Object.entries(i.by_status).reduce((_,[E,T])=>_+(Mu(E)?T:0),0),c=Uu(t.db.db,Date.now()).filter(_=>_.urgent),l=c.length>0?`<section class="warning" role="alert" data-testid="operator-urgent-alert"><p><strong>Urgent operator attention required:</strong> ${Re(`${n}/operator`,`${c.length} urgent escalation${c.length===1?"":"s"} awaiting operator answer`)}.</p></section>`:"",u=Bo(),d=["epic","task","subtask"].map(_=>Re(`${n}/tasks?kind=${_}`,`${i.by_kind[_]??0} ${_}s`)).join(", "),m=u.report===null?"<p>Activity has not yet been observed; running, dead, and idle counts are unknown.</p>":`<p>As of ${u.observedAt?fe(u.observedAt):"an unknown time"}, from the last successful scheduled observation: ${u.report.running.length} running, ${u.report.dead.length} dead, ${u.report.idle.length} idle invocation records.</p>`,f=u.lastError?`<p class="warning">Observer failed${u.lastErrorAt?` ${fe(u.lastErrorAt)}`:""}: ${b(u.lastError)}. ${u.report?"The counts retain the last successful observation.":"No successful observation is available."}</p>`:"",p=t.teams.filter(H),h="";if(u.report!==null){let _=u.report,E=[..._.running,..._.dead,..._.idle],T=p.filter(v=>!E.some(S=>_n(v,S.target)));if(T.length>0){let v=T.map(S=>`<li>${b(S.name)}: ${b(Vo(Ji(t.db.db,S,_,Date.now(),{allLocalTeams:p})))}</li>`).join("");h=`<p>${T.length} local team${T.length===1?"":"s"} in no running, dead, or idle record above \u2014 absent, not necessarily stalled; each line names the specific reason nobody has looked recently, when one is known:</p><ul>${v}</ul>`}}let w=`${l}<p data-testid="page-intro">Work is organized as epics \u2192 tasks \u2192 subtasks in the ${Re(`${n}/tasks`,"task board")}; actors are sessions that receive prompts and produce answers, visible through ${Re(`${n}/running`,"activity and session links")} and the ${Re(`${n}/comm/math`,"Math inbox")}. Recorded ownership connects work to an actor, while a recorded answer does not by itself mean the work is complete.</p>
565
+ ${T}`;return Oe(o,ve(`Operator escalation #${i}`,E,n,{"data-page":"operator-detail"},[],!0))}catch(a){return Oe(o,ve("Operator escalation unavailable",`<p>${b(a instanceof Error?a.message:String(a))}</p>`,n,{},[],!0),500)}}),e.post("/operator/:id/answer",async o=>{let s=o.req.param("id"),i=Number(s);if(!s||!/^[1-9]\d*$/.test(s)||!Number.isSafeInteger(i))return Oe(o,ve("Invalid escalation ID",`<p>Invalid escalation ID.</p><p><a href="${b(n)}/operator">Operator inbox</a></p>`,n,{},[],!0),400);try{let a=await qO(o);return sn(t.db.db,i,"operator",a),o.redirect(`${n}/operator/${i}`,303)}catch(a){let c=a instanceof I?a.code==="NOT_FOUND"?404:a.code==="CONFLICT"?409:400:500;return Oe(o,ve("Answer not recorded",`<p>${b(a instanceof Error?a.message:String(a))}</p><p><a href="${b(n)}/operator/${i}">Back to escalation #${i}</a></p>`,n,{},[],!0),c)}})}function pE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/",o=>{try{let s=new Date().toISOString(),i=kr(t.db.db),a=Object.entries(i.by_status).reduce((_,[T,E])=>_+(Fu(T)?E:0),0),c=ju(t.db.db,Date.now()).filter(_=>_.urgent),l=c.length>0?`<section class="warning" role="alert" data-testid="operator-urgent-alert"><p><strong>Urgent operator attention required:</strong> ${Re(`${n}/operator`,`${c.length} urgent escalation${c.length===1?"":"s"} awaiting operator answer`)}.</p></section>`:"",u=Jo(),d=["epic","task","subtask"].map(_=>Re(`${n}/tasks?kind=${_}`,`${i.by_kind[_]??0} ${_}s`)).join(", "),m=u.report===null?"<p>Activity has not yet been observed; running, dead, and idle counts are unknown.</p>":`<p>As of ${u.observedAt?fe(u.observedAt):"an unknown time"}, from the last successful scheduled observation: ${u.report.running.length} running, ${u.report.dead.length} dead, ${u.report.idle.length} idle invocation records.</p>`,f=u.lastError?`<p class="warning">Observer failed${u.lastErrorAt?` ${fe(u.lastErrorAt)}`:""}: ${b(u.lastError)}. ${u.report?"The counts retain the last successful observation.":"No successful observation is available."}</p>`:"",p=t.teams.filter(B),h="";if(u.report!==null){let _=u.report,T=[..._.running,..._.dead,..._.idle],E=p.filter(v=>!T.some(S=>_n(v,S.target)));if(E.length>0){let v=E.map(S=>`<li>${b(S.name)}: ${b(Yo(Yi(t.db.db,S,_,Date.now(),{allLocalTeams:p})))}</li>`).join("");h=`<p>${E.length} local team${E.length===1?"":"s"} in no running, dead, or idle record above \u2014 absent, not necessarily stalled; each line names the specific reason nobody has looked recently, when one is known:</p><ul>${v}</ul>`}}let w=`${l}<p data-testid="page-intro">Work is organized as epics \u2192 tasks \u2192 subtasks in the ${Re(`${n}/tasks`,"task board")}; actors are sessions that receive prompts and produce answers, visible through ${Re(`${n}/running`,"activity and session links")} and the ${Re(`${n}/comm/math`,"Math inbox")}. Recorded ownership connects work to an actor, while a recorded answer does not by itself mean the work is complete.</p>
566
566
  <section><h2>Work</h2><p>Task-ledger counts read when this page loaded ${fe(s)}: ${i.total} work items \u2014 ${d}.</p>
567
567
  <p>${Re(`${n}/tasks?attention=1`,`${a} work items needing attention`)} across all kinds: recorded statuses blocked, error, on-hold, or rate-limited.</p></section>
568
568
  <section><h2>Actors and activity</h2><p>${t.teams.length} teams in the current registry at page load. Teams group actors; the counts below describe invocation records, not a team or session roster.</p>
569
569
  ${m}${f}<p>${Re(`${n}/running`,"Open Running / Dead / Idle")}. Running means work in flight, Dead means its process stopped, and Idle means a finished invocation.</p>
570
- ${h}<p>This page loaded ${fe(s)}; the activity snapshot is separate and may be older. Refreshing this page does not trigger a new activity scan.</p></section>`;return Oe(o,ve("Overview",w,n,{},[],!0))}catch(s){return Oe(o,ve("Overview unavailable",`<p>${b(s instanceof Error?s.message:String(s))}</p>`,n,{},[],!0),500)}})}function jO(e,t,r){return`${r.replace(/\/$/,"")}/api/session/${encodeURIComponent(e)}/${encodeURIComponent(t)}?limit=20`}function uE(e,t,r,n={}){let o=r.replace(/\/$/,"");if(o&&(!o.startsWith("/")||o.startsWith("//")||/[?#\\]/.test(o)))throw new Error("Invalid mount path");let s=n.commPageEnabled===!0?`<a href="${b(o)}/comm/math">Math inbox \u2014 review and send</a>`:"",i=n.commEnabled===!0&&e==="math"&&t==="Lead";return`<section id="session-detail" data-canonical-teamfile="${b(n.canonicalTeamfile??"")}" data-comm-page-enabled="${n.commPageEnabled===!0}" data-comm-enabled="${i}" data-team="${b(e)}" data-alias="${b(t)}" data-mount="${b(o)}" data-history="${b(jO(e,t,o))}">
570
+ ${h}<p>This page loaded ${fe(s)}; the activity snapshot is separate and may be older. Refreshing this page does not trigger a new activity scan.</p></section>`;return Oe(o,ve("Overview",w,n,{},[],!0))}catch(s){return Oe(o,ve("Overview unavailable",`<p>${b(s instanceof Error?s.message:String(s))}</p>`,n,{},[],!0),500)}})}function KO(e,t,r){return`${r.replace(/\/$/,"")}/api/session/${encodeURIComponent(e)}/${encodeURIComponent(t)}?limit=20`}function hE(e,t,r,n={}){let o=r.replace(/\/$/,"");if(o&&(!o.startsWith("/")||o.startsWith("//")||/[?#\\]/.test(o)))throw new Error("Invalid mount path");let s=n.commPageEnabled===!0?`<a href="${b(o)}/comm/math">Math inbox \u2014 review and send</a>`:"",i=n.commEnabled===!0&&e==="math"&&t==="Lead";return`<section id="session-detail" data-canonical-teamfile="${b(n.canonicalTeamfile??"")}" data-comm-page-enabled="${n.commPageEnabled===!0}" data-comm-enabled="${i}" data-team="${b(e)}" data-alias="${b(t)}" data-mount="${b(o)}" data-history="${b(KO(e,t,o))}">
571
571
  <p>Session: <strong>${b(e)}:${b(t)}</strong>. ${t==="Lead"?"Role: lead.":"Role not recorded."} lmauto hosts this page; the session\u2019s team is ${b(e)}.</p>
572
572
  <p id="session-purpose">Team purpose is not loaded in this HTML view; JavaScript loads it automatically.</p>
573
573
  <p><a href="${b(o)}/running">Observed activity</a> \xB7 <a href="${b(o)}/tasks">Work items</a></p>
@@ -585,48 +585,48 @@ ${s?`<p>This timeline shows incoming and outgoing exchanges. ${s} opens requests
585
585
  <script>(function () {
586
586
  // tsx preserves names using an injected helper; keep serialized source self-contained.
587
587
  function __name(value) { return value; }
588
- return (${HO.toString()})();
589
- })();</script>`}function HO(){let e=document.getElementById("session-detail"),{team:t="",alias:r="",mount:n="",history:o="",canonicalTeamfile:s="",commEnabled:i="false",commPageEnabled:a="false"}=e.dataset,c=D=>document.getElementById(D),l=(D,j)=>{c(D).textContent=j},u=(D,j)=>{let Y=document.createElement(D);return Y.textContent=j,Y},d=new Map,m=!1,f=0,p,h=null,w=0,_=0,E=null,T=null,v=D=>!m&&!document.hidden&&D===f,S=()=>{},N=[],x=!1;function I(D){let j=u("span",D),Y=N.find(K=>K.name===D);if(!Y){let K=x?"Recorded label; current actor unresolved":"Recorded label; current team list unavailable";return j.title=`${D} \u2014 ${K}`,/[\\/]/.test(D)&&(j.textContent=D.split(/[\\/]/).at(-1).replace(/\.lmctl(?=:|$)/,"")),j}if(Y.channel==="lmmail")return j.textContent+=" (remote inbox)",j;if(Y.channel==="local"&&Y.leadAlias&&D!=="operator"){let K=u("a",`${Y.name}:${Y.leadAlias}`);K.title="Current configured inbox lead; not a historical sender session",j.textContent="",K.href=`${n}/sessions/${encodeURIComponent(Y.name)}/${encodeURIComponent(Y.leadAlias)}`,j.append(K)}return j}function k(D,j){let Y=u("span","");return Y.append(I(D),u("span"," \u2192 "),I(j)),Y}let B=D=>`${n}/sessions/${encodeURIComponent(t)}/${encodeURIComponent(r)}?queue=${D}`,C=D=>D instanceof Error?D.message:String(D);async function g(D,j){let Y=new AbortController;d.set(Y,j===void 0);let K=setTimeout(()=>Y.abort(),15e3);try{let re=await fetch(D,{method:j===void 0?"GET":"POST",signal:Y.signal,credentials:"same-origin",cache:"no-store",redirect:"error",headers:{Accept:"application/json",...j===void 0?{}:{"Content-Type":"application/json"}},...j===void 0?{}:{body:JSON.stringify(j)}});if(!re.ok)throw new Error(`HTTP ${re.status}; request unsuccessful`);if(!re.headers.get("content-type")?.includes("application/json"))throw new Error("Expected JSON response");let te=re.body.getReader(),ue=new TextDecoder,$e=0,be="";for(;;){let z=await te.read();if(z.done)break;if($e+=z.value.byteLength,$e>2e6)throw await te.cancel(),new Error("Response exceeds 2 MB limit");be+=ue.decode(z.value,{stream:!0})}return JSON.parse(be+ue.decode())}finally{clearTimeout(K),d.delete(Y)}}function y(D){return D==="merged"||D==="informational"||D==="retracted"}function R(D,j=!1){if(j){if(D.lifecycle==="queued")return"queued";if(D.lifecycle==="finished")return D.lifecycleBasis==="merged"?"finished \xB7 merged into an earlier message":D.lifecycleBasis==="informational"?"finished \xB7 informational, no reply expected":D.lifecycleBasis==="retracted"?"finished \xB7 retracted, no reply expected":"finished \xB7 reply recorded";if(D.lifecycle==="processing")return D.lifecycleBasis==="confirmed"?"processing \xB7 picked up":"processing \xB7 attempted"}if(D.lifecycle==="finished")return D.lifecycleBasis==="merged"?"finished \u2014 merged into an earlier message, no separate response":D.lifecycleBasis==="informational"?"finished \u2014 informational, no response expected":D.lifecycleBasis==="retracted"?"finished \u2014 retracted, no response expected":"finished \u2014 response recorded";if(D.lifecycle==="queued")return"queued \u2014 waiting for handling";if(D.lifecycle==="processing")return D.lifecycleBasis==="confirmed"?"processing \u2014 picked up by inbox":"processing \u2014 delivery attempted; read not confirmed";throw new Error("Unknown lifecycle in owner response")}let P=null,J=D=>D!==null&&typeof D=="object"&&!Array.isArray(D),ee=(D,j)=>typeof D=="string"&&D.trim()?D:j,oe=!1;async function V(){if(!oe||P===f||m||document.hidden)return;let D=f;P=D,c("session-refresh").disabled=!0;try{let j=await g(o);if(!v(D))return;if(!J(j)||!Array.isArray(j.messages))throw new Error("Recent messages were not supplied by the history source");let Y=j.messages.slice(-20).map(K=>{let re=J(K)?K:{},te=re.content==null?"Message content not recorded.":typeof re.content=="string"?re.content:JSON.stringify(re.content),ue=u("article","");return ue.append(u("h3",ee(re.role,"Unknown role")),u("p",ee(re.timestamp,"Time not recorded.")),u("pre",te)),ue});c("session-history").dataset.state="ready",c("session-history").replaceChildren(...Y.length?Y:[u("p","No recent messages returned.")]),l("session-history-status",`Latest ${Y.length} messages.${j.truncated===!0?" Older messages are not shown.":""}`),l("session-source",`Provider ${ee(j.provider,"not recorded")}; session ${ee(j.sessionId,"not recorded")}. Optional bounded provider tail. ${j.truncated===!0?"Older output truncated. ":""}Fetched ${new Date().toISOString()}.`)}catch(j){v(D)&&(c("session-history").dataset.state="error",c("session-history").children.length===0&&c("session-history").replaceChildren(u("p","Recent messages unavailable.")),l("session-history-status","Recent messages unavailable. Try Refresh transcript."),l("session-source",`History unavailable; previous content may be stale. ${C(j)}`))}finally{P===D&&(P=null),v(D)&&(c("session-refresh").disabled=!1)}}async function se(){if(!s||m||document.hidden)return;let D=f;try{let j=new URLSearchParams({ownerTeam:s,ownerAlias:r,limit:"20"}),Y=await g(`${n}/api/tasks?${j}`);if(!v(D))return;if(!Array.isArray(Y.rows))throw new Error("Invalid task response");c("session-tasks").replaceChildren(u("p","Up to 20 assigned work items."),...Y.rows.slice(0,20).map(K=>{let re=u("a",`#${K.id} ${K.title} \u2014 ${K.kind}, ${K.status}`);re.href=`${n}/tasks/${Number(K.id)}`;let te=u("p","");if(te.append(re),Number.isSafeInteger(K.parent_id)&&K.parent_id>0){let ue=u("a",` Parent work item #${K.parent_id}`);ue.href=`${n}/tasks/${K.parent_id}`,te.append(ue)}return te}),...Y.rows.length?[]:[u("p","No recorded assignment for this session.")])}catch(j){v(D)&&l("session-tasks",`Assigned work unavailable: ${C(j)}`)}}async function $(){if(E===w||h===null||m||document.hidden)return;E=w;let D=h,j=w,Y=f;try{let K=await g(`${n}/api/queue/${D}/state`);if(j!==w||!v(Y))return;if(K.id!==D)throw new Error("Queue identity mismatch");if(K.lifecycle==="finished"&&!y(K.lifecycleBasis)&&!K.answer)throw new Error("Finished state has no correlated response");if(K.answer&&K.answer.prompt_queue_id!==D)throw new Error("Answer correlation mismatch");c("comm-state").dataset.queueId=String(D),c("comm-state").dataset.lifecycle=K.lifecycle,c("comm-state").dataset.lifecycleBasis=K.lifecycleBasis,l("comm-state",`Queue #${D}: ${R(K)}. Created ${K.createdAt}. Last checked ${new Date().toISOString()}.`),K.answer?l("comm-response",`${K.answer.answer_text}
590
- ${K.answer.truncated?`Truncated response; ${K.answer.totalBytes} total bytes. No continuation endpoint available.`:""}`):l("comm-response",K.lifecycleBasis==="merged"?"No separate answer: prompt merged into another prompt.":K.lifecycleBasis==="informational"?"No answer expected: this was an informational prompt.":K.lifecycleBasis==="retracted"?"No answer expected: this prompt was retracted.":"Outcome unknown: no reply recorded. This does not establish failure or unread work."),K.lifecycle!=="finished"&&++_<60?p=setTimeout(()=>void $(),5e3):K.lifecycle!=="finished"&&l("comm-state",`Queue #${D}: observation stalled \u2014 automatic checks paused after 60 reads; last state ${R(K)}. Check again manually. This does not establish execution failure.`)}catch(K){j===w&&v(Y)&&l("comm-state",`State check failed; last content may be stale. ${C(K)}. Check again manually.`)}finally{E===j&&(E=null)}}async function O(D,j=!1){if(!Number.isSafeInteger(D)||D<1||m||document.hidden)return;c("comm-reading-panel").hidden=!1,T={id:D,admitted:j},clearTimeout(p),h=null,w++,_=0;let Y=w,K=f;delete c("comm-state").dataset.queueId,delete c("comm-state").dataset.lifecycle,delete c("comm-state").dataset.lifecycleBasis,l("comm-context","Loading recorded endpoints. Related task: not recorded; assigned work shown separately."),l("comm-state",`Loading queue #${D}\u2026`),l("comm-response",""),l("comm-preview","Loading request preview\u2026"),c("comm-check").hidden=!1;let re=new URL(location.href);re.searchParams.set("queue",String(D)),window.history.replaceState(null,"",re);try{let te=await g(`${n}/api/queue/${D}`);if(Y!==w||!v(K))return;if(te.queue.id!==D)throw new Error("Queue envelope identity mismatch");if(j&&te.queue.to_id!=="math")throw new Error("Admitted receipt is not addressed to math");if(te.queue.to_id!==t&&te.queue.from_id!==t)throw new Error("Queue message does not belong to this team");h=D;let ue=c("comm-context");if(ue.replaceChildren(u("span",`Request #${D}: `),k(te.queue.from_id,te.queue.to_id),u("span",". Expected reply context: "),I(te.queue.to_id),u("span",` inbox for prompt #${D} from `),I(te.queue.from_id),u("span",". Check the response status below; a reply may not be recorded. Related task: not recorded; assigned work shown separately.")),typeof te.queue.retracted_reason=="string"&&te.queue.retracted_reason&&ue.append(u("span",` Retraction reason: ${te.queue.retracted_reason}.`)),a==="true"&&te.queue.to_id==="math"){let be=u("a","Open full prompt and answer");be.href=`${n}/comm/math/prompts/${D}`,ue.append(be)}let $e=await g(`${n}/api/queue/${D}/preview`);if(Y!==w||!v(K))return;if($e.id!==D)throw new Error("Preview identity mismatch");l("comm-preview",$e.status==="available"?`${$e.text??""}${$e.truncated?`
591
- [Prompt preview truncated]`:""}`:`Prompt preview ${$e.status}; content unavailable.`)}catch(te){Y===w&&v(K)&&(l("comm-preview",`Prompt preview unavailable: ${C(te)}`),h===null&&l("comm-state","Queue selection unavailable; select a message from this team."))}await $()}let A=null;async function q(){if(A===f||m||document.hidden)return;let D=f;A=D,c("comm-refresh").disabled=!0;try{let j=await g(`${n}/api/teams`).catch(()=>null);if(!v(D))return;N=j?.teams??[],x=j!==null;let Y=N.find(z=>z.name===t),K=Y?.channel==="local"&&typeof Y.description=="string"?Y.description.trim():"";l("session-purpose",j===null?"Team purpose unavailable.":K?`Recorded team description: \u201C${K}\u201D`:"No team purpose recorded.");let re=await Promise.all(["to","from"].map(async z=>{let Te=await g(`${n}/api/queue/prompts?${z}=${encodeURIComponent(t)}&limit=20`);if(!Array.isArray(Te.rows))throw new Error("Invalid message list");return Te}));if(!v(D))return;let te=new Map;for(let z of re)for(let Te of z.rows.slice(0,20)){if(!Number.isSafeInteger(Te.id)||Te.id<1)throw new Error("Invalid queue identity");if(Te.to_id!==t&&Te.from_id!==t)throw new Error("Message outside current team");let Ge=te.get(Te.id);(!Ge||Te.lifecycle==="finished"&&Ge.lifecycle!=="finished")&&te.set(Te.id,Te)}let ue=z=>Number.isFinite(Date.parse(z))?Date.parse(z):Number.MAX_VALUE,be=[...te.values()].sort((z,Te)=>ue(z.created_ts)-ue(Te.created_ts)||z.id-Te.id).map(z=>{let Te=u("li","");Te.dataset.queueId=String(z.id);let Ge=u("a",`Read exchange #${z.id}`);Ge.href=B(z.id),Ge.addEventListener("click",we=>{we.defaultPrevented||we.button!==0||we.metaKey||we.ctrlKey||we.shiftKey||we.altKey||(we.preventDefault(),O(z.id))}),Te.append(Ge);let je=u("div","");je.dataset.queueId=String(z.id),je.dataset.event="request";let Ct=Number.isFinite(Date.parse(z.created_ts))?z.created_ts:"Time not recorded; placed last by request ID",G=u("span",z.lifecycle==="queued"?"Queued":z.lifecycle==="processing"?"Processing":z.lifecycleBasis==="merged"?"Combined":z.lifecycleBasis==="informational"?"Informational":z.lifecycleBasis==="retracted"?"Retracted":"Replied");if(G.className=`status-chip status-${z.lifecycle==="queued"?"queued":z.lifecycle==="processing"?"processing":y(z.lifecycleBasis)?"muted":"replied"}`,G.title=R(z),je.append(u("p",`Request recorded: ${Ct}`),k(z.from_id,z.to_id),G),z.from_id===z.to_id&&je.append(u("p","Self-addressed request.")),z.subject_id!=null&&je.append(u("p",`Recorded subject label: ${z.subject_id}`)),Te.append(je),z.lifecycle==="finished"&&!y(z.lifecycleBasis)){let we=u("div","");we.dataset.queueId=String(z.id),we.dataset.event="response",we.append(u("span","Answer recorded in "),I(z.to_id),u("span",` inbox for prompt #${z.id} from `),I(z.from_id),u("p",`Recorded reply time: ${z.answeredAt??"Time not recorded"}`));let st=u("details",""),Ze=u("pre","Open to load the recorded reply.");st.append(u("summary","Show reply"),Ze);let ft=!1,Ve=!1;st.addEventListener("toggle",async()=>{if(!st.open||ft||Ve||m||document.hidden)return;let mn=f;Ve=!0,Ze.textContent="Loading reply\u2026";try{let gr=await g(`${n}/api/queue/${z.id}/state`);if(!v(mn))return;let or=gr.answer;if(gr.id!==z.id||or===null||or.prompt_queue_id!==z.id)throw new Error("Answer identity mismatch");if(typeof or.answer_text!="string")throw new Error("Reply text unavailable");let et=Array.from(or.answer_text);Ze.textContent=et.slice(0,1200).join("")+(et.length>1200||or.truncated?`
592
- [Reply excerpt; open the full exchange for available text.]`:""),ft=!0}catch(gr){v(mn)&&(Ze.textContent=`Reply unavailable: ${C(gr)}. Close and reopen to retry.`)}finally{Ve=!1}}),we.append(st),Te.append(we)}else Te.append(u("p",z.lifecycleBasis==="merged"?"No separate answer: prompt merged into another prompt.":z.lifecycleBasis==="informational"?"No answer expected: this was an informational prompt.":z.lifecycleBasis==="retracted"?`No answer expected: this prompt was retracted. Reason: ${z.retracted_reason??"no reason recorded"}.`:"Reply: not recorded"));return Te});c("comm-sequence").replaceChildren(...be.slice(-5)),c("comm-older-sequence").replaceChildren(...be.slice(0,-5)),c("comm-older").hidden=be.length<=5,l("comm-older-label",`Show ${Math.max(0,be.length-5)} older loaded prompts`),l("comm-coverage",`Showing newest ${Math.min(5,be.length)} of ${te.size} loaded prompts, ordered by arrival, oldest first; answers are grouped with their prompts. ${re.some(z=>z.meta.next_cursor!==null)?"This is a limited sample; additional records have not been loaded.":"All prompts from the returned pages are available here."}`)}catch(j){v(D)&&l("comm-coverage",`Message context unavailable; previous events may be stale. ${C(j)}`)}finally{A===D&&(A=null),v(D)&&(c("comm-refresh").disabled=!1)}}let M=c("comm-form");if(M&&i==="true"&&t==="math"&&r==="Lead"){let D=c("comm-draft"),j=c("comm-submit"),Y=c("comm-confirm"),K=c("comm-edit"),re=null,te=!1,ue=!1,$e="Page paused during admission";S=()=>{m||document.hidden||!re||!ue||(Y.disabled=te,te||(l("comm-send-status",`Admission uncertain or failed: ${$e}. Retry preserves the exact prompt and dedupe key. Keep this page open until resolved.`),Y.textContent="Retry same prompt safely"))},M.addEventListener("submit",be=>{if(be.preventDefault(),!(m||document.hidden||te||re)){if(!D.value.trim()||new TextEncoder().encode(D.value).length>65536){l("comm-send-status","Enter a nonblank prompt of at most 64 KiB UTF-8.");return}re={to:"math",prompt:D.value,dedupeKey:`localweb:${crypto.randomUUID()}`},D.disabled=!0,j.disabled=!0,l("comm-review",`To math, from operator:
593
- ${re.prompt}`),c("comm-review").hidden=!1,Y.hidden=!1,K.hidden=!1,l("comm-send-status","Review the exact prompt before confirming.")}}),K.addEventListener("click",()=>{te||ue||(re=null,D.disabled=!1,j.disabled=!1,Y.hidden=!0,K.hidden=!0,c("comm-review").hidden=!0)}),Y.addEventListener("click",async()=>{if(!re||te||m||document.hidden)return;let be=f;te=!0,ue=!0,Y.disabled=!0,K.hidden=!0,l("comm-send-status","Submitting; waiting for confirmation that the prompt was queued\u2026");try{let z=await g(`${n}/api/comm/send`,re);if(!v(be))throw new Error("Page paused before receipt could be shown");if(!Number.isSafeInteger(z.queueId)||z.queueId<1)throw new Error("Missing queue receipt");l("comm-send-status",`Accepted as queue #${z.queueId}${z.replayed?" (existing prompt recovered)":""}.`),re=null,ue=!1,D.value="",D.disabled=!1,j.disabled=!1,Y.hidden=!0,Y.textContent="Confirm send to math",c("comm-review").hidden=!0,O(z.queueId,!0),q()}catch(z){$e=C(z)}finally{te=!1,!m&&!document.hidden&&(Y.disabled=!1),S()}})}c("session-refresh").addEventListener("click",()=>{oe=!0,l("session-refresh","Refresh transcript"),V()}),c("comm-refresh").addEventListener("click",()=>void q()),c("comm-check").addEventListener("click",()=>{clearTimeout(p),_=0,$()});let Z=D=>{f++,w++,clearTimeout(p),P=null,A=null;for(let[j,Y]of d)(D||Y)&&j.abort()},W=()=>{m||document.hidden||(oe&&V(),se(),q(),T&&O(T.id,T.admitted),S())},ae=()=>{document.hidden?Z(!1):W()};document.addEventListener("visibilitychange",ae);let Ee=()=>{m=!0,Z(!0),document.removeEventListener("visibilitychange",ae)};window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",D=>{D.persisted&&(m=!1,document.addEventListener("visibilitychange",ae),W())}),se(),q();let ne=Number(new URL(location.href).searchParams.get("queue"));return Number.isSafeInteger(ne)&&ne>0&&O(ne),Ee}function dE(e){let{context:t}=e,r=e.config??pe,n=e.remoteStalledConfig??{},o=e.fetchReport??Ae,s=e.send??Ht,i=e.whoami??xu,a=e.fetchHealth??fy,c=e.heavyLockStatusPath??Fn(),l=e.heavyLockPath??qn(),u=e.tail??Ti,d=e.tailJson??bi,m=new tn;if(e.publish===!0){let g=e.passcodeFilePath!==void 0?e.passcodeFilePath:Bn(t.db.path),y=e.readPasscodeAuthority??(()=>g===null?null:u_(g));$y(m,{allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,readAuthority:y,...e.remoteKey!==void 0?{remoteKey:e.remoteKey}:{}})}else m.use("*",async(g,y)=>{g.header("Cache-Control","no-store");let R=g.req.header("origin");if(R!==void 0&&!e.allowedOrigins.includes(R))return g.json({error:"origin not allowed"},403);await y()});m.route("/",qy({context:t,allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,enabled:!0})),lE(m,t,e.mountPath),Oy(m,{webDistDir:e.webDistDir,mountPath:e.mountPath}),Ky(m,t,e.mountPath),tE(m,t,e.mountPath),cE(m,t,e.mountPath),m.post("/api/jobs/on-demand",async g=>{let y;try{y=await g.req.json()}catch{return g.json({error:"invalid JSON"},400)}if(y===null||typeof y!="object"||Array.isArray(y))return g.json({error:"expected object"},400);let R=y;if(typeof R.db!="string"||typeof R.local_scope!="string"||typeof R.script!="string"||!Array.isArray(R.args)||!R.args.every(P=>typeof P=="string")||R.conversationid!==void 0&&typeof R.conversationid!="string")return g.json({error:"invalid on-demand request"},400);try{let P=await K_(t.db.db,t.db.path,t.teams,{db:R.db,localScope:R.local_scope,script:R.script,args:R.args,...typeof R.conversationid=="string"?{conversationId:R.conversationid}:{}});return g.json(P,202)}catch(P){return g.json({error:P instanceof Error?P.message:String(P)},400)}}),m.get("/api/teams",g=>g.json(ku(t))),m.get("/api/identities/:key",g=>g.json(Ns(t.teams,g.req.param("key")))),m.get("/api/state",g=>{let y=g.req.query("team");return y!==void 0?g.json(vu(t,y)):g.req.query("active")!==void 0?g.json(Au(t)):g.json(Su(t))}),m.get("/api/status",async g=>{let y=g.req.query("live")==="1"||g.req.query("live")==="true",R=await $u(t,{live:y,fetchReport:o});return g.json(R)}),m.get("/api/liveness",async g=>{let y=await o(),R=t.teams.map(P=>{let J=H(P)?null:js(t.db.db,{site:P.peerSite,team:P.name,alias:P.alias});return{team:P.name,running:H(P)?Fe(P,y):!1,deadReclaimable:H(P)?Xr(P,y):!1,remoteOutbound:J?{state:J.state,sentTs:J.sent_ts,ackedTs:J.acked_ts,repliedTs:J.replied_ts}:null}});return g.json({report:y,teams:R})}),m.get("/api/stalled",async g=>{let y=await o(),R=lt(c,l,void 0,ee=>{process.stderr.write(`[api/stalled] heavy-lock probe failed, treating conservatively as held: ${ee.message}
594
- `)}),P=await kn(t.db.db,t.teams.filter(H),y,R,r,void 0,{readOnly:!0}),J=z_(t.db.db,t.teams.filter(ee=>!H(ee)),n);return g.json({stalled:P,remoteStalled:J})});function f(g){let y=t.teams.find(P=>P.name===g);if(!y)return{error:`unknown team "${g}"`,status:404};if(!H(y))return{error:`team "${g}" is a remote team (channel=lmmail) -- not reachable via lctl`,status:400};let R;try{R=Q(y)}catch(P){return{error:P instanceof Error?P.message:String(P),status:500}}return{teamfilePath:R}}function p(g,y,R,P){return d(g,y,{lines:R?Number(R):20,...P?{since:P}:{}})}let h=(e.mountPath??"").replace(/\/$/,"");m.get("/running",g=>{try{let y=Bo(),R=y.report===null?"<p>Activity has not yet been observed; running, dead, and idle counts are unknown.</p>":`<p>Cached observation taken ${y.observedAt?fe(y.observedAt):"at an unknown time"}. Refreshing this page does not run a new activity scan.</p>`,P=y.lastError?`<p class="warning">Observer failed${y.lastErrorAt?` ${fe(y.lastErrorAt)}`:""}: ${b(y.lastError)}. ${y.report?"Showing the last successful observation.":"No successful observation is available."}</p>`:"",J=y.report===null?"":wy(kl(y.report),Mr(t.teams),h);return Oe(g,ve("Running","<p>This page loaded just now; activity data comes from a separate scheduled observation and may be older.</p>"+R+P+J,h))}catch(y){return Oe(g,ve("Running unavailable",`<p>${b(y instanceof Error?y.message:String(y))}</p>`,h),502)}}),m.get("/sessions/:team/:alias",g=>{let y=g.req.param("team"),R=g.req.param("alias"),P=`Session: ${y} / ${R}`,J={"data-page":"session","data-team":y,"data-alias":R},ee=f(y);if("error"in ee)return Oe(g,ve(P,`<p role="alert">${b(ee.error)}</p>`,h,J),ee.status);let oe=uE(y,R,h,{canonicalTeamfile:ee.teamfilePath,commPageEnabled:!0}),V=Array.from(oe.matchAll(/<script>([\s\S]*?)<\/script>/g),se=>se[1]);return Oe(g,ve(P,oe,h,J,V))}),m.get("/api/session/:team/:alias",async g=>{let y=g.req.param("team"),R=g.req.param("alias"),P=f(y);if("error"in P)return g.json({error:P.error},P.status);let{teamfilePath:J}=P,ee=g.req.query("since"),oe=g.req.query("limit");try{let V=await p(J,R,oe,ee);return g.json(V)}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},404)}}),m.get("/api/transcript",async g=>{let y=g.req.query("team");if(!y)return g.json({error:"team is required"},400);let R=t.teams.find(V=>V.name===y);if(!R)return g.json({error:`unknown team "${y}"`},404);if(!H(R))return g.json({error:`team "${y}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let P=g.req.query("alias")??R.leadAlias,J;try{J=Q(R)}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},500)}let ee=g.req.query("lines"),oe=g.req.query("since");try{let V=await u(J,P,{...ee?{lines:Number(ee)}:{},...oe?{since:oe}:{}});return g.json({team:y,alias:P,...V})}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},502)}}),m.get("/api/queue",g=>{let y=g.req.query("to");return g.json(wu(t,y))}),m.get("/api/queue/stats",g=>{try{let y=x(g.req.query("to"),"to");return g.json(Tu(t,y))}catch(y){return _(g,y)}});let w=g=>{try{let y=g.req.query(),R={fromId:x(y.from,"from"),toId:x(y.to,"to"),status:k(y.status),since:B(y.since,"since"),until:B(y.until,"until"),after:T(y.after,"after"),limit:T(y.limit,"limit",200)};return g.json(ia(t,R))}catch(y){return _(g,y)}};m.get("/api/queue/prompts",w),m.get("/api/queue/:id",g=>{let y=Number(g.req.param("id")),R=Vn(t,y);return R?g.json({queue:R}):g.json(ke("queue_not_found",`no queue entry ${y}`),404)}),m.get("/api/queue/:id/state",g=>{let y=Number(g.req.param("id")),R=ts(t,y);return R?g.json(R):g.json(ke("queue_not_found",`no queue entry ${y}`),404)}),m.post("/api/queue/:id/answer",async g=>{try{let y=S(g.req.param("id"),"id"),R=await g.req.json().catch(()=>({})),P=x(R.from,"from"),J=x(R.text,"text");if(P===void 0||J===void 0)return g.json(ke("invalid_argument","from and text are required"),400);let ee=sn(t.db.db,y,P,J);return g.json({answer:ee},202)}catch(y){return _(g,y)}}),m.get("/api/queue/:id/preview",g=>{try{let y=S(g.req.param("id"),"id"),R=Or(t,y);return R?g.json(R):g.json(ke("queue_not_found",`no queue entry ${y}`),404)}catch(y){return _(g,y)}}),m.post("/api/enqueue",async g=>{let y=await g.req.json().catch(()=>({})),R=y.prompt;if(!y.to||!R||!y.from)return g.json({error:"to, prompt, and from are required"},400);if(y.from==="autopilot")return g.json({error:"from: 'autopilot' is reserved for the tool's own automated enqueues"},400);try{let P=e.publish===!0&&y.from==="operator",J=_e(t.db.db,t.teams,y.to,R,{from:y.from,...P?{operatorPriority:!0}:{}});return g.json({id:J})}catch(P){return g.json({error:P instanceof Error?P.message:String(P)},400)}}),m.post("/api/comm/send",async g=>{try{let y=await g.req.json().catch(()=>({})),R=x(y.to,"to"),P=x(y.prompt,"prompt"),J=x(y.dedupeKey,"dedupeKey");if(R===void 0||P===void 0||J===void 0)return g.json(ke("invalid_argument","to, prompt, and dedupeKey are required"),400);let ee=ua(t.db.db,t.teams,{to:R,prompt:P,dedupeKey:J});return g.json(ee,ee.replayed?200:202)}catch(y){return _(g,y)}}),m.post("/api/queue/deliver",async g=>{let y=await o(),R=Er(t.db.db,{teams:t.teams,report:y,...e.remoteMail?{remoteMail:e.remoteMail}:{}});return g.json({delivered:R})}),m.post("/api/queue/retrieve",async g=>{let y=await g.req.json().catch(()=>({}));if(!y.to)return g.json({error:"to is required"},400);if(y.id!==void 0&&(!Number.isInteger(y.id)||y.id<=0))return g.json({error:"id must be a positive integer"},400);try{let P=Vs(t.db.db,y.to,y.id).map(J=>{let ee;try{ee=BO(J.prompt_file,"utf8")}catch{ee="(could not read prompt file)"}return{...J,content:ee}});return g.json({retrieved:P})}catch(R){return _(g,R)}}),m.get("/api/inbox",g=>{let y=g.req.query("to");return y?g.json(Eu(t,y)):g.json(ke("to_required","to is required"),400)});function _(g,y){if(y instanceof L){let R=y.code==="NOT_FOUND"?404:y.code==="CONFLICT"?409:y.code==="DB_BUSY"?503:y.code==="STORAGE_ERROR"?500:400;return g.json(ke(y.code,y.message),R)}return g.json(ke("internal_error",y instanceof Error?y.message:String(y)),500)}let E=new Set(["epic","task","subtask"]);function T(g,y,R){if(g===void 0)return;let P=Number(g);if(!/^[1-9]\d*$/.test(g)||!Number.isSafeInteger(P)||R!==void 0&&P>R)throw new L("INVALID_ARGUMENT",R!==void 0?`${y} must be a positive integer <= ${R}`:`${y} must be a positive integer`);return P}function v(g,y){if(g===void 0)return;let R=Number(g);if(!/^\d+$/.test(g)||!Number.isSafeInteger(R))throw new L("INVALID_ARGUMENT",`${y} must be a nonnegative integer`);return R}function S(g,y){let R=Number(g);if(!/^[1-9]\d*$/.test(g)||!Number.isSafeInteger(R))throw new L("INVALID_ARGUMENT",`${y} must be a positive integer`);return R}function N(g){if(g!==void 0){if(!E.has(g))throw new L("INVALID_ARGUMENT","kind must be 'epic', 'task', or 'subtask'");return g}}function x(g,y){if(g!==void 0){if(g.trim()==="")throw new L("INVALID_ARGUMENT",`${y} must not be blank`);return g}}function I(g,y){if(g!==void 0){if(g==="1"||g==="true")return!0;if(g==="0"||g==="false")return!1;throw new L("INVALID_ARGUMENT",`${y} must be '1'/'true' or '0'/'false'`)}}function k(g){if(g!==void 0){if(!gc.includes(g))throw new L("INVALID_ARGUMENT",`status must be one of: ${gc.join(", ")}`);return g}}function B(g,y){if(g===void 0)return;let R=g.trim()===""?NaN:Date.parse(g);if(Number.isNaN(R))throw new L("INVALID_ARGUMENT",`${y} must be a valid ISO8601 date-time string`);return new Date(R).toISOString()}function C(g,y){let R=x(g,"ownerTeam"),P=x(y,"ownerAlias");if(!(R===void 0&&P===void 0)){if(R===void 0||P===void 0)throw new L("INVALID_ARGUMENT","ownerTeam and ownerAlias must both be given");return{team:R,alias:P}}}return m.get("/api/tasks",g=>{let y=g.req.query();try{let R={project:x(y.project,"project"),kind:N(y.kind),status:x(y.status,"status"),parentId:T(y.parentId,"parentId"),owner:C(y.ownerTeam,y.ownerAlias),unassigned:I(y.unassigned,"unassigned"),limit:T(y.limit,"limit",Ne),after:v(y.after,"after")};return g.json(br(t.db.db,R))}catch(R){return _(g,R)}}),m.get("/api/tasks/summary",g=>{try{let y=T(g.req.query("id"),"id"),R=x(g.req.query("project"),"project");return g.json(Ar(t.db.db,{id:y,project:R}))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id",g=>{try{let y=S(g.req.param("id"),"id");return g.json(Sr(t.db.db,y))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id/tree",g=>{try{let y=S(g.req.param("id"),"id");return g.json(vr(t.db.db,y))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id/notes",g=>{try{let y=S(g.req.param("id"),"id"),R=v(g.req.query("after"),"after"),P=T(g.req.query("limit"),"limit",Ne);return g.json(Tf(t.db.db,y,{limit:P,after:R}))}catch(y){return _(g,y)}}),m.post("/api/send",async g=>{let y=await g.req.json().catch(()=>({})),R=y.prompt;if(!y.team||!R)return g.json({error:"team and prompt are required"},400);let P=t.teams.find(V=>V.name===y.team);if(!P)return g.json({error:`unknown team "${y.team}"`},404);if(!H(P))return g.json({error:`team "${y.team}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let J=await s({teamfilePath:Q(P),alias:P.leadAlias},R),ee=Wn(J),oe=Date.now();return ir(t.db.db,P.name,ee.status,oe),tt(t.db.db,P.name,ee.status,oe,{note:"web send"}),g.json({status:ee.status,outcome:J})}),m.get("/api/history",g=>{let y=g.req.query("team"),R=g.req.query("limit"),P=iu(t,y,R);return"error"in P?g.json(P,400):g.json(P)}),m.get("/api/sources",g=>g.json(bu(t))),m.get("/api/mail/status",g=>g.json(au(t))),m.get("/api/subscriptions",async g=>{let{status:y,body:R}=await py();return g.json(R,y)}),m.get("/api/whoami",async g=>{let{data:y,exitCode:R}=await i();return"error"in y?g.json(y,R===4?502:400):g.json(y)}),m.get("/api/running",async g=>g.json(await o())),m.get("/api/running/humanized",async g=>g.json(kl(await o()))),m.get("/api/running/observed",g=>g.json(Bo())),m.get("/api/heavy-lock",g=>{try{return g.json($l(c,l))}catch(y){if(y instanceof Un)return g.json(ke("heavy_lock_probe_failed",y.message),502);throw y}}),m.get("/api/health",async g=>{let y=g.req.query("target");if(!y)return g.json(ke("target_required","target is required"),400);try{let R=await a(y);return g.json(R)}catch(R){return g.json(ke("health_fetch_failed",R instanceof Error?R.message:String(R)),502)}}),m.post("/api/sources",async g=>{let y=await g.req.json().catch(()=>({}));if(!y.path)return g.json({error:"path is required"},400);let R=aa(t,y.path,y.label??void 0);return R.ok?(t.teams=Jr(t.db.db,t.teamsConfPath),g.json({ok:!0})):g.json({error:R.output},400)}),m.delete("/api/sources",g=>{let y=g.req.query("path");return y?(Ls(t.db.db,y),t.teams=Jr(t.db.db,t.teamsConfPath),g.json({ok:!0})):g.json({error:"path is required"},400)}),m}function qu(e){return e.teams=Jr(e.db.db,e.teamsConfPath),e.teams}var WO=4173,GO="127.0.0.1";function mE(e){if(process.env.LMBEE_SITE_UUID!==void 0)try{let h=En(e.context.db.db,void 0,process.env.LMBEE_SITE_UUID);if(e.remoteMail&&e.remoteMail.localSiteId!==h)throw new Error("Remote mail site identity conflicts with the database binding")}catch(h){return Promise.reject(h)}let t=e.port??WO,r=e.hostname??GO,n=e.publish??!1;if(!["127.0.0.1","::1","localhost"].includes(r)&&!n)return Promise.reject(new Error("LocalWeb refuses a non-loopback bind without --publish (which also requires passcode auth)"));let o=r==="::1"?"[::1]":r,s=Yo(e.context.db.path),i=null;if(s!==null)try{i=ra(s,e.lockOwnerLabel??"lmbee-serve")}catch(h){return Promise.reject(h)}let a=t===0?[]:[`http://${o}:${t}`,`http://localhost:${t}`,`http://[::1]:${t}`],c=e.remoteMail?{client:e.remoteMail.client,localSiteId:e.remoteMail.localSiteId}:void 0,l,u,d,m,f=null,p=null;try{let h=e.passcodeFilePath??Bn(e.context.db.path);n&&h!==null&&na(h),l=dE({context:e.context,allowedOrigins:a,publish:n,passcodeFilePath:h,...e.config!==void 0?{config:e.config}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...e.mountPath!==void 0?{mountPath:e.mountPath}:{},...e.webDistDir!==void 0?{webDistDir:e.webDistDir}:{},...c?{remoteMail:c}:{},...e.remoteStalledConfig!==void 0?{remoteStalledConfig:e.remoteStalledConfig}:{}});let w=e.mountPath?.endsWith("/")?e.mountPath.slice(0,-1):e.mountPath;if(w?u=new tn().route(w,l).get(`${w}/`,async _=>{let E=new URL(_.req.url);E.pathname="/",E.search="";let T=await l.fetch(new Request(E,{method:"GET",headers:_.req.raw.headers}));return T.ok?_.redirect(w,302):T}):u=l,d=Zg({db:e.context.db.db,getTeams:()=>qu(e.context),...e.intervalMs!==void 0?{intervalMs:e.intervalMs}:{},...e.config!==void 0?{config:e.config}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...e.maintainerWake!==void 0?{maintainerWake:e.maintainerWake}:{},...e.autoContinue!==void 0?{autoContinue:e.autoContinue}:{},...e.miniplayerVerify!==void 0?{miniplayerVerify:e.miniplayerVerify}:{},...e.hungHolderCheck!==void 0?{hungHolderCheck:e.hungHolderCheck}:{},...e.epicReview!==void 0?{epicReview:e.epicReview}:{},...e.orphanReconciler!==void 0?{orphanReconciler:e.orphanReconciler}:{},...e.hangProbeCollect!==void 0?{hangProbeCollect:e.hangProbeCollect}:{},...e.autoNudgeRedirectReview!==void 0?{autoNudgeRedirectReview:e.autoNudgeRedirectReview}:{},...e.rateLimitCollect!==void 0?{rateLimitCollect:e.rateLimitCollect}:{},...e.rateLimitPolicy!==void 0?{rateLimitPolicy:e.rateLimitPolicy}:{},...e.rateLimitAutomation!==void 0?{rateLimitAutomation:e.rateLimitAutomation}:{},onTick:_=>{process.stderr.write(`[cron] tick: watch=${_.watch.why}, ${_.stalled.length} stalled (${_.stalled.join(", ")||"none"})${_.maintainerWoken?", maintainer woken":""}${_.autoContinued.length?`, auto-continued (${_.autoContinued.join(", ")})`:""}
588
+ return (${zO.toString()})();
589
+ })();</script>`}function zO(){let e=document.getElementById("session-detail"),{team:t="",alias:r="",mount:n="",history:o="",canonicalTeamfile:s="",commEnabled:i="false",commPageEnabled:a="false"}=e.dataset,c=D=>document.getElementById(D),l=(D,j)=>{c(D).textContent=j},u=(D,j)=>{let Y=document.createElement(D);return Y.textContent=j,Y},d=new Map,m=!1,f=0,p,h=null,w=0,_=0,T=null,E=null,v=D=>!m&&!document.hidden&&D===f,S=()=>{},N=[],$=!1;function L(D){let j=u("span",D),Y=N.find(K=>K.name===D);if(!Y){let K=$?"Recorded label; current actor unresolved":"Recorded label; current team list unavailable";return j.title=`${D} \u2014 ${K}`,/[\\/]/.test(D)&&(j.textContent=D.split(/[\\/]/).at(-1).replace(/\.lmctl(?=:|$)/,"")),j}if(Y.channel==="lmmail")return j.textContent+=" (remote inbox)",j;if(Y.channel==="local"&&Y.leadAlias&&D!=="operator"){let K=u("a",`${Y.name}:${Y.leadAlias}`);K.title="Current configured inbox lead; not a historical sender session",j.textContent="",K.href=`${n}/sessions/${encodeURIComponent(Y.name)}/${encodeURIComponent(Y.leadAlias)}`,j.append(K)}return j}function R(D,j){let Y=u("span","");return Y.append(L(D),u("span"," \u2192 "),L(j)),Y}let H=D=>`${n}/sessions/${encodeURIComponent(t)}/${encodeURIComponent(r)}?queue=${D}`,C=D=>D instanceof Error?D.message:String(D);async function g(D,j){let Y=new AbortController;d.set(Y,j===void 0);let K=setTimeout(()=>Y.abort(),15e3);try{let re=await fetch(D,{method:j===void 0?"GET":"POST",signal:Y.signal,credentials:"same-origin",cache:"no-store",redirect:"error",headers:{Accept:"application/json",...j===void 0?{}:{"Content-Type":"application/json"}},...j===void 0?{}:{body:JSON.stringify(j)}});if(!re.ok)throw new Error(`HTTP ${re.status}; request unsuccessful`);if(!re.headers.get("content-type")?.includes("application/json"))throw new Error("Expected JSON response");let te=re.body.getReader(),ue=new TextDecoder,ke=0,be="";for(;;){let z=await te.read();if(z.done)break;if(ke+=z.value.byteLength,ke>2e6)throw await te.cancel(),new Error("Response exceeds 2 MB limit");be+=ue.decode(z.value,{stream:!0})}return JSON.parse(be+ue.decode())}finally{clearTimeout(K),d.delete(Y)}}function y(D){return D==="merged"||D==="informational"||D==="retracted"}function x(D,j=!1){if(j){if(D.lifecycle==="queued")return"queued";if(D.lifecycle==="finished")return D.lifecycleBasis==="merged"?"finished \xB7 merged into an earlier message":D.lifecycleBasis==="informational"?"finished \xB7 informational, no reply expected":D.lifecycleBasis==="retracted"?"finished \xB7 retracted, no reply expected":"finished \xB7 reply recorded";if(D.lifecycle==="processing")return D.lifecycleBasis==="confirmed"?"processing \xB7 picked up":"processing \xB7 attempted"}if(D.lifecycle==="finished")return D.lifecycleBasis==="merged"?"finished \u2014 merged into an earlier message, no separate response":D.lifecycleBasis==="informational"?"finished \u2014 informational, no response expected":D.lifecycleBasis==="retracted"?"finished \u2014 retracted, no response expected":"finished \u2014 response recorded";if(D.lifecycle==="queued")return"queued \u2014 waiting for handling";if(D.lifecycle==="processing")return D.lifecycleBasis==="confirmed"?"processing \u2014 picked up by inbox":"processing \u2014 delivery attempted; read not confirmed";throw new Error("Unknown lifecycle in owner response")}let P=null,J=D=>D!==null&&typeof D=="object"&&!Array.isArray(D),ee=(D,j)=>typeof D=="string"&&D.trim()?D:j,oe=!1;async function V(){if(!oe||P===f||m||document.hidden)return;let D=f;P=D,c("session-refresh").disabled=!0;try{let j=await g(o);if(!v(D))return;if(!J(j)||!Array.isArray(j.messages))throw new Error("Recent messages were not supplied by the history source");let Y=j.messages.slice(-20).map(K=>{let re=J(K)?K:{},te=re.content==null?"Message content not recorded.":typeof re.content=="string"?re.content:JSON.stringify(re.content),ue=u("article","");return ue.append(u("h3",ee(re.role,"Unknown role")),u("p",ee(re.timestamp,"Time not recorded.")),u("pre",te)),ue});c("session-history").dataset.state="ready",c("session-history").replaceChildren(...Y.length?Y:[u("p","No recent messages returned.")]),l("session-history-status",`Latest ${Y.length} messages.${j.truncated===!0?" Older messages are not shown.":""}`),l("session-source",`Provider ${ee(j.provider,"not recorded")}; session ${ee(j.sessionId,"not recorded")}. Optional bounded provider tail. ${j.truncated===!0?"Older output truncated. ":""}Fetched ${new Date().toISOString()}.`)}catch(j){v(D)&&(c("session-history").dataset.state="error",c("session-history").children.length===0&&c("session-history").replaceChildren(u("p","Recent messages unavailable.")),l("session-history-status","Recent messages unavailable. Try Refresh transcript."),l("session-source",`History unavailable; previous content may be stale. ${C(j)}`))}finally{P===D&&(P=null),v(D)&&(c("session-refresh").disabled=!1)}}async function se(){if(!s||m||document.hidden)return;let D=f;try{let j=new URLSearchParams({ownerTeam:s,ownerAlias:r,limit:"20"}),Y=await g(`${n}/api/tasks?${j}`);if(!v(D))return;if(!Array.isArray(Y.rows))throw new Error("Invalid task response");c("session-tasks").replaceChildren(u("p","Up to 20 assigned work items."),...Y.rows.slice(0,20).map(K=>{let re=u("a",`#${K.id} ${K.title} \u2014 ${K.kind}, ${K.status}`);re.href=`${n}/tasks/${Number(K.id)}`;let te=u("p","");if(te.append(re),Number.isSafeInteger(K.parent_id)&&K.parent_id>0){let ue=u("a",` Parent work item #${K.parent_id}`);ue.href=`${n}/tasks/${K.parent_id}`,te.append(ue)}return te}),...Y.rows.length?[]:[u("p","No recorded assignment for this session.")])}catch(j){v(D)&&l("session-tasks",`Assigned work unavailable: ${C(j)}`)}}async function k(){if(T===w||h===null||m||document.hidden)return;T=w;let D=h,j=w,Y=f;try{let K=await g(`${n}/api/queue/${D}/state`);if(j!==w||!v(Y))return;if(K.id!==D)throw new Error("Queue identity mismatch");if(K.lifecycle==="finished"&&!y(K.lifecycleBasis)&&!K.answer)throw new Error("Finished state has no correlated response");if(K.answer&&K.answer.prompt_queue_id!==D)throw new Error("Answer correlation mismatch");c("comm-state").dataset.queueId=String(D),c("comm-state").dataset.lifecycle=K.lifecycle,c("comm-state").dataset.lifecycleBasis=K.lifecycleBasis,l("comm-state",`Queue #${D}: ${x(K)}. Created ${K.createdAt}. Last checked ${new Date().toISOString()}.`),K.answer?l("comm-response",`${K.answer.answer_text}
590
+ ${K.answer.truncated?`Truncated response; ${K.answer.totalBytes} total bytes. No continuation endpoint available.`:""}`):l("comm-response",K.lifecycleBasis==="merged"?"No separate answer: prompt merged into another prompt.":K.lifecycleBasis==="informational"?"No answer expected: this was an informational prompt.":K.lifecycleBasis==="retracted"?"No answer expected: this prompt was retracted.":"Outcome unknown: no reply recorded. This does not establish failure or unread work."),K.lifecycle!=="finished"&&++_<60?p=setTimeout(()=>void k(),5e3):K.lifecycle!=="finished"&&l("comm-state",`Queue #${D}: observation stalled \u2014 automatic checks paused after 60 reads; last state ${x(K)}. Check again manually. This does not establish execution failure.`)}catch(K){j===w&&v(Y)&&l("comm-state",`State check failed; last content may be stale. ${C(K)}. Check again manually.`)}finally{T===j&&(T=null)}}async function O(D,j=!1){if(!Number.isSafeInteger(D)||D<1||m||document.hidden)return;c("comm-reading-panel").hidden=!1,E={id:D,admitted:j},clearTimeout(p),h=null,w++,_=0;let Y=w,K=f;delete c("comm-state").dataset.queueId,delete c("comm-state").dataset.lifecycle,delete c("comm-state").dataset.lifecycleBasis,l("comm-context","Loading recorded endpoints. Related task: not recorded; assigned work shown separately."),l("comm-state",`Loading queue #${D}\u2026`),l("comm-response",""),l("comm-preview","Loading request preview\u2026"),c("comm-check").hidden=!1;let re=new URL(location.href);re.searchParams.set("queue",String(D)),window.history.replaceState(null,"",re);try{let te=await g(`${n}/api/queue/${D}`);if(Y!==w||!v(K))return;if(te.queue.id!==D)throw new Error("Queue envelope identity mismatch");if(j&&te.queue.to_id!=="math")throw new Error("Admitted receipt is not addressed to math");if(te.queue.to_id!==t&&te.queue.from_id!==t)throw new Error("Queue message does not belong to this team");h=D;let ue=c("comm-context");if(ue.replaceChildren(u("span",`Request #${D}: `),R(te.queue.from_id,te.queue.to_id),u("span",". Expected reply context: "),L(te.queue.to_id),u("span",` inbox for prompt #${D} from `),L(te.queue.from_id),u("span",". Check the response status below; a reply may not be recorded. Related task: not recorded; assigned work shown separately.")),typeof te.queue.retracted_reason=="string"&&te.queue.retracted_reason&&ue.append(u("span",` Retraction reason: ${te.queue.retracted_reason}.`)),a==="true"&&te.queue.to_id==="math"){let be=u("a","Open full prompt and answer");be.href=`${n}/comm/math/prompts/${D}`,ue.append(be)}let ke=await g(`${n}/api/queue/${D}/preview`);if(Y!==w||!v(K))return;if(ke.id!==D)throw new Error("Preview identity mismatch");l("comm-preview",ke.status==="available"?`${ke.text??""}${ke.truncated?`
591
+ [Prompt preview truncated]`:""}`:`Prompt preview ${ke.status}; content unavailable.`)}catch(te){Y===w&&v(K)&&(l("comm-preview",`Prompt preview unavailable: ${C(te)}`),h===null&&l("comm-state","Queue selection unavailable; select a message from this team."))}await k()}let A=null;async function q(){if(A===f||m||document.hidden)return;let D=f;A=D,c("comm-refresh").disabled=!0;try{let j=await g(`${n}/api/teams`).catch(()=>null);if(!v(D))return;N=j?.teams??[],$=j!==null;let Y=N.find(z=>z.name===t),K=Y?.channel==="local"&&typeof Y.description=="string"?Y.description.trim():"";l("session-purpose",j===null?"Team purpose unavailable.":K?`Recorded team description: \u201C${K}\u201D`:"No team purpose recorded.");let re=await Promise.all(["to","from"].map(async z=>{let Te=await g(`${n}/api/queue/prompts?${z}=${encodeURIComponent(t)}&limit=20`);if(!Array.isArray(Te.rows))throw new Error("Invalid message list");return Te}));if(!v(D))return;let te=new Map;for(let z of re)for(let Te of z.rows.slice(0,20)){if(!Number.isSafeInteger(Te.id)||Te.id<1)throw new Error("Invalid queue identity");if(Te.to_id!==t&&Te.from_id!==t)throw new Error("Message outside current team");let Ge=te.get(Te.id);(!Ge||Te.lifecycle==="finished"&&Ge.lifecycle!=="finished")&&te.set(Te.id,Te)}let ue=z=>Number.isFinite(Date.parse(z))?Date.parse(z):Number.MAX_VALUE,be=[...te.values()].sort((z,Te)=>ue(z.created_ts)-ue(Te.created_ts)||z.id-Te.id).map(z=>{let Te=u("li","");Te.dataset.queueId=String(z.id);let Ge=u("a",`Read exchange #${z.id}`);Ge.href=H(z.id),Ge.addEventListener("click",we=>{we.defaultPrevented||we.button!==0||we.metaKey||we.ctrlKey||we.shiftKey||we.altKey||(we.preventDefault(),O(z.id))}),Te.append(Ge);let je=u("div","");je.dataset.queueId=String(z.id),je.dataset.event="request";let Ct=Number.isFinite(Date.parse(z.created_ts))?z.created_ts:"Time not recorded; placed last by request ID",G=u("span",z.lifecycle==="queued"?"Queued":z.lifecycle==="processing"?"Processing":z.lifecycleBasis==="merged"?"Combined":z.lifecycleBasis==="informational"?"Informational":z.lifecycleBasis==="retracted"?"Retracted":"Replied");if(G.className=`status-chip status-${z.lifecycle==="queued"?"queued":z.lifecycle==="processing"?"processing":y(z.lifecycleBasis)?"muted":"replied"}`,G.title=x(z),je.append(u("p",`Request recorded: ${Ct}`),R(z.from_id,z.to_id),G),z.from_id===z.to_id&&je.append(u("p","Self-addressed request.")),z.subject_id!=null&&je.append(u("p",`Recorded subject label: ${z.subject_id}`)),Te.append(je),z.lifecycle==="finished"&&!y(z.lifecycleBasis)){let we=u("div","");we.dataset.queueId=String(z.id),we.dataset.event="response",we.append(u("span","Answer recorded in "),L(z.to_id),u("span",` inbox for prompt #${z.id} from `),L(z.from_id),u("p",`Recorded reply time: ${z.answeredAt??"Time not recorded"}`));let st=u("details",""),Ze=u("pre","Open to load the recorded reply.");st.append(u("summary","Show reply"),Ze);let ft=!1,Ve=!1;st.addEventListener("toggle",async()=>{if(!st.open||ft||Ve||m||document.hidden)return;let mn=f;Ve=!0,Ze.textContent="Loading reply\u2026";try{let _r=await g(`${n}/api/queue/${z.id}/state`);if(!v(mn))return;let or=_r.answer;if(_r.id!==z.id||or===null||or.prompt_queue_id!==z.id)throw new Error("Answer identity mismatch");if(typeof or.answer_text!="string")throw new Error("Reply text unavailable");let et=Array.from(or.answer_text);Ze.textContent=et.slice(0,1200).join("")+(et.length>1200||or.truncated?`
592
+ [Reply excerpt; open the full exchange for available text.]`:""),ft=!0}catch(_r){v(mn)&&(Ze.textContent=`Reply unavailable: ${C(_r)}. Close and reopen to retry.`)}finally{Ve=!1}}),we.append(st),Te.append(we)}else Te.append(u("p",z.lifecycleBasis==="merged"?"No separate answer: prompt merged into another prompt.":z.lifecycleBasis==="informational"?"No answer expected: this was an informational prompt.":z.lifecycleBasis==="retracted"?`No answer expected: this prompt was retracted. Reason: ${z.retracted_reason??"no reason recorded"}.`:"Reply: not recorded"));return Te});c("comm-sequence").replaceChildren(...be.slice(-5)),c("comm-older-sequence").replaceChildren(...be.slice(0,-5)),c("comm-older").hidden=be.length<=5,l("comm-older-label",`Show ${Math.max(0,be.length-5)} older loaded prompts`),l("comm-coverage",`Showing newest ${Math.min(5,be.length)} of ${te.size} loaded prompts, ordered by arrival, oldest first; answers are grouped with their prompts. ${re.some(z=>z.meta.next_cursor!==null)?"This is a limited sample; additional records have not been loaded.":"All prompts from the returned pages are available here."}`)}catch(j){v(D)&&l("comm-coverage",`Message context unavailable; previous events may be stale. ${C(j)}`)}finally{A===D&&(A=null),v(D)&&(c("comm-refresh").disabled=!1)}}let M=c("comm-form");if(M&&i==="true"&&t==="math"&&r==="Lead"){let D=c("comm-draft"),j=c("comm-submit"),Y=c("comm-confirm"),K=c("comm-edit"),re=null,te=!1,ue=!1,ke="Page paused during admission";S=()=>{m||document.hidden||!re||!ue||(Y.disabled=te,te||(l("comm-send-status",`Admission uncertain or failed: ${ke}. Retry preserves the exact prompt and dedupe key. Keep this page open until resolved.`),Y.textContent="Retry same prompt safely"))},M.addEventListener("submit",be=>{if(be.preventDefault(),!(m||document.hidden||te||re)){if(!D.value.trim()||new TextEncoder().encode(D.value).length>65536){l("comm-send-status","Enter a nonblank prompt of at most 64 KiB UTF-8.");return}re={to:"math",prompt:D.value,dedupeKey:`localweb:${crypto.randomUUID()}`},D.disabled=!0,j.disabled=!0,l("comm-review",`To math, from operator:
593
+ ${re.prompt}`),c("comm-review").hidden=!1,Y.hidden=!1,K.hidden=!1,l("comm-send-status","Review the exact prompt before confirming.")}}),K.addEventListener("click",()=>{te||ue||(re=null,D.disabled=!1,j.disabled=!1,Y.hidden=!0,K.hidden=!0,c("comm-review").hidden=!0)}),Y.addEventListener("click",async()=>{if(!re||te||m||document.hidden)return;let be=f;te=!0,ue=!0,Y.disabled=!0,K.hidden=!0,l("comm-send-status","Submitting; waiting for confirmation that the prompt was queued\u2026");try{let z=await g(`${n}/api/comm/send`,re);if(!v(be))throw new Error("Page paused before receipt could be shown");if(!Number.isSafeInteger(z.queueId)||z.queueId<1)throw new Error("Missing queue receipt");l("comm-send-status",`Accepted as queue #${z.queueId}${z.replayed?" (existing prompt recovered)":""}.`),re=null,ue=!1,D.value="",D.disabled=!1,j.disabled=!1,Y.hidden=!0,Y.textContent="Confirm send to math",c("comm-review").hidden=!0,O(z.queueId,!0),q()}catch(z){ke=C(z)}finally{te=!1,!m&&!document.hidden&&(Y.disabled=!1),S()}})}c("session-refresh").addEventListener("click",()=>{oe=!0,l("session-refresh","Refresh transcript"),V()}),c("comm-refresh").addEventListener("click",()=>void q()),c("comm-check").addEventListener("click",()=>{clearTimeout(p),_=0,k()});let Z=D=>{f++,w++,clearTimeout(p),P=null,A=null;for(let[j,Y]of d)(D||Y)&&j.abort()},W=()=>{m||document.hidden||(oe&&V(),se(),q(),E&&O(E.id,E.admitted),S())},ae=()=>{document.hidden?Z(!1):W()};document.addEventListener("visibilitychange",ae);let Ee=()=>{m=!0,Z(!0),document.removeEventListener("visibilitychange",ae)};window.addEventListener("pagehide",Ee),window.addEventListener("pageshow",D=>{D.persisted&&(m=!1,document.addEventListener("visibilitychange",ae),W())}),se(),q();let ne=Number(new URL(location.href).searchParams.get("queue"));return Number.isSafeInteger(ne)&&ne>0&&O(ne),Ee}function gE(e){let{context:t}=e,r=e.config??pe,n=e.remoteStalledConfig??{},o=e.fetchReport??Ae,s=e.send??Ht,i=e.whoami??Lu,a=e.fetchHealth??wy,c=e.heavyLockStatusPath??jn(),l=e.heavyLockPath??Hn(),u=e.tail??Ai,d=e.tailJson??ki,m=new tn;if(e.publish===!0){let g=e.passcodeFilePath!==void 0?e.passcodeFilePath:Gn(t.db.path),y=e.readPasscodeAuthority??(()=>g===null?null:h_(g));Ly(m,{allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,readAuthority:y,...e.remoteKey!==void 0?{remoteKey:e.remoteKey}:{}})}else m.use("*",async(g,y)=>{g.header("Cache-Control","no-store");let x=g.req.header("origin");if(x!==void 0&&!e.allowedOrigins.includes(x))return g.json({error:"origin not allowed"},403);await y()});m.route("/",Gy({context:t,allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,enabled:!0})),pE(m,t,e.mountPath),Fy(m,{webDistDir:e.webDistDir,mountPath:e.mountPath}),Zy(m,t,e.mountPath),iE(m,t,e.mountPath),fE(m,t,e.mountPath),m.post("/api/jobs/on-demand",async g=>{let y;try{y=await g.req.json()}catch{return g.json({error:"invalid JSON"},400)}if(y===null||typeof y!="object"||Array.isArray(y))return g.json({error:"expected object"},400);let x=y;if(typeof x.db!="string"||typeof x.local_scope!="string"||typeof x.script!="string"||!Array.isArray(x.args)||!x.args.every(P=>typeof P=="string")||x.conversationid!==void 0&&typeof x.conversationid!="string")return g.json({error:"invalid on-demand request"},400);try{let P=await Z_(t.db.db,t.db.path,t.teams,{db:x.db,localScope:x.local_scope,script:x.script,args:x.args,...typeof x.conversationid=="string"?{conversationId:x.conversationid}:{}});return g.json(P,202)}catch(P){return g.json({error:P instanceof Error?P.message:String(P)},400)}}),m.get("/api/teams",g=>g.json(Nu(t))),m.get("/api/identities/:key",g=>g.json(Os(t.teams,g.req.param("key")))),m.get("/api/state",g=>{let y=g.req.query("team");return y!==void 0?g.json($u(t,y)):g.req.query("active")!==void 0?g.json(xu(t)):g.json(ku(t))}),m.get("/api/status",async g=>{let y=g.req.query("live")==="1"||g.req.query("live")==="true",x=await Ru(t,{live:y,fetchReport:o});return g.json(x)}),m.get("/api/liveness",async g=>{let y=await o(),x=t.teams.map(P=>{let J=B(P)?null:Gs(t.db.db,{site:P.peerSite,team:P.name,alias:P.alias});return{team:P.name,running:B(P)?Fe(P,y):!1,deadReclaimable:B(P)?Xr(P,y):!1,remoteOutbound:J?{state:J.state,sentTs:J.sent_ts,ackedTs:J.acked_ts,repliedTs:J.replied_ts}:null}});return g.json({report:y,teams:x})}),m.get("/api/stalled",async g=>{let y=await o(),x=lt(c,l,void 0,ee=>{process.stderr.write(`[api/stalled] heavy-lock probe failed, treating conservatively as held: ${ee.message}
594
+ `)}),P=await $n(t.db.db,t.teams.filter(B),y,x,r,void 0,{readOnly:!0}),J=ew(t.db.db,t.teams.filter(ee=>!B(ee)),n);return g.json({stalled:P,remoteStalled:J})});function f(g){let y=t.teams.find(P=>P.name===g);if(!y)return{error:`unknown team "${g}"`,status:404};if(!B(y))return{error:`team "${g}" is a remote team (channel=lmmail) -- not reachable via lctl`,status:400};let x;try{x=Q(y)}catch(P){return{error:P instanceof Error?P.message:String(P),status:500}}return{teamfilePath:x}}function p(g,y,x,P){return d(g,y,{lines:x?Number(x):20,...P?{since:P}:{}})}let h=(e.mountPath??"").replace(/\/$/,"");m.get("/running",g=>{try{let y=Jo(),x=y.report===null?"<p>Activity has not yet been observed; running, dead, and idle counts are unknown.</p>":`<p>Cached observation taken ${y.observedAt?fe(y.observedAt):"at an unknown time"}. Refreshing this page does not run a new activity scan.</p>`,P=y.lastError?`<p class="warning">Observer failed${y.lastErrorAt?` ${fe(y.lastErrorAt)}`:""}: ${b(y.lastError)}. ${y.report?"Showing the last successful observation.":"No successful observation is available."}</p>`:"",J=y.report===null?"":Sy(Nl(y.report),Mr(t.teams),h);return Oe(g,ve("Running","<p>This page loaded just now; activity data comes from a separate scheduled observation and may be older.</p>"+x+P+J,h))}catch(y){return Oe(g,ve("Running unavailable",`<p>${b(y instanceof Error?y.message:String(y))}</p>`,h),502)}}),m.get("/sessions/:team/:alias",g=>{let y=g.req.param("team"),x=g.req.param("alias"),P=`Session: ${y} / ${x}`,J={"data-page":"session","data-team":y,"data-alias":x},ee=f(y);if("error"in ee)return Oe(g,ve(P,`<p role="alert">${b(ee.error)}</p>`,h,J),ee.status);let oe=hE(y,x,h,{canonicalTeamfile:ee.teamfilePath,commPageEnabled:!0}),V=Array.from(oe.matchAll(/<script>([\s\S]*?)<\/script>/g),se=>se[1]);return Oe(g,ve(P,oe,h,J,V))}),m.get("/api/session/:team/:alias",async g=>{let y=g.req.param("team"),x=g.req.param("alias"),P=f(y);if("error"in P)return g.json({error:P.error},P.status);let{teamfilePath:J}=P,ee=g.req.query("since"),oe=g.req.query("limit");try{let V=await p(J,x,oe,ee);return g.json(V)}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},404)}}),m.get("/api/transcript",async g=>{let y=g.req.query("team");if(!y)return g.json({error:"team is required"},400);let x=t.teams.find(V=>V.name===y);if(!x)return g.json({error:`unknown team "${y}"`},404);if(!B(x))return g.json({error:`team "${y}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let P=g.req.query("alias")??x.leadAlias,J;try{J=Q(x)}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},500)}let ee=g.req.query("lines"),oe=g.req.query("since");try{let V=await u(J,P,{...ee?{lines:Number(ee)}:{},...oe?{since:oe}:{}});return g.json({team:y,alias:P,...V})}catch(V){return g.json({error:V instanceof Error?V.message:String(V)},502)}}),m.get("/api/queue",g=>{let y=g.req.query("to");return g.json(Tu(t,y))}),m.get("/api/queue/stats",g=>{try{let y=$(g.req.query("to"),"to");return g.json(vu(t,y))}catch(y){return _(g,y)}});let w=g=>{try{let y=g.req.query(),x={fromId:$(y.from,"from"),toId:$(y.to,"to"),status:R(y.status),since:H(y.since,"since"),until:H(y.until,"until"),after:E(y.after,"after"),limit:E(y.limit,"limit",200)};return g.json(la(t,x))}catch(y){return _(g,y)}};m.get("/api/queue/prompts",w),m.get("/api/queue/:id",g=>{let y=Number(g.req.param("id")),x=Kn(t,y);return x?g.json({queue:x}):g.json($e("queue_not_found",`no queue entry ${y}`),404)}),m.get("/api/queue/:id/state",g=>{let y=Number(g.req.param("id")),x=ss(t,y);return x?g.json(x):g.json($e("queue_not_found",`no queue entry ${y}`),404)}),m.post("/api/queue/:id/answer",async g=>{try{let y=S(g.req.param("id"),"id"),x=await g.req.json().catch(()=>({})),P=$(x.from,"from"),J=$(x.text,"text");if(P===void 0||J===void 0)return g.json($e("invalid_argument","from and text are required"),400);let ee=sn(t.db.db,y,P,J);return g.json({answer:ee},202)}catch(y){return _(g,y)}}),m.get("/api/queue/:id/preview",g=>{try{let y=S(g.req.param("id"),"id"),x=Or(t,y);return x?g.json(x):g.json($e("queue_not_found",`no queue entry ${y}`),404)}catch(y){return _(g,y)}}),m.post("/api/enqueue",async g=>{let y=await g.req.json().catch(()=>({})),x=y.prompt;if(!y.to||!x||!y.from)return g.json({error:"to, prompt, and from are required"},400);if(y.from==="autopilot")return g.json({error:"from: 'autopilot' is reserved for the tool's own automated enqueues"},400);try{let P=e.publish===!0&&y.from==="operator",J=_e(t.db.db,t.teams,y.to,x,{from:y.from,...P?{operatorPriority:!0}:{}});return g.json({id:J})}catch(P){return g.json({error:P instanceof Error?P.message:String(P)},400)}}),m.post("/api/comm/send",async g=>{try{let y=await g.req.json().catch(()=>({})),x=$(y.to,"to"),P=$(y.prompt,"prompt"),J=$(y.dedupeKey,"dedupeKey");if(x===void 0||P===void 0||J===void 0)return g.json($e("invalid_argument","to, prompt, and dedupeKey are required"),400);let ee=fa(t.db.db,t.teams,{to:x,prompt:P,dedupeKey:J});return g.json(ee,ee.replayed?200:202)}catch(y){return _(g,y)}}),m.post("/api/queue/deliver",async g=>{let y=await o(),x=Tr(t.db.db,{teams:t.teams,report:y,...e.remoteMail?{remoteMail:e.remoteMail}:{}});return g.json({delivered:x})}),m.post("/api/queue/retrieve",async g=>{let y=await g.req.json().catch(()=>({}));if(!y.to)return g.json({error:"to is required"},400);if(y.id!==void 0&&(!Number.isInteger(y.id)||y.id<=0))return g.json({error:"id must be a positive integer"},400);try{let P=Ys(t.db.db,y.to,y.id).map(J=>{let ee;try{ee=YO(J.prompt_file,"utf8")}catch{ee="(could not read prompt file)"}return{...J,content:ee}});return g.json({retrieved:P})}catch(x){return _(g,x)}}),m.get("/api/inbox",g=>{let y=g.req.query("to");return y?g.json(Su(t,y)):g.json($e("to_required","to is required"),400)});function _(g,y){if(y instanceof I){let x=y.code==="NOT_FOUND"?404:y.code==="CONFLICT"?409:y.code==="DB_BUSY"?503:y.code==="STORAGE_ERROR"?500:400;return g.json($e(y.code,y.message),x)}return g.json($e("internal_error",y instanceof Error?y.message:String(y)),500)}let T=new Set(["epic","task","subtask"]);function E(g,y,x){if(g===void 0)return;let P=Number(g);if(!/^[1-9]\d*$/.test(g)||!Number.isSafeInteger(P)||x!==void 0&&P>x)throw new I("INVALID_ARGUMENT",x!==void 0?`${y} must be a positive integer <= ${x}`:`${y} must be a positive integer`);return P}function v(g,y){if(g===void 0)return;let x=Number(g);if(!/^\d+$/.test(g)||!Number.isSafeInteger(x))throw new I("INVALID_ARGUMENT",`${y} must be a nonnegative integer`);return x}function S(g,y){let x=Number(g);if(!/^[1-9]\d*$/.test(g)||!Number.isSafeInteger(x))throw new I("INVALID_ARGUMENT",`${y} must be a positive integer`);return x}function N(g){if(g!==void 0){if(!T.has(g))throw new I("INVALID_ARGUMENT","kind must be 'epic', 'task', or 'subtask'");return g}}function $(g,y){if(g!==void 0){if(g.trim()==="")throw new I("INVALID_ARGUMENT",`${y} must not be blank`);return g}}function L(g,y){if(g!==void 0){if(g==="1"||g==="true")return!0;if(g==="0"||g==="false")return!1;throw new I("INVALID_ARGUMENT",`${y} must be '1'/'true' or '0'/'false'`)}}function R(g){if(g!==void 0){if(!yc.includes(g))throw new I("INVALID_ARGUMENT",`status must be one of: ${yc.join(", ")}`);return g}}function H(g,y){if(g===void 0)return;let x=g.trim()===""?NaN:Date.parse(g);if(Number.isNaN(x))throw new I("INVALID_ARGUMENT",`${y} must be a valid ISO8601 date-time string`);return new Date(x).toISOString()}function C(g,y){let x=$(g,"ownerTeam"),P=$(y,"ownerAlias");if(!(x===void 0&&P===void 0)){if(x===void 0||P===void 0)throw new I("INVALID_ARGUMENT","ownerTeam and ownerAlias must both be given");return{team:x,alias:P}}}return m.get("/api/tasks",g=>{let y=g.req.query();try{let x={project:$(y.project,"project"),kind:N(y.kind),status:$(y.status,"status"),parentId:E(y.parentId,"parentId"),owner:C(y.ownerTeam,y.ownerAlias),unassigned:L(y.unassigned,"unassigned"),limit:E(y.limit,"limit",Ne),after:v(y.after,"after")};return g.json(Sr(t.db.db,x))}catch(x){return _(g,x)}}),m.get("/api/tasks/summary",g=>{try{let y=E(g.req.query("id"),"id"),x=$(g.req.query("project"),"project");return g.json(kr(t.db.db,{id:y,project:x}))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id",g=>{try{let y=S(g.req.param("id"),"id");return g.json(vr(t.db.db,y))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id/tree",g=>{try{let y=S(g.req.param("id"),"id");return g.json(Ar(t.db.db,y))}catch(y){return _(g,y)}}),m.get("/api/tasks/:id/notes",g=>{try{let y=S(g.req.param("id"),"id"),x=v(g.req.query("after"),"after"),P=E(g.req.query("limit"),"limit",Ne);return g.json(vf(t.db.db,y,{limit:P,after:x}))}catch(y){return _(g,y)}}),m.post("/api/send",async g=>{let y=await g.req.json().catch(()=>({})),x=y.prompt;if(!y.team||!x)return g.json({error:"team and prompt are required"},400);let P=t.teams.find(V=>V.name===y.team);if(!P)return g.json({error:`unknown team "${y.team}"`},404);if(!B(P))return g.json({error:`team "${y.team}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let J=await s({teamfilePath:Q(P),alias:P.leadAlias},x),ee=Vn(J),oe=Date.now();return ir(t.db.db,P.name,ee.status,oe),tt(t.db.db,P.name,ee.status,oe,{note:"web send"}),g.json({status:ee.status,outcome:J})}),m.get("/api/history",g=>{let y=g.req.query("team"),x=g.req.query("limit"),P=lu(t,y,x);return"error"in P?g.json(P,400):g.json(P)}),m.get("/api/sources",g=>g.json(Au(t))),m.get("/api/mail/status",g=>g.json(uu(t))),m.get("/api/subscriptions",async g=>{let{status:y,body:x}=await yy();return g.json(x,y)}),m.get("/api/whoami",async g=>{let{data:y,exitCode:x}=await i();return"error"in y?g.json(y,x===4?502:400):g.json(y)}),m.get("/api/running",async g=>g.json(await o())),m.get("/api/running/humanized",async g=>g.json(Nl(await o()))),m.get("/api/running/observed",g=>g.json(Jo())),m.get("/api/heavy-lock",g=>{try{return g.json(Rl(c,l))}catch(y){if(y instanceof qn)return g.json($e("heavy_lock_probe_failed",y.message),502);throw y}}),m.get("/api/health",async g=>{let y=g.req.query("target");if(!y)return g.json($e("target_required","target is required"),400);try{let x=await a(y);return g.json(x)}catch(x){return g.json($e("health_fetch_failed",x instanceof Error?x.message:String(x)),502)}}),m.post("/api/sources",async g=>{let y=await g.req.json().catch(()=>({}));if(!y.path)return g.json({error:"path is required"},400);let x=ua(t,y.path,y.label??void 0);return x.ok?(t.teams=Jr(t.db.db,t.teamsConfPath),g.json({ok:!0})):g.json({error:x.output},400)}),m.delete("/api/sources",g=>{let y=g.req.query("path");return y?(Ms(t.db.db,y),t.teams=Jr(t.db.db,t.teamsConfPath),g.json({ok:!0})):g.json({error:"path is required"},400)}),m}function Bu(e){return e.teams=Jr(e.db.db,e.teamsConfPath),e.teams}var QO=4173,XO="127.0.0.1";function _E(e){if(process.env.LMBEE_SITE_UUID!==void 0)try{let h=En(e.context.db.db,void 0,process.env.LMBEE_SITE_UUID);if(e.remoteMail&&e.remoteMail.localSiteId!==h)throw new Error("Remote mail site identity conflicts with the database binding")}catch(h){return Promise.reject(h)}let t=e.port??QO,r=e.hostname??XO,n=e.publish??!1;if(!["127.0.0.1","::1","localhost"].includes(r)&&!n)return Promise.reject(new Error("LocalWeb refuses a non-loopback bind without --publish (which also requires passcode auth)"));let o=r==="::1"?"[::1]":r,s=es(e.context.db.path),i=null;if(s!==null)try{i=sa(s,e.lockOwnerLabel??"lmbee-serve")}catch(h){return Promise.reject(h)}let a=t===0?[]:[`http://${o}:${t}`,`http://localhost:${t}`,`http://[::1]:${t}`],c=e.remoteMail?{client:e.remoteMail.client,localSiteId:e.remoteMail.localSiteId}:void 0,l,u,d,m,f=null,p=null;try{let h=e.passcodeFilePath??Gn(e.context.db.path);n&&h!==null&&ia(h),l=gE({context:e.context,allowedOrigins:a,publish:n,passcodeFilePath:h,...e.config!==void 0?{config:e.config}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...e.mountPath!==void 0?{mountPath:e.mountPath}:{},...e.webDistDir!==void 0?{webDistDir:e.webDistDir}:{},...c?{remoteMail:c}:{},...e.remoteStalledConfig!==void 0?{remoteStalledConfig:e.remoteStalledConfig}:{}});let w=e.mountPath?.endsWith("/")?e.mountPath.slice(0,-1):e.mountPath;if(w?u=new tn().route(w,l).get(`${w}/`,async _=>{let T=new URL(_.req.url);T.pathname="/",T.search="";let E=await l.fetch(new Request(T,{method:"GET",headers:_.req.raw.headers}));return E.ok?_.redirect(w,302):E}):u=l,d=o_({db:e.context.db.db,getTeams:()=>Bu(e.context),...e.intervalMs!==void 0?{intervalMs:e.intervalMs}:{},...e.config!==void 0?{config:e.config}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...e.maintainerWake!==void 0?{maintainerWake:e.maintainerWake}:{},...e.autoContinue!==void 0?{autoContinue:e.autoContinue}:{},...e.miniplayerVerify!==void 0?{miniplayerVerify:e.miniplayerVerify}:{},...e.hungHolderCheck!==void 0?{hungHolderCheck:e.hungHolderCheck}:{},...e.epicReview!==void 0?{epicReview:e.epicReview}:{},...e.orphanReconciler!==void 0?{orphanReconciler:e.orphanReconciler}:{},...e.hangProbeCollect!==void 0?{hangProbeCollect:e.hangProbeCollect}:{},...e.autoNudgeRedirectReview!==void 0?{autoNudgeRedirectReview:e.autoNudgeRedirectReview}:{},...e.rateLimitCollect!==void 0?{rateLimitCollect:e.rateLimitCollect}:{},...e.rateLimitPolicy!==void 0?{rateLimitPolicy:e.rateLimitPolicy}:{},...e.rateLimitAutomation!==void 0?{rateLimitAutomation:e.rateLimitAutomation}:{},onTick:_=>{process.stderr.write(`[cron] tick: watch=${_.watch.why}, ${_.stalled.length} stalled (${_.stalled.join(", ")||"none"})${_.maintainerWoken?", maintainer woken":""}${_.autoContinued.length?`, auto-continued (${_.autoContinued.join(", ")})`:""}
595
595
  `)},onError:_=>{process.stderr.write(`[cron] tick failed: ${_ instanceof Error?_.stack??_.message:String(_)}
596
- `)}}),m=G_({db:e.context.db.db,getTeams:()=>qu(e.context),...e.queueIntervalMs!==void 0?{intervalMs:e.queueIntervalMs}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...c?{remoteMail:c}:{},...e.deliverImpl!==void 0?{deliverImpl:e.deliverImpl}:{},...e.minMemoryPercent!==void 0?{minMemoryPercent:e.minMemoryPercent}:{},onDeliver:_=>{_>0&&process.stderr.write(`[queue] delivered ${_}
596
+ `)}}),m=Y_({db:e.context.db.db,getTeams:()=>Bu(e.context),...e.queueIntervalMs!==void 0?{intervalMs:e.queueIntervalMs}:{},...e.fetchReport!==void 0?{fetchReport:e.fetchReport}:{},...c?{remoteMail:c}:{},...e.deliverImpl!==void 0?{deliverImpl:e.deliverImpl}:{},...e.minMemoryPercent!==void 0?{minMemoryPercent:e.minMemoryPercent}:{},onDeliver:_=>{_>0&&process.stderr.write(`[queue] delivered ${_}
597
597
  `)},onError:_=>{process.stderr.write(`[queue] delivery pass failed: ${_ instanceof Error?_.stack??_.message:String(_)}
598
- `)}}),e.remoteMail){let _=e.remoteMail;f=W_({db:e.context.db.db,client:_.client,mailbox:_.mailbox,worker:{localSiteId:_.localSiteId,allowlist:_.allowlist,dispatch:E=>f_(e.context.db.db,qu(e.context),E,{client:_.client,localSiteId:_.localSiteId})},..._.intervalMs!==void 0?{intervalMs:_.intervalMs}:{},onPoll:E=>{if(_.onPoll?.(E),E.recorded>0||E.retriedFailed>0){let T=e.fetchReport??Ae,v=e.deliverImpl??Er;T().then(S=>v(e.context.db.db,{teams:e.context.teams,report:S,...c?{remoteMail:c}:{}})).catch(S=>{process.stderr.write(`[mail] prompt-delivery trigger failed: ${S instanceof Error?S.stack??S.message:String(S)}
599
- `)})}},onError:_.onMailError??(E=>{process.stderr.write(`[mail] poll failed: ${E instanceof Error?E.stack??E.message:String(E)}
600
- `)})})}if(e.execWorker){let _=e.execWorker;p=(_.createExecWorkerImpl??q_)({client:_.client,mailbox:_.mailbox,adminUsers:_.adminUsers,allowUsers:_.allowUsers,allowAnonymous:_.allowAnonymous,..._.pollIntervalMs!==void 0?{pollIntervalMs:_.pollIntervalMs}:{},..._.timeoutCapSeconds!==void 0?{timeoutCapSeconds:_.timeoutCapSeconds}:{}})}}catch(h){throw i?.release(),h}return new Promise((h,w)=>{let _=!1,E;try{E=Kf({fetch:u.fetch,port:t,hostname:r},T=>{if(t===0&&a.push(`http://${o}:${T.port}`,`http://localhost:${T.port}`,`http://[::1]:${T.port}`),_=!0,d.start(),m.start(),f&&e.remoteMail){let v=e.remoteMail;(v.ensureMailboxImpl??B_)(v.client,v.mailbox).then(()=>f?.start()).catch(N=>{process.stderr.write(`[mail] mailbox provisioning failed, mail lane stays dormant this run: ${N instanceof Error?N.stack??N.message:String(N)}
601
- `),v.onMailError?.(N)})}if(p&&e.execWorker){let v=e.execWorker;(v.ensureExecMailboxImpl??F_)(v.client,v.mailbox).then(()=>p?.start()).catch(N=>{process.stderr.write(`[exec-worker] mailbox provisioning failed, exec stays dormant this run: ${N instanceof Error?N.stack??N.message:String(N)}
602
- `)})}h({app:l,scheduler:d,queueScheduler:m,mailScheduler:f,execWorker:p,server:E,port:T.port,hostname:r,close(){d.stop(),m.stop(),f?.stop(),p?.stop(),E.close(),i?.release()},async shutdown(){d.stop(),m.stop(),f?.stop(),p?.stop();let v=new Promise((N,x)=>{E.close(I=>I?x(I):N())}),S=(async()=>{for(;d.isTicking()||m.isDelivering()||(f?.isPolling()??!1);)await new Promise(N=>setTimeout(N,50))})();await Promise.all([v,S,p?.whenIdle()??Promise.resolve()]),i?.release()}})})}catch(T){i?.release(),w(T instanceof Error?T:new Error(String(T)));return}E.on("error",T=>{if(_){process.stderr.write(`[serve] post-bind server error (ignored -- lock/scheduler untouched): ${T instanceof Error?T.stack??T.message:String(T)}
603
- `);return}_=!0,i?.release(),w(T instanceof Error?T:new Error(String(T)))})})}function wt(e,t=[]){let r=new Set(t),n=[],o={};for(let s=0;s<e.length;s++){let i=e[s];if(i==="-h")o.help=!0;else if(i.startsWith("--")){let a=i.slice(2),c=e[s+1];!r.has(a)&&c!==void 0&&!c.startsWith("--")?(o[a]=c,s++):o[a]=!0}else n.push(i)}return{positionals:n,flags:o}}function an(e,t){if(e===void 0)return;if(typeof e!="string")return new Error(`${t} requires a numeric value (milliseconds)`);let r=Number(e);return!Number.isFinite(r)||r<0?new Error(`${t} must be a finite, non-negative number of milliseconds, got "${e}"`):r}function Zn(e,t){if(e===void 0)return;if(typeof e!="string")return new Error(`${t} requires a numeric value`);let r=Number(e);return!Number.isFinite(r)||r<0?new Error(`${t} must be a finite, non-negative number, got "${e}"`):r}import{existsSync as VO,readFileSync as JO,writeFileSync as KO}from"node:fs";var ju="lmbee-cron-export",fE=["schema_version","kind","exported_at","exported_from","jobs"],pE=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","timezone","enabled"],zO=["provider","model","working_directory","escalation_owner","timezone"];function YO(e){return{id:e.id,title:e.title,schedule_expr:e.schedule_expr,action_kind:e.action_kind,action_payload:e.action_payload,provider:e.provider,model:e.model,working_directory:e.working_directory,escalation_owner:e.escalation_owner,timezone:e.timezone,enabled:!!e.enabled}}function QO(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("SQLITE_BUSY")}function XO(e,t){let r;try{r=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_jobs'").get()!==void 0?e.prepare("SELECT * FROM cron_jobs ORDER BY id").all():[]}catch(n){throw QO(n)?new U("SOURCE_BUSY","source database is locked by another process -- export never waits on locks (busy_timeout = 0); retry shortly",3):n}for(let n of r)if(n.action_kind!=="command"&&n.action_kind!=="script")throw new U("INVALID_ARGUMENT",`cron job ${n.id} "${n.title}" has action_kind "${n.action_kind}" -- export does not carry ${n.action_kind}-kind jobs, so no file was written (import would refuse it; never produce a transferable payload containing one -- re-create the job manually on the target)`);return{schema_version:1,kind:ju,exported_at:new Date().toISOString(),exported_from:t,jobs:r.map(YO)}}function ZO(e,t,r){let n=XO(e,r);try{KO(t,`${JSON.stringify(n,null,2)}
604
- `,{flag:"wx"})}catch(o){throw o&&typeof o=="object"&&"code"in o&&o.code==="EEXIST"?new U("INVALID_ARGUMENT",`export path already exists: ${t} (rm it first; there is no --force)`):new U("INVALID_ARGUMENT",`cannot write export to ${t}: ${o instanceof Error?o.message:String(o)}`)}return n}function eD(e){let t=wo(e);ja(t);let r=new ht(t,{readonly:!0,fileMustExist:!0});return r.pragma("busy_timeout = 0"),{db:r,path:t,close:()=>r.close()}}var hE=`usage: lmbee cron export PATH [--json] -- write all cron job DEFINITIONS (ids preserved) as one JSON document;
605
- refuses if PATH already exists (rm it first; there is no --force). Definitions only, never execution state.`;function ns(e,t,r){if(t.length>1)throw new U("INVALID_ARGUMENT",`cron ${e} takes exactly one PATH argument -- refusing unexpected extra argument ${JSON.stringify(t[1])}`);for(let n of Object.keys(r))if(n!=="json"&&n!=="help")throw new U("INVALID_ARGUMENT",`cron ${e} does not know flag "--${n}" (only --json and --help)`)}function gE(e){let{positionals:t,flags:r}=wt(e,["json","help"]),n=r.json===!0;try{if(r.help===!0)return{output:hE,exitCode:0};ns("export",t,r);let o=t[0];if(o===void 0)throw new U("INVALID_ARGUMENT",`an export PATH is required
606
- ${hE}`);let s=eD();try{let i=ZO(s.db,o,s.path);return n?{output:JSON.stringify({schema_version:1,ok:!0,data:{path:o,exported_from:s.path,jobs:i.jobs.length}}),exitCode:0}:{output:`exported ${i.jobs.length} jobs to ${o}`,exitCode:0}}finally{s.close()}}catch(o){if(o instanceof U)return n?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:o.code,message:o.message}}),exitCode:o.exitCode}:{output:`${o.code}: ${o.message}`,exitCode:o.exitCode};throw o}}function yt(e,t){throw new U("INVALID_ARGUMENT",`jobs[${e}]: ${t}`)}function tD(e,t){(typeof e!="object"||e===null||Array.isArray(e))&&yt(t,"must be a JSON object");let r=e;for(let l of Object.keys(r))pE.includes(l)||yt(t,`unknown key "${l}"`);for(let l of pE)l in r||yt(t,`missing key "${l}"`);let{id:n,title:o,schedule_expr:s,action_kind:i,action_payload:a,enabled:c}=r;(typeof n!="number"||!Number.isSafeInteger(n)||n<1)&&yt(t,"id must be a positive safe integer"),(typeof o!="string"||o.trim().length===0)&&yt(t,"title must be a nonblank string"),typeof s!="string"&&yt(t,"schedule_expr must be a string"),typeof i!="string"&&yt(t,"action_kind must be a string"),i==="enqueue"&&yt(t,"import does not carry enqueue-kind jobs (zero existed when this was designed; refusing rather than risking a payload current validation rejects -- create it manually)"),(i==="session"||i==="miniplayer")&&yt(t,`import does not carry ${i}-kind jobs (out of scope -- untested expansion; create it manually)`),i!=="command"&&i!=="script"&&yt(t,`action_kind "${i}" is not a known kind; only "command" and "script" are accepted`),typeof a!="string"&&yt(t,"action_payload must be a string"),typeof c!="boolean"&&yt(t,`enabled must be a JSON boolean (true/false), not ${JSON.stringify(c)}`);for(let l of zO){let u=r[l];u!==null&&typeof u!="string"&&yt(t,`${l} must be a string or null`)}return r}function _E(e){let t;try{t=JO(e,"utf8")}catch(i){throw new U("INVALID_ARGUMENT",`cannot read import file ${e}: ${i instanceof Error?i.message:String(i)}`)}let r;try{r=JSON.parse(t)}catch(i){throw new U("INVALID_ARGUMENT",`import file ${e} is not valid JSON: ${i instanceof Error?i.message:String(i)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new U("INVALID_ARGUMENT","import document must be a JSON object");let n=r;for(let i of Object.keys(n))if(!fE.includes(i))throw new U("INVALID_ARGUMENT",`unknown top-level key "${i}"`);for(let i of fE)if(!(i in n))throw new U("INVALID_ARGUMENT",`missing top-level key "${i}"`);if(n.schema_version!==1)throw new U("INVALID_ARGUMENT",`schema_version must be 1, got ${JSON.stringify(n.schema_version)}`);if(n.kind!==ju)throw new U("INVALID_ARGUMENT",`kind must be "${ju}", got ${JSON.stringify(n.kind)}`);for(let i of["exported_at","exported_from"])if(typeof n[i]!="string")throw new U("INVALID_ARGUMENT",`${i} must be a string, got ${JSON.stringify(n[i])}`);if(!Array.isArray(n.jobs))throw new U("INVALID_ARGUMENT","jobs must be an array");let o=n.jobs.map((i,a)=>tD(i,a)),s=new Set;for(let i of o){if(s.has(i.id))throw new U("INVALID_ARGUMENT",`duplicate id ${i.id} within the document`);s.add(i.id)}return o}function wE(e){return{...e,title:e.title.trim(),timezone:e.timezone===null?null:e.timezone.trim()}}function rD(e,t){let r=wE(t);return e.title===r.title&&e.schedule_expr===r.schedule_expr&&e.action_kind===r.action_kind&&e.action_payload===r.action_payload&&e.provider===r.provider&&e.model===r.model&&e.working_directory===r.working_directory&&e.escalation_owner===r.escalation_owner&&e.timezone===r.timezone&&!!e.enabled===r.enabled}function nD(e){let t=wE(e);return{id:t.id,title:t.title,scheduleExpr:t.schedule_expr,actionKind:t.action_kind,actionPayload:t.action_payload,enabled:t.enabled,...t.provider!==null?{provider:t.provider}:{},...t.model!==null?{model:t.model}:{},...t.working_directory!==null?{workingDirectory:t.working_directory}:{},...t.escalation_owner!==null?{escalationOwner:t.escalation_owner}:{},...t.timezone!==null?{timezone:t.timezone}:{}}}function yE(e){_E(e)}function EE(e,t){let r=_E(t),n=[],o=[];e.transaction(()=>{for(let a of r){let c=Ii(e,a.id);if(c!==null){if(rD(c,a)){n.push({id:a.id,title:a.title});continue}throw new U("CONFLICT",`cron job ${a.id} already exists with a different definition: existing "${c.title}" vs import "${a.title}" -- refusing the whole file, nothing written`,4)}Pn(e,nD(a)),o.push(a)}}).immediate();let i=[];for(let a of o)a.working_directory!==null&&!VO(a.working_directory)&&i.push(`job ${a.id} "${a.title}": working_directory ${a.working_directory} does not exist on this host`);return{imported:o.length,skipped:n,warnings:i}}function TE(e){let t=[`imported ${e.imported}, skipped ${e.skipped.length} already-present`];for(let r of e.skipped)t.push(`skipped: ${r.id} "${r.title}"`);for(let r of e.warnings)t.push(`warning: ${r}`);return t.join(`
607
- `)}async function bE(e,t={}){let r=t.team===void 0?e.teams:e.teams.filter(c=>c.name===t.team);if(t.team!==void 0){if(r.length===0)throw new Error(`unknown team: ${t.team}`);if(!r.every(H))throw new Error(`stalled verdict requires a local team: ${t.team}`)}let n=r.filter(H),o=await(t.fetchReportImpl??Ae)(),s=t.heavyLockImpl?.()??lt(void 0,void 0,void 0,c=>{process.stderr.write(`[stalled] heavy-lock probe failed, treating conservatively as held: ${c.message}
608
- `)}),i=t.nowMs??Date.now(),a=t.config??pe;return{teams:n.map(c=>({team:c.name,stalled:Lc(e.db.db,c,o,s,a,i)}))}}var fa=Ut(xt(),1);import{readFileSync as oD}from"node:fs";function cn(e,t,r={}){if(e===void 0)return;if(typeof e!="string"||!/^\d+$/.test(e))throw new U("INVALID_ARGUMENT",`${t} must be a nonnegative integer`);let n=Number(e),o=r.minimum??1;if(!Number.isSafeInteger(n)||n<o||r.maximum!==void 0&&n>r.maximum){let s=r.maximum!==void 0?`between ${o} and ${r.maximum}`:`>= ${o}`;throw new U("INVALID_ARGUMENT",`${t} must be an integer ${s}`)}return n}function ur(e,t){let r=cn(e,t,{minimum:1});if(r===void 0)throw new U("INVALID_ARGUMENT",`${t} is required`);return r}function sD(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}var iD=["pending","running","succeeded","failed","escalated"];function aD(e){return iD.includes(e)}function SE(e){let t=e.payload,r=e.prompt,n=e["prompt-file"];if([t,r,n].filter(s=>s!==void 0).length>1)throw new U("INVALID_ARGUMENT","provide only one of --payload, --prompt, or --prompt-file");if(n!==void 0){if(typeof n!="string")throw new U("INVALID_ARGUMENT","--prompt-file requires a path");try{return oD(n,"utf8")}catch(s){throw new U("INVALID_ARGUMENT",`cannot read --prompt-file ${n}: ${s instanceof Error?s.message:String(s)}`)}}if(typeof t=="string")return t;if(typeof r=="string")return r}function We(e){return typeof e=="string"?e:void 0}function dt(e,t,r={}){return e?JSON.stringify({schema_version:1,ok:!0,data:t,meta:r}):cD(t,r)}function vE(e,t){return e?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:t.code,message:t.message}}),exitCode:t.exitCode}:{output:`${t.code}: ${t.message}`,exitCode:t.exitCode}}function cD(e,t){let r;if(Array.isArray(e)){let o=s=>s!==null&&typeof s=="object"&&"title"in s;r=e.length===0?"(empty)":e.every(o)?(0,fa.formatTable)([["ID","ENABLED","KIND","SCHEDULE","TITLE"],...e.map(s=>["id","enabled","action_kind","schedule_expr","title"].map(i=>(0,fa.escapeCell)(String(s[i]??""))))]):e.map(s=>JSON.stringify(s)).join(`
598
+ `)}}),e.remoteMail){let _=e.remoteMail;f=z_({db:e.context.db.db,client:_.client,mailbox:_.mailbox,worker:{localSiteId:_.localSiteId,allowlist:_.allowlist,dispatch:T=>w_(e.context.db.db,Bu(e.context),T,{client:_.client,localSiteId:_.localSiteId})},..._.intervalMs!==void 0?{intervalMs:_.intervalMs}:{},onPoll:T=>{if(_.onPoll?.(T),T.recorded>0||T.retriedFailed>0){let E=e.fetchReport??Ae,v=e.deliverImpl??Tr;E().then(S=>v(e.context.db.db,{teams:e.context.teams,report:S,...c?{remoteMail:c}:{}})).catch(S=>{process.stderr.write(`[mail] prompt-delivery trigger failed: ${S instanceof Error?S.stack??S.message:String(S)}
599
+ `)})}},onError:_.onMailError??(T=>{process.stderr.write(`[mail] poll failed: ${T instanceof Error?T.stack??T.message:String(T)}
600
+ `)})})}if(e.execWorker){let _=e.execWorker;p=(_.createExecWorkerImpl??G_)({client:_.client,mailbox:_.mailbox,adminUsers:_.adminUsers,allowUsers:_.allowUsers,allowAnonymous:_.allowAnonymous,..._.pollIntervalMs!==void 0?{pollIntervalMs:_.pollIntervalMs}:{},..._.timeoutCapSeconds!==void 0?{timeoutCapSeconds:_.timeoutCapSeconds}:{}})}}catch(h){throw i?.release(),h}return new Promise((h,w)=>{let _=!1,T;try{T=Qf({fetch:u.fetch,port:t,hostname:r},E=>{if(t===0&&a.push(`http://${o}:${E.port}`,`http://localhost:${E.port}`,`http://[::1]:${E.port}`),_=!0,d.start(),m.start(),f&&e.remoteMail){let v=e.remoteMail;(v.ensureMailboxImpl??K_)(v.client,v.mailbox).then(()=>f?.start()).catch(N=>{process.stderr.write(`[mail] mailbox provisioning failed, mail lane stays dormant this run: ${N instanceof Error?N.stack??N.message:String(N)}
601
+ `),v.onMailError?.(N)})}if(p&&e.execWorker){let v=e.execWorker;(v.ensureExecMailboxImpl??W_)(v.client,v.mailbox).then(()=>p?.start()).catch(N=>{process.stderr.write(`[exec-worker] mailbox provisioning failed, exec stays dormant this run: ${N instanceof Error?N.stack??N.message:String(N)}
602
+ `)})}h({app:l,scheduler:d,queueScheduler:m,mailScheduler:f,execWorker:p,server:T,port:E.port,hostname:r,close(){d.stop(),m.stop(),f?.stop(),p?.stop(),T.close(),i?.release()},async shutdown(){d.stop(),m.stop(),f?.stop(),p?.stop();let v=new Promise((N,$)=>{T.close(L=>L?$(L):N())}),S=(async()=>{for(;d.isTicking()||m.isDelivering()||(f?.isPolling()??!1);)await new Promise(N=>setTimeout(N,50))})();await Promise.all([v,S,p?.whenIdle()??Promise.resolve()]),i?.release()}})})}catch(E){i?.release(),w(E instanceof Error?E:new Error(String(E)));return}T.on("error",E=>{if(_){process.stderr.write(`[serve] post-bind server error (ignored -- lock/scheduler untouched): ${E instanceof Error?E.stack??E.message:String(E)}
603
+ `);return}_=!0,i?.release(),w(E instanceof Error?E:new Error(String(E)))})})}function yt(e,t=[]){let r=new Set(t),n=[],o={};for(let s=0;s<e.length;s++){let i=e[s];if(i==="-h")o.help=!0;else if(i.startsWith("--")){let a=i.slice(2),c=e[s+1];!r.has(a)&&c!==void 0&&!c.startsWith("--")?(o[a]=c,s++):o[a]=!0}else n.push(i)}return{positionals:n,flags:o}}function an(e,t){if(e===void 0)return;if(typeof e!="string")return new Error(`${t} requires a numeric value (milliseconds)`);let r=Number(e);return!Number.isFinite(r)||r<0?new Error(`${t} must be a finite, non-negative number of milliseconds, got "${e}"`):r}function to(e,t){if(e===void 0)return;if(typeof e!="string")return new Error(`${t} requires a numeric value`);let r=Number(e);return!Number.isFinite(r)||r<0?new Error(`${t} must be a finite, non-negative number, got "${e}"`):r}import{existsSync as ZO,readFileSync as eD,writeFileSync as tD}from"node:fs";var Wu="lmbee-cron-export",wE=["schema_version","kind","exported_at","exported_from","jobs"],yE=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","timezone","enabled"],rD=["provider","model","working_directory","escalation_owner","timezone"];function nD(e){return{id:e.id,title:e.title,schedule_expr:e.schedule_expr,action_kind:e.action_kind,action_payload:e.action_payload,provider:e.provider,model:e.model,working_directory:e.working_directory,escalation_owner:e.escalation_owner,timezone:e.timezone,enabled:!!e.enabled}}function oD(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("SQLITE_BUSY")}function sD(e,t){let r;try{r=e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_jobs'").get()!==void 0?e.prepare("SELECT * FROM cron_jobs ORDER BY id").all():[]}catch(n){throw oD(n)?new U("SOURCE_BUSY","source database is locked by another process -- export never waits on locks (busy_timeout = 0); retry shortly",3):n}for(let n of r)if(n.action_kind!=="command"&&n.action_kind!=="script")throw new U("INVALID_ARGUMENT",`cron job ${n.id} "${n.title}" has action_kind "${n.action_kind}" -- export does not carry ${n.action_kind}-kind jobs, so no file was written (import would refuse it; never produce a transferable payload containing one -- re-create the job manually on the target)`);return{schema_version:1,kind:Wu,exported_at:new Date().toISOString(),exported_from:t,jobs:r.map(nD)}}function iD(e,t,r){let n=sD(e,r);try{tD(t,`${JSON.stringify(n,null,2)}
604
+ `,{flag:"wx"})}catch(o){throw o&&typeof o=="object"&&"code"in o&&o.code==="EEXIST"?new U("INVALID_ARGUMENT",`export path already exists: ${t} (rm it first; there is no --force)`):new U("INVALID_ARGUMENT",`cannot write export to ${t}: ${o instanceof Error?o.message:String(o)}`)}return n}function aD(e){let t=Eo(e);Wa(t);let r=new ht(t,{readonly:!0,fileMustExist:!0});return r.pragma("busy_timeout = 0"),{db:r,path:t,close:()=>r.close()}}var EE=`usage: lmbee cron export PATH [--json] -- write all cron job DEFINITIONS (ids preserved) as one JSON document;
605
+ refuses if PATH already exists (rm it first; there is no --force). Definitions only, never execution state.`;function as(e,t,r){if(t.length>1)throw new U("INVALID_ARGUMENT",`cron ${e} takes exactly one PATH argument -- refusing unexpected extra argument ${JSON.stringify(t[1])}`);for(let n of Object.keys(r))if(n!=="json"&&n!=="help")throw new U("INVALID_ARGUMENT",`cron ${e} does not know flag "--${n}" (only --json and --help)`)}function TE(e){let{positionals:t,flags:r}=yt(e,["json","help"]),n=r.json===!0;try{if(r.help===!0)return{output:EE,exitCode:0};as("export",t,r);let o=t[0];if(o===void 0)throw new U("INVALID_ARGUMENT",`an export PATH is required
606
+ ${EE}`);let s=aD();try{let i=iD(s.db,o,s.path);return n?{output:JSON.stringify({schema_version:1,ok:!0,data:{path:o,exported_from:s.path,jobs:i.jobs.length}}),exitCode:0}:{output:`exported ${i.jobs.length} jobs to ${o}`,exitCode:0}}finally{s.close()}}catch(o){if(o instanceof U)return n?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:o.code,message:o.message}}),exitCode:o.exitCode}:{output:`${o.code}: ${o.message}`,exitCode:o.exitCode};throw o}}function Et(e,t){throw new U("INVALID_ARGUMENT",`jobs[${e}]: ${t}`)}function cD(e,t){(typeof e!="object"||e===null||Array.isArray(e))&&Et(t,"must be a JSON object");let r=e;for(let l of Object.keys(r))yE.includes(l)||Et(t,`unknown key "${l}"`);for(let l of yE)l in r||Et(t,`missing key "${l}"`);let{id:n,title:o,schedule_expr:s,action_kind:i,action_payload:a,enabled:c}=r;(typeof n!="number"||!Number.isSafeInteger(n)||n<1)&&Et(t,"id must be a positive safe integer"),(typeof o!="string"||o.trim().length===0)&&Et(t,"title must be a nonblank string"),typeof s!="string"&&Et(t,"schedule_expr must be a string"),typeof i!="string"&&Et(t,"action_kind must be a string"),i==="enqueue"&&Et(t,"import does not carry enqueue-kind jobs (zero existed when this was designed; refusing rather than risking a payload current validation rejects -- create it manually)"),(i==="session"||i==="miniplayer")&&Et(t,`import does not carry ${i}-kind jobs (out of scope -- untested expansion; create it manually)`),i!=="command"&&i!=="script"&&Et(t,`action_kind "${i}" is not a known kind; only "command" and "script" are accepted`),typeof a!="string"&&Et(t,"action_payload must be a string"),typeof c!="boolean"&&Et(t,`enabled must be a JSON boolean (true/false), not ${JSON.stringify(c)}`);for(let l of rD){let u=r[l];u!==null&&typeof u!="string"&&Et(t,`${l} must be a string or null`)}return r}function bE(e){let t;try{t=eD(e,"utf8")}catch(i){throw new U("INVALID_ARGUMENT",`cannot read import file ${e}: ${i instanceof Error?i.message:String(i)}`)}let r;try{r=JSON.parse(t)}catch(i){throw new U("INVALID_ARGUMENT",`import file ${e} is not valid JSON: ${i instanceof Error?i.message:String(i)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new U("INVALID_ARGUMENT","import document must be a JSON object");let n=r;for(let i of Object.keys(n))if(!wE.includes(i))throw new U("INVALID_ARGUMENT",`unknown top-level key "${i}"`);for(let i of wE)if(!(i in n))throw new U("INVALID_ARGUMENT",`missing top-level key "${i}"`);if(n.schema_version!==1)throw new U("INVALID_ARGUMENT",`schema_version must be 1, got ${JSON.stringify(n.schema_version)}`);if(n.kind!==Wu)throw new U("INVALID_ARGUMENT",`kind must be "${Wu}", got ${JSON.stringify(n.kind)}`);for(let i of["exported_at","exported_from"])if(typeof n[i]!="string")throw new U("INVALID_ARGUMENT",`${i} must be a string, got ${JSON.stringify(n[i])}`);if(!Array.isArray(n.jobs))throw new U("INVALID_ARGUMENT","jobs must be an array");let o=n.jobs.map((i,a)=>cD(i,a)),s=new Set;for(let i of o){if(s.has(i.id))throw new U("INVALID_ARGUMENT",`duplicate id ${i.id} within the document`);s.add(i.id)}return o}function SE(e){return{...e,title:e.title.trim(),timezone:e.timezone===null?null:e.timezone.trim()}}function lD(e,t){let r=SE(t);return e.title===r.title&&e.schedule_expr===r.schedule_expr&&e.action_kind===r.action_kind&&e.action_payload===r.action_payload&&e.provider===r.provider&&e.model===r.model&&e.working_directory===r.working_directory&&e.escalation_owner===r.escalation_owner&&e.timezone===r.timezone&&!!e.enabled===r.enabled}function uD(e){let t=SE(e);return{id:t.id,title:t.title,scheduleExpr:t.schedule_expr,actionKind:t.action_kind,actionPayload:t.action_payload,enabled:t.enabled,...t.provider!==null?{provider:t.provider}:{},...t.model!==null?{model:t.model}:{},...t.working_directory!==null?{workingDirectory:t.working_directory}:{},...t.escalation_owner!==null?{escalationOwner:t.escalation_owner}:{},...t.timezone!==null?{timezone:t.timezone}:{}}}function vE(e){bE(e)}function AE(e,t){let r=bE(t),n=[],o=[];e.transaction(()=>{for(let a of r){let c=Oi(e,a.id);if(c!==null){if(lD(c,a)){n.push({id:a.id,title:a.title});continue}throw new U("CONFLICT",`cron job ${a.id} already exists with a different definition: existing "${c.title}" vs import "${a.title}" -- refusing the whole file, nothing written`,4)}Fn(e,uD(a)),o.push(a)}}).immediate();let i=[];for(let a of o)a.working_directory!==null&&!ZO(a.working_directory)&&i.push(`job ${a.id} "${a.title}": working_directory ${a.working_directory} does not exist on this host`);return{imported:o.length,skipped:n,warnings:i}}function kE(e){let t=[`imported ${e.imported}, skipped ${e.skipped.length} already-present`];for(let r of e.skipped)t.push(`skipped: ${r.id} "${r.title}"`);for(let r of e.warnings)t.push(`warning: ${r}`);return t.join(`
607
+ `)}async function $E(e,t={}){let r=t.team===void 0?e.teams:e.teams.filter(c=>c.name===t.team);if(t.team!==void 0){if(r.length===0)throw new Error(`unknown team: ${t.team}`);if(!r.every(B))throw new Error(`stalled verdict requires a local team: ${t.team}`)}let n=r.filter(B),o=await(t.fetchReportImpl??Ae)(),s=t.heavyLockImpl?.()??lt(void 0,void 0,void 0,c=>{process.stderr.write(`[stalled] heavy-lock probe failed, treating conservatively as held: ${c.message}
608
+ `)}),i=t.nowMs??Date.now(),a=t.config??pe;return{teams:n.map(c=>({team:c.name,stalled:Dc(e.db.db,c,o,s,a,i)}))}}var ga=Ut(xt(),1);import{readFileSync as dD}from"node:fs";function cn(e,t,r={}){if(e===void 0)return;if(typeof e!="string"||!/^\d+$/.test(e))throw new U("INVALID_ARGUMENT",`${t} must be a nonnegative integer`);let n=Number(e),o=r.minimum??1;if(!Number.isSafeInteger(n)||n<o||r.maximum!==void 0&&n>r.maximum){let s=r.maximum!==void 0?`between ${o} and ${r.maximum}`:`>= ${o}`;throw new U("INVALID_ARGUMENT",`${t} must be an integer ${s}`)}return n}function dr(e,t){let r=cn(e,t,{minimum:1});if(r===void 0)throw new U("INVALID_ARGUMENT",`${t} is required`);return r}function mD(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}var fD=["pending","running","succeeded","failed","escalated"];function pD(e){return fD.includes(e)}function xE(e){let t=e.payload,r=e.prompt,n=e["prompt-file"];if([t,r,n].filter(s=>s!==void 0).length>1)throw new U("INVALID_ARGUMENT","provide only one of --payload, --prompt, or --prompt-file");if(n!==void 0){if(typeof n!="string")throw new U("INVALID_ARGUMENT","--prompt-file requires a path");try{return dD(n,"utf8")}catch(s){throw new U("INVALID_ARGUMENT",`cannot read --prompt-file ${n}: ${s instanceof Error?s.message:String(s)}`)}}if(typeof t=="string")return t;if(typeof r=="string")return r}function We(e){return typeof e=="string"?e:void 0}function dt(e,t,r={}){return e?JSON.stringify({schema_version:1,ok:!0,data:t,meta:r}):hD(t,r)}function RE(e,t){return e?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:t.code,message:t.message}}),exitCode:t.exitCode}:{output:`${t.code}: ${t.message}`,exitCode:t.exitCode}}function hD(e,t){let r;if(Array.isArray(e)){let o=s=>s!==null&&typeof s=="object"&&"title"in s;r=e.length===0?"(empty)":e.every(o)?(0,ga.formatTable)([["ID","ENABLED","KIND","SCHEDULE","TITLE"],...e.map(s=>["id","enabled","action_kind","schedule_expr","title"].map(i=>(0,ga.escapeCell)(String(s[i]??""))))]):e.map(s=>JSON.stringify(s)).join(`
609
609
  `)}else typeof e=="string"?r=e:r=JSON.stringify(e,null,2);let n=t.next_cursor;return n!=null?`${r}
610
- More records: --after ${String(n)}`:r}var AE=`usage: lmbee cron create --title TEXT --schedule "m h dom mon dow" --kind enqueue|command|script|session|miniplayer [--payload TEXT | --prompt TEXT | --prompt-file PATH] [--provider P] [--model M] [--cwd DIR] [--owner NAME] [--disabled] [--timezone IANA-name] | show ID | list [--enabled true|false] [--limit N] [--after ID] | update ID [--title T] [--schedule EXPR] [--payload TEXT|--prompt TEXT|--prompt-file PATH] [--provider P] [--model M] [--cwd DIR] [--owner NAME] [--timezone IANA-name|""] [--if-revision N] | enable ID | disable ID | remove ID | reset ID | reset-session ID | export PATH | import PATH | runs [--job ID] [--status pending|running|succeeded|failed|escalated] [--limit N] [--after ID] | run RUN-ID | trigger ID | report RUN-TOKEN --status succeeded|failed|escalated --summary TEXT [--artifact A[,B]] [--requested-action TEXT] [--owner NAME] | resolve RUN-ID [--resolution TEXT] [--actor NAME] [--note TEXT] [--confirm-stopped]
610
+ More records: --after ${String(n)}`:r}var NE=`usage: lmbee cron create --title TEXT --schedule "m h dom mon dow" --kind enqueue|command|script|session|miniplayer [--payload TEXT | --prompt TEXT | --prompt-file PATH] [--provider P] [--model M] [--cwd DIR] [--owner NAME] [--disabled] [--timezone IANA-name] | show ID | list [--enabled true|false] [--limit N] [--after ID] | update ID [--title T] [--schedule EXPR] [--payload TEXT|--prompt TEXT|--prompt-file PATH] [--provider P] [--model M] [--cwd DIR] [--owner NAME] [--timezone IANA-name|""] [--if-revision N] | enable ID | disable ID | remove ID | reset ID | reset-session ID | export PATH | import PATH | runs [--job ID] [--status pending|running|succeeded|failed|escalated] [--limit N] [--after ID] | run RUN-ID | trigger ID | report RUN-TOKEN --status succeeded|failed|escalated --summary TEXT [--artifact A[,B]] [--requested-action TEXT] [--owner NAME] | resolve RUN-ID [--resolution TEXT] [--actor NAME] [--note TEXT] [--confirm-stopped]
611
611
  NOTE: a job fires at most once per daemon tick interval (default 30 minutes), regardless of how frequent its own schedule expression is -- lmcron catches up a missed window, coalesced to one fire, never one fire per missed minute.
612
- NOTE: export/import carry job DEFINITIONS only (ids preserved), NEVER execution state -- runtime/session columns reset on import, historical timestamps are deliberately omitted, and the overlap fences live in cron_runs, which is not migrated. At scheduler cutover, stop the old daemon BEFORE the new one ticks; never run both schedules concurrently.`;async function $E(e,t,r,n,o=[]){try{let[s,...i]=t;switch(s){case"create":{let a=r.title;if(typeof a!="string")throw new U("INVALID_ARGUMENT","--title is required");let c=r.schedule;if(typeof c!="string")throw new U("INVALID_ARGUMENT","--schedule is required");let l=r.kind;if(typeof l!="string"||!sD(l))throw new U("INVALID_ARGUMENT",'--kind must be "enqueue", "command", "script", "session", or "miniplayer"');let u=SE(r);if(u===void 0)throw new U("INVALID_ARGUMENT",l==="session"||l==="miniplayer"?"--prompt or --prompt-file is required":"--payload is required");let d=Pn(e,{title:a,scheduleExpr:c,actionKind:l,actionPayload:u,enabled:r.disabled!==!0,timezone:typeof r.timezone=="string"?r.timezone:void 0,...We(r.provider)!==void 0?{provider:We(r.provider)}:{},...We(r.model)!==void 0?{model:We(r.model)}:{},...We(r.cwd)!==void 0?{workingDirectory:We(r.cwd)}:{},...We(r.owner)!==void 0?{escalationOwner:We(r.owner)}:{}});return{output:dt(n,d),exitCode:0}}case"show":{let a=ur(i[0],"id");return{output:dt(n,Ie(e,a)),exitCode:0}}case"list":{let a=r.enabled,c;if(a!==void 0){if(a!=="true"&&a!=="false")throw new U("INVALID_ARGUMENT",'--enabled must be "true" or "false"');c=a==="true"}let{rows:l,meta:u}=Li(e,{enabled:c,limit:cn(r.limit,"--limit",{maximum:Ne})??100,after:cn(r.after,"--after",{minimum:0})??0});return{output:dt(n,l,u),exitCode:0}}case"update":{let a=ur(i[0],"id"),c=SE(r),l=Eh(e,a,{title:typeof r.title=="string"?r.title:void 0,scheduleExpr:typeof r.schedule=="string"?r.schedule:void 0,actionPayload:c,timezone:typeof r.timezone=="string"?r.timezone===""?null:r.timezone:void 0,provider:We(r.provider),model:We(r.model),workingDirectory:typeof r.cwd=="string"?r.cwd===""?null:r.cwd:void 0,escalationOwner:typeof r.owner=="string"?r.owner===""?null:r.owner:void 0,ifRevision:cn(r["if-revision"],"--if-revision")});return{output:dt(n,l),exitCode:0}}case"enable":case"disable":{let a=ur(i[0],"id"),c=Ci(e,a,s==="enable");return{output:dt(n,c),exitCode:0}}case"remove":{let a=ur(i[0],"id"),c=Th(e,a);return{output:dt(n,c),exitCode:0}}case"reset":{let a=ur(i[0],"id"),c=Ah(e,a);return{output:dt(n,c),exitCode:0}}case"reset-session":{let a=ur(i[0],"id"),c=bh(e,a);return{output:dt(n,c),exitCode:0}}case"runs":{let a=r.status;if(a!==void 0&&(typeof a!="string"||!aD(a)))throw new U("INVALID_ARGUMENT","--status must be one of pending|running|succeeded|failed|escalated");let c=r.job!==void 0?cn(r.job,"--job"):void 0,{rows:l,next_cursor:u}=ki(e,{...c!==void 0?{jobId:c}:{},...a!==void 0?{status:a}:{},limit:cn(r.limit,"--limit",{maximum:Ne})??100,after:cn(r.after,"--after",{minimum:0})??0});return{output:dt(n,l.map(Po),{next_cursor:u}),exitCode:0}}case"run":{let a=ur(i[0],"id");return{output:dt(n,Po(ze(e,a))),exitCode:0}}case"trigger":{let a=ur(i[0],"id"),c=await Ho(e,a,o);return{output:dt(n,{trigger:c.kind,job:c.job}),exitCode:0}}case"report":{let a=i[0];if(a===void 0)throw new U("INVALID_ARGUMENT","a run token is required");let c=r.status;if(typeof c!="string"||c!=="succeeded"&&c!=="failed"&&c!=="escalated")throw new U("INVALID_ARGUMENT",'--status must be "succeeded", "failed", or "escalated"');let l=r.summary;if(typeof l!="string")throw new U("INVALID_ARGUMENT","--summary is required");let u=typeof r.artifact=="string"?r.artifact:void 0,d=u!==void 0?u.split(",").map(p=>p.trim()).filter(p=>p.length>0):void 0,m=typeof r["requested-action"]=="string"?r["requested-action"]:We(r.action),f=nh(e,a,{status:c,summary:l,...d!==void 0?{artifacts:d}:{},...m!==void 0?{action:m}:{},...We(r.owner)!==void 0?{owner:We(r.owner)}:{},...We(r.reason)!==void 0?{reason:We(r.reason)}:{}});return{output:dt(n,Po(f)),exitCode:0}}case"import":{ns("import",i,r);let a=i[0];if(a===void 0)throw new U("INVALID_ARGUMENT","an import PATH is required");let c=EE(e,a);return{output:n?dt(!0,c):TE(c),exitCode:0}}case"resolve":{let a=ur(i[0],"id"),c=ih(e,a,{resolution:We(r.resolution),actor:We(r.actor),note:We(r.note),confirmStopped:r["confirm-stopped"]===!0});return{output:dt(n,Po(c)),exitCode:0}}default:return n?vE(n,new U("INVALID_ARGUMENT",AE)):{output:AE,exitCode:1}}}catch(s){if(s instanceof U)return vE(n,s);throw s}}var kE=["disabled","confirm-stopped"];async function xE(e){let t=e.send??Ht,r=e.config??pe,n=e.nowMs??Date.now(),o=e.maxParallel??4,s=e.readHeavyLockStatusImpl??lt,i=e.teams.filter(l=>!ie(e.db,l.name)?.confirmed_done_ts),a=await lD(i,o,async l=>{if(!await Ic(e.db,l,e.report,e.heavyLock,r,n))return{team:l.name,dispatched:!1,status:null,wake:null};let d;try{d=Q(l)}catch(h){let w=h instanceof Error?h.message:String(h);return ir(e.db,l.name,"ENV-ERROR",n),vo(e.db,l.name,new Date(n).toISOString()),tt(e.db,l.name,"ENV-ERROR",n,{note:w}),{team:l.name,dispatched:!0,status:"ENV-ERROR",wake:"env"}}let m=s(e.heavyLockStatusPath,e.heavyLockPath,void 0,h=>{process.stderr.write(`[scan] heavy-lock probe failed for ${l.name}, treating conservatively as held: ${h.message}
613
- `)});if(m.held&&(m.holder===null||m.holder.holder===l.name))return{team:l.name,dispatched:!1,status:null,wake:null};if(Ps(e.db,l.name,l.leadAlias,n))return{team:l.name,dispatched:!1,status:null,wake:null};let f=await t({teamfilePath:d,alias:l.leadAlias},e.resolveNudgeMessage(l)),p=Wn(f);return ir(e.db,l.name,p.status,n),vo(e.db,l.name,new Date(n).toISOString()),tt(e.db,l.name,p.status,n),{team:l.name,dispatched:!0,status:p.status,wake:p.wake}}),c=a.find(l=>l.wake!==null)?.wake??null;return{results:a,wake:c}}async function lD(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;;){let a=o++;if(a>=e.length)return;n[a]=await r(e[a])}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}async function os(e,t,r={}){let o=await(r.fetchReport??Ae)(),s=r.readHeavyLockStatusImpl??lt,i=s(void 0,void 0,void 0,l=>{process.stderr.write(`[scan] heavy-lock probe failed, treating conservatively as held: ${l.message}
614
- `)}),a=Hi(r.promptsDir);return(r.scanOnceImpl??xE)({db:e,teams:t.filter(H),report:o,heavyLock:i,readHeavyLockStatusImpl:s,resolveNudgeMessage:l=>Bi(a,l)})}function ss(e){let t=e.results.map(r=>`${r.team}: ${r.dispatched?r.status:"skipped (not stalled)"}`);return t.length?t.join(`
615
- `):"(no eligible teams)"}async function RE(e,t,r={}){if(t.length===0)throw new Error("usage: lmbee nudge <team> [team2 ...]");let n=e.teams.filter(s=>t.includes(s.name));if(n.length===0)throw new Error(`nudge: no matching teams for: ${t.join(", ")}`);let o=await os(e.db.db,n,r);return ss(o)}function NE(e,t,r){let n=Tt(e.db.db,t),o={companionTeam:r.companionTeam,workerAlias:r.workerAlias??"Worker",commitThreshold:r.commitThreshold??rl,hoursThresholdMs:r.hoursThresholdMs??nl,shiftStartedTs:n?.companionTeam===r.companionTeam?n?.shiftStartedTs??null:null,shiftStartedSha:n?.companionTeam===r.companionTeam?n?.shiftStartedSha??null:null,turnsDispatched:n?.companionTeam===r.companionTeam?n?.turnsDispatched??0:0,lastReviewedTurn:n?.companionTeam===r.companionTeam?n?.lastReviewedTurn??0:0};return gi(e.db.db,t,o),r.json?JSON.stringify({team:t,...o}):`auto-nudge for ${t} now redirects to ${o.companionTeam}:${o.workerAlias} (review due after ${o.commitThreshold} commits or ${(o.hoursThresholdMs/36e5).toFixed(1)}h, whichever first).
616
- Manual nudge/enqueue/lctl chat and queue delivery to ${t} are unaffected.`}function IE(e,t,r={}){let n=Tt(e.db.db,t)!==null;return bp(e.db.db,t),r.json?JSON.stringify({team:t,redirected:!1}):n?`auto-nudge for ${t} no longer redirects -- back to nudging ${t} directly.`:`auto-nudge for ${t} was not redirected (no-op).`}function uD(e,t){let r=t!==void 0?[t]:ol(e.db.db),n=[];for(let o of r){let s=Tt(e.db.db,o);s!==null&&n.push({team:o,config:s})}return n}function LE(e,t,r={}){let n=uD(e,t);return r.json?JSON.stringify(n):n.length===0?t!==void 0?`${t}: not redirected.`:"no teams are currently redirected.":n.map(o=>{let s=o.config.shiftStartedTs!==null?`shift started ${o.config.shiftStartedTs}`:"no shift started yet (redirect configured, auto-continue has not fired for this team since)",i=o.config.turnsDispatched<Ro?`, ramp-up turn ${o.config.turnsDispatched}/${Ro} (every turn always reviewed)`:"";return`${o.team} -> ${o.config.companionTeam}:${o.config.workerAlias} (${o.config.commitThreshold} commits or ${(o.config.hoursThresholdMs/36e5).toFixed(1)}h) -- ${s}${i}`}).join(`
617
- `)}var dD=new Set(["operator","lmauto"]),mD=new Set(["autopilot"]);function fD(e,t){return mD.has(e)?t:e}function CE(e,t,r,n){if(n.newTaskTitle!==void 0&&n.taskId!==void 0)throw new Error("prompt: --new-task and --task are exclusive -- start a new task OR continue an existing one, not both");if(n.newTaskTitle===void 0&&n.taskId===void 0&&dD.has(n.from))throw new Error(`prompt: --from ${n.from} requires either --new-task <title> or --task <id> -- an operator/proxy-initiated prompt always names the task it belongs to (this is the exact class of prompt #16024 measured going missing)`);let o,s;if(n.newTaskTitle!==void 0){let c=uw(e.db.db,{title:n.newTaskTitle,description:n.newTaskDescription});o=c.id,s=`new task #${c.id}: "${c.title}"`}else if(n.taskId!==void 0){let c=Zo(e.db.db,n.taskId);if(c===null)throw new Error(`prompt: --task ${n.taskId} does not refer to an existing prompt task`);o=c.id,s=`task #${c.id}: "${c.title}"`}else{let c=fD(n.from,t);o=hw(e.db.db,c),s=o!==null?`inherited task #${o} from ${c}'s own most recent message`:`no task (${c} has no prior chat history to inherit from)`}let i=Cr("prompt",r,n.literal);return`prompt#${dw(e.db.db,{taskId:o,fromId:n.from,toId:t,prompt:i}).id} -> ${t} (${s}) -- lives in the prompt_tasks/task_prompts ledger, not queue; enqueue/queue answer are unaffected, and nothing is mirrored between them.`}function OE(e,t,r={}){let n=ww(e.db.db,t);if(r.json)return JSON.stringify({tasks:n});if(n.length===0)return`prompt tasks ${t}: no threads yet`;let o=n.map(s=>`#${s.task.id} "${s.task.title}" -- ${s.promptCount} prompt${s.promptCount===1?"":"s"}, last ${s.lastPromptAt}`);return`prompt tasks ${t}:
612
+ NOTE: export/import carry job DEFINITIONS only (ids preserved), NEVER execution state -- runtime/session columns reset on import, historical timestamps are deliberately omitted, and the overlap fences live in cron_runs, which is not migrated. At scheduler cutover, stop the old daemon BEFORE the new one ticks; never run both schedules concurrently.`;async function LE(e,t,r,n,o=[]){try{let[s,...i]=t;switch(s){case"create":{let a=r.title;if(typeof a!="string")throw new U("INVALID_ARGUMENT","--title is required");let c=r.schedule;if(typeof c!="string")throw new U("INVALID_ARGUMENT","--schedule is required");let l=r.kind;if(typeof l!="string"||!mD(l))throw new U("INVALID_ARGUMENT",'--kind must be "enqueue", "command", "script", "session", or "miniplayer"');let u=xE(r);if(u===void 0)throw new U("INVALID_ARGUMENT",l==="session"||l==="miniplayer"?"--prompt or --prompt-file is required":"--payload is required");let d=Fn(e,{title:a,scheduleExpr:c,actionKind:l,actionPayload:u,enabled:r.disabled!==!0,timezone:typeof r.timezone=="string"?r.timezone:void 0,...We(r.provider)!==void 0?{provider:We(r.provider)}:{},...We(r.model)!==void 0?{model:We(r.model)}:{},...We(r.cwd)!==void 0?{workingDirectory:We(r.cwd)}:{},...We(r.owner)!==void 0?{escalationOwner:We(r.owner)}:{}});return{output:dt(n,d),exitCode:0}}case"show":{let a=dr(i[0],"id");return{output:dt(n,Le(e,a)),exitCode:0}}case"list":{let a=r.enabled,c;if(a!==void 0){if(a!=="true"&&a!=="false")throw new U("INVALID_ARGUMENT",'--enabled must be "true" or "false"');c=a==="true"}let{rows:l,meta:u}=Di(e,{enabled:c,limit:cn(r.limit,"--limit",{maximum:Ne})??100,after:cn(r.after,"--after",{minimum:0})??0});return{output:dt(n,l,u),exitCode:0}}case"update":{let a=dr(i[0],"id"),c=xE(r),l=bh(e,a,{title:typeof r.title=="string"?r.title:void 0,scheduleExpr:typeof r.schedule=="string"?r.schedule:void 0,actionPayload:c,timezone:typeof r.timezone=="string"?r.timezone===""?null:r.timezone:void 0,provider:We(r.provider),model:We(r.model),workingDirectory:typeof r.cwd=="string"?r.cwd===""?null:r.cwd:void 0,escalationOwner:typeof r.owner=="string"?r.owner===""?null:r.owner:void 0,ifRevision:cn(r["if-revision"],"--if-revision")});return{output:dt(n,l),exitCode:0}}case"enable":case"disable":{let a=dr(i[0],"id"),c=Mi(e,a,s==="enable");return{output:dt(n,c),exitCode:0}}case"remove":{let a=dr(i[0],"id"),c=Sh(e,a);return{output:dt(n,c),exitCode:0}}case"reset":{let a=dr(i[0],"id"),c=Nh(e,a);return{output:dt(n,c),exitCode:0}}case"reset-session":{let a=dr(i[0],"id"),c=vh(e,a);return{output:dt(n,c),exitCode:0}}case"runs":{let a=r.status;if(a!==void 0&&(typeof a!="string"||!pD(a)))throw new U("INVALID_ARGUMENT","--status must be one of pending|running|succeeded|failed|escalated");let c=r.job!==void 0?cn(r.job,"--job"):void 0,{rows:l,next_cursor:u}=Ni(e,{...c!==void 0?{jobId:c}:{},...a!==void 0?{status:a}:{},limit:cn(r.limit,"--limit",{maximum:Ne})??100,after:cn(r.after,"--after",{minimum:0})??0});return{output:dt(n,l.map(Fo),{next_cursor:u}),exitCode:0}}case"run":{let a=dr(i[0],"id");return{output:dt(n,Fo(ze(e,a))),exitCode:0}}case"trigger":{let a=dr(i[0],"id"),c=await Vo(e,a,o);return{output:dt(n,{trigger:c.kind,job:c.job}),exitCode:0}}case"report":{let a=i[0];if(a===void 0)throw new U("INVALID_ARGUMENT","a run token is required");let c=r.status;if(typeof c!="string"||c!=="succeeded"&&c!=="failed"&&c!=="escalated")throw new U("INVALID_ARGUMENT",'--status must be "succeeded", "failed", or "escalated"');let l=r.summary;if(typeof l!="string")throw new U("INVALID_ARGUMENT","--summary is required");let u=typeof r.artifact=="string"?r.artifact:void 0,d=u!==void 0?u.split(",").map(p=>p.trim()).filter(p=>p.length>0):void 0,m=typeof r["requested-action"]=="string"?r["requested-action"]:We(r.action),f=ih(e,a,{status:c,summary:l,...d!==void 0?{artifacts:d}:{},...m!==void 0?{action:m}:{},...We(r.owner)!==void 0?{owner:We(r.owner)}:{},...We(r.reason)!==void 0?{reason:We(r.reason)}:{}});return{output:dt(n,Fo(f)),exitCode:0}}case"import":{as("import",i,r);let a=i[0];if(a===void 0)throw new U("INVALID_ARGUMENT","an import PATH is required");let c=AE(e,a);return{output:n?dt(!0,c):kE(c),exitCode:0}}case"resolve":{let a=dr(i[0],"id"),c=ch(e,a,{resolution:We(r.resolution),actor:We(r.actor),note:We(r.note),confirmStopped:r["confirm-stopped"]===!0});return{output:dt(n,Fo(c)),exitCode:0}}default:return n?RE(n,new U("INVALID_ARGUMENT",NE)):{output:NE,exitCode:1}}}catch(s){if(s instanceof U)return RE(n,s);throw s}}var IE=["disabled","confirm-stopped"];async function CE(e){let t=e.send??Ht,r=e.config??pe,n=e.nowMs??Date.now(),o=e.maxParallel??4,s=e.readHeavyLockStatusImpl??lt,i=e.teams.filter(l=>!ie(e.db,l.name)?.confirmed_done_ts),a=await gD(i,o,async l=>{if(!await Oc(e.db,l,e.report,e.heavyLock,r,n))return{team:l.name,dispatched:!1,status:null,wake:null};let d;try{d=Q(l)}catch(h){let w=h instanceof Error?h.message:String(h);return ir(e.db,l.name,"ENV-ERROR",n),ko(e.db,l.name,new Date(n).toISOString()),tt(e.db,l.name,"ENV-ERROR",n,{note:w}),{team:l.name,dispatched:!0,status:"ENV-ERROR",wake:"env"}}let m=s(e.heavyLockStatusPath,e.heavyLockPath,void 0,h=>{process.stderr.write(`[scan] heavy-lock probe failed for ${l.name}, treating conservatively as held: ${h.message}
613
+ `)});if(m.held&&(m.holder===null||m.holder.holder===l.name))return{team:l.name,dispatched:!1,status:null,wake:null};if(js(e.db,l.name,l.leadAlias,n))return{team:l.name,dispatched:!1,status:null,wake:null};let f=await t({teamfilePath:d,alias:l.leadAlias},e.resolveNudgeMessage(l)),p=Vn(f);return ir(e.db,l.name,p.status,n),ko(e.db,l.name,new Date(n).toISOString()),tt(e.db,l.name,p.status,n),{team:l.name,dispatched:!0,status:p.status,wake:p.wake}}),c=a.find(l=>l.wake!==null)?.wake??null;return{results:a,wake:c}}async function gD(e,t,r){let n=new Array(e.length),o=0;async function s(){for(;;){let a=o++;if(a>=e.length)return;n[a]=await r(e[a])}}let i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>s())),n}async function cs(e,t,r={}){let o=await(r.fetchReport??Ae)(),s=r.readHeavyLockStatusImpl??lt,i=s(void 0,void 0,void 0,l=>{process.stderr.write(`[scan] heavy-lock probe failed, treating conservatively as held: ${l.message}
614
+ `)}),a=Gi(r.promptsDir);return(r.scanOnceImpl??CE)({db:e,teams:t.filter(B),report:o,heavyLock:i,readHeavyLockStatusImpl:s,resolveNudgeMessage:l=>Vi(a,l)})}function ls(e){let t=e.results.map(r=>`${r.team}: ${r.dispatched?r.status:"skipped (not stalled)"}`);return t.length?t.join(`
615
+ `):"(no eligible teams)"}async function OE(e,t,r={}){if(t.length===0)throw new Error("usage: lmbee nudge <team> [team2 ...]");let n=e.teams.filter(s=>t.includes(s.name));if(n.length===0)throw new Error(`nudge: no matching teams for: ${t.join(", ")}`);let o=await cs(e.db.db,n,r);return ls(o)}function DE(e,t,r){let n=bt(e.db.db,t),o={companionTeam:r.companionTeam,workerAlias:r.workerAlias??"Worker",commitThreshold:r.commitThreshold??sl,hoursThresholdMs:r.hoursThresholdMs??il,shiftStartedTs:n?.companionTeam===r.companionTeam?n?.shiftStartedTs??null:null,shiftStartedSha:n?.companionTeam===r.companionTeam?n?.shiftStartedSha??null:null,turnsDispatched:n?.companionTeam===r.companionTeam?n?.turnsDispatched??0:0,lastReviewedTurn:n?.companionTeam===r.companionTeam?n?.lastReviewedTurn??0:0};return Ei(e.db.db,t,o),r.json?JSON.stringify({team:t,...o}):`auto-nudge for ${t} now redirects to ${o.companionTeam}:${o.workerAlias} (review due after ${o.commitThreshold} commits or ${(o.hoursThresholdMs/36e5).toFixed(1)}h, whichever first).
616
+ Manual nudge/enqueue/lctl chat and queue delivery to ${t} are unaffected.`}function ME(e,t,r={}){let n=bt(e.db.db,t)!==null;return Ap(e.db.db,t),r.json?JSON.stringify({team:t,redirected:!1}):n?`auto-nudge for ${t} no longer redirects -- back to nudging ${t} directly.`:`auto-nudge for ${t} was not redirected (no-op).`}function _D(e,t){let r=t!==void 0?[t]:al(e.db.db),n=[];for(let o of r){let s=bt(e.db.db,o);s!==null&&n.push({team:o,config:s})}return n}function PE(e,t,r={}){let n=_D(e,t);return r.json?JSON.stringify(n):n.length===0?t!==void 0?`${t}: not redirected.`:"no teams are currently redirected.":n.map(o=>{let s=o.config.shiftStartedTs!==null?`shift started ${o.config.shiftStartedTs}`:"no shift started yet (redirect configured, auto-continue has not fired for this team since)",i=o.config.turnsDispatched<Lo?`, ramp-up turn ${o.config.turnsDispatched}/${Lo} (every turn always reviewed)`:"";return`${o.team} -> ${o.config.companionTeam}:${o.config.workerAlias} (${o.config.commitThreshold} commits or ${(o.config.hoursThresholdMs/36e5).toFixed(1)}h) -- ${s}${i}`}).join(`
617
+ `)}var wD=new Set(["operator","lmauto"]),yD=new Set(["autopilot"]);function ED(e,t){return yD.has(e)?t:e}function UE(e,t,r,n){if(n.newTaskTitle!==void 0&&n.taskId!==void 0)throw new Error("prompt: --new-task and --task are exclusive -- start a new task OR continue an existing one, not both");if(n.newTaskTitle===void 0&&n.taskId===void 0&&wD.has(n.from))throw new Error(`prompt: --from ${n.from} requires either --new-task <title> or --task <id> -- an operator/proxy-initiated prompt always names the task it belongs to (this is the exact class of prompt #16024 measured going missing)`);let o,s;if(n.newTaskTitle!==void 0){let c=hw(e.db.db,{title:n.newTaskTitle,description:n.newTaskDescription});o=c.id,s=`new task #${c.id}: "${c.title}"`}else if(n.taskId!==void 0){let c=ns(e.db.db,n.taskId);if(c===null)throw new Error(`prompt: --task ${n.taskId} does not refer to an existing prompt task`);o=c.id,s=`task #${c.id}: "${c.title}"`}else{let c=ED(n.from,t);o=Ew(e.db.db,c),s=o!==null?`inherited task #${o} from ${c}'s own most recent message`:`no task (${c} has no prior chat history to inherit from)`}let i=Cr("prompt",r,n.literal);return`prompt#${gw(e.db.db,{taskId:o,fromId:n.from,toId:t,prompt:i}).id} -> ${t} (${s}) -- lives in the prompt_tasks/task_prompts ledger, not queue; enqueue/queue answer are unaffected, and nothing is mirrored between them.`}function FE(e,t,r={}){let n=Sw(e.db.db,t);if(r.json)return JSON.stringify({tasks:n});if(n.length===0)return`prompt tasks ${t}: no threads yet`;let o=n.map(s=>`#${s.task.id} "${s.task.title}" -- ${s.promptCount} prompt${s.promptCount===1?"":"s"}, last ${s.lastPromptAt}`);return`prompt tasks ${t}:
618
618
  ${o.join(`
619
- `)}`}function DE(e,t,r={}){let n=Zo(e.db.db,t);if(n===null)return`prompt log: task #${t} does not exist`;let o=mw(e.db.db,t);if(r.json)return JSON.stringify({task:n,messages:o});if(o.length===0)return`prompt log #${t} ("${n.title}"): no prompts yet`;let s=o.map(i=>`#${i.id} ${i.from_id} -> ${i.to_id} (${i.created_at}):
619
+ `)}`}function qE(e,t,r={}){let n=ns(e.db.db,t);if(n===null)return`prompt log: task #${t} does not exist`;let o=_w(e.db.db,t);if(r.json)return JSON.stringify({task:n,messages:o});if(o.length===0)return`prompt log #${t} ("${n.title}"): no prompts yet`;let s=o.map(i=>`#${i.id} ${i.from_id} -> ${i.to_id} (${i.created_at}):
620
620
  ${i.prompt}`);return`prompt log #${t} ("${n.title}"):
621
621
 
622
622
  ${s.join(`
623
623
 
624
- `)}`}function ME(e,t,r,n){let o=e.db.db.prepare("SELECT task_id FROM task_prompts WHERE id = ?").get(t);if(o===void 0)throw new Error(`prompt reassign: prompt #${t} does not exist`);let s=gw(e.db.db,{promptId:t,toTaskId:r,reassignedBy:n.by}),i=o.task_id!==null?`task #${o.task_id}`:"no task";return`prompt reassign: prompt #${t} moved from ${i} to task #${s.task_id} by ${n.by}`}function PE(e,t,r={}){let n=_w(e.db.db,t);if(r.json)return JSON.stringify({reassignments:n});if(n.length===0)return`prompt reassignments #${t}: none`;let o=n.map(s=>`#${s.id} ${s.reassigned_at} by ${s.reassigned_by}: ${s.from_task_id!==null?`task #${s.from_task_id}`:"no task"} -> task #${s.to_task_id}`);return`prompt reassignments #${t}:
624
+ `)}`}function jE(e,t,r,n){let o=e.db.db.prepare("SELECT task_id FROM task_prompts WHERE id = ?").get(t);if(o===void 0)throw new Error(`prompt reassign: prompt #${t} does not exist`);let s=Tw(e.db.db,{promptId:t,toTaskId:r,reassignedBy:n.by}),i=o.task_id!==null?`task #${o.task_id}`:"no task";return`prompt reassign: prompt #${t} moved from ${i} to task #${s.task_id} by ${n.by}`}function HE(e,t,r={}){let n=bw(e.db.db,t);if(r.json)return JSON.stringify({reassignments:n});if(n.length===0)return`prompt reassignments #${t}: none`;let o=n.map(s=>`#${s.id} ${s.reassigned_at} by ${s.reassigned_by}: ${s.from_task_id!==null?`task #${s.from_task_id}`:"no task"} -> task #${s.to_task_id}`);return`prompt reassignments #${t}:
625
625
  ${o.join(`
626
- `)}`}function UE(e,t,r={}){if(yi(e.db.db,t,{reason:r.reason??null,expiresAt:r.expiresAt??null}),r.json)return JSON.stringify(wi(e.db.db,t));let n=r.reason?` (${r.reason})`:"",o=r.expiresAt?`, auto-re-enables at ${r.expiresAt}`:", indefinite (explicit re-enable required)";return`provider "${t}" disabled for auto-nudge${n}${o}.
627
- Every team whose resolved auto-nudge target uses "${t}" goes quiet; manual nudge/enqueue/lctl chat is unaffected.`}function FE(e,t,r={}){let n=wi(e.db.db,t)!==null;return Up(e.db.db,t),r.json?JSON.stringify({provider:t,disabled:!1}):n?`provider "${t}" re-enabled. Any team quiesced by it resumes on its own next-due check -- suppressed #195 reviews coalesce into one, covering everything since the shift began.`:`provider "${t}" was not disabled (no-op).`}function pD(e,t,r=Date.now()){return(t!==void 0?Io(e.db.db).filter(o=>o.provider===t):Io(e.db.db)).map(o=>({provider:o.provider,config:o,expired:!rt(e.db.db,o.provider,r).disabled}))}function qE(e,t,r={}){let n=pD(e,t);return r.json?JSON.stringify(n):n.length===0?t!==void 0?`${t}: not disabled.`:"no providers are currently disabled.":n.map(o=>{let s=o.config.reason?` (${o.config.reason})`:"",i=o.expired?", EXPIRED -- effectively re-enabled, run `provider enable` to clear the stale record":o.config.expiresAt!==null?`, auto-re-enables at ${o.config.expiresAt}`:", indefinite";return`${o.provider}: disabled since ${o.config.disabledAt}${s}${i}`}).join(`
628
- `)}function gD(e,t){let r=e-t.readAt*1e3,n=t.resetsAtIso?Date.parse(t.resetsAtIso):NaN,o=Number.isFinite(n)&&n<e?e-n:null;return{ageMs:r,stale:r>9e5,expiredMs:o}}function _D(e,t,r,n){let o=Date.now(),s=Math.floor((o-18e5)/1e3),a=e.prepare(`SELECT used_fraction AS usedFraction, read_at AS readAt
629
- FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ? AND resets_at = ? AND read_at >= ? ORDER BY read_at ASC`).all(t,r,n,s).map(m=>({readAt:m.readAt,usedFraction:m.usedFraction})),c=a.length>0?(a[a.length-1].readAt-a[0].readAt)*1e3:0,l=`samples=${a.length} span=${Math.round(c/1e3)}s (lookback ${Math.round(18e5/6e4)}m)`,u=Pi(a,o),d=u.kind==="insufficient_data"?`no-forecast: ${u.reason}`:u.kind==="no_forecast"?"no-forecast: flat or non-increasing usage":`forecastable: reaches 100% at ${new Date(u.forecastAtMs).toISOString()}`;return`${l} -- ${d}`}function jE(e,t={}){let r=e.db.db,n=r.prepare(`SELECT r1.provider, r1.status, r1.source, r1.read_at, r1.reason, r1.detail
626
+ `)}`}function BE(e,t,r={}){if(Si(e.db.db,t,{reason:r.reason??null,expiresAt:r.expiresAt??null}),r.json)return JSON.stringify(bi(e.db.db,t));let n=r.reason?` (${r.reason})`:"",o=r.expiresAt?`, auto-re-enables at ${r.expiresAt}`:", indefinite (explicit re-enable required)";return`provider "${t}" disabled for auto-nudge${n}${o}.
627
+ Every team whose resolved auto-nudge target uses "${t}" goes quiet; manual nudge/enqueue/lctl chat is unaffected.`}function WE(e,t,r={}){let n=bi(e.db.db,t)!==null;return jp(e.db.db,t),r.json?JSON.stringify({provider:t,disabled:!1}):n?`provider "${t}" re-enabled. Any team quiesced by it resumes on its own next-due check -- suppressed #195 reviews coalesce into one, covering everything since the shift began.`:`provider "${t}" was not disabled (no-op).`}function TD(e,t,r=Date.now()){return(t!==void 0?Co(e.db.db).filter(o=>o.provider===t):Co(e.db.db)).map(o=>({provider:o.provider,config:o,expired:!rt(e.db.db,o.provider,r).disabled}))}function GE(e,t,r={}){let n=TD(e,t);return r.json?JSON.stringify(n):n.length===0?t!==void 0?`${t}: not disabled.`:"no providers are currently disabled.":n.map(o=>{let s=o.config.reason?` (${o.config.reason})`:"",i=o.expired?", EXPIRED -- effectively re-enabled, run `provider enable` to clear the stale record":o.config.expiresAt!==null?`, auto-re-enables at ${o.config.expiresAt}`:", indefinite";return`${o.provider}: disabled since ${o.config.disabledAt}${s}${i}`}).join(`
628
+ `)}function SD(e,t){let r=e-t.readAt*1e3,n=t.resetsAtIso?Date.parse(t.resetsAtIso):NaN,o=Number.isFinite(n)&&n<e?e-n:null;return{ageMs:r,stale:r>9e5,expiredMs:o}}function vD(e,t,r,n){let o=Date.now(),s=Math.floor((o-18e5)/1e3),a=e.prepare(`SELECT used_fraction AS usedFraction, read_at AS readAt
629
+ FROM rate_limit_bucket_samples WHERE provider = ? AND bucket_id = ? AND resets_at = ? AND read_at >= ? ORDER BY read_at ASC`).all(t,r,n,s).map(m=>({readAt:m.readAt,usedFraction:m.usedFraction})),c=a.length>0?(a[a.length-1].readAt-a[0].readAt)*1e3:0,l=`samples=${a.length} span=${Math.round(c/1e3)}s (lookback ${Math.round(18e5/6e4)}m)`,u=qi(a,o),d=u.kind==="insufficient_data"?`no-forecast: ${u.reason}`:u.kind==="no_forecast"?"no-forecast: flat or non-increasing usage":`forecastable: reaches 100% at ${new Date(u.forecastAtMs).toISOString()}`;return`${l} -- ${d}`}function VE(e,t={}){let r=e.db.db,n=r.prepare(`SELECT r1.provider, r1.status, r1.source, r1.read_at, r1.reason, r1.detail
630
630
  FROM rate_limit_readings r1
631
631
  WHERE r1.id = (SELECT id FROM rate_limit_readings r2 WHERE r2.provider = r1.provider ORDER BY read_at DESC, id DESC LIMIT 1)
632
632
  ORDER BY r1.provider`).all(),o=r.prepare(`SELECT s.provider, s.bucket_id AS bucketId, s.window_type AS windowType, s.used_fraction AS usedFraction,
@@ -638,37 +638,37 @@ Every team whose resolved auto-nudge target uses "${t}" goes quiet; manual nudge
638
638
  ORDER BY read_at DESC, id DESC LIMIT 1
639
639
  )
640
640
  AND s.resets_at = (SELECT MAX(resets_at) FROM rate_limit_bucket_samples s3 WHERE s3.provider = s.provider AND s3.bucket_id = s.bucket_id)
641
- ORDER BY s.provider, s.bucket_id`).all(),s=r.prepare("SELECT provider, bucket_id AS bucketId, resets_at AS resetsAt, rule, armed_at AS armedAt, forecast_at AS forecastAt FROM rate_limit_policy_arm ORDER BY provider, bucket_id").all(),i=qi(r),a=(()=>{if(i===null)return"policy: never run.";let d=Math.round((Date.now()-i.lastRunAtMs)/1e3),m=Object.entries(i.outcomeCounts).map(([f,p])=>`${p} ${f}`).join(", ")||"nothing to evaluate";return`policy: last ran ${new Date(i.lastRunAtMs).toISOString()} (${d}s ago), evaluated ${i.seriesEvaluated} series (${m}).`})(),c=Date.now(),l=o.map(d=>({...d,...gD(c,d)}));if(t.json)return JSON.stringify({latestByProvider:n,series:l,armed:s,policyHeartbeat:i});if(n.length===0)return`rate-limit: no readings collected yet.
642
- ${a}`;let u=[a];for(let d of n){let m=new Date(d.read_at*1e3).toISOString();d.status==="ok"?u.push(`${d.provider}: ok (${d.source??"unknown source"}), last read ${m}`):u.push(`${d.provider}: ${d.status} (${d.reason??"no reason given"}), last read ${m}${d.detail?` -- ${d.detail}`:""}`);for(let f of l.filter(p=>p.provider===d.provider)){let p=s.find(E=>E.provider===f.provider&&E.bucketId===f.bucketId&&E.resetsAt===f.resetsAt),h=p?` [ARMED rule=${p.rule}, forecast ${new Date(p.forecastAt).toISOString()}]`:"",w=f.stale?` [STALE, read ${me(f.ageMs)} ago]`:"",_=f.expiredMs!==null?` [WINDOW EXPIRED ${me(f.expiredMs)} ago -- not a current reading]`:"";u.push(` ${f.bucketId} (${f.windowType}): used_fraction=${f.usedFraction} resets_at=${f.resetsAtIso??"unknown"}${w}${_}${h}`),u.push(` ${_D(r,f.provider,f.bucketId,f.resetsAt)}`)}}return u.join(`
643
- `)}function HE(e,t={}){let r=e.db.db,n=t.limit??20,o=t.provider?r.prepare(`SELECT ts, provider, bucket_id AS bucketId, window_type AS windowType, outcome, detail
644
- FROM rate_limit_policy_log WHERE provider = ? ORDER BY ts DESC, id DESC LIMIT ?`).all(t.provider,n):r.prepare("SELECT ts, provider, bucket_id AS bucketId, window_type AS windowType, outcome, detail FROM rate_limit_policy_log ORDER BY ts DESC, id DESC LIMIT ?").all(n),s=qi(r);if(t.json)return JSON.stringify({rows:o,policyHeartbeat:s});if(o.length===0){let i=t.provider?` for ${t.provider}`:"";if(s===null)return`rate-limit log: empty${i} (policy has never run -- collection may be off, or --rate-limit-policy/--rate-limit-automation is not enabled).`;let a=Math.round((Date.now()-s.lastRunAtMs)/1e3);return`rate-limit log: empty${i} (policy last evaluated ${a}s ago, ${s.seriesEvaluated} series fleet-wide, nothing crossed a threshold).`}return o.map(i=>`${new Date(i.ts).toISOString()} ${i.provider}/${i.bucketId} (${i.windowType}) ${i.outcome}: ${i.detail}`).join(`
645
- `)}var wD=[7,30],Hu=3,yD=20,ED="USD cost not computed -- lmbi's pricing engine is a governed per-snapshot process, not yet exposed as a reusable query surface; token totals shown instead";function TD(e){if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]}function bD(e){if(e.length===0)return null;let t=Math.min(e.length-1,Math.ceil(e.length*.9)-1);return e[Math.max(0,t)]}function SD(e){return(e.tokens_in_cached??0)+(e.tokens_in_uncached??0)+(e.tokens_cache_write??0)+(e.tokens_out??0)}function vD(e,t,r){if(!r||t.sessionid===null||t.endedAtIso===null)return null;let n=e.prepare(`SELECT provider, sessionid, timestamp, tokens_in_cached, tokens_in_uncached, tokens_cache_write, tokens_out
641
+ ORDER BY s.provider, s.bucket_id`).all(),s=r.prepare("SELECT provider, bucket_id AS bucketId, resets_at AS resetsAt, rule, armed_at AS armedAt, forecast_at AS forecastAt FROM rate_limit_policy_arm ORDER BY provider, bucket_id").all(),i=Bi(r),a=(()=>{if(i===null)return"policy: never run.";let d=Math.round((Date.now()-i.lastRunAtMs)/1e3),m=Object.entries(i.outcomeCounts).map(([f,p])=>`${p} ${f}`).join(", ")||"nothing to evaluate";return`policy: last ran ${new Date(i.lastRunAtMs).toISOString()} (${d}s ago), evaluated ${i.seriesEvaluated} series (${m}).`})(),c=Date.now(),l=o.map(d=>({...d,...SD(c,d)}));if(t.json)return JSON.stringify({latestByProvider:n,series:l,armed:s,policyHeartbeat:i});if(n.length===0)return`rate-limit: no readings collected yet.
642
+ ${a}`;let u=[a];for(let d of n){let m=new Date(d.read_at*1e3).toISOString();d.status==="ok"?u.push(`${d.provider}: ok (${d.source??"unknown source"}), last read ${m}`):u.push(`${d.provider}: ${d.status} (${d.reason??"no reason given"}), last read ${m}${d.detail?` -- ${d.detail}`:""}`);for(let f of l.filter(p=>p.provider===d.provider)){let p=s.find(T=>T.provider===f.provider&&T.bucketId===f.bucketId&&T.resetsAt===f.resetsAt),h=p?` [ARMED rule=${p.rule}, forecast ${new Date(p.forecastAt).toISOString()}]`:"",w=f.stale?` [STALE, read ${me(f.ageMs)} ago]`:"",_=f.expiredMs!==null?` [WINDOW EXPIRED ${me(f.expiredMs)} ago -- not a current reading]`:"";u.push(` ${f.bucketId} (${f.windowType}): used_fraction=${f.usedFraction} resets_at=${f.resetsAtIso??"unknown"}${w}${_}${h}`),u.push(` ${vD(r,f.provider,f.bucketId,f.resetsAt)}`)}}return u.join(`
643
+ `)}function JE(e,t={}){let r=e.db.db,n=t.limit??20,o=t.provider?r.prepare(`SELECT ts, provider, bucket_id AS bucketId, window_type AS windowType, outcome, detail
644
+ FROM rate_limit_policy_log WHERE provider = ? ORDER BY ts DESC, id DESC LIMIT ?`).all(t.provider,n):r.prepare("SELECT ts, provider, bucket_id AS bucketId, window_type AS windowType, outcome, detail FROM rate_limit_policy_log ORDER BY ts DESC, id DESC LIMIT ?").all(n),s=Bi(r);if(t.json)return JSON.stringify({rows:o,policyHeartbeat:s});if(o.length===0){let i=t.provider?` for ${t.provider}`:"";if(s===null)return`rate-limit log: empty${i} (policy has never run -- collection may be off, or --rate-limit-policy/--rate-limit-automation is not enabled).`;let a=Math.round((Date.now()-s.lastRunAtMs)/1e3);return`rate-limit log: empty${i} (policy last evaluated ${a}s ago, ${s.seriesEvaluated} series fleet-wide, nothing crossed a threshold).`}return o.map(i=>`${new Date(i.ts).toISOString()} ${i.provider}/${i.bucketId} (${i.windowType}) ${i.outcome}: ${i.detail}`).join(`
645
+ `)}var AD=[7,30],Gu=3,kD=20,$D="USD cost not computed -- lmbi's pricing engine is a governed per-snapshot process, not yet exposed as a reusable query surface; token totals shown instead";function xD(e){if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]}function RD(e){if(e.length===0)return null;let t=Math.min(e.length-1,Math.ceil(e.length*.9)-1);return e[Math.max(0,t)]}function ND(e){return(e.tokens_in_cached??0)+(e.tokens_in_uncached??0)+(e.tokens_cache_write??0)+(e.tokens_out??0)}function LD(e,t,r){if(!r||t.sessionid===null||t.endedAtIso===null)return null;let n=e.prepare(`SELECT provider, sessionid, timestamp, tokens_in_cached, tokens_in_uncached, tokens_cache_write, tokens_out
646
646
  FROM lmbi_session_responses
647
- WHERE provider = ? AND sessionid = ? AND timestamp IS NOT NULL AND timestamp >= ? AND timestamp <= ?`).all(t.provider,t.sessionid,t.startedAtIso,t.endedAtIso);return n.length===0?null:n.reduce((o,s)=>o+SD(s),0)}function AD(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}function BE(e){let t=e.filter(s=>s.outcome==="done").length,r=e.filter(s=>s.outcome==="failed").length,n=e.filter(s=>s.outcome==="contention").length,o=t+r;return{doneCount:t,failedCount:r,contentionCount:n,completionRate:o>0?t/o:null,sampleSize:e.length,lowConfidence:e.length<yD}}function WE(e){let t=e.nowMs??Date.now(),r=[],n={},o=AD(e.lmautoDb,"lmbi_session_responses");for(let s of wD){let i=new Date(t-s*24*60*60*1e3).toISOString(),{rows:a,skippedUnattributable:c}=Bp(e.lctlDb,i);n[s]=c;let l=new Map;for(let d of a){let m=`${d.provider}\0${d.model??""}`,f=l.get(m)??{provider:d.provider,model:d.model,invocations:[]};f.invocations.push(d),l.set(m,f)}let u=t-Hu*24*60*60*1e3;for(let d of l.values()){let m=d.invocations.filter(S=>S.outcome==="done"&&S.durationMs!==null).map(S=>S.durationMs).sort((S,N)=>S-N),f=BE(d.invocations),{doneCount:p,failedCount:h,contentionCount:w}=f,_=d.invocations.filter(S=>Date.parse(S.startedAtIso)>=u),E=BE(_),T=0,v=0;for(let S of d.invocations){if(S.outcome!=="done")continue;let N=vD(e.lmautoDb,S,o);N===null?v++:T+=N}r.push({provider:d.provider,model:d.model,windowDays:s,sampleSize:f.sampleSize,lowConfidence:f.lowConfidence,recentCompletionRate:E.completionRate,recentSampleSize:E.sampleSize,recentLowConfidence:E.lowConfidence,medianDurationMs:TD(m),p90DurationMs:bD(m),completionRate:f.completionRate,doneCount:p,failedCount:h,contentionCount:w,totalTokens:T,tokenJoinMisses:v,costUnavailableReason:ED})}}return{rows:r.sort((s,i)=>s.windowDays-i.windowDays||s.provider.localeCompare(i.provider)||(s.model??"").localeCompare(i.model??"")),skippedUnattributableByWindow:n}}function GE(e,t={}){let r=Object.values(t).reduce((i,a)=>i+a,0);if(e.length===0)return r>0?`reliability report: no attributable chat dispatches found (${r} skipped as unattributable -- see tracked_invocation's own meta shape).`:"reliability report: no chat dispatches found in either window.";let n=[],o=null;for(let i of e){i.windowDays!==o&&(o=i.windowDays,n.push(`
648
- -- ${i.windowDays}d reliability window --`));let a=i.model??"(default)",c=i.lowConfidence?`n=${i.sampleSize}, LOW CONFIDENCE`:`n=${i.sampleSize}`,l=i.completionRate===null?"completion rate unknown (no done/failed evidence)":`completion rate ${(i.completionRate*100).toFixed(1)}%`,u=i.recentCompletionRate===null?`last ${Hu}d unknown (n=${i.recentSampleSize})`:`last ${Hu}d ${(i.recentCompletionRate*100).toFixed(1)}%${i.recentLowConfidence?" LOW CONFIDENCE":""} (n=${i.recentSampleSize})`,d=i.medianDurationMs!==null?`median ${Math.round(i.medianDurationMs/1e3)}s / p90 ${Math.round(i.p90DurationMs/1e3)}s`:i.doneCount>0?"duration unknown (completed dispatch(es) recorded no end time)":"duration unknown (no completed dispatch)",m=i.tokenJoinMisses>0?` (${i.tokenJoinMisses} join miss(es), tokens undercounted)`:"";n.push(` ${i.provider}/${a} (${c}): ${l} [${u}], ${d}, ${i.totalTokens} tokens across ${i.doneCount} completed dispatch(es)${m} -- ${i.costUnavailableReason}`)}let s=Object.entries(t).filter(([,i])=>i>0).map(([i,a])=>`${a} unattributable dispatch(es) skipped in the ${i}d window`);return s.length>0&&n.push(`
647
+ WHERE provider = ? AND sessionid = ? AND timestamp IS NOT NULL AND timestamp >= ? AND timestamp <= ?`).all(t.provider,t.sessionid,t.startedAtIso,t.endedAtIso);return n.length===0?null:n.reduce((o,s)=>o+ND(s),0)}function ID(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}function KE(e){let t=e.filter(s=>s.outcome==="done").length,r=e.filter(s=>s.outcome==="failed").length,n=e.filter(s=>s.outcome==="contention").length,o=t+r;return{doneCount:t,failedCount:r,contentionCount:n,completionRate:o>0?t/o:null,sampleSize:e.length,lowConfidence:e.length<kD}}function zE(e){let t=e.nowMs??Date.now(),r=[],n={},o=ID(e.lmautoDb,"lmbi_session_responses");for(let s of AD){let i=new Date(t-s*24*60*60*1e3).toISOString(),{rows:a,skippedUnattributable:c}=Vp(e.lctlDb,i);n[s]=c;let l=new Map;for(let d of a){let m=`${d.provider}\0${d.model??""}`,f=l.get(m)??{provider:d.provider,model:d.model,invocations:[]};f.invocations.push(d),l.set(m,f)}let u=t-Gu*24*60*60*1e3;for(let d of l.values()){let m=d.invocations.filter(S=>S.outcome==="done"&&S.durationMs!==null).map(S=>S.durationMs).sort((S,N)=>S-N),f=KE(d.invocations),{doneCount:p,failedCount:h,contentionCount:w}=f,_=d.invocations.filter(S=>Date.parse(S.startedAtIso)>=u),T=KE(_),E=0,v=0;for(let S of d.invocations){if(S.outcome!=="done")continue;let N=LD(e.lmautoDb,S,o);N===null?v++:E+=N}r.push({provider:d.provider,model:d.model,windowDays:s,sampleSize:f.sampleSize,lowConfidence:f.lowConfidence,recentCompletionRate:T.completionRate,recentSampleSize:T.sampleSize,recentLowConfidence:T.lowConfidence,medianDurationMs:xD(m),p90DurationMs:RD(m),completionRate:f.completionRate,doneCount:p,failedCount:h,contentionCount:w,totalTokens:E,tokenJoinMisses:v,costUnavailableReason:$D})}}return{rows:r.sort((s,i)=>s.windowDays-i.windowDays||s.provider.localeCompare(i.provider)||(s.model??"").localeCompare(i.model??"")),skippedUnattributableByWindow:n}}function YE(e,t={}){let r=Object.values(t).reduce((i,a)=>i+a,0);if(e.length===0)return r>0?`reliability report: no attributable chat dispatches found (${r} skipped as unattributable -- see tracked_invocation's own meta shape).`:"reliability report: no chat dispatches found in either window.";let n=[],o=null;for(let i of e){i.windowDays!==o&&(o=i.windowDays,n.push(`
648
+ -- ${i.windowDays}d reliability window --`));let a=i.model??"(default)",c=i.lowConfidence?`n=${i.sampleSize}, LOW CONFIDENCE`:`n=${i.sampleSize}`,l=i.completionRate===null?"completion rate unknown (no done/failed evidence)":`completion rate ${(i.completionRate*100).toFixed(1)}%`,u=i.recentCompletionRate===null?`last ${Gu}d unknown (n=${i.recentSampleSize})`:`last ${Gu}d ${(i.recentCompletionRate*100).toFixed(1)}%${i.recentLowConfidence?" LOW CONFIDENCE":""} (n=${i.recentSampleSize})`,d=i.medianDurationMs!==null?`median ${Math.round(i.medianDurationMs/1e3)}s / p90 ${Math.round(i.p90DurationMs/1e3)}s`:i.doneCount>0?"duration unknown (completed dispatch(es) recorded no end time)":"duration unknown (no completed dispatch)",m=i.tokenJoinMisses>0?` (${i.tokenJoinMisses} join miss(es), tokens undercounted)`:"";n.push(` ${i.provider}/${a} (${c}): ${l} [${u}], ${d}, ${i.totalTokens} tokens across ${i.doneCount} completed dispatch(es)${m} -- ${i.costUnavailableReason}`)}let s=Object.entries(t).filter(([,i])=>i>0).map(([i,a])=>`${a} unattributable dispatch(es) skipped in the ${i}d window`);return s.length>0&&n.push(`
649
649
  (${s.join("; ")} -- see tracked_invocation's own meta shape)`),n.join(`
650
- `).trimStart()}function VE(e,t={}){let r=On(t.lctlDbPath);try{let{rows:n,skippedUnattributableByWindow:o}=WE({lctlDb:r,lmautoDb:e.db.db});return t.json?JSON.stringify({rows:n,skippedUnattributableByWindow:o}):GE(n,o)}finally{r.close()}}async function JE(e,t={}){let r=await Ru({configPath:e});return t.json?JSON.stringify(r):JSON.stringify(r,null,2)}import{execFile as $D}from"node:child_process";import{basename as kD}from"node:path";import{promisify as xD}from"node:util";var RD=xD($D),ND=["lmplayer run","opencode run"];function ID(){return Kr[Kr.length-1]??"lmctl"}function LD(e){let t=e.lastIndexOf(":");if(t===-1)return[e];let r=e.slice(0,t),n=e.slice(t+1);return[e,`${kD(r)} ${n}`]}async function KE(e,t=Ae,r=RD){let n=(typeof e=="string"?[e]:e).filter(d=>d!==""),o;try{o=await t()}catch{o=null}let s=o===null?null:o.running.filter(d=>!n.includes(d.target??"")),i;try{i=(await r("ps",["aux"])).stdout}catch{i=""}let a=ID(),c=[`${a} chat`,`${a} terminal`,...ND],l=n.flatMap(LD),u=i.split(`
651
- `).filter(d=>c.some(m=>d.includes(m))).filter(d=>!l.some(m=>d.includes(m)));return{lctlRunning:o,otherTeamsRunning:s,externalWrapperProcessLines:u}}function zE(e){return(e.otherTeamsRunning?.length??0)>0||e.externalWrapperProcessLines.length>0}function CD(e){let t=process.env.LMBEE_TEAM_NAME;if(!t)return null;let r=e.teams.find(n=>n.name===t);if(r===void 0||!H(r))return null;try{return`${Q(r)}:${r.leadAlias}`}catch{return null}}async function YE(e,t={}){let r=t.exclude===void 0?[]:typeof t.exclude=="string"?t.exclude.split(","):t.exclude,n=CD(e),o=n===null?r:[n,...r],i=await(t.checkInFlightDispatchImpl??KE)(o),a=zE(i);if(t.json)return JSON.stringify({inFlight:a,...i});if(!a)return"clear -- no other team's session or external wrapper process currently running.";let c=[];for(let u of i.otherTeamsRunning??[])c.push(` lmctl running: ${u.target??"(unknown target)"}`);for(let u of i.externalWrapperProcessLines)c.push(` process: ${u.trim()}`);let l=i.lctlRunning===null?"\n(note: `lmctl running --json` itself failed -- this reading is from the process scan alone)":"";return`IN FLIGHT -- hold the restart:
650
+ `).trimStart()}function QE(e,t={}){let r=On(t.lctlDbPath);try{let{rows:n,skippedUnattributableByWindow:o}=zE({lctlDb:r,lmautoDb:e.db.db});return t.json?JSON.stringify({rows:n,skippedUnattributableByWindow:o}):YE(n,o)}finally{r.close()}}async function XE(e,t={}){let r=await Iu({configPath:e});return t.json?JSON.stringify(r):JSON.stringify(r,null,2)}import{execFile as CD}from"node:child_process";import{basename as OD}from"node:path";import{promisify as DD}from"node:util";var MD=DD(CD),PD=["lmplayer run","opencode run"];function UD(){return Kr[Kr.length-1]??"lmctl"}function FD(e){let t=e.lastIndexOf(":");if(t===-1)return[e];let r=e.slice(0,t),n=e.slice(t+1);return[e,`${OD(r)} ${n}`]}async function ZE(e,t=Ae,r=MD){let n=(typeof e=="string"?[e]:e).filter(d=>d!==""),o;try{o=await t()}catch{o=null}let s=o===null?null:o.running.filter(d=>!n.includes(d.target??"")),i;try{i=(await r("ps",["aux"])).stdout}catch{i=""}let a=UD(),c=[`${a} chat`,`${a} terminal`,...PD],l=n.flatMap(FD),u=i.split(`
651
+ `).filter(d=>c.some(m=>d.includes(m))).filter(d=>!l.some(m=>d.includes(m)));return{lctlRunning:o,otherTeamsRunning:s,externalWrapperProcessLines:u}}function eT(e){return(e.otherTeamsRunning?.length??0)>0||e.externalWrapperProcessLines.length>0}function qD(e){let t=process.env.LMBEE_TEAM_NAME;if(!t)return null;let r=e.teams.find(n=>n.name===t);if(r===void 0||!B(r))return null;try{return`${Q(r)}:${r.leadAlias}`}catch{return null}}async function tT(e,t={}){let r=t.exclude===void 0?[]:typeof t.exclude=="string"?t.exclude.split(","):t.exclude,n=qD(e),o=n===null?r:[n,...r],i=await(t.checkInFlightDispatchImpl??ZE)(o),a=eT(i);if(t.json)return JSON.stringify({inFlight:a,...i});if(!a)return"clear -- no other team's session or external wrapper process currently running.";let c=[];for(let u of i.otherTeamsRunning??[])c.push(` lmctl running: ${u.target??"(unknown target)"}`);for(let u of i.externalWrapperProcessLines)c.push(` process: ${u.trim()}`);let l=i.lctlRunning===null?"\n(note: `lmctl running --json` itself failed -- this reading is from the process scan alone)":"";return`IN FLIGHT -- hold the restart:
652
652
  ${c.join(`
653
- `)}${l}`}import{readFileSync as OD,statSync as QE}from"node:fs";function pa(e,t=OD){try{let r=t(`/proc/${e}/stat`,"utf8");return r.slice(r.lastIndexOf(")")+2).trim().split(/\s+/)[19]??null}catch{return null}}function DD(e,t=process.kill,r=pa){let n;try{t(e.pid,0),n=!0}catch(s){n=s.code==="EPERM"}return n?e.startTicks===null?{alive:!0,identityVerified:!1}:r(e.pid)===e.startTicks?{alive:!0,identityVerified:!0}:{alive:!1,identityVerified:!0}:{alive:!1,identityVerified:e.startTicks!==null}}function MD(e,t=QE){let r=[],n=[],o=[];for(let s of e){let i;try{i=t(s).size}catch{o.push(s);continue}i>0?r.push(s):n.push(s)}return{complete:r,empty:n,missing:o}}function XE(e,t,r=process.kill,n=pa,o=QE){let s=DD(e,r,n),i=MD(t,o),a;return s.alive?a="running":t.length===0?a="unknown":i.missing.length===0&&i.empty.length===0?a="finished":i.complete.length>0||i.empty.length>0?a="finished-partial":a="unknown",{status:a,process:s,artifacts:i}}function ZE(e,t={}){let r=pa(e);return t.json?JSON.stringify({pid:e,startTicks:r}):r===null?`could not capture an identity for pid ${e} -- process may not exist, or /proc is unavailable (non-Linux)`:`pid ${e} startTicks=${r} -- save this and pass it back as --start-ticks to \`dispatch-status check\` later`}function PD(e,t){let r=[`status: ${t.status}`];return r.push(`process: pid ${e}, alive=${t.process.alive}, identityVerified=${t.process.identityVerified}`),!t.process.identityVerified&&t.process.alive&&r.push(' (no start-ticks identity was given -- "alive" reflects raw pid existence only, PID reuse cannot be ruled out)'),t.artifacts.complete.length>0&&r.push(` complete: ${t.artifacts.complete.join(", ")}`),t.artifacts.empty.length>0&&r.push(` empty (exists, zero bytes): ${t.artifacts.empty.join(", ")}`),t.artifacts.missing.length>0&&r.push(` missing: ${t.artifacts.missing.join(", ")}`),r.join(`
654
- `)}function eT(e,t,r={}){let n=XE({pid:e,startTicks:r.startTicks??null},t);return r.json?JSON.stringify({pid:e,...n}):PD(e,n)}function tT(e,t,r,n,o={}){return Tw(e.db.db,t,r,n),o.json?JSON.stringify({name:t,teamfilePath:r,alias:n}):`logical name "${t}" -> ${r}:${n}`}function rT(e,t,r={}){let n=sa(e.db.db,t);return r.json?JSON.stringify(n):n===null?`"${t}" is not registered`:`"${t}" -> ${n.teamfilePath}:${n.alias}`}function nT(e,t={}){let r=bw(e.db.db);return t.json?JSON.stringify(r):r.length===0?"no logical names registered":r.map(n=>`${n.name} -> ${n.teamfilePath}:${n.alias} (updated ${n.updatedAt})`).join(`
655
- `)}function oT(e,t,r={}){let n=sa(e.db.db,t)!==null;return Sw(e.db.db,t),r.json?JSON.stringify({name:t,cleared:n}):n?`logical name "${t}" cleared`:`"${t}" was not registered (no-op)`}import{execFile as UD}from"node:child_process";import{promisify as FD}from"node:util";var dr=Ut(xt(),1),sT=FD(UD);async function qD(e){try{let[{stdout:t},{stdout:r}]=await Promise.all([sT("git",["-C",e,"log","--oneline","-1"],{timeout:1e4}),sT("git",["-C",e,"status","--porcelain"],{timeout:1e4})]),n=r.split(`
656
- `).filter(o=>o.trim().length>0).length;return{head:t.trim().slice(0,48)||"(empty)",dirty:String(n)}}catch{return{head:"(no git)",dirty:"-"}}}function jD(e,t){return H(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead":"Idle":"remote -- delivery only"}async function iT(e,t={}){let n=await(t.fetchReport??Ae)(),o=t.only&&t.only.length>0?new Set(t.only):null,s=o?e.teams.filter(c=>o.has(c.name)):e.teams,i=["TEAM","LIVE","STATUS(self-report)","PROGRESS","GIT-HEAD","UNCOMMITTED"],a=await Promise.all(s.map(async c=>{let l=Ue(e.db.db,c.name),u=ie(e.db.db,c.name),d=H(c)?await qD(c.repoPath):{head:"(remote)",dirty:"-"},m=u?.confirmed_done_ts?"DONE(confirmed)":u?.progress_status??"?";return[(0,dr.escapeCell)(c.name),(0,dr.escapeCell)(jD(c,n)),(0,dr.escapeCell)(l?.status??"?"),(0,dr.escapeCell)(m),(0,dr.escapeCell)(d.head),(0,dr.escapeCell)(d.dirty)]}));return(0,dr.formatTable)([i,...a])}var HD=8,BD=18e5;function Bu(e){return e.teams.filter(H).filter(t=>t.autoNudge)}function WD(e){let t=Bu(e);return t.length>0&&t.every(r=>ie(e.db.db,r.name)?.confirmed_done_ts)}async function aT(e,t={}){let r=await os(e.db.db,Bu(e),t);return ss(r)}async function cT(e,t={}){let r=t.maxScans??HD,n=t.scanIntervalMs??BD,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i))),s="(no scans ran)";for(let i=1;i<=r;i++){let a=await os(e.db.db,Bu(e),t);if(s=ss(a),a.wake)return`AUTOPILOT WAKE [${a.wake}]:
657
- ${s}`;if(WD(e))return`AUTOPILOT WAKE [all-done]:
653
+ `)}${l}`}import{readFileSync as jD,statSync as rT}from"node:fs";function _a(e,t=jD){try{let r=t(`/proc/${e}/stat`,"utf8");return r.slice(r.lastIndexOf(")")+2).trim().split(/\s+/)[19]??null}catch{return null}}function HD(e,t=process.kill,r=_a){let n;try{t(e.pid,0),n=!0}catch(s){n=s.code==="EPERM"}return n?e.startTicks===null?{alive:!0,identityVerified:!1}:r(e.pid)===e.startTicks?{alive:!0,identityVerified:!0}:{alive:!1,identityVerified:!0}:{alive:!1,identityVerified:e.startTicks!==null}}function BD(e,t=rT){let r=[],n=[],o=[];for(let s of e){let i;try{i=t(s).size}catch{o.push(s);continue}i>0?r.push(s):n.push(s)}return{complete:r,empty:n,missing:o}}function nT(e,t,r=process.kill,n=_a,o=rT){let s=HD(e,r,n),i=BD(t,o),a;return s.alive?a="running":t.length===0?a="unknown":i.missing.length===0&&i.empty.length===0?a="finished":i.complete.length>0||i.empty.length>0?a="finished-partial":a="unknown",{status:a,process:s,artifacts:i}}function oT(e,t={}){let r=_a(e);return t.json?JSON.stringify({pid:e,startTicks:r}):r===null?`could not capture an identity for pid ${e} -- process may not exist, or /proc is unavailable (non-Linux)`:`pid ${e} startTicks=${r} -- save this and pass it back as --start-ticks to \`dispatch-status check\` later`}function WD(e,t){let r=[`status: ${t.status}`];return r.push(`process: pid ${e}, alive=${t.process.alive}, identityVerified=${t.process.identityVerified}`),!t.process.identityVerified&&t.process.alive&&r.push(' (no start-ticks identity was given -- "alive" reflects raw pid existence only, PID reuse cannot be ruled out)'),t.artifacts.complete.length>0&&r.push(` complete: ${t.artifacts.complete.join(", ")}`),t.artifacts.empty.length>0&&r.push(` empty (exists, zero bytes): ${t.artifacts.empty.join(", ")}`),t.artifacts.missing.length>0&&r.push(` missing: ${t.artifacts.missing.join(", ")}`),r.join(`
654
+ `)}function sT(e,t,r={}){let n=nT({pid:e,startTicks:r.startTicks??null},t);return r.json?JSON.stringify({pid:e,...n}):WD(e,n)}function iT(e,t,r,n,o={}){return kw(e.db.db,t,r,n),o.json?JSON.stringify({name:t,teamfilePath:r,alias:n}):`logical name "${t}" -> ${r}:${n}`}function aT(e,t,r={}){let n=ca(e.db.db,t);return r.json?JSON.stringify(n):n===null?`"${t}" is not registered`:`"${t}" -> ${n.teamfilePath}:${n.alias}`}function cT(e,t={}){let r=$w(e.db.db);return t.json?JSON.stringify(r):r.length===0?"no logical names registered":r.map(n=>`${n.name} -> ${n.teamfilePath}:${n.alias} (updated ${n.updatedAt})`).join(`
655
+ `)}function lT(e,t,r={}){let n=ca(e.db.db,t)!==null;return xw(e.db.db,t),r.json?JSON.stringify({name:t,cleared:n}):n?`logical name "${t}" cleared`:`"${t}" was not registered (no-op)`}import{execFile as GD}from"node:child_process";import{promisify as VD}from"node:util";var mr=Ut(xt(),1),uT=VD(GD);async function JD(e){try{let[{stdout:t},{stdout:r}]=await Promise.all([uT("git",["-C",e,"log","--oneline","-1"],{timeout:1e4}),uT("git",["-C",e,"status","--porcelain"],{timeout:1e4})]),n=r.split(`
656
+ `).filter(o=>o.trim().length>0).length;return{head:t.trim().slice(0,48)||"(empty)",dirty:String(n)}}catch{return{head:"(no git)",dirty:"-"}}}function KD(e,t){return B(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead":"Idle":"remote -- delivery only"}async function dT(e,t={}){let n=await(t.fetchReport??Ae)(),o=t.only&&t.only.length>0?new Set(t.only):null,s=o?e.teams.filter(c=>o.has(c.name)):e.teams,i=["TEAM","LIVE","STATUS(self-report)","PROGRESS","GIT-HEAD","UNCOMMITTED"],a=await Promise.all(s.map(async c=>{let l=Ue(e.db.db,c.name),u=ie(e.db.db,c.name),d=B(c)?await JD(c.repoPath):{head:"(remote)",dirty:"-"},m=u?.confirmed_done_ts?"DONE(confirmed)":u?.progress_status??"?";return[(0,mr.escapeCell)(c.name),(0,mr.escapeCell)(KD(c,n)),(0,mr.escapeCell)(l?.status??"?"),(0,mr.escapeCell)(m),(0,mr.escapeCell)(d.head),(0,mr.escapeCell)(d.dirty)]}));return(0,mr.formatTable)([i,...a])}var zD=8,YD=18e5;function Vu(e){return e.teams.filter(B).filter(t=>t.autoNudge)}function QD(e){let t=Vu(e);return t.length>0&&t.every(r=>ie(e.db.db,r.name)?.confirmed_done_ts)}async function mT(e,t={}){let r=await cs(e.db.db,Vu(e),t);return ls(r)}async function fT(e,t={}){let r=t.maxScans??zD,n=t.scanIntervalMs??YD,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i))),s="(no scans ran)";for(let i=1;i<=r;i++){let a=await cs(e.db.db,Vu(e),t);if(s=ls(a),a.wake)return`AUTOPILOT WAKE [${a.wake}]:
657
+ ${s}`;if(QD(e))return`AUTOPILOT WAKE [all-done]:
658
658
  ${s}`;i<r&&await o(n)}return`AUTOPILOT WAKE [heartbeat]: exhausted ${r} scans with no wake condition
659
- ${s}`}function GD(e){let t=Ir(e.db.db);return{paused:t!==null,state:t}}function lT(e,t={}){let r=GD(e);if(t.json)return JSON.stringify(r);if(!r.paused)return"auto-scan: running (auto-continue nudges active)";let n=r.state;return`auto-scan: paused${` since ${n.paused_at}`+(n.actor!==null?`, by ${n.actor}`:"")+(n.note!==null?` -- ${n.note}`:"")+(n.resume_after!==null?` (resume_after: ${n.resume_after})`:"")}
660
- (manual nudge and queue delivery are unaffected)`}function uT(e,t={}){let r={paused_at:new Date().toISOString(),actor:t.actor??null,note:t.note??null,resume_after:t.resumeAfter??null};if(r.resume_after!==null&&Number.isNaN(Date.parse(r.resume_after)))throw new Error(`--resume-after "${r.resume_after}" is not a parseable timestamp`);if(Gh(e.db.db,r),t.json)return JSON.stringify({paused:!0,state:r});let n=r.resume_after!==null?` (flagged stale if still paused past ${r.resume_after})`:"";return`auto-scan paused at ${r.paused_at}${n} -- the daemon stops auto-continue nudging within one tick.
661
- (manual nudge and queue delivery are unaffected; \`lmbee scan start\` resumes)`}function dT(e,t={}){let r=Ir(e.db.db)!==null;return Vh(e.db.db),t.json?JSON.stringify({paused:!1,state:null}):r?"auto-scan resumed -- the daemon picks it up within one tick.":"auto-scan is already running (no pause was in effect)."}async function mT(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=e.teams.find(E=>E.name===o);if(!i)throw new Error(`send: unknown team "${o}"`);if(!H(i))throw new Error(`send: team "${o}" is a remote team (channel=lmmail) -- not reachable via lctl`);let a=s??i.leadAlias,c=Q(i),l=Vr(i);if(l.length>0&&!l.some(E=>E.alias===a))throw new Error(`send: "${a}" is not a configured member of team "${o}" -- actual members: ${l.map(E=>E.alias).join(", ")}`);let u=Cr("send",r,n.literal),d=n.send??Ht,m=n.probe??Jo,f=n.nowMs??Date.now(),p=await d({teamfilePath:c,alias:a},u),h=Wn(p);if(ir(e.db.db,i.name,h.status,f),tt(e.db.db,i.name,h.status,f,{note:"send"}),h.status==="ENV-ERROR"||h.status==="NO-OUTPUT")try{(await m(c,a)).sessionResolves||cw(e.db.db,c,a,{kind:"evicted",remedy:`lctl refresh ${c} ${a}`})}catch{}else Xo(e.db.db,c,a)!==null&&lw(e.db.db,c,a);let w=p.kind==="ok"?p.replyText.split(`
659
+ ${s}`}function XD(e){let t=Lr(e.db.db);return{paused:t!==null,state:t}}function pT(e,t={}){let r=XD(e);if(t.json)return JSON.stringify(r);if(!r.paused)return"auto-scan: running (auto-continue nudges active)";let n=r.state;return`auto-scan: paused${` since ${n.paused_at}`+(n.actor!==null?`, by ${n.actor}`:"")+(n.note!==null?` -- ${n.note}`:"")+(n.resume_after!==null?` (resume_after: ${n.resume_after})`:"")}
660
+ (manual nudge and queue delivery are unaffected)`}function hT(e,t={}){let r={paused_at:new Date().toISOString(),actor:t.actor??null,note:t.note??null,resume_after:t.resumeAfter??null};if(r.resume_after!==null&&Number.isNaN(Date.parse(r.resume_after)))throw new Error(`--resume-after "${r.resume_after}" is not a parseable timestamp`);if(Yh(e.db.db,r),t.json)return JSON.stringify({paused:!0,state:r});let n=r.resume_after!==null?` (flagged stale if still paused past ${r.resume_after})`:"";return`auto-scan paused at ${r.paused_at}${n} -- the daemon stops auto-continue nudging within one tick.
661
+ (manual nudge and queue delivery are unaffected; \`lmbee scan start\` resumes)`}function gT(e,t={}){let r=Lr(e.db.db)!==null;return Qh(e.db.db),t.json?JSON.stringify({paused:!1,state:null}):r?"auto-scan resumed -- the daemon picks it up within one tick.":"auto-scan is already running (no pause was in effect)."}async function _T(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=e.teams.find(T=>T.name===o);if(!i)throw new Error(`send: unknown team "${o}"`);if(!B(i))throw new Error(`send: team "${o}" is a remote team (channel=lmmail) -- not reachable via lctl`);let a=s??i.leadAlias,c=Q(i),l=Vr(i);if(l.length>0&&!l.some(T=>T.alias===a))throw new Error(`send: "${a}" is not a configured member of team "${o}" -- actual members: ${l.map(T=>T.alias).join(", ")}`);let u=Cr("send",r,n.literal),d=n.send??Ht,m=n.probe??Qo,f=n.nowMs??Date.now(),p=await d({teamfilePath:c,alias:a},u),h=Vn(p);if(ir(e.db.db,i.name,h.status,f),tt(e.db.db,i.name,h.status,f,{note:"send"}),h.status==="ENV-ERROR"||h.status==="NO-OUTPUT")try{(await m(c,a)).sessionResolves||fw(e.db.db,c,a,{kind:"evicted",remedy:`lctl refresh ${c} ${a}`})}catch{}else rs(e.db.db,c,a)!==null&&pw(e.db.db,c,a);let w=p.kind==="ok"?p.replyText.split(`
662
662
  `).slice(-6).join(`
663
663
  `):"";return`${a===i.leadAlias?i.name:`${i.name}:${a}`}: ${h.status}${w?`
664
- ${w}`:""}`}import{spawnSync as JD}from"node:child_process";var KD=2e3,zD=3e4;async function fT(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=o.endsWith(".lmctl")?o.slice(0,-6):null,a=i??o,c=r??s,l=e.teams.find(C=>C.name===a);if(l===void 0||!H(l)){if(i!==null)return{output:`terminal: "${o}" is not a known local team -- did you mean "${i}"?
665
- (lctl takes a teamfile path; lmbee takes a team name)`,exitCode:1};let C=e.teams.filter(H).map(g=>g.name).sort();return{output:`terminal: "${o}" is not a known local team -- known local teams: ${C.length>0?C.join(", "):"(none configured)"}`,exitCode:1}}let u=c??l.leadAlias,d;try{d=Q(l)}catch(C){return{output:`terminal: could not resolve ${a}'s teamfile: ${C instanceof Error?C.message:String(C)}`,exitCode:1}}let m=n.pollIntervalMs??KD,f=n.leaseMs??6e4,p=n.maxWaitMs??zD,h=n.fetchReport??Ae,w=n.spawnSyncImpl??JD,_=n.sleep??(C=>new Promise(g=>setTimeout(g,C))),E=n.now??Date.now,T=n.reason??null,v=n.pid??process.pid,S=E();if(Mm(e.db.db,a,u,v,new Date(S).toISOString(),T,f)===null){let C=cc(e.db.db,a,u,S),g=C?`held by pid ${C.holderPid} since ${C.reservedAt}${C.reason?` (${C.reason})`:""}`:"held by another acquirer";return{output:`terminal: ${a}:${u} is already reserved -- ${g}`,exitCode:1}}let x=[`reserved ${a}:${u} -- no other automated dispatch (queue delivery, auto-scan, escalation) will claim it while this runs`],I=!1;try{for(;;){let C=await h();if(!wm(d,u,C))break;if(E()-S>=p){I=!0;break}await _(m)}}finally{Um(e.db.db,a,u,v)}if(I)return x.push(`${a}:${u} is still busy after ${me(p)} -- reservation released, try again`),{output:x.join(`
666
- `),exitCode:1};x.push(`${a}:${u} is available -- launching terminal now (reservation released)`);let k=w("lmctl",["terminal",d,u],{stdio:"inherit"}),B=k.status??(k.error?1:0);return{output:x.join(`
667
- `),exitCode:B}}import{readFileSync as wT}from"node:fs";import{basename as eM}from"node:path";import{execFileSync as pT}from"node:child_process";import{dirname as YD}from"node:path";var QD=new Set(["done","closed","cancelled"]);function XD(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}function ZD(e){return YD(e)}function hT(e,t,r=pT){let n=Le(e,t);return gT(n,r)}function gT(e,t){let r={id:e.id,title:e.title,status:e.status};if(QD.has(XD(e.status)))return{...r,repoRoot:null,commits:[],checkError:"already terminal -- nothing to audit"};if(e.owner_team_path===null)return{...r,repoRoot:null,commits:[],checkError:"unowned -- no repo to check"};let n=ZD(e.owner_team_path),o=`#${e.id}([^0-9]|$)`;try{let i=t("git",["-C",n,"log","--oneline","--date=short","--pretty=format:%h %ad %s","-i","-E",`--grep=${o}`,`--since=${e.created_at}`],{encoding:"utf8"}).split(`
668
- `).filter(a=>a.trim().length>0).map(a=>{let[c,l,...u]=a.split(" ");return{hash:c??"",date:l??"",subject:u.join(" ")}});return{...r,repoRoot:n,commits:i,checkError:null}}catch(s){let i=s instanceof Error?s.message:String(s);return{...r,repoRoot:n,commits:[],checkError:`could not check ${n}: ${i}`}}}function _T(e,t,r=pT){let n=vr(e,t),o=[],s=i=>{o.push(i);for(let a of i.children)s(a)};return s(n),o.map(i=>gT(i,r))}var TT=["unassigned","clear-parent","clear-owner","attention","clear-blocked-on"];function Pr(e,t,r,n){let o=e[t],s=e[r];if(o!==void 0&&s!==void 0)throw new L("INVALID_ARGUMENT",`--${t} and --${r} are mutually exclusive`);if(typeof o=="string")return o;if(typeof s=="string"){if(s==="-"){if(n.used)throw new L("INVALID_ARGUMENT","At most one input may read stdin");n.used=!0;try{return wT(0,"utf8")}catch(i){throw new L("INPUT_ERROR",`Cannot read UTF-8 input from stdin: ${i instanceof Error?i.message:String(i)}`)}}try{return wT(s,"utf8")}catch(i){throw new L("INPUT_ERROR",`Cannot read UTF-8 input from ${s}: ${i instanceof Error?i.message:String(i)}`)}}}function Yt(e,t,r={}){if(e===void 0)return;if(typeof e!="string"||!/^\d+$/.test(e))throw new L("INVALID_ARGUMENT",`${t} must be a nonnegative integer`);let n=Number(e),o=r.minimum??1;if(!Number.isSafeInteger(n)||n<o||r.maximum!==void 0&&n>r.maximum){let s=r.maximum!==void 0?`between ${o} and ${r.maximum}`:`>= ${o}`;throw new L("INVALID_ARGUMENT",`${t} must be an integer ${s}`)}return n}function zt(e,t){let r=Yt(e,t,{minimum:1});if(r===void 0)throw new L("INVALID_ARGUMENT",`${t} is required`);return r}function ha(e,t){let r=e[`${t}-team`],n=e[`${t}-alias`];if(!(r===void 0&&n===void 0)){if(r===void 0||n===void 0)throw new L("INVALID_ARGUMENT",`--${t}-team and --${t}-alias must both be given`);if(typeof r!="string"||typeof n!="string")throw new L("INVALID_ARGUMENT",`--${t}-team and --${t}-alias require values`);return{team:r,alias:n}}}function yT(e,t,r){let n=typeof e["blocked-on"]=="string"?e["blocked-on"]:void 0;if(n!==void 0&&n!=="operator"&&!t.some(o=>o.name===n))throw new L("INVALID_ARGUMENT",`--blocked-on "${n}" is not "operator" or a registered team name`);if(n!==void 0&&n!=="operator"&&r&&eM(r)===`${n}.lmctl`)throw new L("INVALID_ARGUMENT",`--blocked-on "${n}" is this task's own owner team -- a team cannot be blocked on itself`);return n}function ET(e){return e==="epic"||e==="task"||e==="subtask"}function Rt(e,t,r={}){return e?JSON.stringify({schema_version:1,ok:!0,data:t,meta:r}):rM(t,r)}function tM(e,t){return e?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:t.code,message:t.message}}),exitCode:t.exitCode}:{output:`${t.code}: ${t.message}`,exitCode:t.exitCode}}function rM(e,t){let r;Array.isArray(e)?r=e.length===0?"(empty)":e.map(o=>o&&typeof o=="object"&&"title"in o?[..."attentionReason"in o?["attentionReason"]:[],"id","kind","status","project","title"].map(s=>String(o[s]??"")).join(" "):JSON.stringify(o)).join(`
664
+ ${w}`:""}`}import{spawnSync as eM}from"node:child_process";var tM=2e3,rM=3e4;async function wT(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=o.endsWith(".lmctl")?o.slice(0,-6):null,a=i??o,c=r??s,l=e.teams.find(C=>C.name===a);if(l===void 0||!B(l)){if(i!==null)return{output:`terminal: "${o}" is not a known local team -- did you mean "${i}"?
665
+ (lctl takes a teamfile path; lmbee takes a team name)`,exitCode:1};let C=e.teams.filter(B).map(g=>g.name).sort();return{output:`terminal: "${o}" is not a known local team -- known local teams: ${C.length>0?C.join(", "):"(none configured)"}`,exitCode:1}}let u=c??l.leadAlias,d;try{d=Q(l)}catch(C){return{output:`terminal: could not resolve ${a}'s teamfile: ${C instanceof Error?C.message:String(C)}`,exitCode:1}}let m=n.pollIntervalMs??tM,f=n.leaseMs??6e4,p=n.maxWaitMs??rM,h=n.fetchReport??Ae,w=n.spawnSyncImpl??eM,_=n.sleep??(C=>new Promise(g=>setTimeout(g,C))),T=n.now??Date.now,E=n.reason??null,v=n.pid??process.pid,S=T();if(Fm(e.db.db,a,u,v,new Date(S).toISOString(),E,f)===null){let C=dc(e.db.db,a,u,S),g=C?`held by pid ${C.holderPid} since ${C.reservedAt}${C.reason?` (${C.reason})`:""}`:"held by another acquirer";return{output:`terminal: ${a}:${u} is already reserved -- ${g}`,exitCode:1}}let $=[`reserved ${a}:${u} -- no other automated dispatch (queue delivery, auto-scan, escalation) will claim it while this runs`],L=!1;try{for(;;){let C=await h();if(!Tm(d,u,C))break;if(T()-S>=p){L=!0;break}await _(m)}}finally{jm(e.db.db,a,u,v)}if(L)return $.push(`${a}:${u} is still busy after ${me(p)} -- reservation released, try again`),{output:$.join(`
666
+ `),exitCode:1};$.push(`${a}:${u} is available -- launching terminal now (reservation released)`);let R=w("lmctl",["terminal",d,u],{stdio:"inherit"}),H=R.status??(R.error?1:0);return{output:$.join(`
667
+ `),exitCode:H}}import{readFileSync as ST}from"node:fs";import{basename as aM}from"node:path";import{execFileSync as yT}from"node:child_process";import{dirname as nM}from"node:path";var oM=new Set(["done","closed","cancelled"]);function sM(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}function iM(e){return nM(e)}function ET(e,t,r=yT){let n=Ie(e,t);return TT(n,r)}function TT(e,t){let r={id:e.id,title:e.title,status:e.status};if(oM.has(sM(e.status)))return{...r,repoRoot:null,commits:[],checkError:"already terminal -- nothing to audit"};if(e.owner_team_path===null)return{...r,repoRoot:null,commits:[],checkError:"unowned -- no repo to check"};let n=iM(e.owner_team_path),o=`#${e.id}([^0-9]|$)`;try{let i=t("git",["-C",n,"log","--oneline","--date=short","--pretty=format:%h %ad %s","-i","-E",`--grep=${o}`,`--since=${e.created_at}`],{encoding:"utf8"}).split(`
668
+ `).filter(a=>a.trim().length>0).map(a=>{let[c,l,...u]=a.split(" ");return{hash:c??"",date:l??"",subject:u.join(" ")}});return{...r,repoRoot:n,commits:i,checkError:null}}catch(s){let i=s instanceof Error?s.message:String(s);return{...r,repoRoot:n,commits:[],checkError:`could not check ${n}: ${i}`}}}function bT(e,t,r=yT){let n=Ar(e,t),o=[],s=i=>{o.push(i);for(let a of i.children)s(a)};return s(n),o.map(i=>TT(i,r))}var kT=["unassigned","clear-parent","clear-owner","attention","clear-blocked-on"];function Pr(e,t,r,n){let o=e[t],s=e[r];if(o!==void 0&&s!==void 0)throw new I("INVALID_ARGUMENT",`--${t} and --${r} are mutually exclusive`);if(typeof o=="string")return o;if(typeof s=="string"){if(s==="-"){if(n.used)throw new I("INVALID_ARGUMENT","At most one input may read stdin");n.used=!0;try{return ST(0,"utf8")}catch(i){throw new I("INPUT_ERROR",`Cannot read UTF-8 input from stdin: ${i instanceof Error?i.message:String(i)}`)}}try{return ST(s,"utf8")}catch(i){throw new I("INPUT_ERROR",`Cannot read UTF-8 input from ${s}: ${i instanceof Error?i.message:String(i)}`)}}}function Yt(e,t,r={}){if(e===void 0)return;if(typeof e!="string"||!/^\d+$/.test(e))throw new I("INVALID_ARGUMENT",`${t} must be a nonnegative integer`);let n=Number(e),o=r.minimum??1;if(!Number.isSafeInteger(n)||n<o||r.maximum!==void 0&&n>r.maximum){let s=r.maximum!==void 0?`between ${o} and ${r.maximum}`:`>= ${o}`;throw new I("INVALID_ARGUMENT",`${t} must be an integer ${s}`)}return n}function zt(e,t){let r=Yt(e,t,{minimum:1});if(r===void 0)throw new I("INVALID_ARGUMENT",`${t} is required`);return r}function wa(e,t){let r=e[`${t}-team`],n=e[`${t}-alias`];if(!(r===void 0&&n===void 0)){if(r===void 0||n===void 0)throw new I("INVALID_ARGUMENT",`--${t}-team and --${t}-alias must both be given`);if(typeof r!="string"||typeof n!="string")throw new I("INVALID_ARGUMENT",`--${t}-team and --${t}-alias require values`);return{team:r,alias:n}}}function vT(e,t,r){let n=typeof e["blocked-on"]=="string"?e["blocked-on"]:void 0;if(n!==void 0&&n!=="operator"&&!t.some(o=>o.name===n))throw new I("INVALID_ARGUMENT",`--blocked-on "${n}" is not "operator" or a registered team name`);if(n!==void 0&&n!=="operator"&&r&&aM(r)===`${n}.lmctl`)throw new I("INVALID_ARGUMENT",`--blocked-on "${n}" is this task's own owner team -- a team cannot be blocked on itself`);return n}function AT(e){return e==="epic"||e==="task"||e==="subtask"}function Rt(e,t,r={}){return e?JSON.stringify({schema_version:1,ok:!0,data:t,meta:r}):lM(t,r)}function cM(e,t){return e?{output:JSON.stringify({schema_version:1,ok:!1,error:{code:t.code,message:t.message}}),exitCode:t.exitCode}:{output:`${t.code}: ${t.message}`,exitCode:t.exitCode}}function lM(e,t){let r;Array.isArray(e)?r=e.length===0?"(empty)":e.map(o=>o&&typeof o=="object"&&"title"in o?[..."attentionReason"in o?["attentionReason"]:[],"id","kind","status","project","title"].map(s=>String(o[s]??"")).join(" "):JSON.stringify(o)).join(`
669
669
  `):typeof e=="string"?r=e:r=JSON.stringify(e,null,2);let n=t.next_cursor;return n!=null?`${r}
670
- More records: --after ${String(n)}`:r}function nM(e){return e.length===0?"(no non-terminal tasks in scope)":e.map(r=>{if(r.checkError!==null)return`#${r.id} [${r.status}] ${r.title} -- ${r.checkError}`;if(r.commits.length===0)return`#${r.id} [${r.status}] ${r.title} -- no commits mention #${r.id} in ${r.repoRoot} since it was created`;let n=r.commits[0];return`#${r.id} [${r.status}] ${r.title} -- POSSIBLY DONE: ${r.commits.length} commit(s) mention #${r.id} in ${r.repoRoot} since creation, most recent ${n.hash} (${n.date}) ${n.subject}`}).join(`
671
- `)}var oM="usage: lmbee tasks create <epic|task|subtask> --title TEXT [--parent ID] [--project LABEL] [--status TEXT] [--blocked-on operator|TEAM] [--owner-team PATH --owner-alias ALIAS | --unassigned] (--blocked-on without --status implies --status blocked) | show ID | list [--project L] [--kind K] [--status S] [--parent ID] [--owner-team P --owner-alias A | --unassigned] [--limit N] [--after ID] | list --attention [--project L] | update ID [--title T] [--status S] [--parent ID | --clear-parent] [--owner-team P --owner-alias A | --clear-owner] [--if-revision N] [--blocked-on operator|TEAM | --clear-blocked-on] (--blocked-on without --status implies --status blocked) | tree ID | summary [ID] [--project L] | audit ID | audit --epic ID | note add ID --body T|--body-file P | note list ID | dep add|remove ID REQUIRED_ID | dep list ID [--direction D]";function bT(e,t,r,n,o=[]){try{let[s,...i]=t,a={used:!1};switch(s){case"create":{let c=i[0];if(c===void 0||!ET(c))throw new L("INVALID_ARGUMENT","create requires a kind: epic, task, or subtask");let l=r.title;if(typeof l!="string")throw new L("INVALID_ARGUMENT","--title is required");let u=ha(r,"owner"),d=yT(r,o,u?.team),m=typeof r.status=="string"?r.status:void 0,f=_f(e,{kind:c,title:l,parentId:Yt(r.parent,"--parent"),project:typeof r.project=="string"?r.project:void 0,status:m??(d!==void 0?"blocked":void 0),blockedOn:d,owner:u,unassigned:r.unassigned===!0,description:Pr(r,"description","description-file",a),requirements:Pr(r,"requirements","requirements-file",a),acceptanceCriteria:Pr(r,"acceptance-criteria","acceptance-criteria-file",a)});return{output:Rt(n,f),exitCode:0}}case"show":{let c=zt(i[0],"id");return{output:Rt(n,Sr(e,c)),exitCode:0}}case"tree":{let c=zt(i[0],"id");return{output:Rt(n,vr(e,c)),exitCode:0}}case"list":{if(r.attention===!0){let m=typeof r.project=="string"?r.project:void 0,f=Af(e,{project:m});return{output:Rt(n,f),exitCode:0}}let c=ha(r,"owner"),l=r.kind;if(l!==void 0&&(typeof l!="string"||!ET(l)))throw new L("INVALID_ARGUMENT","--kind must be epic, task, or subtask");let{rows:u,meta:d}=br(e,{project:typeof r.project=="string"?r.project:void 0,kind:typeof l=="string"?l:void 0,status:typeof r.status=="string"?r.status:void 0,parentId:Yt(r.parent,"--parent"),owner:c,unassigned:r.unassigned===!0,limit:Yt(r.limit,"--limit",{maximum:Ne})??100,after:Yt(r.after,"--after",{minimum:0})??0});return{output:Rt(n,u,d),exitCode:0}}case"audit":{let c=Yt(r.epic,"--epic"),l=i[0];if(c===void 0==(l===void 0))throw new L("INVALID_ARGUMENT","audit requires exactly one of: an id, or --epic ID");let u=c!==void 0?_T(e,c):[hT(e,zt(l,"id"))];return n?{output:JSON.stringify({schema_version:1,ok:!0,data:u}),exitCode:0}:{output:nM(u),exitCode:0}}case"summary":{let c=i[0]!==void 0?zt(i[0],"id"):void 0,l=typeof r.project=="string"?r.project:void 0;return{output:Rt(n,Ar(e,{id:c,project:l})),exitCode:0}}case"update":{let c=zt(i[0],"id"),l=ha(r,"owner"),u=Yt(r.parent,"--parent");if(u!==void 0&&r["clear-parent"]===!0)throw new L("INVALID_ARGUMENT","--parent and --clear-parent are exclusive");let d=l?.team??(r["clear-owner"]===!0?null:Le(e,c).owner_team_path),m=yT(r,o,d),f=typeof r.status=="string"?r.status:void 0,p=Ks(e,c,{title:typeof r.title=="string"?r.title:void 0,status:f??(m!==void 0?"blocked":void 0),parentId:u,clearParent:r["clear-parent"]===!0,owner:l,clearOwner:r["clear-owner"]===!0,ifRevision:Yt(r["if-revision"],"--if-revision"),description:Pr(r,"description","description-file",a),requirements:Pr(r,"requirements","requirements-file",a),acceptanceCriteria:Pr(r,"acceptance-criteria","acceptance-criteria-file",a),holdUntil:typeof r["hold-until"]=="string"?r["hold-until"]:void 0,holdReason:Pr(r,"hold-reason","hold-reason-file",a),clearHold:r["clear-hold"]===!0,blockedOn:m,clearBlockedOn:r["clear-blocked-on"]===!0});return{output:Rt(n,p),exitCode:0}}case"note":{let[c,...l]=i;if(c==="add"){let u=zt(l[0],"id"),d=Pr(r,"body","body-file",a);if(d===void 0)throw new L("INVALID_ARGUMENT","--body or --body-file is required");let m=ha(r,"author");return{output:Rt(n,Bt(e,u,{body:d,author:m})),exitCode:0}}if(c==="list"){let u=zt(l[0],"id"),{rows:d,meta:m}=Tc(e,u,{limit:Yt(r.limit,"--limit",{maximum:Ne})??100,after:Yt(r.after,"--after",{minimum:0})??0});return{output:Rt(n,d,m),exitCode:0}}throw new L("INVALID_ARGUMENT","note requires add or list")}case"dep":{let[c,...l]=i;if(c==="add"||c==="remove"){let u=zt(l[0],"id"),d=zt(l[1],"required_id"),m=c==="add"?Sf(e,u,d):vf(e,u,d);return{output:Rt(n,m),exitCode:0}}if(c==="list"){let u=zt(l[0],"id"),d=r.direction;if(d!==void 0&&d!=="outgoing"&&d!=="incoming"&&d!=="both")throw new L("INVALID_ARGUMENT","--direction must be outgoing, incoming, or both");return Le(e,u),{output:Rt(n,ct(e,u,d??"outgoing")),exitCode:0}}throw new L("INVALID_ARGUMENT","dep requires add, remove, or list")}default:return{output:oM,exitCode:n?2:1}}}catch(s){if(s instanceof L)return tM(n,s);throw s}}var mt=Ut(xt(),1);var sM=20;function iM(e,t,r={}){let n=Ns(e.teams,t),o=r.limit??sM,s=yu(e,{toId:t,limit:o}).rows,i=yu(e,{fromId:t,limit:o}).rows,a=null;if(n.kind==="local"&&n.repoPath!==void 0&&n.leadAlias!==void 0)try{let c=Q({name:n.key,repoPath:n.repoPath});a=xe(e.db.db,c,n.leadAlias)?.entities??[]}catch{a=null}return{team:{key:n.key,kind:n.kind},messagesTo:s,messagesFrom:i,ownedTasks:a,invocationHistoryCoverage:"unavailable"}}function ST(e,t,r={}){let n=iM(e,t,r);if(r.json)return JSON.stringify(n);let o=[];o.push(`Team: ${n.team.key} (${n.team.kind})`);let s=[],i=n.messagesTo.map(u=>[String(u.id),(0,mt.escapeCell)(u.from_id),(0,mt.escapeCell)(u.status),he(u.created_ts)]),a=n.messagesFrom.map(u=>[String(u.id),(0,mt.escapeCell)(u.to_id),(0,mt.escapeCell)(u.status),he(u.created_ts)]),c=(n.ownedTasks??[]).map(u=>[String(u.id),(0,mt.escapeCell)(u.kind),(0,mt.escapeCell)(u.status),(0,mt.escapeCell)(u.title)]);i.length>0&&s.push({rows:i,headers:["ID","FROM","STATUS","CREATED"]}),a.length>0&&s.push({rows:a,headers:["ID","TO","STATUS","CREATED"]}),c.length>0&&s.push({rows:c,headers:["ID","KIND","STATUS","TITLE"]});let l=(0,mt.measureColumns)(s);return o.push(`
670
+ More records: --after ${String(n)}`:r}function uM(e){return e.length===0?"(no non-terminal tasks in scope)":e.map(r=>{if(r.checkError!==null)return`#${r.id} [${r.status}] ${r.title} -- ${r.checkError}`;if(r.commits.length===0)return`#${r.id} [${r.status}] ${r.title} -- no commits mention #${r.id} in ${r.repoRoot} since it was created`;let n=r.commits[0];return`#${r.id} [${r.status}] ${r.title} -- POSSIBLY DONE: ${r.commits.length} commit(s) mention #${r.id} in ${r.repoRoot} since creation, most recent ${n.hash} (${n.date}) ${n.subject}`}).join(`
671
+ `)}var dM="usage: lmbee tasks create <epic|task|subtask> --title TEXT [--parent ID] [--project LABEL] [--status TEXT] [--blocked-on operator|TEAM] [--owner-team PATH --owner-alias ALIAS | --unassigned] (--blocked-on without --status implies --status blocked) | show ID | list [--project L] [--kind K] [--status S] [--parent ID] [--owner-team P --owner-alias A | --unassigned] [--limit N] [--after ID] | list --attention [--project L] | update ID [--title T] [--status S] [--parent ID | --clear-parent] [--owner-team P --owner-alias A | --clear-owner] [--if-revision N] [--blocked-on operator|TEAM | --clear-blocked-on] (--blocked-on without --status implies --status blocked) | tree ID | summary [ID] [--project L] | audit ID | audit --epic ID | note add ID --body T|--body-file P | note list ID | dep add|remove ID REQUIRED_ID | dep list ID [--direction D]";function $T(e,t,r,n,o=[]){try{let[s,...i]=t,a={used:!1};switch(s){case"create":{let c=i[0];if(c===void 0||!AT(c))throw new I("INVALID_ARGUMENT","create requires a kind: epic, task, or subtask");let l=r.title;if(typeof l!="string")throw new I("INVALID_ARGUMENT","--title is required");let u=wa(r,"owner"),d=vT(r,o,u?.team),m=typeof r.status=="string"?r.status:void 0,f=Ef(e,{kind:c,title:l,parentId:Yt(r.parent,"--parent"),project:typeof r.project=="string"?r.project:void 0,status:m??(d!==void 0?"blocked":void 0),blockedOn:d,owner:u,unassigned:r.unassigned===!0,description:Pr(r,"description","description-file",a),requirements:Pr(r,"requirements","requirements-file",a),acceptanceCriteria:Pr(r,"acceptance-criteria","acceptance-criteria-file",a)});return{output:Rt(n,f),exitCode:0}}case"show":{let c=zt(i[0],"id");return{output:Rt(n,vr(e,c)),exitCode:0}}case"tree":{let c=zt(i[0],"id");return{output:Rt(n,Ar(e,c)),exitCode:0}}case"list":{if(r.attention===!0){let m=typeof r.project=="string"?r.project:void 0,f=xf(e,{project:m});return{output:Rt(n,f),exitCode:0}}let c=wa(r,"owner"),l=r.kind;if(l!==void 0&&(typeof l!="string"||!AT(l)))throw new I("INVALID_ARGUMENT","--kind must be epic, task, or subtask");let{rows:u,meta:d}=Sr(e,{project:typeof r.project=="string"?r.project:void 0,kind:typeof l=="string"?l:void 0,status:typeof r.status=="string"?r.status:void 0,parentId:Yt(r.parent,"--parent"),owner:c,unassigned:r.unassigned===!0,limit:Yt(r.limit,"--limit",{maximum:Ne})??100,after:Yt(r.after,"--after",{minimum:0})??0});return{output:Rt(n,u,d),exitCode:0}}case"audit":{let c=Yt(r.epic,"--epic"),l=i[0];if(c===void 0==(l===void 0))throw new I("INVALID_ARGUMENT","audit requires exactly one of: an id, or --epic ID");let u=c!==void 0?bT(e,c):[ET(e,zt(l,"id"))];return n?{output:JSON.stringify({schema_version:1,ok:!0,data:u}),exitCode:0}:{output:uM(u),exitCode:0}}case"summary":{let c=i[0]!==void 0?zt(i[0],"id"):void 0,l=typeof r.project=="string"?r.project:void 0;return{output:Rt(n,kr(e,{id:c,project:l})),exitCode:0}}case"update":{let c=zt(i[0],"id"),l=wa(r,"owner"),u=Yt(r.parent,"--parent");if(u!==void 0&&r["clear-parent"]===!0)throw new I("INVALID_ARGUMENT","--parent and --clear-parent are exclusive");let d=l?.team??(r["clear-owner"]===!0?null:Ie(e,c).owner_team_path),m=vT(r,o,d),f=typeof r.status=="string"?r.status:void 0,p=Xs(e,c,{title:typeof r.title=="string"?r.title:void 0,status:f??(m!==void 0?"blocked":void 0),parentId:u,clearParent:r["clear-parent"]===!0,owner:l,clearOwner:r["clear-owner"]===!0,ifRevision:Yt(r["if-revision"],"--if-revision"),description:Pr(r,"description","description-file",a),requirements:Pr(r,"requirements","requirements-file",a),acceptanceCriteria:Pr(r,"acceptance-criteria","acceptance-criteria-file",a),holdUntil:typeof r["hold-until"]=="string"?r["hold-until"]:void 0,holdReason:Pr(r,"hold-reason","hold-reason-file",a),clearHold:r["clear-hold"]===!0,blockedOn:m,clearBlockedOn:r["clear-blocked-on"]===!0});return{output:Rt(n,p),exitCode:0}}case"note":{let[c,...l]=i;if(c==="add"){let u=zt(l[0],"id"),d=Pr(r,"body","body-file",a);if(d===void 0)throw new I("INVALID_ARGUMENT","--body or --body-file is required");let m=wa(r,"author");return{output:Rt(n,Bt(e,u,{body:d,author:m})),exitCode:0}}if(c==="list"){let u=zt(l[0],"id"),{rows:d,meta:m}=vc(e,u,{limit:Yt(r.limit,"--limit",{maximum:Ne})??100,after:Yt(r.after,"--after",{minimum:0})??0});return{output:Rt(n,d,m),exitCode:0}}throw new I("INVALID_ARGUMENT","note requires add or list")}case"dep":{let[c,...l]=i;if(c==="add"||c==="remove"){let u=zt(l[0],"id"),d=zt(l[1],"required_id"),m=c==="add"?kf(e,u,d):$f(e,u,d);return{output:Rt(n,m),exitCode:0}}if(c==="list"){let u=zt(l[0],"id"),d=r.direction;if(d!==void 0&&d!=="outgoing"&&d!=="incoming"&&d!=="both")throw new I("INVALID_ARGUMENT","--direction must be outgoing, incoming, or both");return Ie(e,u),{output:Rt(n,ct(e,u,d??"outgoing")),exitCode:0}}throw new I("INVALID_ARGUMENT","dep requires add, remove, or list")}default:return{output:dM,exitCode:n?2:1}}}catch(s){if(s instanceof I)return cM(n,s);throw s}}var mt=Ut(xt(),1);var mM=20;function fM(e,t,r={}){let n=Os(e.teams,t),o=r.limit??mM,s=bu(e,{toId:t,limit:o}).rows,i=bu(e,{fromId:t,limit:o}).rows,a=null;if(n.kind==="local"&&n.repoPath!==void 0&&n.leadAlias!==void 0)try{let c=Q({name:n.key,repoPath:n.repoPath});a=xe(e.db.db,c,n.leadAlias)?.entities??[]}catch{a=null}return{team:{key:n.key,kind:n.kind},messagesTo:s,messagesFrom:i,ownedTasks:a,invocationHistoryCoverage:"unavailable"}}function xT(e,t,r={}){let n=fM(e,t,r);if(r.json)return JSON.stringify(n);let o=[];o.push(`Team: ${n.team.key} (${n.team.kind})`);let s=[],i=n.messagesTo.map(u=>[String(u.id),(0,mt.escapeCell)(u.from_id),(0,mt.escapeCell)(u.status),he(u.created_ts)]),a=n.messagesFrom.map(u=>[String(u.id),(0,mt.escapeCell)(u.to_id),(0,mt.escapeCell)(u.status),he(u.created_ts)]),c=(n.ownedTasks??[]).map(u=>[String(u.id),(0,mt.escapeCell)(u.kind),(0,mt.escapeCell)(u.status),(0,mt.escapeCell)(u.title)]);i.length>0&&s.push({rows:i,headers:["ID","FROM","STATUS","CREATED"]}),a.length>0&&s.push({rows:a,headers:["ID","TO","STATUS","CREATED"]}),c.length>0&&s.push({rows:c,headers:["ID","KIND","STATUS","TITLE"]});let l=(0,mt.measureColumns)(s);return o.push(`
672
672
  Messages to this team (queue, newest first):
673
673
  ${i.length===0?"(none)":(0,mt.renderGrid)(i,{widths:l,headers:["ID","FROM","STATUS","CREATED"]})}`),o.push(`
674
674
  Messages from this team (queue, newest first):
@@ -676,9 +676,9 @@ ${a.length===0?"(none)":(0,mt.renderGrid)(a,{widths:l,headers:["ID","TO","STATUS
676
676
  Owned tasks (lmtasks):
677
677
  ${n.ownedTasks===null?"(unavailable -- not a local team with a resolvable teamfile)":c.length===0?"(none)":(0,mt.renderGrid)(c,{widths:l,headers:["ID","KIND","STATUS","TITLE"]})}`),o.push(`
678
678
  Provider/invocation/mail history: unavailable -- pending lctl-src's own increment-2 delivery (not silently omitted; this coverage state is explicit).`),o.join(`
679
- `)}import{mkdirSync as aM,readFileSync as cM,statSync as lM,writeFileSync as uM}from"node:fs";import{homedir as dM}from"node:os";import{basename as vT,dirname as AT,join as mM}from"node:path";function fM(){return mM(dM(),".lmbee","on-demand-teams.conf")}function $T(e,t,r,n={}){let o;try{o=lM(r)}catch{return{output:`error: teamfile not found: ${r}`,ok:!1}}if(!o.isFile())return{output:`error: teamfile must be a regular file, not a directory: ${r}`,ok:!1};if(vT(r)!==`${t}.lmctl`)return{output:`error: teamfile must be named "${t}.lmctl" to match team name "${t}" (got "${vT(r)}") -- resolveTeamfilePath's own convention, not a new rule`,ok:!1};let s=n.alias??"Lead",i=AT(r),a=n.confPath??fM(),c="";try{c=cM(a,"utf8")}catch{}let l=c.split(/\r?\n/).filter(w=>w.trim().length>0&&!w.trim().startsWith("#")),u=w=>w.split(/\t+/)[0]?.trim()===t,d=l.some(u),m=l.filter(w=>!u(w)),f=`${t} ${i} ${s} on-demand registered via "lmbee team register", ${new Date().toISOString().slice(0,10)}`,p=[...m,f].join(`
679
+ `)}import{mkdirSync as pM,readFileSync as hM,statSync as gM,writeFileSync as _M}from"node:fs";import{homedir as wM}from"node:os";import{basename as RT,dirname as NT,join as yM}from"node:path";function EM(){return yM(wM(),".lmbee","on-demand-teams.conf")}function LT(e,t,r,n={}){let o;try{o=gM(r)}catch{return{output:`error: teamfile not found: ${r}`,ok:!1}}if(!o.isFile())return{output:`error: teamfile must be a regular file, not a directory: ${r}`,ok:!1};if(RT(r)!==`${t}.lmctl`)return{output:`error: teamfile must be named "${t}.lmctl" to match team name "${t}" (got "${RT(r)}") -- resolveTeamfilePath's own convention, not a new rule`,ok:!1};let s=n.alias??"Lead",i=NT(r),a=n.confPath??EM(),c="";try{c=hM(a,"utf8")}catch{}let l=c.split(/\r?\n/).filter(w=>w.trim().length>0&&!w.trim().startsWith("#")),u=w=>w.split(/\t+/)[0]?.trim()===t,d=l.some(u),m=l.filter(w=>!u(w)),f=`${t} ${i} ${s} on-demand registered via "lmbee team register", ${new Date().toISOString().slice(0,10)}`,p=[...m,f].join(`
680
680
  `)+`
681
- `;return aM(AT(a),{recursive:!0}),uM(a,p),Is(e.db.db,a,"on-demand teams (lmbee team register)"),yo(p).some(w=>w.name===t)?{output:`team ${d?"re-registered":"registered"}: ${t} (teamfile ${r}, alias ${s}) -- addressable via enqueue/chat now, on-demand (no standing auto-nudge)`,ok:!0}:{output:`error: wrote ${a} but the team did not parse back out -- not registered`,ok:!1}}async function kT(e,t={}){let n=await(t.fetchReport??Ae)(),o=Os(e.db.db,e.teams.filter(H),n),s=o.active.length?o.active.join(","):"(none)";if(o.wake)return{text:`WATCH CHANGE [${o.why}] | now-active: ${s}`,changed:!0};let i=o.newlyActive.length?` (newly-active: ${o.newlyActive.join(",")})`:"";return{text:`WATCH nochange | active: ${s}${i}`,changed:!1}}var Ur=`usage: lmbee <command> [args]
681
+ `;return pM(NT(a),{recursive:!0}),_M(a,p),Ds(e.db.db,a,"on-demand teams (lmbee team register)"),To(p).some(w=>w.name===t)?{output:`team ${d?"re-registered":"registered"}: ${t} (teamfile ${r}, alias ${s}) -- addressable via enqueue/chat now, on-demand (no standing auto-nudge)`,ok:!0}:{output:`error: wrote ${a} but the team did not parse back out -- not registered`,ok:!1}}async function IT(e,t={}){let n=await(t.fetchReport??Ae)(),o=Us(e.db.db,e.teams.filter(B),n),s=o.active.length?o.active.join(","):"(none)";if(o.wake)return{text:`WATCH CHANGE [${o.why}] | now-active: ${s}`,changed:!0};let i=o.newlyActive.length?` (newly-active: ${o.newlyActive.join(",")})`:"";return{text:`WATCH nochange | active: ${s}${i}`,changed:!1}}var Ur=`usage: lmbee <command> [args]
682
682
 
683
683
  Core loop:
684
684
  lmbee run | once | watch
@@ -829,7 +829,7 @@ Daemon:
829
829
  [--remote-mail --remote-allow user_id1,user_id2,...]
830
830
  [--exec-worker [--exec-mailbox name] [--exec-admin id1,id2,...] [--exec-allow id1,id2,...] [--exec-allow-anonymous]]
831
831
  lmbee shutdown --force (graceful stop of the systemd-managed daemon: systemctl --user stop lmbee.service --
832
- --force is required; the unconfirmed default refuses rather than acting)`;function NT(e){if(e.length===0)return!0;let[t,r]=e;return t==="-h"||t==="--help"||t==="help"?!0:r==="-h"||r==="--help"}var pM=new Set(["status","oversee","history","teams","attention","stalled","in-flight"]);function IT(e){let[t,r]=e;return pM.has(t)?!0:t==="team"?r!=="register"&&e.includes("--timeline"):t==="state"?r==="list"||r==="get"||r==="active":t==="queue"?r==="list"||r==="get"||r==="inbox"||r==="stats"||r==="redeliver-check"||r==="pause-status"||r==="owed"||r==="close-answered"||r==="pull":t==="source"?r==="list":t==="mail"||t==="scan"||t==="auto-nudge-redirect"||t==="provider"?r==="status":t==="dispatch-status"?!0:t==="logical-name"?r==="get"||r==="list":t==="tasks"?r==="show"||r==="list"||r==="tree"||r==="summary"?!0:r==="note"||r==="dep"?e[2]==="list":!1:t==="cron"?r==="show"||r==="list"||r==="runs"||r==="run"||r==="export":t==="prompt"?r==="log"||r==="tasks"||r==="reassignments":!1}var xT=`usage: lmbee queue <command> [args]
832
+ --force is required; the unconfirmed default refuses rather than acting)`;function DT(e){if(e.length===0)return!0;let[t,r]=e;return t==="-h"||t==="--help"||t==="help"?!0:r==="-h"||r==="--help"}var TM=new Set(["status","oversee","history","teams","attention","stalled","in-flight"]);function MT(e){let[t,r]=e;return TM.has(t)?!0:t==="team"?r!=="register"&&e.includes("--timeline"):t==="state"?r==="list"||r==="get"||r==="active":t==="queue"?r==="list"||r==="get"||r==="inbox"||r==="stats"||r==="redeliver-check"||r==="pause-status"||r==="owed"||r==="close-answered"||r==="pull":t==="source"?r==="list":t==="mail"||t==="scan"||t==="auto-nudge-redirect"||t==="provider"?r==="status":t==="dispatch-status"?!0:t==="logical-name"?r==="get"||r==="list":t==="tasks"?r==="show"||r==="list"||r==="tree"||r==="summary"?!0:r==="note"||r==="dep"?e[2]==="list":!1:t==="cron"?r==="show"||r==="list"||r==="runs"||r==="run"||r==="export":t==="prompt"?r==="log"||r==="tasks"||r==="reassignments":!1}var CT=`usage: lmbee queue <command> [args]
833
833
 
834
834
  Read: inbox <to> [--prompts] prompts waiting for a team (authoritative)
835
835
  list [team] all rows, optionally filtered
@@ -855,109 +855,109 @@ Close: answer <id[,id,...]> <text|@file> --from <team>
855
855
  Control: pause <team> [--reason <text>] | resume <team> | pause-status [<team>]
856
856
  gc [days]
857
857
 
858
- Pass --help after any subcommand for its own usage line, e.g. "lmbee queue list --help".`,RT={list:{usage:"usage: lmbee queue list [team] [--json]",allowedFlags:["json"]},get:{usage:"usage: lmbee queue get <id> [--json]",allowedFlags:["json"]},deliver:{usage:"usage: lmbee queue deliver [team]",allowedFlags:[]},retrieve:{usage:"usage: lmbee queue retrieve <to> [--id <queueId>]",allowedFlags:["id"]},inbox:{usage:"usage: lmbee queue inbox <to> [--prompts] [--json]",allowedFlags:["prompts","json"]},gc:{usage:"usage: lmbee queue gc [days]",allowedFlags:[]},stats:{usage:"usage: lmbee queue stats [to] [--json]",allowedFlags:["json"]},state:{usage:"usage: lmbee queue state <id> [--json]",allowedFlags:["json"]},answer:{usage:"usage: lmbee queue answer <id[,id,...]> <text|@file> --from <team> [--amend] [--literal] [--json]",allowedFlags:["from","literal","amend","json"]},retract:{usage:"usage: lmbee queue retract <id> --from <team> --reason <text> [--no-notice] [--json]",allowedFlags:["from","reason","no-notice","json"]},resolve:{usage:"usage: lmbee queue resolve <id> --from <proxyTeam> --reason <text> [--amend] [--literal] [--json]",allowedFlags:["from","reason","literal","amend","json"]},pause:{usage:"usage: lmbee queue pause <team> [--reason <text>] [--json]",allowedFlags:["reason","json"]},resume:{usage:"usage: lmbee queue resume <team> [--json]",allowedFlags:["json"]},"pause-status":{usage:"usage: lmbee queue pause-status [team] [--json]",allowedFlags:["json"]},owed:{usage:"usage: lmbee queue owed <team> [--ids] [--json]",allowedFlags:["ids","json"]},pull:{usage:"usage: lmbee queue pull [id id ...] [--from <team>] [--all] [--open] [--mark [id,id,...]] [--json] [--full]",allowedFlags:["from","all","open","mark","json","full"]},"close-answered":{usage:"usage: lmbee queue close-answered <team> [--ids] [--json]",allowedFlags:["ids","json"]},"redeliver-check":{usage:"usage: lmbee queue redeliver-check <team> [--json]",allowedFlags:["json"]},redeliver:{usage:"usage: lmbee queue redeliver <id> --reason <text> [--json]",allowedFlags:["reason","json"]},doctor:{usage:"usage: lmbee queue doctor [toId] [--repair] [--swallowed] [--json]",allowedFlags:["repair","swallowed","json"]}};async function LT(e,t){if(t.length===0)return{output:`${Ur}
859
- `,exitCode:0};let[r,...n]=t,{positionals:o,flags:s}=wt(n,["live","json","timeline","stuck-processing-all","ids","prompts","literal","amend","help","no-notice"]),i=s.json===!0;if(s.help===!0&&r!=="queue")return{output:`${Ur}
860
- `,exitCode:0};switch(r){case"run":return{output:await cT(e),exitCode:0};case"once":return{output:await aT(e),exitCode:0};case"watch":{let a=await kT(e);return{output:a.text,exitCode:a.changed?10:0}}case"status":return{output:await uy(e,{live:s.live===!0,json:i}),exitCode:0};case"oversee":return{output:await iT(e,{only:o}),exitCode:0};case"state":{let[a,...c]=o;return a==="list"?{output:oy(e,{json:i,nonDone:s["non-done"]===!0}),exitCode:0}:a==="get"?c[0]===void 0?X("usage: lmbee state get <team>"):{output:sy(e,c[0],{json:i}),exitCode:0}:a==="set"?c[0]===void 0||c[1]===void 0?X("usage: lmbee state set <team> <status> [note]"):{output:iy(e,c[0],c[1],c.slice(2).join(" ")),exitCode:0}:a==="active"?{output:ly(e,{json:i}),exitCode:0}:a==="confirm-done"?c[0]===void 0?X("usage: lmbee state confirm-done <team> [note]"):{output:ay(e,c[0],c.slice(1).join(" ")||void 0),exitCode:0}:a==="reopen"?c[0]===void 0?X("usage: lmbee state reopen <team> [note]"):{output:await cy(e,c[0],c.slice(1).join(" ")||void 0),exitCode:0}:X("usage: lmbee state list | get <team> | set <team> <status> [note] | confirm-done <team> [note] | reopen <team> [note] | active")}case"enqueue":{let[a,...c]=o,l="usage: lmbee enqueue <team>[:<alias>] <prompt|@file> --from <operator|team-name> [--expects-response true|false] [--in-reply-to <id>] [--literal]";if(a===void 0||c.length===0)return X(l);let u=typeof s.from=="string"?s.from:void 0;if(u===void 0)return X(l);if(u==="autopilot")return X("enqueue: --from 'autopilot' is reserved for the tool's own automated enqueues");let d;if(s["expects-response"]!==void 0)if(s["expects-response"]==="true")d=!0;else if(s["expects-response"]==="false")d=!1;else return X(`enqueue: --expects-response must be "true" or "false"; ${l}`);let m;if(s["in-reply-to"]!==void 0){let f=Number(s["in-reply-to"]);if(typeof s["in-reply-to"]!="string"||!Number.isInteger(f)||f<=0)return X(`enqueue: --in-reply-to must be a positive integer queue id; ${l}`);m=f}return{output:await Cw(e,a,c.join(" "),{from:u,...d!==void 0?{expectsResponse:d}:{},...m!==void 0?{inReplyTo:m}:{},...s.literal===!0?{literal:!0}:{}}),exitCode:0}}case"prompt":{let a='usage: lmbee prompt <to> <prompt|@file> --from <id> [--new-task "title" [--task-description TEXT] | --task <id>] [--literal] | lmbee prompt log <task-id> [--json] | lmbee prompt tasks <team> [--json] | lmbee prompt reassign <prompt-id> --task <task-id> --by <id> | lmbee prompt reassignments <prompt-id> [--json]';if(o[0]==="tasks"){let p=o[1];return p===void 0?X(`prompt tasks: requires a team id; ${a}`):{output:OE(e,p,{json:s.json===!0}),exitCode:0}}if(o[0]==="log"){let p=o[1],h=p!==void 0?Number(p):NaN;return p===void 0||!Number.isInteger(h)||h<=0?X(`prompt log: requires a positive integer task id; ${a}`):{output:DE(e,h,{json:s.json===!0}),exitCode:0}}if(o[0]==="reassign"){let p=o[1],h=p!==void 0?Number(p):NaN;if(p===void 0||!Number.isInteger(h)||h<=0)return X(`prompt reassign: requires a positive integer prompt id; ${a}`);let w=typeof s.task=="string"?Number(s.task):NaN;if(typeof s.task!="string"||!Number.isInteger(w)||w<=0)return X(`prompt reassign: --task must be a positive integer task id; ${a}`);let _=typeof s.by=="string"?s.by:void 0;return _===void 0?X(`prompt reassign: --by is required; ${a}`):{output:ME(e,h,w,{by:_}),exitCode:0}}if(o[0]==="reassignments"){let p=o[1],h=p!==void 0?Number(p):NaN;return p===void 0||!Number.isInteger(h)||h<=0?X(`prompt reassignments: requires a positive integer prompt id; ${a}`):{output:PE(e,h,{json:s.json===!0}),exitCode:0}}let[c,...l]=o;if(c===void 0||l.length===0)return X(a);let u=typeof s.from=="string"?s.from:void 0;if(u===void 0)return X(a);let d=typeof s["new-task"]=="string"?s["new-task"]:void 0,m=typeof s["task-description"]=="string"?s["task-description"]:void 0,f;if(s.task!==void 0){let p=Number(s.task);if(typeof s.task!="string"||!Number.isInteger(p)||p<=0)return X(`prompt: --task must be a positive integer task id; ${a}`);f=p}return{output:CE(e,c,l.join(" "),{from:u,...d!==void 0?{newTaskTitle:d}:{},...m!==void 0?{newTaskDescription:m}:{},...f!==void 0?{taskId:f}:{},...s.literal===!0?{literal:!0}:{}}),exitCode:0}}case"queue":{let[a,...c]=o,l=a!==void 0?RT[a]:void 0;if(l!==void 0){if(s.help===!0)return{output:`${l.usage}
858
+ Pass --help after any subcommand for its own usage line, e.g. "lmbee queue list --help".`,OT={list:{usage:"usage: lmbee queue list [team] [--json]",allowedFlags:["json"]},get:{usage:"usage: lmbee queue get <id> [--json]",allowedFlags:["json"]},deliver:{usage:"usage: lmbee queue deliver [team]",allowedFlags:[]},retrieve:{usage:"usage: lmbee queue retrieve <to> [--id <queueId>]",allowedFlags:["id"]},inbox:{usage:"usage: lmbee queue inbox <to> [--prompts] [--json]",allowedFlags:["prompts","json"]},gc:{usage:"usage: lmbee queue gc [days]",allowedFlags:[]},stats:{usage:"usage: lmbee queue stats [to] [--json]",allowedFlags:["json"]},state:{usage:"usage: lmbee queue state <id> [--json]",allowedFlags:["json"]},answer:{usage:"usage: lmbee queue answer <id[,id,...]> <text|@file> --from <team> [--amend] [--literal] [--json]",allowedFlags:["from","literal","amend","json"]},retract:{usage:"usage: lmbee queue retract <id> --from <team> --reason <text> [--no-notice] [--json]",allowedFlags:["from","reason","no-notice","json"]},resolve:{usage:"usage: lmbee queue resolve <id> --from <proxyTeam> --reason <text> [--amend] [--literal] [--json]",allowedFlags:["from","reason","literal","amend","json"]},pause:{usage:"usage: lmbee queue pause <team> [--reason <text>] [--json]",allowedFlags:["reason","json"]},resume:{usage:"usage: lmbee queue resume <team> [--json]",allowedFlags:["json"]},"pause-status":{usage:"usage: lmbee queue pause-status [team] [--json]",allowedFlags:["json"]},owed:{usage:"usage: lmbee queue owed <team> [--ids] [--json]",allowedFlags:["ids","json"]},pull:{usage:"usage: lmbee queue pull [id id ...] [--from <team>] [--all] [--open] [--mark [id,id,...]] [--json] [--full]",allowedFlags:["from","all","open","mark","json","full"]},"close-answered":{usage:"usage: lmbee queue close-answered <team> [--ids] [--json]",allowedFlags:["ids","json"]},"redeliver-check":{usage:"usage: lmbee queue redeliver-check <team> [--json]",allowedFlags:["json"]},redeliver:{usage:"usage: lmbee queue redeliver <id> --reason <text> [--json]",allowedFlags:["reason","json"]},doctor:{usage:"usage: lmbee queue doctor [toId] [--repair] [--swallowed] [--json]",allowedFlags:["repair","swallowed","json"]}};async function PT(e,t){if(t.length===0)return{output:`${Ur}
859
+ `,exitCode:0};let[r,...n]=t,{positionals:o,flags:s}=yt(n,["live","json","timeline","stuck-processing-all","ids","prompts","literal","amend","help","no-notice"]),i=s.json===!0;if(s.help===!0&&r!=="queue")return{output:`${Ur}
860
+ `,exitCode:0};switch(r){case"run":return{output:await fT(e),exitCode:0};case"once":return{output:await mT(e),exitCode:0};case"watch":{let a=await IT(e);return{output:a.text,exitCode:a.changed?10:0}}case"status":return{output:await hy(e,{live:s.live===!0,json:i}),exitCode:0};case"oversee":return{output:await dT(e,{only:o}),exitCode:0};case"state":{let[a,...c]=o;return a==="list"?{output:ly(e,{json:i,nonDone:s["non-done"]===!0}),exitCode:0}:a==="get"?c[0]===void 0?X("usage: lmbee state get <team>"):{output:uy(e,c[0],{json:i}),exitCode:0}:a==="set"?c[0]===void 0||c[1]===void 0?X("usage: lmbee state set <team> <status> [note]"):{output:dy(e,c[0],c[1],c.slice(2).join(" ")),exitCode:0}:a==="active"?{output:py(e,{json:i}),exitCode:0}:a==="confirm-done"?c[0]===void 0?X("usage: lmbee state confirm-done <team> [note]"):{output:my(e,c[0],c.slice(1).join(" ")||void 0),exitCode:0}:a==="reopen"?c[0]===void 0?X("usage: lmbee state reopen <team> [note]"):{output:await fy(e,c[0],c.slice(1).join(" ")||void 0),exitCode:0}:X("usage: lmbee state list | get <team> | set <team> <status> [note] | confirm-done <team> [note] | reopen <team> [note] | active")}case"enqueue":{let[a,...c]=o,l="usage: lmbee enqueue <team>[:<alias>] <prompt|@file> --from <operator|team-name> [--expects-response true|false] [--in-reply-to <id>] [--literal]";if(a===void 0||c.length===0)return X(l);let u=typeof s.from=="string"?s.from:void 0;if(u===void 0)return X(l);if(u==="autopilot")return X("enqueue: --from 'autopilot' is reserved for the tool's own automated enqueues");let d;if(s["expects-response"]!==void 0)if(s["expects-response"]==="true")d=!0;else if(s["expects-response"]==="false")d=!1;else return X(`enqueue: --expects-response must be "true" or "false"; ${l}`);let m;if(s["in-reply-to"]!==void 0){let f=Number(s["in-reply-to"]);if(typeof s["in-reply-to"]!="string"||!Number.isInteger(f)||f<=0)return X(`enqueue: --in-reply-to must be a positive integer queue id; ${l}`);m=f}return{output:await Uw(e,a,c.join(" "),{from:u,...d!==void 0?{expectsResponse:d}:{},...m!==void 0?{inReplyTo:m}:{},...s.literal===!0?{literal:!0}:{}}),exitCode:0}}case"prompt":{let a='usage: lmbee prompt <to> <prompt|@file> --from <id> [--new-task "title" [--task-description TEXT] | --task <id>] [--literal] | lmbee prompt log <task-id> [--json] | lmbee prompt tasks <team> [--json] | lmbee prompt reassign <prompt-id> --task <task-id> --by <id> | lmbee prompt reassignments <prompt-id> [--json]';if(o[0]==="tasks"){let p=o[1];return p===void 0?X(`prompt tasks: requires a team id; ${a}`):{output:FE(e,p,{json:s.json===!0}),exitCode:0}}if(o[0]==="log"){let p=o[1],h=p!==void 0?Number(p):NaN;return p===void 0||!Number.isInteger(h)||h<=0?X(`prompt log: requires a positive integer task id; ${a}`):{output:qE(e,h,{json:s.json===!0}),exitCode:0}}if(o[0]==="reassign"){let p=o[1],h=p!==void 0?Number(p):NaN;if(p===void 0||!Number.isInteger(h)||h<=0)return X(`prompt reassign: requires a positive integer prompt id; ${a}`);let w=typeof s.task=="string"?Number(s.task):NaN;if(typeof s.task!="string"||!Number.isInteger(w)||w<=0)return X(`prompt reassign: --task must be a positive integer task id; ${a}`);let _=typeof s.by=="string"?s.by:void 0;return _===void 0?X(`prompt reassign: --by is required; ${a}`):{output:jE(e,h,w,{by:_}),exitCode:0}}if(o[0]==="reassignments"){let p=o[1],h=p!==void 0?Number(p):NaN;return p===void 0||!Number.isInteger(h)||h<=0?X(`prompt reassignments: requires a positive integer prompt id; ${a}`):{output:HE(e,h,{json:s.json===!0}),exitCode:0}}let[c,...l]=o;if(c===void 0||l.length===0)return X(a);let u=typeof s.from=="string"?s.from:void 0;if(u===void 0)return X(a);let d=typeof s["new-task"]=="string"?s["new-task"]:void 0,m=typeof s["task-description"]=="string"?s["task-description"]:void 0,f;if(s.task!==void 0){let p=Number(s.task);if(typeof s.task!="string"||!Number.isInteger(p)||p<=0)return X(`prompt: --task must be a positive integer task id; ${a}`);f=p}return{output:UE(e,c,l.join(" "),{from:u,...d!==void 0?{newTaskTitle:d}:{},...m!==void 0?{newTaskDescription:m}:{},...f!==void 0?{taskId:f}:{},...s.literal===!0?{literal:!0}:{}}),exitCode:0}}case"queue":{let[a,...c]=o,l=a!==void 0?OT[a]:void 0;if(l!==void 0){if(s.help===!0)return{output:`${l.usage}
861
861
  `,exitCode:0};let u=new Set(["help",...l.allowedFlags]),d=Object.keys(s).find(m=>!u.has(m));if(d!==void 0)return X(`queue ${a}: unknown flag --${d}
862
- ${l.usage}`)}if(a==="list")return{output:Ow(e,c[0],{json:i}),exitCode:0};if(a==="get")return c[0]===void 0?X("usage: lmbee queue get <id>"):{output:Dw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="deliver")return{output:await Vw(e,c[0]),exitCode:0};if(a==="retrieve"){if(c[0]===void 0)return X("usage: lmbee queue retrieve <to> [--id <queueId>]");let u=s.id;return u!==void 0&&(typeof u!="string"||!/^\d+$/.test(u)||!Number.isSafeInteger(Number(u))||Number(u)<=0)?X(`queue retrieve: --id must be a positive integer
863
- usage: lmbee queue retrieve <to> [--id <queueId>]`):{output:Jw(e,c[0],u===void 0?{}:{id:Number(u)}),exitCode:0}}if(a==="inbox")return c[0]===void 0?X("usage: lmbee queue inbox <to> [--prompts]"):{output:Kw(e,c[0],{json:i,promptsOnly:s.prompts===!0}),exitCode:0};if(a==="gc")return{output:Zw(e,c[0]!==void 0?Number(c[0]):void 0),exitCode:0};if(a==="stats")return{output:Xw(e,c[0],{json:i}),exitCode:0};if(a==="doctor")return{output:ey(e,c[0],{repair:s.repair===!0,swallowed:s.swallowed===!0,json:i}),exitCode:0};if(a==="state")return c[0]===void 0?X("usage: lmbee queue state <id>"):{output:Mw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="answer"){let[u,...d]=c,m="usage: lmbee queue answer <id[,id,...]> <text|@file> --from <team> [--amend] [--literal]";if(u===void 0||d.length===0)return X(m);let f=typeof s.from=="string"?s.from:void 0;if(f===void 0)return X(m);let p=s.literal===!0,h=s.amend===!0;if(u.includes(",")){if(h)return X(`queue answer: --amend does not support a comma-separated id list
864
- ${m}`);let w=u.split(",").map(Number);return Uw(e,w,f,d.join(" "),{json:i,literal:p})}return Pw(e,Number(u),f,d.join(" "),{json:i,literal:p,amend:h})}if(a==="retract"){let[u,...d]=c,m="usage: lmbee queue retract <id> --from <team> --reason <text> [--no-notice]";if(u===void 0)return X(m);let f=typeof s.from=="string"?s.from:void 0,h=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return f===void 0||h===void 0?X(m):qw(e,Number(u),f,h,{json:i,noNotice:s["no-notice"]===!0})}if(a==="resolve"){let[u,...d]=c,m="usage: lmbee queue resolve <id> --from <proxyTeam> --reason <text> [--amend] [--literal]";if(u===void 0)return X(m);let f=typeof s.from=="string"?s.from:void 0,h=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return f===void 0||h===void 0?X(m):Fw(e,Number(u),f,h,{json:i,literal:s.literal===!0,amend:s.amend===!0})}if(a==="pause"){if(c[0]===void 0)return X("usage: lmbee queue pause <team> [--reason <text>]");let u=typeof s.reason=="string"?s.reason:void 0;return Bw(e,c[0],u,{json:i})}if(a==="resume")return c[0]===void 0?X("usage: lmbee queue resume <team>"):Ww(e,c[0],{json:i});if(a==="pause-status")return Gw(e,c[0],{json:i});if(a==="owed")return c[0]===void 0?X("usage: lmbee queue owed <team> [--ids]"):{output:zw(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="pull"){let u=RT.pull.usage,d=typeof s.from=="string"?s.from:process.env.LMBEE_TEAM_NAME;if(d===void 0)return X(`queue pull: cannot infer the calling team -- pass --from <team> or set LMBEE_TEAM_NAME
862
+ ${l.usage}`)}if(a==="list")return{output:Fw(e,c[0],{json:i}),exitCode:0};if(a==="get")return c[0]===void 0?X("usage: lmbee queue get <id>"):{output:qw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="deliver")return{output:await Qw(e,c[0]),exitCode:0};if(a==="retrieve"){if(c[0]===void 0)return X("usage: lmbee queue retrieve <to> [--id <queueId>]");let u=s.id;return u!==void 0&&(typeof u!="string"||!/^\d+$/.test(u)||!Number.isSafeInteger(Number(u))||Number(u)<=0)?X(`queue retrieve: --id must be a positive integer
863
+ usage: lmbee queue retrieve <to> [--id <queueId>]`):{output:Xw(e,c[0],u===void 0?{}:{id:Number(u)}),exitCode:0}}if(a==="inbox")return c[0]===void 0?X("usage: lmbee queue inbox <to> [--prompts]"):{output:Zw(e,c[0],{json:i,promptsOnly:s.prompts===!0}),exitCode:0};if(a==="gc")return{output:oy(e,c[0]!==void 0?Number(c[0]):void 0),exitCode:0};if(a==="stats")return{output:ny(e,c[0],{json:i}),exitCode:0};if(a==="doctor")return{output:sy(e,c[0],{repair:s.repair===!0,swallowed:s.swallowed===!0,json:i}),exitCode:0};if(a==="state")return c[0]===void 0?X("usage: lmbee queue state <id>"):{output:jw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="answer"){let[u,...d]=c,m="usage: lmbee queue answer <id[,id,...]> <text|@file> --from <team> [--amend] [--literal]";if(u===void 0||d.length===0)return X(m);let f=typeof s.from=="string"?s.from:void 0;if(f===void 0)return X(m);let p=s.literal===!0,h=s.amend===!0;if(u.includes(",")){if(h)return X(`queue answer: --amend does not support a comma-separated id list
864
+ ${m}`);let w=u.split(",").map(Number);return Bw(e,w,f,d.join(" "),{json:i,literal:p})}return Hw(e,Number(u),f,d.join(" "),{json:i,literal:p,amend:h})}if(a==="retract"){let[u,...d]=c,m="usage: lmbee queue retract <id> --from <team> --reason <text> [--no-notice]";if(u===void 0)return X(m);let f=typeof s.from=="string"?s.from:void 0,h=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return f===void 0||h===void 0?X(m):Gw(e,Number(u),f,h,{json:i,noNotice:s["no-notice"]===!0})}if(a==="resolve"){let[u,...d]=c,m="usage: lmbee queue resolve <id> --from <proxyTeam> --reason <text> [--amend] [--literal]";if(u===void 0)return X(m);let f=typeof s.from=="string"?s.from:void 0,h=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return f===void 0||h===void 0?X(m):Ww(e,Number(u),f,h,{json:i,literal:s.literal===!0,amend:s.amend===!0})}if(a==="pause"){if(c[0]===void 0)return X("usage: lmbee queue pause <team> [--reason <text>]");let u=typeof s.reason=="string"?s.reason:void 0;return Kw(e,c[0],u,{json:i})}if(a==="resume")return c[0]===void 0?X("usage: lmbee queue resume <team>"):zw(e,c[0],{json:i});if(a==="pause-status")return Yw(e,c[0],{json:i});if(a==="owed")return c[0]===void 0?X("usage: lmbee queue owed <team> [--ids]"):{output:ey(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="pull"){let u=OT.pull.usage,d=typeof s.from=="string"?s.from:process.env.LMBEE_TEAM_NAME;if(d===void 0)return X(`queue pull: cannot infer the calling team -- pass --from <team> or set LMBEE_TEAM_NAME
865
865
  ${u}`);let m;if(c.length>0&&(m=c.map(Number),m.some(p=>!Number.isInteger(p)||p<=0)))return X(`queue pull: prompt ids must be positive integers
866
866
  ${u}`);let f;if(s.mark!==void 0)if(typeof s.mark!="string")f=!0;else{let p=s.mark.split(",").map(Number);if(p.some(h=>!Number.isInteger(h)||h<=0))return X(`queue pull: --mark ids must be a comma-separated list of positive integers
867
- ${u}`);f=p}return{output:Qw(e,d,{...m!==void 0?{ids:m}:{},all:s.all===!0,open:s.open===!0,...f!==void 0?{mark:f}:{},json:i,full:s.full===!0}),exitCode:0}}if(a==="close-answered")return c[0]===void 0?X("usage: lmbee queue close-answered <team> [--ids]"):{output:Yw(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="redeliver-check")return c[0]===void 0?X("usage: lmbee queue redeliver-check <team>"):jw(e,c[0],{json:i});if(a==="redeliver"){let[u,...d]=c,m="usage: lmbee queue redeliver <id> --reason <text>";if(u===void 0)return X(m);let p=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return p===void 0?X(m):Hw(e,Number(u),p,{json:i})}return s.help===!0?{output:`${xT}
868
- `,exitCode:0}:X(xT)}case"nudge":return o.length===0?X("usage: lmbee nudge <team> [team2 ...]"):{output:await RE(e,o),exitCode:0};case"send":{let[a,...c]=o;return a===void 0||c.length===0?X("usage: lmbee send <team> <prompt|@file> [--literal]"):{output:await mT(e,a,c.join(" "),{literal:s.literal===!0}),exitCode:0}}case"terminal":{let[a,c]=o;if(a===void 0)return X("usage: lmbee terminal <team>[:<alias>] [<alias>] [--reason <text>]");let l=typeof s.reason=="string"?s.reason:void 0;return fT(e,a,c,{reason:l})}case"history":{let a=o[0]!==void 0&&/^\d+$/.test(o[0]),c=a?void 0:o[0],l=a?o[0]:o[1];return{output:sw(e,c,l,{json:i}),exitCode:0}}case"teams":return{output:dy(e,{json:i}),exitCode:0};case"in-flight":{let a=typeof s.exclude=="string"?s.exclude:void 0;return{output:await YE(e,{...a!==void 0?{exclude:a}:{},json:i}),exitCode:0}}case"dispatch-status":{let[a]=o,c=typeof s.pid=="string"?Number.parseInt(s.pid,10):NaN;if(Number.isNaN(c))return X("usage: lmbee dispatch-status capture --pid N | check --pid N [--start-ticks T] --artifacts P1,P2,...");if(a==="capture")return{output:ZE(c,{json:i}),exitCode:0};if(a==="check"){let l=typeof s.artifacts=="string"?s.artifacts.split(",").map(d=>d.trim()).filter(d=>d.length>0):[],u=typeof s["start-ticks"]=="string"?s["start-ticks"]:void 0;return{output:eT(c,l,{...u!==void 0?{startTicks:u}:{},json:i}),exitCode:0}}return X("usage: lmbee dispatch-status capture --pid N | check --pid N [--start-ticks T] --artifacts P1,P2,...")}case"logical-name":{let[a,c]=o;if(a==="set"){let l=typeof s.teamfile=="string"?s.teamfile:void 0,u=typeof s.alias=="string"?s.alias:void 0;if(c===void 0||l===void 0||u===void 0)return X("usage: lmbee logical-name set <name> --teamfile PATH --alias ALIAS");try{return{output:tT(e,c,l,u,{json:i}),exitCode:0}}catch(d){return{output:d instanceof Error?d.message:String(d),exitCode:1}}}return a==="get"?c===void 0?X("usage: lmbee logical-name get <name>"):{output:rT(e,c,{json:i}),exitCode:0}:a==="list"?{output:nT(e,{json:i}),exitCode:0}:a==="clear"?c===void 0?X("usage: lmbee logical-name clear <name>"):{output:oT(e,c,{json:i}),exitCode:0}:X("usage: lmbee logical-name set <name> --teamfile PATH --alias ALIAS | get <name> | list | clear <name>")}case"attention":{let a=typeof s.team=="string"?s.team:void 0,c=typeof s.maintainer=="string"?s.maintainer:void 0,l=s["stuck-processing-all"]===!0,u=await Zi(e,{team:a,maintainer:c,stuckProcessingFleetWide:l});return{output:zo(u,{json:i}),exitCode:0}}case"stalled":{if(o.length>1)return X("usage: lmbee stalled [team] [--json]");let a=Zn(s["idle-threshold-ms"],"--idle-threshold-ms"),c=Zn(s["cooldown-ms"],"--cooldown-ms");if(a instanceof Error)return X(a.message);if(c instanceof Error)return X(c.message);let l=await bE(e,{team:o[0],config:{idleThresholdMs:a??pe.idleThresholdMs,cooldownMs:c??pe.cooldownMs}});return{output:i?JSON.stringify(l):l.teams.map(({team:u,stalled:d})=>`${u} ${d}`).join(`
869
- `),exitCode:0}}case"team":{if(o[0]==="register"){let l=o[1],u=typeof s.teamfile=="string"?s.teamfile:void 0;if(l===void 0||u===void 0)return X("usage: lmbee team register <name> --teamfile <path> [--alias <alias>]");let d=typeof s.alias=="string"?s.alias:void 0,m=$T(e,l,u,{alias:d});return{output:m.output,exitCode:m.ok?0:1}}let[a]=o;if(a===void 0||s.timeline!==!0)return X("usage: lmbee team <name> --timeline [--limit N] | lmbee team register <name> --teamfile <path> [--alias <alias>]");let c=Zn(s.limit,"--limit");return c instanceof Error?{output:`error: ${c.message}`,exitCode:1}:c!==void 0&&(c<1||c>bo)?{output:`error: --limit must be a positive integer <= ${bo}`,exitCode:1}:{output:ST(e,a,{limit:c,json:i}),exitCode:0}}case"source":{let[a,...c]=o;if(a==="add"){if(c[0]===void 0)return X("usage: lmbee source add <path> [label...]");let l=aa(e,c[0],c.slice(1).join(" ")||void 0);return{output:l.output,exitCode:l.ok?0:1}}return a==="list"?{output:ty(e,{json:i}),exitCode:0}:a==="remove"?c[0]===void 0?X("usage: lmbee source remove <path>"):{output:ry(e,c[0]),exitCode:0}:X("usage: lmbee source add <path> [label...] | list | remove <path>")}case"mail":{let[a]=o;return a==="status"?{output:aw(e,{json:i}),exitCode:0}:X("usage: lmbee mail status")}case"scan":{let[a]=o;if(a==="status")return{output:lT(e,{json:i}),exitCode:0};if(a==="pause"){let c=typeof s.actor=="string"?s.actor:void 0,l=typeof s.note=="string"?s.note:void 0,u=typeof s["resume-after"]=="string"?s["resume-after"]:void 0;return{output:uT(e,{...c!==void 0?{actor:c}:{},...l!==void 0?{note:l}:{},...u!==void 0?{resumeAfter:u}:{},json:i}),exitCode:0}}return a==="start"?{output:dT(e,{json:i}),exitCode:0}:X("usage: lmbee scan pause [--actor NAME] [--note TEXT] [--resume-after ISO] | start | status")}case"auto-nudge-redirect":{let[a,c]=o;if(a==="status")return{output:LE(e,c,{json:i}),exitCode:0};if(a==="clear")return c===void 0?X("usage: lmbee auto-nudge-redirect clear <team>"):{output:IE(e,c,{json:i}),exitCode:0};if(a==="set"){if(c===void 0||typeof s.companion!="string")return X("usage: lmbee auto-nudge-redirect set <team> --companion <team> [--worker-alias A] [--commit-threshold N] [--hours-threshold-ms N]");let l=typeof s["worker-alias"]=="string"?s["worker-alias"]:void 0,u=typeof s["commit-threshold"]=="string"?Number.parseInt(s["commit-threshold"],10):void 0,d=typeof s["hours-threshold-ms"]=="string"?Number.parseInt(s["hours-threshold-ms"],10):void 0;return{output:NE(e,c,{companionTeam:s.companion,...l!==void 0?{workerAlias:l}:{},...u!==void 0&&!Number.isNaN(u)?{commitThreshold:u}:{},...d!==void 0&&!Number.isNaN(d)?{hoursThresholdMs:d}:{},json:i}),exitCode:0}}return X("usage: lmbee auto-nudge-redirect set <team> --companion <team> [...] | clear <team> | status [<team>]")}case"provider":{let[a,c]=o;if(a==="status")return{output:qE(e,c,{json:i}),exitCode:0};if(a==="enable")return c===void 0?X("usage: lmbee provider enable <name>"):{output:FE(e,c,{json:i}),exitCode:0};if(a==="disable"){if(c===void 0)return X("usage: lmbee provider disable <name> [--reason TEXT] [--expires-at ISO]");let l=typeof s.reason=="string"?s.reason:void 0,u=typeof s["expires-at"]=="string"?s["expires-at"]:void 0;return{output:UE(e,c,{...l!==void 0?{reason:l}:{},...u!==void 0?{expiresAt:u}:{},json:i}),exitCode:0}}return X("usage: lmbee provider disable <name> [--reason TEXT] [--expires-at ISO] | enable <name> | status [<name>]")}case"rate-limit":{let[a]=o;if(a==="status")return{output:jE(e,{json:i}),exitCode:0};if(a==="log"){let c=typeof s.provider=="string"?s.provider:void 0,l=typeof s.limit=="string"?Number.parseInt(s.limit,10):void 0,u=l!==void 0&&!Number.isNaN(l)?l:void 0;return{output:HE(e,{...c!==void 0?{provider:c}:{},...u!==void 0?{limit:u}:{},json:i}),exitCode:0}}return X("usage: lmbee rate-limit status | log [--provider NAME] [--limit N]")}case"reliability-report":try{return{output:VE(e,{json:i}),exitCode:0}}catch(a){return{output:`reliability-report: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}case"subscriptions":{let a=typeof s.config=="string"?s.config:void 0;if(a===void 0)return X("usage: lmbee subscriptions --config <path> [--json]");try{return{output:await JE(a,{json:i}),exitCode:0}}catch(c){return{output:`subscriptions: ${c instanceof Error?c.message:String(c)}`,exitCode:1}}}case"tasks":{let a=wt(n,["json",...TT]),c=bT(e.db.db,a.positionals,a.flags,a.flags.json===!0||i,e.teams);return{output:c.output,exitCode:c.exitCode}}case"cron":{let a=wt(n,["json",...kE]),c=await $E(e.db.db,a.positionals,a.flags,a.flags.json===!0||i,e.teams);return{output:c.output,exitCode:c.exitCode}}default:return{output:`unknown command: ${r}
870
- ${Ur}`,exitCode:1}}}function X(e){return{output:e,exitCode:1}}import{mkdir as DU,readFile as MU,stat as PU,writeFile as UU}from"node:fs/promises";import{mkdir as kM,readFile as zT,stat as xM,writeFile as RM}from"node:fs/promises";import{readFileSync as NM}from"node:fs";import{homedir as IM}from"node:os";import{dirname as LM,extname as CM}from"node:path";var XT="https://lmctl.ai/tools/lmchat";async function ZT(e,t={}){let r=VM(t),n=Ju(e);if(n.kind==="whoami"){r.stdout(GM(r.env,n.api));return}if(n.kind==="login"){let{runLogin:s}=await Promise.resolve().then(()=>(KT(),JT));if(await s({io:{stdout:{write:a=>r.stdout(a.replace(/\n$/,""))},stderr:{write:a=>r.stderr(a.replace(/\n$/,""))}},env:r.env})!==0)throw new Qt("login failed");return}let o=HM(n.api,r.env);if(n.kind==="register-room"){await Fr(r.fetch,`${o}/rooms`,{method:"POST",headers:{...mr(r.env),"content-type":"application/json"},body:JSON.stringify({room_name:n.roomName})}),r.stdout(`created ${n.roomName}`);return}if(n.kind==="rooms"){let s=await Fr(r.fetch,`${o}/rooms`,{method:"GET",headers:mr(r.env)});if(n.json)r.stdout(JSON.stringify(s.rooms));else{r.stdout("room next_seq created_at");for(let i of s.rooms)r.stdout(`${i.room_name} ${i.next_seq} ${i.created_at}`)}return}if(n.kind==="read"&&await YT(r,o,n),n.kind==="post"){let s=await OM(r,o,n);r.stdout(String(s));return}if(n.kind==="say"){let s=await DM(r,o,n);r.stdout(String(s));return}if(n.kind==="list"){await YT(r,o,{...n,kind:"read"});return}if(n.kind==="get"){await PM(r,o,n),r.stdout(`saved ${n.out}`);return}if(n.kind==="delete"){let s=await UM(r,o,n);r.stdout(`deleted ${s}`);return}if(n.kind==="delete-room"){let s=await FM(r,o,n);r.stdout(`deleted room ${s}`);return}}function Ju(e){let t=[...e],r=De(t,"--api"),n=t.shift();if(!n||n==="help"||n==="--help"||n==="-h")throw new Qt(QT());if(n==="whoami"){let o=De(t,"--api")??r;return It(t),{kind:"whoami",...o?{api:o}:{}}}if(n==="login"){let o=De(t,"--api")??r;return It(t),{kind:"login",...o?{api:o}:{}}}if(n==="rooms"){let o=De(t,"--api")??r,s=_a(t,"--json");return It(t),{kind:"rooms",...s?{json:!0}:{},...o?{api:o}:{}}}if(n==="read"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--after"),a=De(t,"--limit"),c=De(t,"--interval"),l=_a(t,"--follow"),u=_a(t,"--json");return It(t),{kind:"read",roomName:s,...i!==void 0?{after:i}:{},...a!==void 0?{limit:a}:{},...c!==void 0?{interval:c}:{},...l?{follow:!0}:{},...u?{json:!0}:{},...o?{api:o}:{}}}if(n==="register-room"||n==="create"){let o=De(t,"--api")??r,s=Nt(t,"room_name");return It(t),{kind:"register-room",roomName:s,...o?{api:o}:{}}}if(n==="post"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Gu(t,"--name"),a=Gu(t,"--file"),c=De(t,"--content-type");return It(t),{kind:"post",roomName:s,name:i,file:a,...c?{contentType:c}:{},...o?{api:o}:{}}}if(n==="say"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--title"),a=Nt(t,"text");return It(t),{kind:"say",roomName:s,text:a,...i?{title:i}:{},...o?{api:o}:{}}}if(n==="list"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--after"),a=De(t,"--limit"),c=_a(t,"--json");return It(t),{kind:"list",roomName:s,...i!==void 0?{after:i}:{},...a!==void 0?{limit:a}:{},...c?{json:!0}:{},...o?{api:o}:{}}}if(n==="get"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Nt(t,"seq"),a=Gu(t,"--out");return It(t),{kind:"get",roomName:s,seq:i,out:a,...o?{api:o}:{}}}if(n==="delete"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Nt(t,"seq");return It(t),{kind:"delete",roomName:s,seq:i,...o?{api:o}:{}}}if(n==="delete-room"){let o=De(t,"--api")??r,s=Nt(t,"room_name");return It(t),{kind:"delete-room",roomName:s,...o?{api:o}:{}}}throw new Qt(`unknown command: ${n}
867
+ ${u}`);f=p}return{output:ry(e,d,{...m!==void 0?{ids:m}:{},all:s.all===!0,open:s.open===!0,...f!==void 0?{mark:f}:{},json:i,full:s.full===!0}),exitCode:0}}if(a==="close-answered")return c[0]===void 0?X("usage: lmbee queue close-answered <team> [--ids]"):{output:ty(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="redeliver-check")return c[0]===void 0?X("usage: lmbee queue redeliver-check <team>"):Vw(e,c[0],{json:i});if(a==="redeliver"){let[u,...d]=c,m="usage: lmbee queue redeliver <id> --reason <text>";if(u===void 0)return X(m);let p=(typeof s.reason=="string"?s.reason:void 0)??(d.length>0?d.join(" "):void 0);return p===void 0?X(m):Jw(e,Number(u),p,{json:i})}return s.help===!0?{output:`${CT}
868
+ `,exitCode:0}:X(CT)}case"nudge":return o.length===0?X("usage: lmbee nudge <team> [team2 ...]"):{output:await OE(e,o),exitCode:0};case"send":{let[a,...c]=o;return a===void 0||c.length===0?X("usage: lmbee send <team> <prompt|@file> [--literal]"):{output:await _T(e,a,c.join(" "),{literal:s.literal===!0}),exitCode:0}}case"terminal":{let[a,c]=o;if(a===void 0)return X("usage: lmbee terminal <team>[:<alias>] [<alias>] [--reason <text>]");let l=typeof s.reason=="string"?s.reason:void 0;return wT(e,a,c,{reason:l})}case"history":{let a=o[0]!==void 0&&/^\d+$/.test(o[0]),c=a?void 0:o[0],l=a?o[0]:o[1];return{output:uw(e,c,l,{json:i}),exitCode:0}}case"teams":return{output:gy(e,{json:i}),exitCode:0};case"in-flight":{let a=typeof s.exclude=="string"?s.exclude:void 0;return{output:await tT(e,{...a!==void 0?{exclude:a}:{},json:i}),exitCode:0}}case"dispatch-status":{let[a]=o,c=typeof s.pid=="string"?Number.parseInt(s.pid,10):NaN;if(Number.isNaN(c))return X("usage: lmbee dispatch-status capture --pid N | check --pid N [--start-ticks T] --artifacts P1,P2,...");if(a==="capture")return{output:oT(c,{json:i}),exitCode:0};if(a==="check"){let l=typeof s.artifacts=="string"?s.artifacts.split(",").map(d=>d.trim()).filter(d=>d.length>0):[],u=typeof s["start-ticks"]=="string"?s["start-ticks"]:void 0;return{output:sT(c,l,{...u!==void 0?{startTicks:u}:{},json:i}),exitCode:0}}return X("usage: lmbee dispatch-status capture --pid N | check --pid N [--start-ticks T] --artifacts P1,P2,...")}case"logical-name":{let[a,c]=o;if(a==="set"){let l=typeof s.teamfile=="string"?s.teamfile:void 0,u=typeof s.alias=="string"?s.alias:void 0;if(c===void 0||l===void 0||u===void 0)return X("usage: lmbee logical-name set <name> --teamfile PATH --alias ALIAS");try{return{output:iT(e,c,l,u,{json:i}),exitCode:0}}catch(d){return{output:d instanceof Error?d.message:String(d),exitCode:1}}}return a==="get"?c===void 0?X("usage: lmbee logical-name get <name>"):{output:aT(e,c,{json:i}),exitCode:0}:a==="list"?{output:cT(e,{json:i}),exitCode:0}:a==="clear"?c===void 0?X("usage: lmbee logical-name clear <name>"):{output:lT(e,c,{json:i}),exitCode:0}:X("usage: lmbee logical-name set <name> --teamfile PATH --alias ALIAS | get <name> | list | clear <name>")}case"attention":{let a=typeof s.team=="string"?s.team:void 0,c=typeof s.maintainer=="string"?s.maintainer:void 0,l=s["stuck-processing-all"]===!0,u=await ra(e,{team:a,maintainer:c,stuckProcessingFleetWide:l});return{output:Zo(u,{json:i}),exitCode:0}}case"stalled":{if(o.length>1)return X("usage: lmbee stalled [team] [--json]");let a=to(s["idle-threshold-ms"],"--idle-threshold-ms"),c=to(s["cooldown-ms"],"--cooldown-ms");if(a instanceof Error)return X(a.message);if(c instanceof Error)return X(c.message);let l=await $E(e,{team:o[0],config:{idleThresholdMs:a??pe.idleThresholdMs,cooldownMs:c??pe.cooldownMs}});return{output:i?JSON.stringify(l):l.teams.map(({team:u,stalled:d})=>`${u} ${d}`).join(`
869
+ `),exitCode:0}}case"team":{if(o[0]==="register"){let l=o[1],u=typeof s.teamfile=="string"?s.teamfile:void 0;if(l===void 0||u===void 0)return X("usage: lmbee team register <name> --teamfile <path> [--alias <alias>]");let d=typeof s.alias=="string"?s.alias:void 0,m=LT(e,l,u,{alias:d});return{output:m.output,exitCode:m.ok?0:1}}let[a]=o;if(a===void 0||s.timeline!==!0)return X("usage: lmbee team <name> --timeline [--limit N] | lmbee team register <name> --teamfile <path> [--alias <alias>]");let c=to(s.limit,"--limit");return c instanceof Error?{output:`error: ${c.message}`,exitCode:1}:c!==void 0&&(c<1||c>vo)?{output:`error: --limit must be a positive integer <= ${vo}`,exitCode:1}:{output:xT(e,a,{limit:c,json:i}),exitCode:0}}case"source":{let[a,...c]=o;if(a==="add"){if(c[0]===void 0)return X("usage: lmbee source add <path> [label...]");let l=ua(e,c[0],c.slice(1).join(" ")||void 0);return{output:l.output,exitCode:l.ok?0:1}}return a==="list"?{output:iy(e,{json:i}),exitCode:0}:a==="remove"?c[0]===void 0?X("usage: lmbee source remove <path>"):{output:ay(e,c[0]),exitCode:0}:X("usage: lmbee source add <path> [label...] | list | remove <path>")}case"mail":{let[a]=o;return a==="status"?{output:mw(e,{json:i}),exitCode:0}:X("usage: lmbee mail status")}case"scan":{let[a]=o;if(a==="status")return{output:pT(e,{json:i}),exitCode:0};if(a==="pause"){let c=typeof s.actor=="string"?s.actor:void 0,l=typeof s.note=="string"?s.note:void 0,u=typeof s["resume-after"]=="string"?s["resume-after"]:void 0;return{output:hT(e,{...c!==void 0?{actor:c}:{},...l!==void 0?{note:l}:{},...u!==void 0?{resumeAfter:u}:{},json:i}),exitCode:0}}return a==="start"?{output:gT(e,{json:i}),exitCode:0}:X("usage: lmbee scan pause [--actor NAME] [--note TEXT] [--resume-after ISO] | start | status")}case"auto-nudge-redirect":{let[a,c]=o;if(a==="status")return{output:PE(e,c,{json:i}),exitCode:0};if(a==="clear")return c===void 0?X("usage: lmbee auto-nudge-redirect clear <team>"):{output:ME(e,c,{json:i}),exitCode:0};if(a==="set"){if(c===void 0||typeof s.companion!="string")return X("usage: lmbee auto-nudge-redirect set <team> --companion <team> [--worker-alias A] [--commit-threshold N] [--hours-threshold-ms N]");let l=typeof s["worker-alias"]=="string"?s["worker-alias"]:void 0,u=typeof s["commit-threshold"]=="string"?Number.parseInt(s["commit-threshold"],10):void 0,d=typeof s["hours-threshold-ms"]=="string"?Number.parseInt(s["hours-threshold-ms"],10):void 0;return{output:DE(e,c,{companionTeam:s.companion,...l!==void 0?{workerAlias:l}:{},...u!==void 0&&!Number.isNaN(u)?{commitThreshold:u}:{},...d!==void 0&&!Number.isNaN(d)?{hoursThresholdMs:d}:{},json:i}),exitCode:0}}return X("usage: lmbee auto-nudge-redirect set <team> --companion <team> [...] | clear <team> | status [<team>]")}case"provider":{let[a,c]=o;if(a==="status")return{output:GE(e,c,{json:i}),exitCode:0};if(a==="enable")return c===void 0?X("usage: lmbee provider enable <name>"):{output:WE(e,c,{json:i}),exitCode:0};if(a==="disable"){if(c===void 0)return X("usage: lmbee provider disable <name> [--reason TEXT] [--expires-at ISO]");let l=typeof s.reason=="string"?s.reason:void 0,u=typeof s["expires-at"]=="string"?s["expires-at"]:void 0;return{output:BE(e,c,{...l!==void 0?{reason:l}:{},...u!==void 0?{expiresAt:u}:{},json:i}),exitCode:0}}return X("usage: lmbee provider disable <name> [--reason TEXT] [--expires-at ISO] | enable <name> | status [<name>]")}case"rate-limit":{let[a]=o;if(a==="status")return{output:VE(e,{json:i}),exitCode:0};if(a==="log"){let c=typeof s.provider=="string"?s.provider:void 0,l=typeof s.limit=="string"?Number.parseInt(s.limit,10):void 0,u=l!==void 0&&!Number.isNaN(l)?l:void 0;return{output:JE(e,{...c!==void 0?{provider:c}:{},...u!==void 0?{limit:u}:{},json:i}),exitCode:0}}return X("usage: lmbee rate-limit status | log [--provider NAME] [--limit N]")}case"reliability-report":try{return{output:QE(e,{json:i}),exitCode:0}}catch(a){return{output:`reliability-report: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}case"subscriptions":{let a=typeof s.config=="string"?s.config:void 0;if(a===void 0)return X("usage: lmbee subscriptions --config <path> [--json]");try{return{output:await XE(a,{json:i}),exitCode:0}}catch(c){return{output:`subscriptions: ${c instanceof Error?c.message:String(c)}`,exitCode:1}}}case"tasks":{let a=yt(n,["json",...kT]),c=$T(e.db.db,a.positionals,a.flags,a.flags.json===!0||i,e.teams);return{output:c.output,exitCode:c.exitCode}}case"cron":{let a=yt(n,["json",...IE]),c=await LE(e.db.db,a.positionals,a.flags,a.flags.json===!0||i,e.teams);return{output:c.output,exitCode:c.exitCode}}default:return{output:`unknown command: ${r}
870
+ ${Ur}`,exitCode:1}}}function X(e){return{output:e,exitCode:1}}import{mkdir as HU,readFile as BU,stat as WU,writeFile as GU}from"node:fs/promises";import{mkdir as OM,readFile as eb,stat as DM,writeFile as MM}from"node:fs/promises";import{readFileSync as PM}from"node:fs";import{homedir as UM}from"node:os";import{dirname as FM,extname as qM}from"node:path";var nb="https://lmctl.ai/tools/lmchat";async function ob(e,t={}){let r=ZM(t),n=Yu(e);if(n.kind==="whoami"){r.stdout(XM(r.env,n.api));return}if(n.kind==="login"){let{runLogin:s}=await Promise.resolve().then(()=>(ZT(),XT));if(await s({io:{stdout:{write:a=>r.stdout(a.replace(/\n$/,""))},stderr:{write:a=>r.stderr(a.replace(/\n$/,""))}},env:r.env})!==0)throw new Qt("login failed");return}let o=zM(n.api,r.env);if(n.kind==="register-room"){await Fr(r.fetch,`${o}/rooms`,{method:"POST",headers:{...fr(r.env),"content-type":"application/json"},body:JSON.stringify({room_name:n.roomName})}),r.stdout(`created ${n.roomName}`);return}if(n.kind==="rooms"){let s=await Fr(r.fetch,`${o}/rooms`,{method:"GET",headers:fr(r.env)});if(n.json)r.stdout(JSON.stringify(s.rooms));else{r.stdout("room next_seq created_at");for(let i of s.rooms)r.stdout(`${i.room_name} ${i.next_seq} ${i.created_at}`)}return}if(n.kind==="read"&&await tb(r,o,n),n.kind==="post"){let s=await jM(r,o,n);r.stdout(String(s));return}if(n.kind==="say"){let s=await HM(r,o,n);r.stdout(String(s));return}if(n.kind==="list"){await tb(r,o,{...n,kind:"read"});return}if(n.kind==="get"){await WM(r,o,n),r.stdout(`saved ${n.out}`);return}if(n.kind==="delete"){let s=await GM(r,o,n);r.stdout(`deleted ${s}`);return}if(n.kind==="delete-room"){let s=await VM(r,o,n);r.stdout(`deleted room ${s}`);return}}function Yu(e){let t=[...e],r=De(t,"--api"),n=t.shift();if(!n||n==="help"||n==="--help"||n==="-h")throw new Qt(rb());if(n==="whoami"){let o=De(t,"--api")??r;return Lt(t),{kind:"whoami",...o?{api:o}:{}}}if(n==="login"){let o=De(t,"--api")??r;return Lt(t),{kind:"login",...o?{api:o}:{}}}if(n==="rooms"){let o=De(t,"--api")??r,s=Ea(t,"--json");return Lt(t),{kind:"rooms",...s?{json:!0}:{},...o?{api:o}:{}}}if(n==="read"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--after"),a=De(t,"--limit"),c=De(t,"--interval"),l=Ea(t,"--follow"),u=Ea(t,"--json");return Lt(t),{kind:"read",roomName:s,...i!==void 0?{after:i}:{},...a!==void 0?{limit:a}:{},...c!==void 0?{interval:c}:{},...l?{follow:!0}:{},...u?{json:!0}:{},...o?{api:o}:{}}}if(n==="register-room"||n==="create"){let o=De(t,"--api")??r,s=Nt(t,"room_name");return Lt(t),{kind:"register-room",roomName:s,...o?{api:o}:{}}}if(n==="post"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Ku(t,"--name"),a=Ku(t,"--file"),c=De(t,"--content-type");return Lt(t),{kind:"post",roomName:s,name:i,file:a,...c?{contentType:c}:{},...o?{api:o}:{}}}if(n==="say"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--title"),a=Nt(t,"text");return Lt(t),{kind:"say",roomName:s,text:a,...i?{title:i}:{},...o?{api:o}:{}}}if(n==="list"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=De(t,"--after"),a=De(t,"--limit"),c=Ea(t,"--json");return Lt(t),{kind:"list",roomName:s,...i!==void 0?{after:i}:{},...a!==void 0?{limit:a}:{},...c?{json:!0}:{},...o?{api:o}:{}}}if(n==="get"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Nt(t,"seq"),a=Ku(t,"--out");return Lt(t),{kind:"get",roomName:s,seq:i,out:a,...o?{api:o}:{}}}if(n==="delete"){let o=De(t,"--api")??r,s=Nt(t,"room_name"),i=Nt(t,"seq");return Lt(t),{kind:"delete",roomName:s,seq:i,...o?{api:o}:{}}}if(n==="delete-room"){let o=De(t,"--api")??r,s=Nt(t,"room_name");return Lt(t),{kind:"delete-room",roomName:s,...o?{api:o}:{}}}throw new Qt(`unknown command: ${n}
871
871
 
872
- ${QT()}`)}async function OM(e,t,r){let n=await e.stat(r.file);if(!n.isFile())throw new Error(`not a file: ${r.file}`);let o=r.contentType??WM(r.name),s=await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files`,{method:"POST",headers:{...mr(e.env),"content-type":"application/json"},body:JSON.stringify({name:r.name,content_type:o,size:n.size})}),i=await e.readFile(r.file),a=typeof i=="string"?Buffer.from(i):i,c=new FormData;for(let[d,m]of Object.entries(s.fields))c.append(d,m);c.append("file",new Blob([a],{type:s.content_type}),s.name);let l=await e.fetch(s.upload_url,{method:"POST",body:c});if(!l.ok)throw new Error(`S3 upload failed: ${l.status} ${await l.text().catch(()=>"")}`.trim());return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(String(s.seq))}/commit`,{method:"POST",headers:{...mr(e.env),"content-type":"application/json"},body:JSON.stringify({name:s.name})})).seq}async function DM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/messages`,{method:"POST",headers:{...mr(e.env),"content-type":"application/json"},body:JSON.stringify({text:r.text,...r.title?{title:r.title}:{}})})).seq}async function YT(e,t,r){let n=r.after,o=Number(r.interval??"5");if(!Number.isFinite(o)||o<1)throw new Qt(`--interval must be a finite number >= 1 seconds (got "${r.interval}")`);let s=o*1e3,i=!1,a=[];for(;;){let c=await MM(e,t,r.roomName,n,r.limit);r.follow?r.json?c.files.length>0&&e.stdout(JSON.stringify(c.files)):(i||(tb(e.stdout),i=!0),rb(e.stdout,c.files)):a.push(...c.files);let l=typeof c.next_after=="number"?String(c.next_after):n,u=l!==void 0&&l!==n;if(u&&(n=l),!c.has_more||!u){if(!r.follow){r.json?e.stdout(JSON.stringify(a)):BM(e.stdout,a);return}await qM(s)}}}async function MM(e,t,r,n,o){let s=new URLSearchParams;n!==void 0&&s.set("after",n),o!==void 0&&s.set("limit",o);let i=s.toString();return Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r)}/files${i?`?${i}`:""}`,{method:"GET",headers:mr(e.env)})}async function PM(e,t,r){let n=await e.fetch(`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(r.seq)}`,{method:"GET",headers:mr(e.env),redirect:"manual"});if(n.status!==302)throw await Vu(n,"download request failed"),new Error(`download request did not return a redirect: ${n.status}`);let o=n.headers.get("location");if(!o)throw new Error("download redirect missing Location header");let s=await e.fetch(o,{method:"GET"});await Vu(s,"presigned download failed");let i=new Uint8Array(await s.arrayBuffer());await e.mkdir(LM(r.out),{recursive:!0}),await e.writeFile(r.out,i)}async function UM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(r.seq)}`,{method:"DELETE",headers:mr(e.env)})).seq}async function FM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}`,{method:"DELETE",headers:mr(e.env)})).room_name}function qM(e){return new Promise(t=>setTimeout(t,e))}async function Fr(e,t,r){let n=await e(t,r);return await Vu(n,"API request failed"),await n.json()}async function Vu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function jM(e){return eb(e).appkey}function eb(e){if(wa(e.LMCTL_APPKEY))return{appkey:e.LMCTL_APPKEY,source:"LMCTL_APPKEY"};let t=e.LMCTL_APPKEY_FILE?.trim();if(t){let s=Wu(t);if(s)return{appkey:s,source:"LMCTL_APPKEY_FILE"}}let r=e.XDG_CONFIG_HOME?.trim()||`${IM()}/.config`,n=Wu(`${r}/lmctl/appkey.json`);if(n)return{appkey:n,source:"~/.config/lmctl/appkey.json"};let o=Wu(`${r}/lmctl/lmchat-apikey`);if(o)return{appkey:o,source:"~/.config/lmctl/lmchat-apikey (legacy)"};if(wa(e.LMCHAT_APP_KEY))return{appkey:e.LMCHAT_APP_KEY,source:"LMCHAT_APP_KEY (legacy)"};throw new Error("no appkey found; run `lmchat login` (or put a key in ~/.config/lmctl/appkey.json or ~/.config/lmctl/lmchat-apikey)")}function wa(e){return!!(e&&e===e.trim()&&!/[\u0000-\u001f\u007f]/.test(e))}function Wu(e){let t;try{t=NM(e,"utf8")}catch{return}let r=t.trim();if(r){if(r.startsWith("{"))try{let n=JSON.parse(r),o=typeof n.appkey=="string"?n.appkey.trim():void 0;return wa(o)?o:void 0}catch{return}return wa(r)?r:void 0}}function mr(e){return{authorization:`Bearer ${jM(e)}`}}function HM(e,t){return(e??t.LMCHAT_API_URL??XT).replace(/\/+$/,"")}function BM(e,t){tb(e),rb(e,t)}function tb(e){e("seq name size content_type created_at")}function rb(e,t){for(let r of t)e(`${r.seq} ${r.name} ${r.size} ${r.content_type} ${r.created_at}`)}function WM(e){let t=CM(e).toLowerCase();return{".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".txt":"text/plain",".webp":"image/webp",".zip":"application/zip"}[t]??"application/octet-stream"}function GM(e,t){let r="unset";try{r=eb(e).source}catch{r="unset"}return[`API: ${t??e.LMCHAT_API_URL??XT}`,`appkey source: ${r}`,"","All commands authenticate with the ONE shared appkey (Authorization: Bearer <appkey>).","Get a key with `lmchat login`; it is resolved from LMCTL_APPKEY, LMCTL_APPKEY_FILE,","~/.config/lmctl/appkey.json, or ~/.config/lmctl/lmchat-apikey.","LMCHAT_APP_KEY is still accepted for compatibility.","The server derives your user from the appkey \u2014 the client never sends a user id."].join(`
873
- `)}function _a(e,t){let r=e.indexOf(t);return r===-1?!1:(e.splice(r,1),!0)}function De(e,t){let r=e.indexOf(t);if(r===-1)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new Qt(`missing value for ${t}`);return e.splice(r,2),n}function Gu(e,t){let r=De(e,t);if(!r)throw new Qt(`missing required ${t}`);return r}function Nt(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Qt(`missing ${t}`);return r}function It(e){if(e.length>0)throw new Qt(`unexpected argument: ${e[0]}`)}function VM(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),stderr:e.stderr??(t=>console.error(t)),readFile:e.readFile??((t,r)=>r?zT(t,{encoding:r}):zT(t)),writeFile:e.writeFile??((t,r)=>RM(t,r)),mkdir:e.mkdir??((t,r)=>kM(t,r)),stat:e.stat??(t=>xM(t))}}function QT(){return["usage: (all commands use the shared appkey \u2014 run `lmchat login` first)"," lmchat login # browser sign-in -> saves ~/.config/lmctl/appkey.json"," lmchat whoami [--api URL]"," lmchat rooms [--json] [--api URL] # list your rooms"," lmchat create <room_name> [--api URL] # create a room"," lmchat say <room_name> <text> [--title title] # post a text message"," lmchat read <room_name> [--after N] [--limit N] [--follow] [--interval S] [--json] # read/poll new messages"," lmchat list <room_name> [--after N] [--limit N] [--json] # alias for read"," lmchat post <room_name> --name <filename> --file <path> [--content-type type] # upload a file"," lmchat get <room_name> <seq> --out <path> # download"," lmchat delete <room_name> <seq> # remove a handled message"," lmchat delete-room <room_name> # remove a room and its files"," (register-room is an alias for create; list is an alias for read)"].join(`
874
- `)}var Qt=class extends Error{};import{mkdir as sP,readFile as iP,stat as aP,writeFile as cP}from"node:fs/promises";import{basename as lP,extname as uP,join as dP}from"node:path";async function Tb(e,t={}){let r=EP(t),n=Ku(e);if(n.kind==="whoami"){r.stdout(gP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:a}=await Promise.resolve().then(()=>(wb(),_b));if(await a({env:r.env})!==0)throw new Error("login failed");return}let o=hP(n.api,r.env),s=Se({env:r.env}).appkey,i=pt({apiUrl:o,appkey:s,fetch:r.fetch});if(n.kind==="mailboxes"){let a=await ln(()=>i.listMailboxes());r.stdout("mailbox created_at");for(let c of a)r.stdout(`${c.mailbox_name} ${c.created_at}`);return}if(n.kind==="create"){await ln(()=>i.createMailbox(n.mailbox,{tolerate409:!1})),r.stdout(`created ${n.mailbox}`);return}if(n.kind==="send"){let a=await ln(()=>mP(r,i,n));r.stdout(String(a));return}if(n.kind==="list"){let a=await ln(()=>i.listMessages(n.mailbox,{...n.status?{status:n.status}:{},...n.after?{after:fP(n.after)}:{}}));r.stdout("seq status sender subject attachments created_at");for(let c of a.messages)r.stdout(`${c.seq} ${c.read?"read":"unread"} ${c.sender} ${c.subject} ${c.attachments.length} ${c.created_at}`);return}if(n.kind==="read"){let a=yb(n.seq),c=await ln(()=>i.getMessage(n.mailbox,a));await r.mkdir(n.out,{recursive:!0});let l=new Set;for(let[u,d]of[c.body,...c.attachments].entries()){let m=d.name;l.has(m)&&(m=`${String(u).padStart(3,"0")}_${m}`),l.add(m);let f=dP(n.out,m);await r.writeFile(f,await ln(()=>i.download(d.download_url),"presigned download failed")),r.stdout(`saved ${f}`)}return}n.kind==="delete"&&(await ln(()=>i.deleteMessage(n.mailbox,yb(n.seq))),r.stdout(`deleted ${n.seq}`))}function Ku(e){let t=[...e],r=to(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new fr(Eb());if(n==="login"||n==="whoami"||n==="mailboxes")return eo(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=un(t,"mailbox");return eo(t),{kind:"create",mailbox:o,...r?{api:r}:{}}}if(n==="send"){let o=un(t,"mailbox"),s=yP(t,"--file"),i=to(t,"--subject"),a=wP(t,"--attach");return eo(t),{kind:"send",mailbox:o,file:s,attachments:a,...i?{subject:i}:{},...r?{api:r}:{}}}if(n==="list"){let o=un(t,"mailbox"),s=to(t,"--status"),i=to(t,"--after");return eo(t),{kind:"list",mailbox:o,...s?{status:s}:{},...i?{after:i}:{},...r?{api:r}:{}}}if(n==="read"){let o=un(t,"mailbox"),s=un(t,"seq"),i=to(t,"--out")??".";return eo(t),{kind:"read",mailbox:o,seq:s,out:i,...r?{api:r}:{}}}if(n==="delete"){let o=un(t,"mailbox"),s=un(t,"seq");return eo(t),{kind:"delete",mailbox:o,seq:s,...r?{api:r}:{}}}throw new fr(`unknown command: ${n}
872
+ ${rb()}`)}async function jM(e,t,r){let n=await e.stat(r.file);if(!n.isFile())throw new Error(`not a file: ${r.file}`);let o=r.contentType??QM(r.name),s=await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files`,{method:"POST",headers:{...fr(e.env),"content-type":"application/json"},body:JSON.stringify({name:r.name,content_type:o,size:n.size})}),i=await e.readFile(r.file),a=typeof i=="string"?Buffer.from(i):i,c=new FormData;for(let[d,m]of Object.entries(s.fields))c.append(d,m);c.append("file",new Blob([a],{type:s.content_type}),s.name);let l=await e.fetch(s.upload_url,{method:"POST",body:c});if(!l.ok)throw new Error(`S3 upload failed: ${l.status} ${await l.text().catch(()=>"")}`.trim());return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(String(s.seq))}/commit`,{method:"POST",headers:{...fr(e.env),"content-type":"application/json"},body:JSON.stringify({name:s.name})})).seq}async function HM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/messages`,{method:"POST",headers:{...fr(e.env),"content-type":"application/json"},body:JSON.stringify({text:r.text,...r.title?{title:r.title}:{}})})).seq}async function tb(e,t,r){let n=r.after,o=Number(r.interval??"5");if(!Number.isFinite(o)||o<1)throw new Qt(`--interval must be a finite number >= 1 seconds (got "${r.interval}")`);let s=o*1e3,i=!1,a=[];for(;;){let c=await BM(e,t,r.roomName,n,r.limit);r.follow?r.json?c.files.length>0&&e.stdout(JSON.stringify(c.files)):(i||(ib(e.stdout),i=!0),ab(e.stdout,c.files)):a.push(...c.files);let l=typeof c.next_after=="number"?String(c.next_after):n,u=l!==void 0&&l!==n;if(u&&(n=l),!c.has_more||!u){if(!r.follow){r.json?e.stdout(JSON.stringify(a)):YM(e.stdout,a);return}await JM(s)}}}async function BM(e,t,r,n,o){let s=new URLSearchParams;n!==void 0&&s.set("after",n),o!==void 0&&s.set("limit",o);let i=s.toString();return Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r)}/files${i?`?${i}`:""}`,{method:"GET",headers:fr(e.env)})}async function WM(e,t,r){let n=await e.fetch(`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(r.seq)}`,{method:"GET",headers:fr(e.env),redirect:"manual"});if(n.status!==302)throw await zu(n,"download request failed"),new Error(`download request did not return a redirect: ${n.status}`);let o=n.headers.get("location");if(!o)throw new Error("download redirect missing Location header");let s=await e.fetch(o,{method:"GET"});await zu(s,"presigned download failed");let i=new Uint8Array(await s.arrayBuffer());await e.mkdir(FM(r.out),{recursive:!0}),await e.writeFile(r.out,i)}async function GM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}/files/${encodeURIComponent(r.seq)}`,{method:"DELETE",headers:fr(e.env)})).seq}async function VM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}`,{method:"DELETE",headers:fr(e.env)})).room_name}function JM(e){return new Promise(t=>setTimeout(t,e))}async function Fr(e,t,r){let n=await e(t,r);return await zu(n,"API request failed"),await n.json()}async function zu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function KM(e){return sb(e).appkey}function sb(e){if(Ta(e.LMCTL_APPKEY))return{appkey:e.LMCTL_APPKEY,source:"LMCTL_APPKEY"};let t=e.LMCTL_APPKEY_FILE?.trim();if(t){let s=Ju(t);if(s)return{appkey:s,source:"LMCTL_APPKEY_FILE"}}let r=e.XDG_CONFIG_HOME?.trim()||`${UM()}/.config`,n=Ju(`${r}/lmctl/appkey.json`);if(n)return{appkey:n,source:"~/.config/lmctl/appkey.json"};let o=Ju(`${r}/lmctl/lmchat-apikey`);if(o)return{appkey:o,source:"~/.config/lmctl/lmchat-apikey (legacy)"};if(Ta(e.LMCHAT_APP_KEY))return{appkey:e.LMCHAT_APP_KEY,source:"LMCHAT_APP_KEY (legacy)"};throw new Error("no appkey found; run `lmchat login` (or put a key in ~/.config/lmctl/appkey.json or ~/.config/lmctl/lmchat-apikey)")}function Ta(e){return!!(e&&e===e.trim()&&!/[\u0000-\u001f\u007f]/.test(e))}function Ju(e){let t;try{t=PM(e,"utf8")}catch{return}let r=t.trim();if(r){if(r.startsWith("{"))try{let n=JSON.parse(r),o=typeof n.appkey=="string"?n.appkey.trim():void 0;return Ta(o)?o:void 0}catch{return}return Ta(r)?r:void 0}}function fr(e){return{authorization:`Bearer ${KM(e)}`}}function zM(e,t){return(e??t.LMCHAT_API_URL??nb).replace(/\/+$/,"")}function YM(e,t){ib(e),ab(e,t)}function ib(e){e("seq name size content_type created_at")}function ab(e,t){for(let r of t)e(`${r.seq} ${r.name} ${r.size} ${r.content_type} ${r.created_at}`)}function QM(e){let t=qM(e).toLowerCase();return{".gif":"image/gif",".jpeg":"image/jpeg",".jpg":"image/jpeg",".json":"application/json",".md":"text/markdown",".pdf":"application/pdf",".png":"image/png",".txt":"text/plain",".webp":"image/webp",".zip":"application/zip"}[t]??"application/octet-stream"}function XM(e,t){let r="unset";try{r=sb(e).source}catch{r="unset"}return[`API: ${t??e.LMCHAT_API_URL??nb}`,`appkey source: ${r}`,"","All commands authenticate with the ONE shared appkey (Authorization: Bearer <appkey>).","Get a key with `lmchat login`; it is resolved from LMCTL_APPKEY, LMCTL_APPKEY_FILE,","~/.config/lmctl/appkey.json, or ~/.config/lmctl/lmchat-apikey.","LMCHAT_APP_KEY is still accepted for compatibility.","The server derives your user from the appkey \u2014 the client never sends a user id."].join(`
873
+ `)}function Ea(e,t){let r=e.indexOf(t);return r===-1?!1:(e.splice(r,1),!0)}function De(e,t){let r=e.indexOf(t);if(r===-1)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new Qt(`missing value for ${t}`);return e.splice(r,2),n}function Ku(e,t){let r=De(e,t);if(!r)throw new Qt(`missing required ${t}`);return r}function Nt(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Qt(`missing ${t}`);return r}function Lt(e){if(e.length>0)throw new Qt(`unexpected argument: ${e[0]}`)}function ZM(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),stderr:e.stderr??(t=>console.error(t)),readFile:e.readFile??((t,r)=>r?eb(t,{encoding:r}):eb(t)),writeFile:e.writeFile??((t,r)=>MM(t,r)),mkdir:e.mkdir??((t,r)=>OM(t,r)),stat:e.stat??(t=>DM(t))}}function rb(){return["usage: (all commands use the shared appkey \u2014 run `lmchat login` first)"," lmchat login # browser sign-in -> saves ~/.config/lmctl/appkey.json"," lmchat whoami [--api URL]"," lmchat rooms [--json] [--api URL] # list your rooms"," lmchat create <room_name> [--api URL] # create a room"," lmchat say <room_name> <text> [--title title] # post a text message"," lmchat read <room_name> [--after N] [--limit N] [--follow] [--interval S] [--json] # read/poll new messages"," lmchat list <room_name> [--after N] [--limit N] [--json] # alias for read"," lmchat post <room_name> --name <filename> --file <path> [--content-type type] # upload a file"," lmchat get <room_name> <seq> --out <path> # download"," lmchat delete <room_name> <seq> # remove a handled message"," lmchat delete-room <room_name> # remove a room and its files"," (register-room is an alias for create; list is an alias for read)"].join(`
874
+ `)}var Qt=class extends Error{};import{mkdir as mP,readFile as fP,stat as pP,writeFile as hP}from"node:fs/promises";import{basename as gP,extname as _P,join as wP}from"node:path";async function kb(e,t={}){let r=$P(t),n=Qu(e);if(n.kind==="whoami"){r.stdout(SP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:a}=await Promise.resolve().then(()=>(Sb(),bb));if(await a({env:r.env})!==0)throw new Error("login failed");return}let o=bP(n.api,r.env),s=Se({env:r.env}).appkey,i=pt({apiUrl:o,appkey:s,fetch:r.fetch});if(n.kind==="mailboxes"){let a=await ln(()=>i.listMailboxes());r.stdout("mailbox created_at");for(let c of a)r.stdout(`${c.mailbox_name} ${c.created_at}`);return}if(n.kind==="create"){await ln(()=>i.createMailbox(n.mailbox,{tolerate409:!1})),r.stdout(`created ${n.mailbox}`);return}if(n.kind==="send"){let a=await ln(()=>yP(r,i,n));r.stdout(String(a));return}if(n.kind==="list"){let a=await ln(()=>i.listMessages(n.mailbox,{...n.status?{status:n.status}:{},...n.after?{after:EP(n.after)}:{}}));r.stdout("seq status sender subject attachments created_at");for(let c of a.messages)r.stdout(`${c.seq} ${c.read?"read":"unread"} ${c.sender} ${c.subject} ${c.attachments.length} ${c.created_at}`);return}if(n.kind==="read"){let a=vb(n.seq),c=await ln(()=>i.getMessage(n.mailbox,a));await r.mkdir(n.out,{recursive:!0});let l=new Set;for(let[u,d]of[c.body,...c.attachments].entries()){let m=d.name;l.has(m)&&(m=`${String(u).padStart(3,"0")}_${m}`),l.add(m);let f=wP(n.out,m);await r.writeFile(f,await ln(()=>i.download(d.download_url),"presigned download failed")),r.stdout(`saved ${f}`)}return}n.kind==="delete"&&(await ln(()=>i.deleteMessage(n.mailbox,vb(n.seq))),r.stdout(`deleted ${n.seq}`))}function Qu(e){let t=[...e],r=no(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new pr(Ab());if(n==="login"||n==="whoami"||n==="mailboxes")return ro(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=un(t,"mailbox");return ro(t),{kind:"create",mailbox:o,...r?{api:r}:{}}}if(n==="send"){let o=un(t,"mailbox"),s=kP(t,"--file"),i=no(t,"--subject"),a=AP(t,"--attach");return ro(t),{kind:"send",mailbox:o,file:s,attachments:a,...i?{subject:i}:{},...r?{api:r}:{}}}if(n==="list"){let o=un(t,"mailbox"),s=no(t,"--status"),i=no(t,"--after");return ro(t),{kind:"list",mailbox:o,...s?{status:s}:{},...i?{after:i}:{},...r?{api:r}:{}}}if(n==="read"){let o=un(t,"mailbox"),s=un(t,"seq"),i=no(t,"--out")??".";return ro(t),{kind:"read",mailbox:o,seq:s,out:i,...r?{api:r}:{}}}if(n==="delete"){let o=un(t,"mailbox"),s=un(t,"seq");return ro(t),{kind:"delete",mailbox:o,seq:s,...r?{api:r}:{}}}throw new pr(`unknown command: ${n}
875
875
 
876
- ${Eb()}`)}async function mP(e,t,r){let n=[r.file,...r.attachments],o=await Promise.all(n.map(async s=>{if(!(await e.stat(s)).isFile())throw new Error(`not a file: ${s}`);return{name:lP(s),contentType:_P(s),bytes:await e.readFile(s)}}));return t.sendMessage({mailbox:r.mailbox,...r.subject?{subject:r.subject}:{},body:o[0],attachments:o.slice(1)})}async function ln(e,t){try{return await e()}catch(r){if(!(r instanceof Ft))throw r;let n=/^upload failed for (.+?): HTTP/.exec(r.message),o=t??(n?`S3 upload failed for ${n[1]}`:"API request failed");throw bb(o,r.status,r.responseBody)}}function yb(e){if(!/^[1-9]\d*$/.test(e))throw Ea("seq_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw Ea("seq_invalid");return t}function fP(e){if(!/^(0|[1-9]\d*)$/.test(e))throw Ea("after_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw Ea("after_invalid");return t}function Ea(e){return bb("API request failed",400,JSON.stringify({error:e}))}function bb(e,t,r){return new Error(`${e}: ${t}${r?` ${r}`:""}`)}function pP(e){try{let{source:t}=Se({env:e});return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function hP(e,t){let r=e??t.LMMAIL_API_URL;if(!r)throw new Error("missing LMMAIL_API_URL or --api");return r.replace(/\/+$/,"")}function gP(e,t){return[`API: ${t??e.LMMAIL_API_URL??"unset (set --api or LMMAIL_API_URL)"}`,`appkey source: ${pP(e)}`,"identity: derived server-side from the shared appkey"].join(`
877
- `)}function _P(e){return{".txt":"text/plain",".md":"text/markdown",".html":"text/html",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".zip":"application/zip"}[uP(e).toLowerCase()]??"application/octet-stream"}function to(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new fr(`missing value for ${t}`);return e.splice(r,2),n}function wP(e,t){let r=e.indexOf(t);if(r<0)return[];let n=[],o=r+1;for(;o<e.length&&!e[o].startsWith("--");)n.push(e[o]),o+=1;if(!n.length)throw new fr(`missing value for ${t}`);return e.splice(r,n.length+1),n}function yP(e,t){let r=to(e,t);if(!r)throw new fr(`missing required ${t}`);return r}function un(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new fr(`missing ${t}`);return r}function eo(e){if(e.length)throw new fr(`unexpected argument: ${e[0]}`)}function EP(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>iP(t)),writeFile:e.writeFile??((t,r)=>cP(t,r)),mkdir:e.mkdir??((t,r)=>sP(t,r)),stat:e.stat??(t=>aP(t))}}function Eb(){return["usage:"," lmmail login"," lmmail whoami [--api URL]"," lmmail mailboxes [--api URL]"," lmmail create <name> [--api URL]"," lmmail send <mailbox> --file <body.txt|md|html> [--attach <file...>] [--subject text]"," lmmail list <mailbox> [--status all|unread|read] [--after N]"," lmmail read <mailbox> <seq> [--out dir]"," lmmail delete <mailbox> <seq>"].join(`
878
- `)}var fr=class extends Error{};import{mkdir as CP,readFile as OP,stat as DP,writeFile as MP}from"node:fs/promises";import{dirname as PP,extname as UP}from"node:path";async function qb(e,t={}){let r=JP(t),n=Yu(e);if(n.kind==="whoami"){r.stdout(WP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(Ub(),Pb));if(await i({env:r.env})!==0)throw new Error("login failed");return}let o=HP(n.api,r.env),s=BP(r.env);if(n.kind==="push"||n.kind==="update"){await FP(r,o,s,n),r.stdout(`${n.kind==="push"?"created":"updated"} ${n.name}`);return}if(n.kind==="list"){let i=new URLSearchParams;n.after&&i.set("after",n.after),n.limit&&i.set("limit",n.limit);let a=await ds(r.fetch,`${o}/notes${i.size?`?${i}`:""}`,{method:"GET",headers:s});r.stdout("name size content_type created_at updated_at");for(let c of a.notes)r.stdout(`${c.name} ${c.size} ${c.content_type} ${c.created_at} ${c.updated_at}`);r.stdout(`next_after=${a.next_after} has_more=${a.has_more}`);return}if(n.kind==="read"){let i=await ds(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"GET",headers:s}),a=await r.fetch(i.download_url);await Qu(a,"presigned download failed");let c=new Uint8Array(await a.arrayBuffer());n.out?(await r.mkdir(PP(n.out),{recursive:!0}),await r.writeFile(n.out,c),r.stdout(`saved ${n.out}`)):r.stdout(Buffer.from(c).toString("utf8"));return}n.kind==="delete"&&(await ds(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"DELETE",headers:s}),r.stdout(`deleted ${n.name}`))}function Yu(e){let t=[...e],r=us(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new qr(Fb());if(n==="login"||n==="whoami")return ls(t),{kind:n,...r?{api:r}:{}};if(n==="push"||n==="update"){let o=zu(t,"name"),s=VP(t,"--file");return ls(t),{kind:n,name:o,file:s,...r?{api:r}:{}}}if(n==="list"){let o=us(t,"--after"),s=us(t,"--limit");return ls(t),{kind:"list",...o?{after:o}:{},...s?{limit:s}:{},...r?{api:r}:{}}}if(n==="read"){let o=zu(t,"name"),s=us(t,"--out");return ls(t),{kind:"read",name:o,...s?{out:s}:{},...r?{api:r}:{}}}if(n==="delete"){let o=zu(t,"name");return ls(t),{kind:"delete",name:o,...r?{api:r}:{}}}throw new qr(`unknown command: ${n}
876
+ ${Ab()}`)}async function yP(e,t,r){let n=[r.file,...r.attachments],o=await Promise.all(n.map(async s=>{if(!(await e.stat(s)).isFile())throw new Error(`not a file: ${s}`);return{name:gP(s),contentType:vP(s),bytes:await e.readFile(s)}}));return t.sendMessage({mailbox:r.mailbox,...r.subject?{subject:r.subject}:{},body:o[0],attachments:o.slice(1)})}async function ln(e,t){try{return await e()}catch(r){if(!(r instanceof Ft))throw r;let n=/^upload failed for (.+?): HTTP/.exec(r.message),o=t??(n?`S3 upload failed for ${n[1]}`:"API request failed");throw $b(o,r.status,r.responseBody)}}function vb(e){if(!/^[1-9]\d*$/.test(e))throw Sa("seq_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw Sa("seq_invalid");return t}function EP(e){if(!/^(0|[1-9]\d*)$/.test(e))throw Sa("after_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw Sa("after_invalid");return t}function Sa(e){return $b("API request failed",400,JSON.stringify({error:e}))}function $b(e,t,r){return new Error(`${e}: ${t}${r?` ${r}`:""}`)}function TP(e){try{let{source:t}=Se({env:e});return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function bP(e,t){let r=e??t.LMMAIL_API_URL;if(!r)throw new Error("missing LMMAIL_API_URL or --api");return r.replace(/\/+$/,"")}function SP(e,t){return[`API: ${t??e.LMMAIL_API_URL??"unset (set --api or LMMAIL_API_URL)"}`,`appkey source: ${TP(e)}`,"identity: derived server-side from the shared appkey"].join(`
877
+ `)}function vP(e){return{".txt":"text/plain",".md":"text/markdown",".html":"text/html",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".zip":"application/zip"}[_P(e).toLowerCase()]??"application/octet-stream"}function no(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new pr(`missing value for ${t}`);return e.splice(r,2),n}function AP(e,t){let r=e.indexOf(t);if(r<0)return[];let n=[],o=r+1;for(;o<e.length&&!e[o].startsWith("--");)n.push(e[o]),o+=1;if(!n.length)throw new pr(`missing value for ${t}`);return e.splice(r,n.length+1),n}function kP(e,t){let r=no(e,t);if(!r)throw new pr(`missing required ${t}`);return r}function un(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new pr(`missing ${t}`);return r}function ro(e){if(e.length)throw new pr(`unexpected argument: ${e[0]}`)}function $P(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>fP(t)),writeFile:e.writeFile??((t,r)=>hP(t,r)),mkdir:e.mkdir??((t,r)=>mP(t,r)),stat:e.stat??(t=>pP(t))}}function Ab(){return["usage:"," lmmail login"," lmmail whoami [--api URL]"," lmmail mailboxes [--api URL]"," lmmail create <name> [--api URL]"," lmmail send <mailbox> --file <body.txt|md|html> [--attach <file...>] [--subject text]"," lmmail list <mailbox> [--status all|unread|read] [--after N]"," lmmail read <mailbox> <seq> [--out dir]"," lmmail delete <mailbox> <seq>"].join(`
878
+ `)}var pr=class extends Error{};import{mkdir as qP,readFile as jP,stat as HP,writeFile as BP}from"node:fs/promises";import{dirname as WP,extname as GP}from"node:path";async function Gb(e,t={}){let r=eU(t),n=Zu(e);if(n.kind==="whoami"){r.stdout(QP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(Bb(),Hb));if(await i({env:r.env})!==0)throw new Error("login failed");return}let o=zP(n.api,r.env),s=YP(r.env);if(n.kind==="push"||n.kind==="update"){await VP(r,o,s,n),r.stdout(`${n.kind==="push"?"created":"updated"} ${n.name}`);return}if(n.kind==="list"){let i=new URLSearchParams;n.after&&i.set("after",n.after),n.limit&&i.set("limit",n.limit);let a=await hs(r.fetch,`${o}/notes${i.size?`?${i}`:""}`,{method:"GET",headers:s});r.stdout("name size content_type created_at updated_at");for(let c of a.notes)r.stdout(`${c.name} ${c.size} ${c.content_type} ${c.created_at} ${c.updated_at}`);r.stdout(`next_after=${a.next_after} has_more=${a.has_more}`);return}if(n.kind==="read"){let i=await hs(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"GET",headers:s}),a=await r.fetch(i.download_url);await ed(a,"presigned download failed");let c=new Uint8Array(await a.arrayBuffer());n.out?(await r.mkdir(WP(n.out),{recursive:!0}),await r.writeFile(n.out,c),r.stdout(`saved ${n.out}`)):r.stdout(Buffer.from(c).toString("utf8"));return}n.kind==="delete"&&(await hs(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"DELETE",headers:s}),r.stdout(`deleted ${n.name}`))}function Zu(e){let t=[...e],r=ps(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new qr(Wb());if(n==="login"||n==="whoami")return fs(t),{kind:n,...r?{api:r}:{}};if(n==="push"||n==="update"){let o=Xu(t,"name"),s=ZP(t,"--file");return fs(t),{kind:n,name:o,file:s,...r?{api:r}:{}}}if(n==="list"){let o=ps(t,"--after"),s=ps(t,"--limit");return fs(t),{kind:"list",...o?{after:o}:{},...s?{limit:s}:{},...r?{api:r}:{}}}if(n==="read"){let o=Xu(t,"name"),s=ps(t,"--out");return fs(t),{kind:"read",name:o,...s?{out:s}:{},...r?{api:r}:{}}}if(n==="delete"){let o=Xu(t,"name");return fs(t),{kind:"delete",name:o,...r?{api:r}:{}}}throw new qr(`unknown command: ${n}
879
879
 
880
- ${Fb()}`)}async function FP(e,t,r,n){let o=await e.stat(n.file);if(!o.isFile())throw new Error(`not a file: ${n.file}`);let s=GP(n.file),i=n.kind==="push"?`${t}/notes`:`${t}/notes/${encodeURIComponent(n.name)}`,a=await ds(e.fetch,i,{method:n.kind==="push"?"POST":"PUT",headers:{...r,"content-type":"application/json"},body:JSON.stringify({...n.kind==="push"?{name:n.name}:{},content_type:s,size:o.size})}),c=await e.readFile(n.file),l=new FormData;for(let[m,f]of Object.entries(a.fields))l.append(m,f);l.append("file",new Blob([c],{type:a.content_type}),a.name);let u=await e.fetch(a.upload_url,{method:"POST",body:l});await Qu(u,"S3 upload failed");let d=a.finalize_url.startsWith("http")?a.finalize_url:`${t}${a.finalize_url.startsWith("/")?"":"/"}${a.finalize_url}`;await ds(e.fetch,d,{method:"POST",headers:{...r,"content-type":"application/json"},body:JSON.stringify({operation_token:a.operation_token})})}function qP(e){try{return Se({env:e}).appkey}catch{throw new Error("no appkey found; run `lmnote login` (or set LMCTL_APPKEY / copy ~/.config/lmctl/appkey.json here)")}}function jP(e){try{let t=Se({env:e}).source;return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function HP(e,t){let r=e??t.LMNOTE_API_URL;if(!r)throw new Error("missing LMNOTE_API_URL or --api");return r.replace(/\/+$/,"")}function BP(e){return{authorization:`Bearer ${qP(e)}`}}function WP(e,t){return[`API: ${t??e.LMNOTE_API_URL??"unset (set --api or LMNOTE_API_URL)"}`,`appkey source: ${jP(e)}`,"notebook identity: derived server-side from the shared appkey"].join(`
881
- `)}function GP(e){return{".txt":"text/plain",".md":"text/markdown",".html":"text/html",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".zip":"application/zip"}[UP(e).toLowerCase()]??"application/octet-stream"}async function ds(e,t,r){let n=await e(t,r);return await Qu(n,"API request failed"),n.json()}async function Qu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function us(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new qr(`missing value for ${t}`);return e.splice(r,2),n}function VP(e,t){let r=us(e,t);if(!r)throw new qr(`missing required ${t}`);return r}function zu(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new qr(`missing ${t}`);return r}function ls(e){if(e.length)throw new qr(`unexpected argument: ${e[0]}`)}function JP(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>OP(t)),writeFile:e.writeFile??((t,r)=>MP(t,r)),mkdir:e.mkdir??((t,r)=>CP(t,r)),stat:e.stat??(t=>DP(t))}}function Fb(){return["usage:"," lmnote login"," lmnote whoami [--api URL]"," lmnote push <name> --file <path>"," lmnote list [--after name] [--limit N]"," lmnote read <name> [--out path]"," lmnote update <name> --file <path>"," lmnote delete <name>"].join(`
882
- `)}var qr=class extends Error{};async function aS(e,t={}){let r=t.fetch??fetch,n=t.env??process.env,o=t.stdout??(l=>console.log(l)),s=Xu(e);if(s.kind==="whoami"){o(uU(n,s.api));return}if(s.kind==="login"){let{runLogin:l}=await Promise.resolve().then(()=>(rS(),tS));if(await l({env:n})!==0)throw new Error("login failed");return}let i=cU(s.api,n),a=lU(n),c={...a,"content-type":"application/json"};if(s.kind==="create"){await Xt(r,`${i}/sheets`,{method:"POST",headers:c,body:JSON.stringify({name:s.name,columns:s.columns})}),o(`created ${s.name}`);return}if(s.kind==="sheets"){o("name columns next_row created_at updated_at");let l="";for(let u=0;u<100;u+=1){let d=await Xt(r,`${i}/sheets${l?`?after=${encodeURIComponent(l)}`:""}`,{method:"GET",headers:a});for(let m of d.sheets)o(`${m.name} ${nS(m.columns)} ${m.next_row} ${m.created_at} ${m.updated_at}`);if(!d.has_more){o(`next_after=${d.next_after} has_more=false`);return}if(!d.next_after||d.next_after===l)throw new Error("sheet list cursor did not advance");l=d.next_after}throw new Error("sheet listing did not finish")}if(s.kind==="add-column"){let l=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/columns`,{method:"POST",headers:c,body:JSON.stringify({label:s.label})});o(`added ${l.column.letter} ${l.column.label}`);return}if(s.kind==="read"){let l=new URLSearchParams;s.after&&l.set("after",s.after),s.limit&&l.set("limit",s.limit);let u=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows${l.size?`?${l}`:""}`,{method:"GET",headers:a});o(`columns ${nS(u.sheet.columns)}`),o("row_num created_at updated_at cells");for(let d of u.rows)o(`${d.row_num} ${d.created_at} ${d.updated_at} ${JSON.stringify(d.cells)}`);o(`next_after=${u.next_after} has_more=${u.has_more}`);return}if(s.kind==="add-row"){let l=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows`,{method:"POST",headers:c,body:JSON.stringify({cells:s.cells,...s.row?{row_num:Number(s.row)}:{}})});o(`added row ${l.row_num}`);return}if(s.kind==="update-row"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows/${s.row}`,{method:"PUT",headers:c,body:JSON.stringify({cells:s.cells})}),o(`updated ${s.sheet} row ${s.row}`);return}if(s.kind==="set-cell"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/cells/${encodeURIComponent(s.address)}`,{method:"PUT",headers:c,body:JSON.stringify({value:s.value})}),o(`set ${s.sheet} ${s.address}`);return}if(s.kind==="clear-cell"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/cells/${encodeURIComponent(s.address)}`,{method:"DELETE",headers:a}),o(`cleared ${s.sheet} ${s.address}`);return}if(s.kind==="delete-row"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows/${s.row}`,{method:"DELETE",headers:a}),o(`deleted ${s.sheet} row ${s.row}`);return}if(s.kind==="delete-sheet"){for(let l=0;l<100;l+=1)if((await Xt(r,`${i}/sheets/${encodeURIComponent(s.name)}`,{method:"DELETE",headers:a})).deleted){o(`deleted ${s.name}`);return}throw new Error("sheet deletion did not finish")}}function Xu(e){let t=[...e],r=ro(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new er(iS());if(n==="login"||n==="whoami"||n==="sheets")return Zt(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=ot(t,"name"),s=dU(t,"--cols").split(",").map(i=>i.trim());return Zt(t),{kind:"create",name:o,columns:s,...r?{api:r}:{}}}if(n==="add-column"){let o=ot(t,"sheet"),s=ot(t,"label");return Zt(t),{kind:"add-column",sheet:o,label:s,...r?{api:r}:{}}}if(n==="read"){let o=ot(t,"sheet"),s=ro(t,"--after"),i=ro(t,"--limit");return Zt(t),{kind:"read",sheet:o,...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="add-row"){let o=ot(t,"sheet"),s=ro(t,"--row"),i=oS(sS(t,"--set"));return Zt(t),{kind:"add-row",sheet:o,cells:i,...s?{row:s}:{},...r?{api:r}:{}}}if(n==="update-row"){let o=ot(t,"sheet"),s=ot(t,"row"),i=oS(sS(t,"--set"),!0);return Zt(t),{kind:"update-row",sheet:o,row:s,cells:i,...r?{api:r}:{}}}if(n==="set-cell"){let o=ot(t,"sheet"),s=ot(t,"cell"),i=ot(t,"value");return Zt(t),{kind:"set-cell",sheet:o,address:s,value:i,...r?{api:r}:{}}}if(n==="clear-cell"){let o=ot(t,"sheet"),s=ot(t,"cell");return Zt(t),{kind:"clear-cell",sheet:o,address:s,...r?{api:r}:{}}}if(n==="delete-row"){let o=ot(t,"sheet"),s=ot(t,"row");return Zt(t),{kind:"delete-row",sheet:o,row:s,...r?{api:r}:{}}}if(n==="delete-sheet"){let o=ot(t,"name");return Zt(t),{kind:"delete-sheet",name:o,...r?{api:r}:{}}}throw new er(`unknown command: ${n}
880
+ ${Wb()}`)}async function VP(e,t,r,n){let o=await e.stat(n.file);if(!o.isFile())throw new Error(`not a file: ${n.file}`);let s=XP(n.file),i=n.kind==="push"?`${t}/notes`:`${t}/notes/${encodeURIComponent(n.name)}`,a=await hs(e.fetch,i,{method:n.kind==="push"?"POST":"PUT",headers:{...r,"content-type":"application/json"},body:JSON.stringify({...n.kind==="push"?{name:n.name}:{},content_type:s,size:o.size})}),c=await e.readFile(n.file),l=new FormData;for(let[m,f]of Object.entries(a.fields))l.append(m,f);l.append("file",new Blob([c],{type:a.content_type}),a.name);let u=await e.fetch(a.upload_url,{method:"POST",body:l});await ed(u,"S3 upload failed");let d=a.finalize_url.startsWith("http")?a.finalize_url:`${t}${a.finalize_url.startsWith("/")?"":"/"}${a.finalize_url}`;await hs(e.fetch,d,{method:"POST",headers:{...r,"content-type":"application/json"},body:JSON.stringify({operation_token:a.operation_token})})}function JP(e){try{return Se({env:e}).appkey}catch{throw new Error("no appkey found; run `lmnote login` (or set LMCTL_APPKEY / copy ~/.config/lmctl/appkey.json here)")}}function KP(e){try{let t=Se({env:e}).source;return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function zP(e,t){let r=e??t.LMNOTE_API_URL;if(!r)throw new Error("missing LMNOTE_API_URL or --api");return r.replace(/\/+$/,"")}function YP(e){return{authorization:`Bearer ${JP(e)}`}}function QP(e,t){return[`API: ${t??e.LMNOTE_API_URL??"unset (set --api or LMNOTE_API_URL)"}`,`appkey source: ${KP(e)}`,"notebook identity: derived server-side from the shared appkey"].join(`
881
+ `)}function XP(e){return{".txt":"text/plain",".md":"text/markdown",".html":"text/html",".json":"application/json",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".zip":"application/zip"}[GP(e).toLowerCase()]??"application/octet-stream"}async function hs(e,t,r){let n=await e(t,r);return await ed(n,"API request failed"),n.json()}async function ed(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function ps(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new qr(`missing value for ${t}`);return e.splice(r,2),n}function ZP(e,t){let r=ps(e,t);if(!r)throw new qr(`missing required ${t}`);return r}function Xu(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new qr(`missing ${t}`);return r}function fs(e){if(e.length)throw new qr(`unexpected argument: ${e[0]}`)}function eU(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>jP(t)),writeFile:e.writeFile??((t,r)=>BP(t,r)),mkdir:e.mkdir??((t,r)=>qP(t,r)),stat:e.stat??(t=>HP(t))}}function Wb(){return["usage:"," lmnote login"," lmnote whoami [--api URL]"," lmnote push <name> --file <path>"," lmnote list [--after name] [--limit N]"," lmnote read <name> [--out path]"," lmnote update <name> --file <path>"," lmnote delete <name>"].join(`
882
+ `)}var qr=class extends Error{};async function mS(e,t={}){let r=t.fetch??fetch,n=t.env??process.env,o=t.stdout??(l=>console.log(l)),s=td(e);if(s.kind==="whoami"){o(_U(n,s.api));return}if(s.kind==="login"){let{runLogin:l}=await Promise.resolve().then(()=>(aS(),iS));if(await l({env:n})!==0)throw new Error("login failed");return}let i=hU(s.api,n),a=gU(n),c={...a,"content-type":"application/json"};if(s.kind==="create"){await Xt(r,`${i}/sheets`,{method:"POST",headers:c,body:JSON.stringify({name:s.name,columns:s.columns})}),o(`created ${s.name}`);return}if(s.kind==="sheets"){o("name columns next_row created_at updated_at");let l="";for(let u=0;u<100;u+=1){let d=await Xt(r,`${i}/sheets${l?`?after=${encodeURIComponent(l)}`:""}`,{method:"GET",headers:a});for(let m of d.sheets)o(`${m.name} ${cS(m.columns)} ${m.next_row} ${m.created_at} ${m.updated_at}`);if(!d.has_more){o(`next_after=${d.next_after} has_more=false`);return}if(!d.next_after||d.next_after===l)throw new Error("sheet list cursor did not advance");l=d.next_after}throw new Error("sheet listing did not finish")}if(s.kind==="add-column"){let l=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/columns`,{method:"POST",headers:c,body:JSON.stringify({label:s.label})});o(`added ${l.column.letter} ${l.column.label}`);return}if(s.kind==="read"){let l=new URLSearchParams;s.after&&l.set("after",s.after),s.limit&&l.set("limit",s.limit);let u=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows${l.size?`?${l}`:""}`,{method:"GET",headers:a});o(`columns ${cS(u.sheet.columns)}`),o("row_num created_at updated_at cells");for(let d of u.rows)o(`${d.row_num} ${d.created_at} ${d.updated_at} ${JSON.stringify(d.cells)}`);o(`next_after=${u.next_after} has_more=${u.has_more}`);return}if(s.kind==="add-row"){let l=await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows`,{method:"POST",headers:c,body:JSON.stringify({cells:s.cells,...s.row?{row_num:Number(s.row)}:{}})});o(`added row ${l.row_num}`);return}if(s.kind==="update-row"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows/${s.row}`,{method:"PUT",headers:c,body:JSON.stringify({cells:s.cells})}),o(`updated ${s.sheet} row ${s.row}`);return}if(s.kind==="set-cell"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/cells/${encodeURIComponent(s.address)}`,{method:"PUT",headers:c,body:JSON.stringify({value:s.value})}),o(`set ${s.sheet} ${s.address}`);return}if(s.kind==="clear-cell"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/cells/${encodeURIComponent(s.address)}`,{method:"DELETE",headers:a}),o(`cleared ${s.sheet} ${s.address}`);return}if(s.kind==="delete-row"){await Xt(r,`${i}/sheets/${encodeURIComponent(s.sheet)}/rows/${s.row}`,{method:"DELETE",headers:a}),o(`deleted ${s.sheet} row ${s.row}`);return}if(s.kind==="delete-sheet"){for(let l=0;l<100;l+=1)if((await Xt(r,`${i}/sheets/${encodeURIComponent(s.name)}`,{method:"DELETE",headers:a})).deleted){o(`deleted ${s.name}`);return}throw new Error("sheet deletion did not finish")}}function td(e){let t=[...e],r=oo(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new er(dS());if(n==="login"||n==="whoami"||n==="sheets")return Zt(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=ot(t,"name"),s=wU(t,"--cols").split(",").map(i=>i.trim());return Zt(t),{kind:"create",name:o,columns:s,...r?{api:r}:{}}}if(n==="add-column"){let o=ot(t,"sheet"),s=ot(t,"label");return Zt(t),{kind:"add-column",sheet:o,label:s,...r?{api:r}:{}}}if(n==="read"){let o=ot(t,"sheet"),s=oo(t,"--after"),i=oo(t,"--limit");return Zt(t),{kind:"read",sheet:o,...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="add-row"){let o=ot(t,"sheet"),s=oo(t,"--row"),i=lS(uS(t,"--set"));return Zt(t),{kind:"add-row",sheet:o,cells:i,...s?{row:s}:{},...r?{api:r}:{}}}if(n==="update-row"){let o=ot(t,"sheet"),s=ot(t,"row"),i=lS(uS(t,"--set"),!0);return Zt(t),{kind:"update-row",sheet:o,row:s,cells:i,...r?{api:r}:{}}}if(n==="set-cell"){let o=ot(t,"sheet"),s=ot(t,"cell"),i=ot(t,"value");return Zt(t),{kind:"set-cell",sheet:o,address:s,value:i,...r?{api:r}:{}}}if(n==="clear-cell"){let o=ot(t,"sheet"),s=ot(t,"cell");return Zt(t),{kind:"clear-cell",sheet:o,address:s,...r?{api:r}:{}}}if(n==="delete-row"){let o=ot(t,"sheet"),s=ot(t,"row");return Zt(t),{kind:"delete-row",sheet:o,row:s,...r?{api:r}:{}}}if(n==="delete-sheet"){let o=ot(t,"name");return Zt(t),{kind:"delete-sheet",name:o,...r?{api:r}:{}}}throw new er(`unknown command: ${n}
883
883
 
884
- ${iS()}`)}function iU(e){try{return Se({env:e}).appkey}catch{throw new Error("no appkey found; run `lmsheet login` (or set LMCTL_APPKEY / copy ~/.config/lmctl/appkey.json here)")}}function aU(e){try{let t=Se({env:e}).source;return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function cU(e,t){let r=e??t.LMSHEET_API_URL;if(!r)throw new Error("missing LMSHEET_API_URL or --api");return r.replace(/\/+$/,"")}function lU(e){return{authorization:`Bearer ${iU(e)}`}}function uU(e,t){return[`API: ${t??e.LMSHEET_API_URL??"unset (set --api or LMSHEET_API_URL)"}`,`appkey source: ${aU(e)}`,"sheet identity: derived server-side from the shared appkey"].join(`
885
- `)}function nS(e){return e.map(t=>`${t.letter}:${t.label}`).join(",")}function oS(e,t=!1){if(t&&e.length===0)throw new er("at least one --set is required");let r={};for(let n of e){let o=n.indexOf("="),s=o>0?n.slice(0,o):"";if(!/^[A-Z]+$/.test(s))throw new er(`invalid --set: ${n}`);r[s]=n.slice(o+1)}return r}async function Xt(e,t,r){let n=await e(t,r);if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`API request failed: ${n.status}${o?` ${o}`:""}`)}return n.json()}function ro(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new er(`missing value for ${t}`);return e.splice(r,2),n}function sS(e,t){let r=[];for(;e.includes(t);){let n=ro(e,t);n!==void 0&&r.push(n)}return r}function dU(e,t){let r=ro(e,t);if(!r)throw new er(`missing required ${t}`);return r}function ot(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new er(`missing ${t}`);return r}function Zt(e){if(e.length)throw new er(`unexpected argument: ${e[0]}`)}function iS(){return["usage:"," lmsheet login"," lmsheet whoami [--api URL]",' lmsheet create <name> --cols "Name,Email,Age"'," lmsheet sheets"," lmsheet add-column <sheet> <label>"," lmsheet read <sheet> [--after N] [--limit N]"," lmsheet add-row <sheet> [--set A=value ...] [--row N]"," lmsheet update-row <sheet> <row> --set A=value [--set B=value ...]"," lmsheet set-cell <sheet> <A1> <value>"," lmsheet clear-cell <sheet> <A1>"," lmsheet delete-row <sheet> <row>"," lmsheet delete-sheet <name>"].join(`
886
- `)}var er=class extends Error{};import{readFile as vU,stat as AU}from"node:fs/promises";import{basename as vS,extname as $U}from"node:path";async function AS(e,t={}){let r=OU(t);if(!e.length||["help","-h","--help"].includes(e[0]??"")){r.stdout(ed());return}let n=td(e);if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(SS(),bS));if(await i({env:r.env})!==0)throw new Error("login failed");return}if(n.kind==="whoami"){let i=kU(r.env);r.stdout(`API: ${n.api??r.env.LMTEXT_API_URL??"unset (set --api or LMTEXT_API_URL)"}`),r.stdout(`appkey source: ${i.source}`),r.stdout("identity: derived server-side from the shared appkey");return}let o=xU(n.api,r.env),s=RU(r.env);if(n.kind==="transcribe"){let i=await r.stat(n.file);if(!i.isFile())throw new Error(`not a file: ${n.file}`);if(i.size<1||i.size>25*1024*1024)throw new Error("audio file must be between 1 byte and 25 MB");let a=LU(n.file),c=await no(r.fetch,`${o}/transcriptions`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({file_name:vS(n.file),content_type:a,...n.language?{language_code:n.language}:{}})}),l=await r.readFile(n.file),u=new FormData;for(let[m,f]of Object.entries(c.upload_fields))u.append(m,f);u.append("file",new Blob([new Uint8Array(l)],{type:a}),vS(n.file));let d=await r.fetch(c.upload_url,{method:"POST",body:u});if(await IU(d,"S3 upload failed"),await no(r.fetch,`${o}/transcriptions/${encodeURIComponent(c.transcription_id)}/finalize`,{method:"POST",headers:s}),!n.wait){r.stdout(c.transcription_id);return}for(;;){let m=await no(r.fetch,`${o}/transcriptions/${encodeURIComponent(c.transcription_id)}`,{method:"GET",headers:s});if(m.status==="completed"){r.stdout(m.transcript??"");return}if(m.status==="failed")throw new Error(m.failure_reason??"transcription_failed");await r.sleep(3e3)}}if(n.kind==="list"){let i=new URLSearchParams;n.status&&i.set("status",n.status),n.after&&i.set("after",n.after),n.limit&&i.set("limit",n.limit);let a=await no(r.fetch,`${o}/transcriptions${i.size?`?${i}`:""}`,{method:"GET",headers:s});r.stdout("transcription_id status created_at duration_ms");for(let c of a.transcriptions)r.stdout(`${c.transcription_id} ${c.status} ${c.created_at} ${c.duration_ms??""}`);a.has_more&&a.next_after&&r.stdout(`next_after=${a.next_after} has_more=true`),a.truncated&&r.stderr("warning: list results are truncated at the 1,000-object scan ceiling; older matching transcriptions may be omitted");return}if(n.kind==="get"){let i=await no(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"GET",headers:s});r.stdout(JSON.stringify(i,null,2));return}if(n.kind==="delete"){let i=await no(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"DELETE",headers:s});r.stdout(JSON.stringify(i,null,2));return}}function td(e){let t=[...e],r=ps(t,"--api"),n=t.shift();if(!n||["help","-h","--help"].includes(n))throw new dn(ed());if(n==="login"||n==="whoami")return hs(t),{kind:n,...r?{api:r}:{}};if(n==="transcribe"){let o=Zu(t,"file"),s=ps(t,"--language"),i=CU(t,"--wait");return hs(t),{kind:"transcribe",file:o,...s?{language:s}:{},wait:i,...r?{api:r}:{}}}if(n==="list"){let o=ps(t,"--status"),s=ps(t,"--after"),i=ps(t,"--limit");return hs(t),{kind:"list",...o?{status:o}:{},...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="get"){let o=Zu(t,"id");return hs(t),{kind:"get",id:o,...r?{api:r}:{}}}if(n==="delete"){let o=Zu(t,"id");return hs(t),{kind:"delete",id:o,...r?{api:r}:{}}}throw new dn(`unknown command: ${n}
884
+ ${dS()}`)}function fU(e){try{return Se({env:e}).appkey}catch{throw new Error("no appkey found; run `lmsheet login` (or set LMCTL_APPKEY / copy ~/.config/lmctl/appkey.json here)")}}function pU(e){try{let t=Se({env:e}).source;return t==="env:LMCTL_APPKEY"?"LMCTL_APPKEY":t==="env:LMCTL_APPKEY_FILE"?"LMCTL_APPKEY_FILE":t==="file:default"?"~/.config/lmctl/appkey.json":t}catch{return"unset"}}function hU(e,t){let r=e??t.LMSHEET_API_URL;if(!r)throw new Error("missing LMSHEET_API_URL or --api");return r.replace(/\/+$/,"")}function gU(e){return{authorization:`Bearer ${fU(e)}`}}function _U(e,t){return[`API: ${t??e.LMSHEET_API_URL??"unset (set --api or LMSHEET_API_URL)"}`,`appkey source: ${pU(e)}`,"sheet identity: derived server-side from the shared appkey"].join(`
885
+ `)}function cS(e){return e.map(t=>`${t.letter}:${t.label}`).join(",")}function lS(e,t=!1){if(t&&e.length===0)throw new er("at least one --set is required");let r={};for(let n of e){let o=n.indexOf("="),s=o>0?n.slice(0,o):"";if(!/^[A-Z]+$/.test(s))throw new er(`invalid --set: ${n}`);r[s]=n.slice(o+1)}return r}async function Xt(e,t,r){let n=await e(t,r);if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`API request failed: ${n.status}${o?` ${o}`:""}`)}return n.json()}function oo(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new er(`missing value for ${t}`);return e.splice(r,2),n}function uS(e,t){let r=[];for(;e.includes(t);){let n=oo(e,t);n!==void 0&&r.push(n)}return r}function wU(e,t){let r=oo(e,t);if(!r)throw new er(`missing required ${t}`);return r}function ot(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new er(`missing ${t}`);return r}function Zt(e){if(e.length)throw new er(`unexpected argument: ${e[0]}`)}function dS(){return["usage:"," lmsheet login"," lmsheet whoami [--api URL]",' lmsheet create <name> --cols "Name,Email,Age"'," lmsheet sheets"," lmsheet add-column <sheet> <label>"," lmsheet read <sheet> [--after N] [--limit N]"," lmsheet add-row <sheet> [--set A=value ...] [--row N]"," lmsheet update-row <sheet> <row> --set A=value [--set B=value ...]"," lmsheet set-cell <sheet> <A1> <value>"," lmsheet clear-cell <sheet> <A1>"," lmsheet delete-row <sheet> <row>"," lmsheet delete-sheet <name>"].join(`
886
+ `)}var er=class extends Error{};import{readFile as LU,stat as IU}from"node:fs/promises";import{basename as RS,extname as CU}from"node:path";async function NS(e,t={}){let r=jU(t);if(!e.length||["help","-h","--help"].includes(e[0]??"")){r.stdout(nd());return}let n=od(e);if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(xS(),$S));if(await i({env:r.env})!==0)throw new Error("login failed");return}if(n.kind==="whoami"){let i=OU(r.env);r.stdout(`API: ${n.api??r.env.LMTEXT_API_URL??"unset (set --api or LMTEXT_API_URL)"}`),r.stdout(`appkey source: ${i.source}`),r.stdout("identity: derived server-side from the shared appkey");return}let o=DU(n.api,r.env),s=MU(r.env);if(n.kind==="transcribe"){let i=await r.stat(n.file);if(!i.isFile())throw new Error(`not a file: ${n.file}`);if(i.size<1||i.size>25*1024*1024)throw new Error("audio file must be between 1 byte and 25 MB");let a=FU(n.file),c=await so(r.fetch,`${o}/transcriptions`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({file_name:RS(n.file),content_type:a,...n.language?{language_code:n.language}:{}})}),l=await r.readFile(n.file),u=new FormData;for(let[m,f]of Object.entries(c.upload_fields))u.append(m,f);u.append("file",new Blob([new Uint8Array(l)],{type:a}),RS(n.file));let d=await r.fetch(c.upload_url,{method:"POST",body:u});if(await UU(d,"S3 upload failed"),await so(r.fetch,`${o}/transcriptions/${encodeURIComponent(c.transcription_id)}/finalize`,{method:"POST",headers:s}),!n.wait){r.stdout(c.transcription_id);return}for(;;){let m=await so(r.fetch,`${o}/transcriptions/${encodeURIComponent(c.transcription_id)}`,{method:"GET",headers:s});if(m.status==="completed"){r.stdout(m.transcript??"");return}if(m.status==="failed")throw new Error(m.failure_reason??"transcription_failed");await r.sleep(3e3)}}if(n.kind==="list"){let i=new URLSearchParams;n.status&&i.set("status",n.status),n.after&&i.set("after",n.after),n.limit&&i.set("limit",n.limit);let a=await so(r.fetch,`${o}/transcriptions${i.size?`?${i}`:""}`,{method:"GET",headers:s});r.stdout("transcription_id status created_at duration_ms");for(let c of a.transcriptions)r.stdout(`${c.transcription_id} ${c.status} ${c.created_at} ${c.duration_ms??""}`);a.has_more&&a.next_after&&r.stdout(`next_after=${a.next_after} has_more=true`),a.truncated&&r.stderr("warning: list results are truncated at the 1,000-object scan ceiling; older matching transcriptions may be omitted");return}if(n.kind==="get"){let i=await so(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"GET",headers:s});r.stdout(JSON.stringify(i,null,2));return}if(n.kind==="delete"){let i=await so(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"DELETE",headers:s});r.stdout(JSON.stringify(i,null,2));return}}function od(e){let t=[...e],r=ws(t,"--api"),n=t.shift();if(!n||["help","-h","--help"].includes(n))throw new dn(nd());if(n==="login"||n==="whoami")return ys(t),{kind:n,...r?{api:r}:{}};if(n==="transcribe"){let o=rd(t,"file"),s=ws(t,"--language"),i=qU(t,"--wait");return ys(t),{kind:"transcribe",file:o,...s?{language:s}:{},wait:i,...r?{api:r}:{}}}if(n==="list"){let o=ws(t,"--status"),s=ws(t,"--after"),i=ws(t,"--limit");return ys(t),{kind:"list",...o?{status:o}:{},...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="get"){let o=rd(t,"id");return ys(t),{kind:"get",id:o,...r?{api:r}:{}}}if(n==="delete"){let o=rd(t,"id");return ys(t),{kind:"delete",id:o,...r?{api:r}:{}}}throw new dn(`unknown command: ${n}
887
887
 
888
- ${ed()}`)}function kU(e){try{return{source:Se({env:e}).source}}catch(t){return t instanceof Gr?{source:"unset"}:{source:"unset"}}}function xU(e,t){let r=e??t.LMTEXT_API_URL;if(!r)throw new Error("missing LMTEXT_API_URL or --api");return r.replace(/\/+$/,"")}function RU(e){return{authorization:`Bearer ${NU(e)}`}}function NU(e){return Se({env:e}).appkey}async function no(e,t,r){let n=await e(t,r);if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`API request failed: ${n.status} ${o}`)}return await n.json()}async function IU(e,t){if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status} ${r}`)}}function LU(e){return{".mp3":"audio/mpeg",".mp4":"audio/mp4",".m4a":"audio/mp4",".wav":"audio/wav",".flac":"audio/flac",".ogg":"audio/ogg",".webm":"audio/webm",".amr":"audio/amr"}[$U(e).toLowerCase()]??"application/octet-stream"}function ps(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new dn(`missing value for ${t}`);return e.splice(r,2),n}function CU(e,t){let r=e.indexOf(t);return r<0?!1:(e.splice(r,1),!0)}function Zu(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new dn(`missing ${t}`);return r}function hs(e){if(e.length)throw new dn(`unexpected argument: ${e[0]}`)}function ed(){return["usage:"," lmtext login"," lmtext whoami [--api URL]"," lmtext transcribe <file> [--language LANG] [--wait] [--api URL]"," lmtext list [--status all|uploading|in_progress|completed|failed] [--after CURSOR] [--limit N] [--api URL]"," lmtext get <id> [--api URL]"," lmtext delete <id> [--api URL]"].join(`
889
- `)}function OU(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>process.stdout.write(`${t}
888
+ ${nd()}`)}function OU(e){try{return{source:Se({env:e}).source}}catch(t){return t instanceof Gr?{source:"unset"}:{source:"unset"}}}function DU(e,t){let r=e??t.LMTEXT_API_URL;if(!r)throw new Error("missing LMTEXT_API_URL or --api");return r.replace(/\/+$/,"")}function MU(e){return{authorization:`Bearer ${PU(e)}`}}function PU(e){return Se({env:e}).appkey}async function so(e,t,r){let n=await e(t,r);if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`API request failed: ${n.status} ${o}`)}return await n.json()}async function UU(e,t){if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status} ${r}`)}}function FU(e){return{".mp3":"audio/mpeg",".mp4":"audio/mp4",".m4a":"audio/mp4",".wav":"audio/wav",".flac":"audio/flac",".ogg":"audio/ogg",".webm":"audio/webm",".amr":"audio/amr"}[CU(e).toLowerCase()]??"application/octet-stream"}function ws(e,t){let r=e.indexOf(t);if(r<0)return;let n=e[r+1];if(!n||n.startsWith("--"))throw new dn(`missing value for ${t}`);return e.splice(r,2),n}function qU(e,t){let r=e.indexOf(t);return r<0?!1:(e.splice(r,1),!0)}function rd(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new dn(`missing ${t}`);return r}function ys(e){if(e.length)throw new dn(`unexpected argument: ${e[0]}`)}function nd(){return["usage:"," lmtext login"," lmtext whoami [--api URL]"," lmtext transcribe <file> [--language LANG] [--wait] [--api URL]"," lmtext list [--status all|uploading|in_progress|completed|failed] [--after CURSOR] [--limit N] [--api URL]"," lmtext get <id> [--api URL]"," lmtext delete <id> [--api URL]"].join(`
889
+ `)}function jU(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>process.stdout.write(`${t}
890
890
  `)),stderr:e.stderr??(t=>process.stderr.write(`${t}
891
- `)),sleep:e.sleep??(t=>new Promise(r=>setTimeout(r,t))),readFile:e.readFile??(t=>vU(t)),stat:e.stat??(t=>AU(t))}}var dn=class extends Error{};var gs=class extends Error{status;responseBody;constructor(t,r){super(`HTTP ${t}${r?` ${r}`:""}`),this.status=t,this.responseBody=r,this.name="HttpResponseError"}},oo=class extends Error{service;status;cause;constructor(t,r,n){super(`${t} request failed: HTTP ${r}`),this.service=t,this.status=r,this.cause=n,this.name="AdapterHttpError"}},so=class extends Error{service;cause;constructor(t,r){super(r instanceof Error?r.message:String(r)),this.service=t,this.cause=r,this.name="ServiceCliUsageError"}},io=class extends Error{service;exitCode;constructor(t,r){super(`${t} CLI reported exit code ${r}`),this.service=t,this.exitCode=r,this.name="ServiceCliExitError"}};async function va(e){if(!e.ok)throw new gs(e.status,await e.text().catch(()=>""))}var $S=Object.freeze({lmchat:ao("https://lmctl.ai/tools/lmchat","LMCTL_LMCHAT_API_URL","LMCHAT_API_URL"),lmmail:ao("https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMMAIL_API_URL","LMMAIL_API_URL"),lmnote:ao("https://vijni9tfxh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMNOTE_API_URL","LMNOTE_API_URL"),lmsheet:ao("https://9zdvg8wfjh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMSHEET_API_URL","LMSHEET_API_URL"),lmtext:ao("https://bxdbjn5k90.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMTEXT_API_URL","LMTEXT_API_URL"),lmsound:ao("https://lmctl.ai/tools/lmsound","LMCTL_LMSOUND_API_URL")});function rd(e,t){let r=$S[e];return(t[r.overrideEnv]?.trim()||r.defaultUrl).replace(/\/+$/,"")}function kS(e,t){let r=$S[e];return{...t,[r.serviceEnv]:rd(e,t)}}function ao(e,t,r){return{defaultUrl:e,overrideEnv:t,...r?{serviceEnv:r}:{}}}var FU={lmchat:(e,t)=>ZT(e,t),lmmail:(e,t)=>Tb(e,t),lmnote:(e,t)=>qb(e,t),lmsheet:(e,t)=>aS(e,t),lmtext:(e,t)=>AS(e,t)},qU={lmchat:Ju,lmmail:Ku,lmnote:Yu,lmsheet:Xu,lmtext:td},jU=Object.freeze({lmchat:new Set(["delete","delete-room"]),lmmail:new Set(["delete"]),lmnote:new Set(["delete"]),lmsheet:new Set(["delete-row","delete-sheet"]),lmtext:new Set(["delete"])});async function xS(e,t,r={}){let n=r.env??process.env,o=r.stdout??(_=>process.stdout.write(_)),s=r.stderr??(_=>process.stderr.write(_)),i=r.resolveAppkeyImpl??Se,a=r.serviceRunners??FU,c=r.serviceParsers??qU,l=r.fetchImpl??fetch,u=t.indexOf("--force"),d=u!==-1,m=d?[...t.slice(0,u),...t.slice(u+1)]:t,f=m.length===0||m.length===1&&(m[0]==="--help"||m[0]==="-h");if(!f){let _=m[0];if(_!==void 0&&jU[e].has(_)&&!d)return o(`lmbee ${e}: refusing to run "${_}" without --force -- this permanently deletes data. Re-run with --force to proceed.
892
- `),1}let p=m.length===0?["--help"]:m,h=process.exitCode,w;try{let _=kS(e,n);if(!f){try{c[e](p)}catch(S){throw S instanceof Error&&S.constructor.name==="UsageError"?new so(e,S):S}_.LMCTL_APPKEY=i({env:n}).appkey}let T=HU(_,o,s,async(S,N)=>{let x=await l(S,N);return x.ok||(w=x.status),x});await a[e](p,T);let v=process.exitCode;if(v!=null&&v!==0&&v!==h){let S=typeof v=="number"?v:Number(v);throw new io(e,S)}return 0}catch(_){if(f)return o(`${WU(_)}
893
- `),0;throw w!==void 0&&!BU(_)?new oo(e,w,_):_}finally{process.exitCode=h}}function HU(e,t,r,n){return{env:e,fetch:n,stdout:o=>t(`${o}
891
+ `)),sleep:e.sleep??(t=>new Promise(r=>setTimeout(r,t))),readFile:e.readFile??(t=>LU(t)),stat:e.stat??(t=>IU(t))}}var dn=class extends Error{};var Es=class extends Error{status;responseBody;constructor(t,r){super(`HTTP ${t}${r?` ${r}`:""}`),this.status=t,this.responseBody=r,this.name="HttpResponseError"}},io=class extends Error{service;status;cause;constructor(t,r,n){super(`${t} request failed: HTTP ${r}`),this.service=t,this.status=r,this.cause=n,this.name="AdapterHttpError"}},ao=class extends Error{service;cause;constructor(t,r){super(r instanceof Error?r.message:String(r)),this.service=t,this.cause=r,this.name="ServiceCliUsageError"}},co=class extends Error{service;exitCode;constructor(t,r){super(`${t} CLI reported exit code ${r}`),this.service=t,this.exitCode=r,this.name="ServiceCliExitError"}};async function $a(e){if(!e.ok)throw new Es(e.status,await e.text().catch(()=>""))}var LS=Object.freeze({lmchat:lo("https://lmctl.ai/tools/lmchat","LMCTL_LMCHAT_API_URL","LMCHAT_API_URL"),lmmail:lo("https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMMAIL_API_URL","LMMAIL_API_URL"),lmnote:lo("https://vijni9tfxh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMNOTE_API_URL","LMNOTE_API_URL"),lmsheet:lo("https://9zdvg8wfjh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMSHEET_API_URL","LMSHEET_API_URL"),lmtext:lo("https://bxdbjn5k90.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMTEXT_API_URL","LMTEXT_API_URL"),lmsound:lo("https://lmctl.ai/tools/lmsound","LMCTL_LMSOUND_API_URL")});function sd(e,t){let r=LS[e];return(t[r.overrideEnv]?.trim()||r.defaultUrl).replace(/\/+$/,"")}function IS(e,t){let r=LS[e];return{...t,[r.serviceEnv]:sd(e,t)}}function lo(e,t,r){return{defaultUrl:e,overrideEnv:t,...r?{serviceEnv:r}:{}}}var VU={lmchat:(e,t)=>ob(e,t),lmmail:(e,t)=>kb(e,t),lmnote:(e,t)=>Gb(e,t),lmsheet:(e,t)=>mS(e,t),lmtext:(e,t)=>NS(e,t)},JU={lmchat:Yu,lmmail:Qu,lmnote:Zu,lmsheet:td,lmtext:od},KU=Object.freeze({lmchat:new Set(["delete","delete-room"]),lmmail:new Set(["delete"]),lmnote:new Set(["delete"]),lmsheet:new Set(["delete-row","delete-sheet"]),lmtext:new Set(["delete"])});async function CS(e,t,r={}){let n=r.env??process.env,o=r.stdout??(_=>process.stdout.write(_)),s=r.stderr??(_=>process.stderr.write(_)),i=r.resolveAppkeyImpl??Se,a=r.serviceRunners??VU,c=r.serviceParsers??JU,l=r.fetchImpl??fetch,u=t.indexOf("--force"),d=u!==-1,m=d?[...t.slice(0,u),...t.slice(u+1)]:t,f=m.length===0||m.length===1&&(m[0]==="--help"||m[0]==="-h");if(!f){let _=m[0];if(_!==void 0&&KU[e].has(_)&&!d)return o(`lmbee ${e}: refusing to run "${_}" without --force -- this permanently deletes data. Re-run with --force to proceed.
892
+ `),1}let p=m.length===0?["--help"]:m,h=process.exitCode,w;try{let _=IS(e,n);if(!f){try{c[e](p)}catch(S){throw S instanceof Error&&S.constructor.name==="UsageError"?new ao(e,S):S}_.LMCTL_APPKEY=i({env:n}).appkey}let E=zU(_,o,s,async(S,N)=>{let $=await l(S,N);return $.ok||(w=$.status),$});await a[e](p,E);let v=process.exitCode;if(v!=null&&v!==0&&v!==h){let S=typeof v=="number"?v:Number(v);throw new co(e,S)}return 0}catch(_){if(f)return o(`${QU(_)}
893
+ `),0;throw w!==void 0&&!YU(_)?new io(e,w,_):_}finally{process.exitCode=h}}function zU(e,t,r,n){return{env:e,fetch:n,stdout:o=>t(`${o}
894
894
  `),stderr:o=>r(`${o}
895
- `),sleep:o=>new Promise(s=>setTimeout(s,o)),readFile:(o,s)=>MU(o,s),writeFile:(o,s)=>UU(o,s),mkdir:(o,s)=>DU(o,s),stat:o=>PU(o)}}function BU(e){return!!(e&&typeof e=="object"&&"status"in e&&typeof e.status=="number")}function WU(e){return e instanceof Error?e.message:String(e)}import{writeFile as GU}from"node:fs/promises";function co(e,t,r){let n=e.indexOf(t);if(n<0)return;let o=e[n+1];if(!o||o.startsWith("--"))throw r(`${t} requires a value`);return e.splice(n,2),o}var pr=class extends Error{};function VU(){return["usage:",' lmbee lmsound speak "text" [--voice ID] [--engine ENGINE] [--format FORMAT] [--out FILE]'," lmbee lmsound voices"].join(`
896
- `)}function Aa(e,t){return co(e,t,r=>new pr(r))}function JU(e){let t=[...e],r=t.shift();if(r==="voices"){if(t.length)throw new pr(`unexpected argument: ${t[0]}`);return{kind:"voices"}}if(r==="speak"){let n=t.shift();if(!n)throw new pr("lmsound speak requires text");let o=Aa(t,"--voice"),s=Aa(t,"--engine"),i=Aa(t,"--format"),a=Aa(t,"--out");if(t.length)throw new pr(`unexpected argument: ${t[0]}`);return{kind:"speak",text:n,...o?{voice:o}:{},...s?{engine:s}:{},...i?{format:i}:{},...a?{out:a}:{}}}throw new pr(`unknown lmsound command: ${r??""}`)}async function RS(e,t={}){if(e.length===0||e.length===1&&(e[0]==="--help"||e[0]==="-h"))return VU();let r=t.env??process.env,n=t.resolveAppkeyImpl??Se,o=t.fetchImpl??fetch,s=t.writeFileImpl??GU,i=JU(e),a=n({env:r}).appkey,c=rd("lmsound",r),l={authorization:`Bearer ${a}`};if(i.kind==="voices"){let f=await o(`${c}/voices`,{headers:l});await va(f);let p=await f.json(),h=["id name language gender engines"];for(let w of p.voices??[])h.push(`${w.id} ${w.name} ${w.language_code} ${w.gender} ${w.supported_engines.join(",")}`);return h.join(`
897
- `)}let u=await o(`${c}/speak`,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify({text:i.text,...i.voice?{voice_id:i.voice}:{},...i.engine?{engine:i.engine}:{},...i.format?{format:i.format}:{}})});await va(u);let d=await u.json();if(typeof d.download_url!="string")throw new Error("lmsound response missing download_url");if(!i.out)return d.download_url;let m=await o(d.download_url);return await va(m),await s(i.out,new Uint8Array(await m.arrayBuffer())),`saved ${i.out}`}var KU=new Set(["lmchat","lmmail","lmnote","lmsheet","lmtext"]);function NS(e){return KU.has(e)}async function IS(e,t){try{return await xS(e,[...t])}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
898
- `),CS(r)}}async function LS(e){try{return{output:await RS(e),exitCode:0}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:CS(t)}}}function CS(e){if(e instanceof so||e instanceof pr)return 2;if(e instanceof io)return zU(e.exitCode);if(e instanceof Gr||e instanceof Es)return 3;if(e instanceof sr||e instanceof Ts)return 4;let t=e instanceof gs||e instanceof oo?e.status:void 0;return t===401||t===403?3:YU(e)?4:1}function zU(e){return Number.isInteger(e)&&e>0&&e<=255?e:1}function YU(e){if(!(e instanceof Error))return!1;let t=e.code,r=e.cause,n=typeof t=="string"?t:typeof r?.code=="string"?r.code:"";return/^(ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR_)/.test(n)}import{randomUUID as AF}from"node:crypto";import{randomUUID as XU}from"node:crypto";import{hostname as ZU,userInfo as eF}from"node:os";var tF=120,OS=60,rF=20,nF=1e3,oF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function nd(e,t,r){try{await e.createMailbox(t,{tolerate409:!1});return}catch(o){if(!sF(o))throw o}let n=5;for(let o=1;o<=n;o+=1){if((await e.listMailboxes()).some(i=>i.mailbox_name===t))return;o<n&&await r(100*2**(o-1))}throw new Error(`refusing exec: reply mailbox ${t} is not owned by the current user`)}function sF(e){if(!e||typeof e!="object")return!1;let t=e;return t.status===409&&t.code==="mailbox_exists"}async function od(e,t){let r=Xl({v:1,type:Ql,id:t.id,command:t.command,timeout_s:t.timeoutSeconds??OS,reply_to:t.replyMailbox});await e.sendMessage({mailbox:t.daemonMailbox,subject:`exec ${t.id}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(r),"utf8")}})}async function sd(e,t,r,n,o,s={}){let i=new Set(r),a=new Map,c=s.longPoll??{supported:!0};for(;i.size>0&&o.now()<n;){let l=0;for(;i.size>0;){let d=n-o.now();if(d<=0)return a;let m=await iF(e,t,l,d,c);for(let f of m.messages){let p=uF(f.subject,i);if(p)try{let h=await lF(e,t,f.seq,p,o.now);a.set(p,h),i.delete(p)}catch(h){s.onMalformed?.(h)}}if(i.size===0)return a;if(m.messages.length===0||m.next_after<=l)break;l=m.next_after}let u=n-o.now();if(u<=0)break;await o.sleep(Math.min(nF,u))}return a}async function iF(e,t,r,n,o){let s=o.supported?Math.min(rF,Math.floor(n/1e3)):0,i={status:"unread",after:r,...s>0?{wait_s:s}:{}};try{return await e.listMessages(t,i)}catch(a){if(!o.supported||s===0||!aF(a))throw a;return o.supported=!1,await e.listMessages(t,{status:"unread",after:r})}}function aF(e){let t=e;return t?.status===400&&t.code==="wait_s_invalid"}function DS(e,t){return`lmexec-replies-${`${e}-${t}`.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[^A-Za-z0-9]+/,"").replace(/[.-]+$/,"")||"user-host"}`.slice(0,128).replace(/[.-]+$/,"")}function MS(e){return DS(e,"fleet")}function cF(e){return oF.test(e)?yn(e.toLowerCase()):e}async function lF(e,t,r,n,o){let s=await e.getMessage(t,r),i=Buffer.from(await e.download(s.body.download_url)).toString("utf8"),a=E_(i);if(a.id!==n)throw new Error("reply body id does not match subject id");let c=new Map(await Promise.all(s.attachments.map(async d=>[d.name,Buffer.from(await e.download(d.download_url)).toString("utf8")]))),l=c.get("stdout.txt")??a.stdout,u=c.get("stderr.txt")??a.stderr;return{result:a,stdout:l,stderr:u,receivedAt:o()}}function uF(e,t){for(let r of t)if(e===Zl(r))return r}var Lt=class extends Error{};async function PS(e,t,r={}){let n=r.env??process.env,o=r.resolveAppkeyImpl??Se,s=r.createMailClientImpl??pt,i=r.now??Date.now,a=r.sleep??(S=>new Promise(N=>setTimeout(N,S))),c=r.username??(()=>eF().username),l=r.hostname??ZU,u=r.waitSeconds??tF;if(!Number.isFinite(u)||u<=0)throw new Lt("--wait-s must be positive");let d=r.replyMailbox??(n.LMEXEC_REPLY_MAILBOX?.trim()||DS(c(),l())),{appkey:m}=o({env:n}),f=s({apiUrl:$t(n),appkey:m}),p=XU();await nd(f,d,a),await od(f,{id:p,daemonMailbox:cF(e),command:t,replyMailbox:d,timeoutSeconds:OS});let h=[],w=i()+Math.round(u*1e3),E=(await sd(f,d,new Set([p]),w,{now:i,sleep:a},{onMalformed:S=>h.push(`[lmbee exec] ignored malformed matching reply: ${S instanceof Error?S.message:String(S)}
899
- `)})).get(p);if(!E)return{stdout:"",stderr:`${h.join("")}[lmbee exec] timed out waiting for a reply
900
- `,exitCode:124};let T=E.result.v===2?` trust=${E.result.sender_trust} sender=${E.result.sender}`:"",v=`[lmbee exec] exit=${E.result.exit_code===null?"timeout":E.result.exit_code} duration_ms=${E.result.duration_ms} truncated=${E.result.truncated}${T}
901
- `;return{stdout:E.stdout,stderr:`${E.stderr}${v}`,exitCode:E.result.exit_code??124}}import{randomUUID as dF}from"node:crypto";import{mkdir as mF,readFile as fF,rename as pF,rm as hF,writeFile as gF}from"node:fs/promises";import{dirname as qS,join as _F}from"node:path";var jS=2,wF=/^[A-Za-z0-9_-]+$/,id=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Me=class extends Error{};function HS(){return _F(qS(ar()),"lmt-peers.json")}function tr(e,t){if(!id.test(e))throw new Me(`${t} must be a UUID`);return e.toLowerCase()}function ad(e){return id.test(e)}function BS(e){return $a(e,"peer alias")}function $a(e,t){if(e.length>128||!wF.test(e))throw new Me(`${t} must match [A-Za-z0-9_-]+`);if(id.test(e))throw new Me(`${t} must not be a UUID`);return e}function _s(e,t){try{return fm(e,t)}catch(r){throw new Me(r instanceof Error?r.message:String(r))}}function US(){return Object.create(null)}async function ws(){let e=HS(),t;try{t=await fF(e,"utf8")}catch(i){if(i.code==="ENOENT")return US();throw i}let r;try{r=JSON.parse(t)}catch{throw new Error(`peer registry is invalid JSON: ${e}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`peer registry is invalid: ${e}`);let n=r;if(n.v!==jS||!n.peers||typeof n.peers!="object"||Array.isArray(n.peers))throw new Error(`peer registry is invalid: ${e}`);let o=US(),s=new Set;for(let[i,a]of Object.entries(n.peers)){if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`peer registry has invalid entry for ${i}`);let c=a;try{let l=tr(i,"peer registry site-uuid"),u=_s(l,FS(c.mailbox,`peer registry has invalid mailbox for ${i}`)),d=c.alias===void 0?void 0:BS(FS(c.alias,`peer registry has invalid alias for ${i}`));if(d){if(s.has(d))throw new Error(`peer registry has duplicate alias: ${d}`);s.add(d)}o[l]=d===void 0?{mailbox:u}:{mailbox:u,alias:d}}catch{throw new Error(`peer registry has invalid entry for ${i}`)}}return o}async function WS(e){let t=HS(),r={v:jS,peers:e},n=`${t}.${process.pid}.${dF()}.tmp`;await mF(qS(t),{recursive:!0});let o=!1;try{await gF(n,`${JSON.stringify(r,null,2)}
902
- `),await pF(n,t),o=!0}finally{if(!o)try{await hF(n)}catch(s){if(s.code!=="ENOENT")throw s}}}function yF(e,t,r){if(r!==void 0){for(let[n,o]of Object.entries(e))if(n!==t&&o.alias===r)throw new Error(`peer alias already registered: ${r}`)}}function GS(e,t){for(let[r,n]of Object.entries(t))if(n.alias===e)return{siteUuid:tr(r,"wire site-uuid"),mailbox:_s(r,n.mailbox)}}function FS(e,t){if(typeof e!="string")throw new Error(t);return e}async function VS(){let e=await ws(),t=["site-uuid alias mailbox"];for(let r of Object.keys(e).sort()){let n=e[r];t.push(`${r} ${n.alias??""} ${n.mailbox}`)}return t.join(`
903
- `)}async function JS(e,t,r){let n=tr(e,"site-uuid"),o=_s(n,t),s=await ws(),i=s[n],a=r===void 0?i?.alias:BS(r);return yF(s,n,a),s[n]=a===void 0?{mailbox:o}:{mailbox:o,alias:a},await WS(s),`peer ${n}${a?` (${a})`:""} -> ${o}`}async function KS(e){let t=tr(e,"site-uuid"),r=await ws();if(!Object.hasOwn(r,t))throw new Error(`unknown peer site-uuid: ${t}`);return delete r[t],await WS(r),`removed peer ${t}`}function lo(e){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??pt,{appkey:o}=r({env:t});return n({apiUrl:$t(t),appkey:o})}function ld(e){try{return Ya(e)}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function EF(e){if(e.includes("..")||e.endsWith(".")||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Me("--mailbox must be a valid mailbox name");return e}async function zS(e,t={}){let r=ld(e),n=t.siteUuid===void 0?await Us(ar()):tr(t.siteUuid,"--site-uuid"),o=t.mailbox??hn(n),s=lo(t),i;try{i=await s.registerSite(r,n,o)}catch(a){throw a instanceof Ft&&a.code==="site_name_taken"?new Error(`site name already registered to a different site in this account: ${r}`):a}return`registered ${i.site_name} -> ${i.site_uuid} (${i.mailbox})`}async function YS(e,t={}){let r=ld(e),n=lo(t),o;try{o=await n.resolveSite(r)}catch(s){if(!(s instanceof Ft&&s.status===404))throw s}return o?{output:`${o.site_name} ${o.site_uuid} ${o.mailbox}`,exitCode:0}:{output:`unknown site name in this account: ${r}`,exitCode:1}}async function ka(e){let t=new Map,r=new Map,n=new Set,o;do{let s=await e.listSites({limit:50,...o?{cursor:o}:{}});for(let i of s.sites)t.set(i.site_uuid.toLowerCase(),i);for(let i of s.discovered){let a=QS(i),c=r.get(a);(!c||i.last_seen_at>c.last_seen_at)&&r.set(a,i)}if(o=s.next_cursor,o){if(n.has(o))throw new Error("site listing returned a repeated cursor");n.add(o)}}while(o);return{sites:[...t.values()],discovered:[...r.values()]}}function QS(e){return e.site_uuid?`uuid#${e.site_uuid.toLowerCase()}`:`mailbox#${e.mailbox}#${e.owner_user_id}`}function TF(e){let t=[`uuid#${e.site_uuid.toLowerCase()}`],r=e.content_mailbox??e.mailbox,n=e.content_mailbox_owner_user_id??e.mailbox_owner_user_id;return n&&t.push(`mailbox#${r}#${n}`),e.exec_mailbox&&e.exec_mailbox_owner_user_id&&t.push(`mailbox#${e.exec_mailbox}#${e.exec_mailbox_owner_user_id}`),t}function bF(e,t){let r=new Set(e.flatMap(TF));return t.filter(n=>!r.has(QS(n))&&!r.has(`mailbox#${n.mailbox}#${n.owner_user_id}`))}function cd(e){return e.display_name??e.registered_name??e.site_name}function SF(e,t){let r=["REGISTERED","display-name registered-name site-uuid content-mailbox exec-mailbox"];for(let n of e.sort((o,s)=>cd(o).localeCompare(cd(s))))r.push([cd(n),n.registered_name??n.site_name,n.site_uuid,n.content_mailbox??n.mailbox,n.exec_mailbox??"-"].join(" "));r.push("","DISCOVERED","display-name site-uuid mailbox owner-user-id last-seen-at");for(let n of t.sort((o,s)=>s.last_seen_at-o.last_seen_at))r.push([n.name??"-",n.site_uuid??"-",n.mailbox,n.owner_user_id,n.last_seen_at].join(" "));return r.join(`
904
- `)}async function XS(e={}){let t=lo(e),r=await ka(t);return SF(r.sites,bF(r.sites,r.discovered))}async function vF(e,t){let r=await ka(e),n=[...new Set(r.discovered.filter(o=>o.mailbox===t).map(o=>o.owner_user_id))];if(n.length===0)throw new Error(`mailbox is not present in site discovery: ${t}`);if(n.length>1)throw new Error(`mailbox ownership changed during site discovery; retry: ${t}`);return{kind:"mailbox",value:t,owner_user_id:n[0]}}async function ZS(e,t,r){return t!==void 0?{kind:"uuid",value:tr(t,"--uuid")}:await vF(e,EF(r))}async function ev(e,t){let r=e.trim();if(!r)throw new Me("site display name must be non-empty");let n=lo(t),o=await ZS(n,t.uuid,t.mailbox),s=await n.setSiteName(o,r);return`named ${s.site_key} -> ${s.name}`}async function tv(e){let t=lo(e),r=await ZS(t,e.uuid,e.mailbox);return`cleared ${(await t.deleteSiteName(r)).site_key}`}async function rv(e,t={}){let r=ld(e);return await lo(t).deleteSite(r),`removed ${r}`}function jr(){return"usage: lmbee sites register <name> [--site-uuid <uuid>] [--mailbox <name>] | resolve <name> | list | set-name (--uuid <uuid> | --mailbox <name>) <name> | clear-name (--uuid <uuid> | --mailbox <name>) | remove <name>"}var $F=15,kF=60,xF="lmbee status --live --json";async function nv(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??pt,o=e.now??Date.now,s=e.sleep??(m=>new Promise(f=>setTimeout(f,m))),i=e.username??(()=>process.env.USER??process.env.USERNAME??"user"),a=e.waitSeconds??$F;if(!Number.isFinite(a)||a<=0)throw new Error("--wait-s must be positive");let{appkey:c}=r({env:t}),l=n({apiUrl:$t(t),appkey:c}),u=(await ka(l)).sites.sort((m,f)=>m.site_name.localeCompare(f.site_name)),d=MS(i());await nd(l,d,s);try{let m=u.map(v=>({site:v,execMailbox:yn(v.site_uuid),id:AF(),sentAt:o()}));await Promise.all(m.map(async v=>{try{await od(l,{id:v.id,daemonMailbox:v.execMailbox,command:xF,replyMailbox:d,timeoutSeconds:kF})}catch(S){v.sendError=S instanceof Error?S.message:String(S)}}));let f=o()+Math.round(a*1e3),p=new Set(m.filter(v=>v.sendError===void 0).map(v=>v.id)),h=await sd(l,d,p,f,{now:o,sleep:s}),w=m.filter(v=>v.sendError===void 0).length,_=h.size,E=u.length===0?"empty":_===u.length?"all":_===0?"none":"partial";return{verdict:E,exit_code:E==="none"?2:E==="partial"?3:0,sent:w,answered:_,sites:m.map(v=>RF(v,h.get(v.id))),generated_at:new Date(o()).toISOString()}}finally{await l.deleteMailbox(d)}}function RF(e,t){let r={site_name:e.site.site_name,site_uuid:e.site.site_uuid,mailbox:e.execMailbox};if(!t)return{...r,liveness:"stale",error:e.sendError??"no_reply"};let n={...r,liveness:"live",latency_ms:Math.max(0,t.receivedAt-e.sentAt)},o=NF(t);if(o)return{...n,error:o};if(t.result.exit_code!==0)return{...n,error:t.result.timed_out?"remote_timeout":`remote_exit_${t.result.exit_code}`};try{let s=JSON.parse(t.stdout);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("expected JSON object");return{...n,status:s}}catch{return{...n,error:"invalid_status_json"}}}function NF(e){if(e.result.exit_code===126)try{let t=JSON.parse(e.stderr);return typeof t.error?.code=="string"?t.error.code:"remote_rejected"}catch{return"remote_rejected"}}function ov(e){let t=["SITE LIVENESS LATENCY_MS TEAMS DAEMON ERROR"];for(let r of e.sites)t.push([r.site_name||r.site_uuid,r.liveness,r.latency_ms??"-",IF(r.status)??"-",LF(r.status)??"-",r.error??"-"].join(" "));return t.push(`Fleet: ${e.verdict} (sent ${e.sent}/${e.sites.length}, answered ${e.answered}/${e.sites.length}; exit ${e.exit_code})`),t.join(`
905
- `)}function IF(e){return Array.isArray(e?.teams)?e.teams.length:void 0}function LF(e){return typeof e?.live=="boolean"?`live:${e.live}`:void 0}function sv(){return"usage: lmbee exec <site-uuid-or-mailbox> [--wait-s N] <command...> | lmbee exec <site-uuid-or-mailbox> [--wait-s N] -- <literal command...>"}function ud(){return"usage: lmbee fleet status [--json] [--wait-s N]"}function iv(e,t){return co(e,t,r=>new Lt(r))}function CF(e){let t=e.indexOf("--"),r=t<0?[...e]:[...e.slice(0,t)],n=t<0?void 0:e.slice(t+1),o=iv(r,"--wait-s"),s=o===void 0?void 0:Number(o);if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new Lt("--wait-s must be positive");let i=r.shift();if(!i)throw new Lt(sv());let a=n??r;if(n&&r.length>0)throw new Lt(`unexpected argument before --: ${r[0]}`);if(a.length===0)throw new Lt(sv());return{target:i,command:a.join(" "),...s===void 0?{}:{waitSeconds:s}}}async function av(e){try{let{target:t,command:r,waitSeconds:n}=CF(e),o=await PS(t,r,{waitSeconds:n});return{output:`${o.stdout}${o.stderr}`.replace(/\n$/,""),exitCode:o.exitCode}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:t instanceof Lt?1:2}}}async function cv(e){let[t,...r]=e;if(t!=="status")return{output:ud(),exitCode:1};let n=r.includes("--json");try{let o=[...r],s=o.indexOf("--json");n&&o.splice(s,1);let i=iv(o,"--wait-s"),a=i===void 0?void 0:Number(i);if(a!==void 0&&(!Number.isFinite(a)||a<=0))return{output:ud(),exitCode:1};if(o.length>0)return{output:ud(),exitCode:1};let c=await nv({waitSeconds:a});return{output:n?JSON.stringify(c,null,2):ov(c),exitCode:c.exit_code}}catch(o){let s=o instanceof Error?o.message:String(o),i=o instanceof Lt?1:2;return{output:n?JSON.stringify({verdict:"error",exit_code:i,error:s},null,2):s,exitCode:i}}}import{cpSync as xa,existsSync as Hr,mkdirSync as OF,readFileSync as dd,readdirSync as DF,rmSync as lv,statSync as uv}from"node:fs";import{homedir as fv}from"node:os";import{join as Xe,sep as md}from"node:path";var uo=class extends Error{constructor(t){super(`migrate-home: refusing to run -- an lmauto daemon appears to be live (${t}). Stop it first (systemctl --user stop lmauto.service if it runs as a service, or kill the pid) before re-running.`),this.name="DaemonLiveError"}},fd=class extends Error{targetDbPath;sizeBytes;constructor(t,r){super(`migrate-home: refusing to replace an existing target database: ${t} already exists (${r} bytes). migrate-home never deletes a database it did not create this run. If this file is debris from an interrupted migrate-home run, or you are certain it is disposable, re-run with --replace-existing-target-db; otherwise move it aside yourself (e.g. \`mv ${t} ${t}.bak\`) and re-run.`),this.targetDbPath=t,this.sizeBytes=r,this.name="TargetDbExistsError"}};function pv(){return Xe(fv(),".lmauto")}function hv(){return Xe(process.env.LMCTL_HOME??Xe(fv(),".lmctl"),"lmauto")}function MF(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function PF(e){try{return(await fetch(`http://127.0.0.1:${e}/api/teams`,{signal:AbortSignal.timeout(1e3)})).body?.cancel(),!0}catch{return!1}}function UF(e,t){let r=Xe(e,"serve.pid");if(!Hr(r))return null;let n=dd(r,"utf8").trim(),o=Number(n);return!Number.isInteger(o)||o<=0?null:t(o)?o:null}var dv=["team_state","kv","events","queue","sources","team_progress","mail_ledger","mail_outbound_ledger"];function mv(e,t){return e.prepare(`SELECT COUNT(*) as n FROM ${t}`).get().n}function pd(e){if(!Hr(e))return 0;let t=0;for(let r of DF(e,{withFileTypes:!0}))r.isDirectory()?t+=pd(Xe(e,r.name)):t+=1;return t}function FF(e,t,r){let n=t.endsWith(md)?t:t+md,o=e.prepare("SELECT id, prompt_file FROM queue").all(),s=new Map(o.map(l=>[l.id,l.prompt_file])),i=o.filter(l=>l.prompt_file.startsWith(n)),a=e.prepare("UPDATE queue SET prompt_file = ? WHERE id = ?");return e.transaction(l=>{for(let u of l){let d=r+u.prompt_file.slice(t.length);a.run(d,u.id)}})(i),{rewrittenCount:i.length,originalPathById:s}}async function gv(e){let{sourceDir:t,targetDir:r,port:n=4173}=e,o=e.isDaemonAlive??MF,s=e.probeHttpAlive??PF,i=e.checkSiteLock??o_,a=Xe(t,"state.db"),c=Xe(r,"state.db"),l=i(a);if(l!==null)throw new uo(`${l.ownerLabel} pid ${l.pid} (site lock for ${a})`);let u=UF(t,o);if(u!==null)throw new uo(`pid ${u}, ${Xe(t,"serve.pid")}`);if(await s(n))throw new uo(`something is listening on port ${n}`);if(t===r||r.startsWith(t+md))throw new Error(`migrate-home: target (${r}) must not be, or be nested inside, source (${t})`);let d=e.acquireSiteLock??ra,m=Yo(a),f=[];try{f.push(d(m,"migrate-home")),f.push(d(Xe(t,"site.lock"),"migrate-home"))}catch(p){for(let h of f.splice(0))h.release();throw p instanceof Hn?new uo(`${p.holder.ownerLabel} pid ${p.holder.pid}, ${p.lockPath}`):p}try{OF(r,{recursive:!0});let p=!1,h=!1;if(Hr(a)){let oe=Hr(c);if(oe&&e.replaceExistingTargetDb!==!0)throw new fd(c,uv(c).size);let V=new ht(a);try{if(V.prepare("SELECT COUNT(*) AS n FROM sqlite_master").get(),oe){process.stderr.write(`migrate-home: replacing existing target database ${c} (${uv(c).size} bytes) with a snapshot of ${a} (explicit replaceExistingTargetDb consent)
906
- `);for(let se of["","-wal","-shm"])lv(c+se,{force:!0});h=!0}else for(let se of["-wal","-shm"])lv(c+se,{force:!0});V.prepare("VACUUM INTO ?").run(c)}finally{V.close()}p=!0}let w=Xe(t,"queue"),_=Xe(r,"queue"),E=pd(w);E>0&&xa(w,_,{recursive:!0});let T=Xe(t,"prompts"),v=Xe(r,"prompts"),S=pd(T);S>0&&xa(T,v,{recursive:!0});let N=Xe(t,"site-uuid"),x=Xe(r,"site-uuid"),I=!1,k=!1;Hr(N)&&(xa(N,x),I=!0,k=dd(N,"utf8")!==dd(x,"utf8"));let B=Xe(t,"lmt-peers.json"),C=Xe(r,"lmt-peers.json"),g=!1;Hr(B)&&(xa(B,C),g=!0);let y=0,R=0,P=[],J=[],ee={};if(p){let oe=new ht(a,{readonly:!0});try{for(let se of dv)ee[se]={source:mv(oe,se),target:0}}finally{oe.close()}let V=new ht(c);try{for(let A of dv)ee[A].target=mv(V,A);let{rewrittenCount:se,originalPathById:$}=FF(V,w,_);y=se;let O=V.prepare("SELECT id, prompt_file FROM queue").all();R=O.length;for(let A of O){if(Hr(A.prompt_file))continue;let q=$.get(A.id);Hr(q)?P.push(`#${A.id} -> ${A.prompt_file}`):J.push(`#${A.id} -> ${A.prompt_file}`)}}finally{V.close()}}return{sourceDir:t,targetDir:r,stateDbCopied:p,replacedExistingTargetDb:h,queueFilesCopied:E,promptFilesCopied:S,rewrittenPromptPaths:y,queueRowCount:R,missingPromptFiles:P,preExistingMissingPromptFiles:J,siteIdentityCopied:I,siteIdentityMismatch:k,lmtPeersCopied:g,rowCountParity:ee}}finally{for(let p of f.splice(0))p.release()}}async function _v(e={}){let t=e.source??pv(),r=e.target??hv(),n=await gv({sourceDir:t,targetDir:r,replaceExistingTargetDb:e.replaceExistingTargetDb});return{output:BF(n),exitCode:qF(n)}}function qF(e){return e.missingPromptFiles.length>0||e.siteIdentityMismatch||jF(e)?1:0}function jF(e){return Object.values(e.rowCountParity).some(t=>t.source!==t.target)}function HF(e){let t=Object.entries(e).filter(([,r])=>r.source!==r.target);return t.length===0?` table row-count parity: OK (${Object.keys(e).length} table(s) checked, all match)`:` PARITY CHECK FAILED -- ${t.length} table(s) with a source/target row-count mismatch:
895
+ `),sleep:o=>new Promise(s=>setTimeout(s,o)),readFile:(o,s)=>BU(o,s),writeFile:(o,s)=>GU(o,s),mkdir:(o,s)=>HU(o,s),stat:o=>WU(o)}}function YU(e){return!!(e&&typeof e=="object"&&"status"in e&&typeof e.status=="number")}function QU(e){return e instanceof Error?e.message:String(e)}import{writeFile as XU}from"node:fs/promises";function uo(e,t,r){let n=e.indexOf(t);if(n<0)return;let o=e[n+1];if(!o||o.startsWith("--"))throw r(`${t} requires a value`);return e.splice(n,2),o}var hr=class extends Error{};function ZU(){return["usage:",' lmbee lmsound speak "text" [--voice ID] [--engine ENGINE] [--format FORMAT] [--out FILE]'," lmbee lmsound voices"].join(`
896
+ `)}function xa(e,t){return uo(e,t,r=>new hr(r))}function eF(e){let t=[...e],r=t.shift();if(r==="voices"){if(t.length)throw new hr(`unexpected argument: ${t[0]}`);return{kind:"voices"}}if(r==="speak"){let n=t.shift();if(!n)throw new hr("lmsound speak requires text");let o=xa(t,"--voice"),s=xa(t,"--engine"),i=xa(t,"--format"),a=xa(t,"--out");if(t.length)throw new hr(`unexpected argument: ${t[0]}`);return{kind:"speak",text:n,...o?{voice:o}:{},...s?{engine:s}:{},...i?{format:i}:{},...a?{out:a}:{}}}throw new hr(`unknown lmsound command: ${r??""}`)}async function OS(e,t={}){if(e.length===0||e.length===1&&(e[0]==="--help"||e[0]==="-h"))return ZU();let r=t.env??process.env,n=t.resolveAppkeyImpl??Se,o=t.fetchImpl??fetch,s=t.writeFileImpl??XU,i=eF(e),a=n({env:r}).appkey,c=sd("lmsound",r),l={authorization:`Bearer ${a}`};if(i.kind==="voices"){let f=await o(`${c}/voices`,{headers:l});await $a(f);let p=await f.json(),h=["id name language gender engines"];for(let w of p.voices??[])h.push(`${w.id} ${w.name} ${w.language_code} ${w.gender} ${w.supported_engines.join(",")}`);return h.join(`
897
+ `)}let u=await o(`${c}/speak`,{method:"POST",headers:{...l,"content-type":"application/json"},body:JSON.stringify({text:i.text,...i.voice?{voice_id:i.voice}:{},...i.engine?{engine:i.engine}:{},...i.format?{format:i.format}:{}})});await $a(u);let d=await u.json();if(typeof d.download_url!="string")throw new Error("lmsound response missing download_url");if(!i.out)return d.download_url;let m=await o(d.download_url);return await $a(m),await s(i.out,new Uint8Array(await m.arrayBuffer())),`saved ${i.out}`}var tF=new Set(["lmchat","lmmail","lmnote","lmsheet","lmtext"]);function DS(e){return tF.has(e)}async function MS(e,t){try{return await CS(e,[...t])}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
898
+ `),US(r)}}async function PS(e){try{return{output:await OS(e),exitCode:0}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:US(t)}}}function US(e){if(e instanceof ao||e instanceof hr)return 2;if(e instanceof co)return rF(e.exitCode);if(e instanceof Gr||e instanceof vs)return 3;if(e instanceof sr||e instanceof As)return 4;let t=e instanceof Es||e instanceof io?e.status:void 0;return t===401||t===403?3:nF(e)?4:1}function rF(e){return Number.isInteger(e)&&e>0&&e<=255?e:1}function nF(e){if(!(e instanceof Error))return!1;let t=e.code,r=e.cause,n=typeof t=="string"?t:typeof r?.code=="string"?r.code:"";return/^(ECONNREFUSED|ECONNRESET|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|UND_ERR_)/.test(n)}import{randomUUID as IF}from"node:crypto";import{randomUUID as sF}from"node:crypto";import{hostname as iF,userInfo as aF}from"node:os";var cF=120,FS=60,lF=20,uF=1e3,dF=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function id(e,t,r){try{await e.createMailbox(t,{tolerate409:!1});return}catch(o){if(!mF(o))throw o}let n=5;for(let o=1;o<=n;o+=1){if((await e.listMailboxes()).some(i=>i.mailbox_name===t))return;o<n&&await r(100*2**(o-1))}throw new Error(`refusing exec: reply mailbox ${t} is not owned by the current user`)}function mF(e){if(!e||typeof e!="object")return!1;let t=e;return t.status===409&&t.code==="mailbox_exists"}async function ad(e,t){let r=tu({v:1,type:eu,id:t.id,command:t.command,timeout_s:t.timeoutSeconds??FS,reply_to:t.replyMailbox});await e.sendMessage({mailbox:t.daemonMailbox,subject:`exec ${t.id}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(r),"utf8")}})}async function cd(e,t,r,n,o,s={}){let i=new Set(r),a=new Map,c=s.longPoll??{supported:!0};for(;i.size>0&&o.now()<n;){let l=0;for(;i.size>0;){let d=n-o.now();if(d<=0)return a;let m=await fF(e,t,l,d,c);for(let f of m.messages){let p=_F(f.subject,i);if(p)try{let h=await gF(e,t,f.seq,p,o.now);a.set(p,h),i.delete(p)}catch(h){s.onMalformed?.(h)}}if(i.size===0)return a;if(m.messages.length===0||m.next_after<=l)break;l=m.next_after}let u=n-o.now();if(u<=0)break;await o.sleep(Math.min(uF,u))}return a}async function fF(e,t,r,n,o){let s=o.supported?Math.min(lF,Math.floor(n/1e3)):0,i={status:"unread",after:r,...s>0?{wait_s:s}:{}};try{return await e.listMessages(t,i)}catch(a){if(!o.supported||s===0||!pF(a))throw a;return o.supported=!1,await e.listMessages(t,{status:"unread",after:r})}}function pF(e){let t=e;return t?.status===400&&t.code==="wait_s_invalid"}function qS(e,t){return`lmexec-replies-${`${e}-${t}`.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[^A-Za-z0-9]+/,"").replace(/[.-]+$/,"")||"user-host"}`.slice(0,128).replace(/[.-]+$/,"")}function jS(e){return qS(e,"fleet")}function hF(e){return dF.test(e)?yn(e.toLowerCase()):e}async function gF(e,t,r,n,o){let s=await e.getMessage(t,r),i=Buffer.from(await e.download(s.body.download_url)).toString("utf8"),a=A_(i);if(a.id!==n)throw new Error("reply body id does not match subject id");let c=new Map(await Promise.all(s.attachments.map(async d=>[d.name,Buffer.from(await e.download(d.download_url)).toString("utf8")]))),l=c.get("stdout.txt")??a.stdout,u=c.get("stderr.txt")??a.stderr;return{result:a,stdout:l,stderr:u,receivedAt:o()}}function _F(e,t){for(let r of t)if(e===ru(r))return r}var It=class extends Error{};async function HS(e,t,r={}){let n=r.env??process.env,o=r.resolveAppkeyImpl??Se,s=r.createMailClientImpl??pt,i=r.now??Date.now,a=r.sleep??(S=>new Promise(N=>setTimeout(N,S))),c=r.username??(()=>aF().username),l=r.hostname??iF,u=r.waitSeconds??cF;if(!Number.isFinite(u)||u<=0)throw new It("--wait-s must be positive");let d=r.replyMailbox??(n.LMEXEC_REPLY_MAILBOX?.trim()||qS(c(),l())),{appkey:m}=o({env:n}),f=s({apiUrl:kt(n),appkey:m}),p=sF();await id(f,d,a),await ad(f,{id:p,daemonMailbox:hF(e),command:t,replyMailbox:d,timeoutSeconds:FS});let h=[],w=i()+Math.round(u*1e3),T=(await cd(f,d,new Set([p]),w,{now:i,sleep:a},{onMalformed:S=>h.push(`[lmbee exec] ignored malformed matching reply: ${S instanceof Error?S.message:String(S)}
899
+ `)})).get(p);if(!T)return{stdout:"",stderr:`${h.join("")}[lmbee exec] timed out waiting for a reply
900
+ `,exitCode:124};let E=T.result.v===2?` trust=${T.result.sender_trust} sender=${T.result.sender}`:"",v=`[lmbee exec] exit=${T.result.exit_code===null?"timeout":T.result.exit_code} duration_ms=${T.result.duration_ms} truncated=${T.result.truncated}${E}
901
+ `;return{stdout:T.stdout,stderr:`${T.stderr}${v}`,exitCode:T.result.exit_code??124}}import{randomUUID as wF}from"node:crypto";import{mkdir as yF,readFile as EF,rename as TF,rm as bF,writeFile as SF}from"node:fs/promises";import{dirname as GS,join as vF}from"node:path";var VS=2,AF=/^[A-Za-z0-9_-]+$/,ld=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Me=class extends Error{};function JS(){return vF(GS(ar()),"lmt-peers.json")}function tr(e,t){if(!ld.test(e))throw new Me(`${t} must be a UUID`);return e.toLowerCase()}function ud(e){return ld.test(e)}function KS(e){return Ra(e,"peer alias")}function Ra(e,t){if(e.length>128||!AF.test(e))throw new Me(`${t} must match [A-Za-z0-9_-]+`);if(ld.test(e))throw new Me(`${t} must not be a UUID`);return e}function Ts(e,t){try{return gm(e,t)}catch(r){throw new Me(r instanceof Error?r.message:String(r))}}function BS(){return Object.create(null)}async function bs(){let e=JS(),t;try{t=await EF(e,"utf8")}catch(i){if(i.code==="ENOENT")return BS();throw i}let r;try{r=JSON.parse(t)}catch{throw new Error(`peer registry is invalid JSON: ${e}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`peer registry is invalid: ${e}`);let n=r;if(n.v!==VS||!n.peers||typeof n.peers!="object"||Array.isArray(n.peers))throw new Error(`peer registry is invalid: ${e}`);let o=BS(),s=new Set;for(let[i,a]of Object.entries(n.peers)){if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`peer registry has invalid entry for ${i}`);let c=a;try{let l=tr(i,"peer registry site-uuid"),u=Ts(l,WS(c.mailbox,`peer registry has invalid mailbox for ${i}`)),d=c.alias===void 0?void 0:KS(WS(c.alias,`peer registry has invalid alias for ${i}`));if(d){if(s.has(d))throw new Error(`peer registry has duplicate alias: ${d}`);s.add(d)}o[l]=d===void 0?{mailbox:u}:{mailbox:u,alias:d}}catch{throw new Error(`peer registry has invalid entry for ${i}`)}}return o}async function zS(e){let t=JS(),r={v:VS,peers:e},n=`${t}.${process.pid}.${wF()}.tmp`;await yF(GS(t),{recursive:!0});let o=!1;try{await SF(n,`${JSON.stringify(r,null,2)}
902
+ `),await TF(n,t),o=!0}finally{if(!o)try{await bF(n)}catch(s){if(s.code!=="ENOENT")throw s}}}function kF(e,t,r){if(r!==void 0){for(let[n,o]of Object.entries(e))if(n!==t&&o.alias===r)throw new Error(`peer alias already registered: ${r}`)}}function YS(e,t){for(let[r,n]of Object.entries(t))if(n.alias===e)return{siteUuid:tr(r,"wire site-uuid"),mailbox:Ts(r,n.mailbox)}}function WS(e,t){if(typeof e!="string")throw new Error(t);return e}async function QS(){let e=await bs(),t=["site-uuid alias mailbox"];for(let r of Object.keys(e).sort()){let n=e[r];t.push(`${r} ${n.alias??""} ${n.mailbox}`)}return t.join(`
903
+ `)}async function XS(e,t,r){let n=tr(e,"site-uuid"),o=Ts(n,t),s=await bs(),i=s[n],a=r===void 0?i?.alias:KS(r);return kF(s,n,a),s[n]=a===void 0?{mailbox:o}:{mailbox:o,alias:a},await zS(s),`peer ${n}${a?` (${a})`:""} -> ${o}`}async function ZS(e){let t=tr(e,"site-uuid"),r=await bs();if(!Object.hasOwn(r,t))throw new Error(`unknown peer site-uuid: ${t}`);return delete r[t],await zS(r),`removed peer ${t}`}function mo(e){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??pt,{appkey:o}=r({env:t});return n({apiUrl:kt(t),appkey:o})}function md(e){try{return Za(e)}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function $F(e){if(e.includes("..")||e.endsWith(".")||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(e))throw new Me("--mailbox must be a valid mailbox name");return e}async function ev(e,t={}){let r=md(e),n=t.siteUuid===void 0?await Hs(ar()):tr(t.siteUuid,"--site-uuid"),o=t.mailbox??hn(n),s=mo(t),i;try{i=await s.registerSite(r,n,o)}catch(a){throw a instanceof Ft&&a.code==="site_name_taken"?new Error(`site name already registered to a different site in this account: ${r}`):a}return`registered ${i.site_name} -> ${i.site_uuid} (${i.mailbox})`}async function tv(e,t={}){let r=md(e),n=mo(t),o;try{o=await n.resolveSite(r)}catch(s){if(!(s instanceof Ft&&s.status===404))throw s}return o?{output:`${o.site_name} ${o.site_uuid} ${o.mailbox}`,exitCode:0}:{output:`unknown site name in this account: ${r}`,exitCode:1}}async function Na(e){let t=new Map,r=new Map,n=new Set,o;do{let s=await e.listSites({limit:50,...o?{cursor:o}:{}});for(let i of s.sites)t.set(i.site_uuid.toLowerCase(),i);for(let i of s.discovered){let a=rv(i),c=r.get(a);(!c||i.last_seen_at>c.last_seen_at)&&r.set(a,i)}if(o=s.next_cursor,o){if(n.has(o))throw new Error("site listing returned a repeated cursor");n.add(o)}}while(o);return{sites:[...t.values()],discovered:[...r.values()]}}function rv(e){return e.site_uuid?`uuid#${e.site_uuid.toLowerCase()}`:`mailbox#${e.mailbox}#${e.owner_user_id}`}function xF(e){let t=[`uuid#${e.site_uuid.toLowerCase()}`],r=e.content_mailbox??e.mailbox,n=e.content_mailbox_owner_user_id??e.mailbox_owner_user_id;return n&&t.push(`mailbox#${r}#${n}`),e.exec_mailbox&&e.exec_mailbox_owner_user_id&&t.push(`mailbox#${e.exec_mailbox}#${e.exec_mailbox_owner_user_id}`),t}function RF(e,t){let r=new Set(e.flatMap(xF));return t.filter(n=>!r.has(rv(n))&&!r.has(`mailbox#${n.mailbox}#${n.owner_user_id}`))}function dd(e){return e.display_name??e.registered_name??e.site_name}function NF(e,t){let r=["REGISTERED","display-name registered-name site-uuid content-mailbox exec-mailbox"];for(let n of e.sort((o,s)=>dd(o).localeCompare(dd(s))))r.push([dd(n),n.registered_name??n.site_name,n.site_uuid,n.content_mailbox??n.mailbox,n.exec_mailbox??"-"].join(" "));r.push("","DISCOVERED","display-name site-uuid mailbox owner-user-id last-seen-at");for(let n of t.sort((o,s)=>s.last_seen_at-o.last_seen_at))r.push([n.name??"-",n.site_uuid??"-",n.mailbox,n.owner_user_id,n.last_seen_at].join(" "));return r.join(`
904
+ `)}async function nv(e={}){let t=mo(e),r=await Na(t);return NF(r.sites,RF(r.sites,r.discovered))}async function LF(e,t){let r=await Na(e),n=[...new Set(r.discovered.filter(o=>o.mailbox===t).map(o=>o.owner_user_id))];if(n.length===0)throw new Error(`mailbox is not present in site discovery: ${t}`);if(n.length>1)throw new Error(`mailbox ownership changed during site discovery; retry: ${t}`);return{kind:"mailbox",value:t,owner_user_id:n[0]}}async function ov(e,t,r){return t!==void 0?{kind:"uuid",value:tr(t,"--uuid")}:await LF(e,$F(r))}async function sv(e,t){let r=e.trim();if(!r)throw new Me("site display name must be non-empty");let n=mo(t),o=await ov(n,t.uuid,t.mailbox),s=await n.setSiteName(o,r);return`named ${s.site_key} -> ${s.name}`}async function iv(e){let t=mo(e),r=await ov(t,e.uuid,e.mailbox);return`cleared ${(await t.deleteSiteName(r)).site_key}`}async function av(e,t={}){let r=md(e);return await mo(t).deleteSite(r),`removed ${r}`}function jr(){return"usage: lmbee sites register <name> [--site-uuid <uuid>] [--mailbox <name>] | resolve <name> | list | set-name (--uuid <uuid> | --mailbox <name>) <name> | clear-name (--uuid <uuid> | --mailbox <name>) | remove <name>"}var CF=15,OF=60,DF="lmbee status --live --json";async function cv(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??pt,o=e.now??Date.now,s=e.sleep??(m=>new Promise(f=>setTimeout(f,m))),i=e.username??(()=>process.env.USER??process.env.USERNAME??"user"),a=e.waitSeconds??CF;if(!Number.isFinite(a)||a<=0)throw new Error("--wait-s must be positive");let{appkey:c}=r({env:t}),l=n({apiUrl:kt(t),appkey:c}),u=(await Na(l)).sites.sort((m,f)=>m.site_name.localeCompare(f.site_name)),d=jS(i());await id(l,d,s);try{let m=u.map(v=>({site:v,execMailbox:yn(v.site_uuid),id:IF(),sentAt:o()}));await Promise.all(m.map(async v=>{try{await ad(l,{id:v.id,daemonMailbox:v.execMailbox,command:DF,replyMailbox:d,timeoutSeconds:OF})}catch(S){v.sendError=S instanceof Error?S.message:String(S)}}));let f=o()+Math.round(a*1e3),p=new Set(m.filter(v=>v.sendError===void 0).map(v=>v.id)),h=await cd(l,d,p,f,{now:o,sleep:s}),w=m.filter(v=>v.sendError===void 0).length,_=h.size,T=u.length===0?"empty":_===u.length?"all":_===0?"none":"partial";return{verdict:T,exit_code:T==="none"?2:T==="partial"?3:0,sent:w,answered:_,sites:m.map(v=>MF(v,h.get(v.id))),generated_at:new Date(o()).toISOString()}}finally{await l.deleteMailbox(d)}}function MF(e,t){let r={site_name:e.site.site_name,site_uuid:e.site.site_uuid,mailbox:e.execMailbox};if(!t)return{...r,liveness:"stale",error:e.sendError??"no_reply"};let n={...r,liveness:"live",latency_ms:Math.max(0,t.receivedAt-e.sentAt)},o=PF(t);if(o)return{...n,error:o};if(t.result.exit_code!==0)return{...n,error:t.result.timed_out?"remote_timeout":`remote_exit_${t.result.exit_code}`};try{let s=JSON.parse(t.stdout);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("expected JSON object");return{...n,status:s}}catch{return{...n,error:"invalid_status_json"}}}function PF(e){if(e.result.exit_code===126)try{let t=JSON.parse(e.stderr);return typeof t.error?.code=="string"?t.error.code:"remote_rejected"}catch{return"remote_rejected"}}function lv(e){let t=["SITE LIVENESS LATENCY_MS TEAMS DAEMON ERROR"];for(let r of e.sites)t.push([r.site_name||r.site_uuid,r.liveness,r.latency_ms??"-",UF(r.status)??"-",FF(r.status)??"-",r.error??"-"].join(" "));return t.push(`Fleet: ${e.verdict} (sent ${e.sent}/${e.sites.length}, answered ${e.answered}/${e.sites.length}; exit ${e.exit_code})`),t.join(`
905
+ `)}function UF(e){return Array.isArray(e?.teams)?e.teams.length:void 0}function FF(e){return typeof e?.live=="boolean"?`live:${e.live}`:void 0}function uv(){return"usage: lmbee exec <site-uuid-or-mailbox> [--wait-s N] <command...> | lmbee exec <site-uuid-or-mailbox> [--wait-s N] -- <literal command...>"}function fd(){return"usage: lmbee fleet status [--json] [--wait-s N]"}function dv(e,t){return uo(e,t,r=>new It(r))}function qF(e){let t=e.indexOf("--"),r=t<0?[...e]:[...e.slice(0,t)],n=t<0?void 0:e.slice(t+1),o=dv(r,"--wait-s"),s=o===void 0?void 0:Number(o);if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new It("--wait-s must be positive");let i=r.shift();if(!i)throw new It(uv());let a=n??r;if(n&&r.length>0)throw new It(`unexpected argument before --: ${r[0]}`);if(a.length===0)throw new It(uv());return{target:i,command:a.join(" "),...s===void 0?{}:{waitSeconds:s}}}async function mv(e){try{let{target:t,command:r,waitSeconds:n}=qF(e),o=await HS(t,r,{waitSeconds:n});return{output:`${o.stdout}${o.stderr}`.replace(/\n$/,""),exitCode:o.exitCode}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:t instanceof It?1:2}}}async function fv(e){let[t,...r]=e;if(t!=="status")return{output:fd(),exitCode:1};let n=r.includes("--json");try{let o=[...r],s=o.indexOf("--json");n&&o.splice(s,1);let i=dv(o,"--wait-s"),a=i===void 0?void 0:Number(i);if(a!==void 0&&(!Number.isFinite(a)||a<=0))return{output:fd(),exitCode:1};if(o.length>0)return{output:fd(),exitCode:1};let c=await cv({waitSeconds:a});return{output:n?JSON.stringify(c,null,2):lv(c),exitCode:c.exit_code}}catch(o){let s=o instanceof Error?o.message:String(o),i=o instanceof It?1:2;return{output:n?JSON.stringify({verdict:"error",exit_code:i,error:s},null,2):s,exitCode:i}}}import{cpSync as La,existsSync as Hr,mkdirSync as jF,readFileSync as pd,readdirSync as HF,rmSync as pv,statSync as hv}from"node:fs";import{homedir as wv}from"node:os";import{join as Xe,sep as hd}from"node:path";var fo=class extends Error{constructor(t){super(`migrate-home: refusing to run -- an lmauto daemon appears to be live (${t}). Stop it first (systemctl --user stop lmauto.service if it runs as a service, or kill the pid) before re-running.`),this.name="DaemonLiveError"}},gd=class extends Error{targetDbPath;sizeBytes;constructor(t,r){super(`migrate-home: refusing to replace an existing target database: ${t} already exists (${r} bytes). migrate-home never deletes a database it did not create this run. If this file is debris from an interrupted migrate-home run, or you are certain it is disposable, re-run with --replace-existing-target-db; otherwise move it aside yourself (e.g. \`mv ${t} ${t}.bak\`) and re-run.`),this.targetDbPath=t,this.sizeBytes=r,this.name="TargetDbExistsError"}};function yv(){return Xe(wv(),".lmauto")}function Ev(){return Xe(process.env.LMCTL_HOME??Xe(wv(),".lmctl"),"lmauto")}function BF(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function WF(e){try{return(await fetch(`http://127.0.0.1:${e}/api/teams`,{signal:AbortSignal.timeout(1e3)})).body?.cancel(),!0}catch{return!1}}function GF(e,t){let r=Xe(e,"serve.pid");if(!Hr(r))return null;let n=pd(r,"utf8").trim(),o=Number(n);return!Number.isInteger(o)||o<=0?null:t(o)?o:null}var gv=["team_state","kv","events","queue","sources","team_progress","mail_ledger","mail_outbound_ledger"];function _v(e,t){return e.prepare(`SELECT COUNT(*) as n FROM ${t}`).get().n}function _d(e){if(!Hr(e))return 0;let t=0;for(let r of HF(e,{withFileTypes:!0}))r.isDirectory()?t+=_d(Xe(e,r.name)):t+=1;return t}function VF(e,t,r){let n=t.endsWith(hd)?t:t+hd,o=e.prepare("SELECT id, prompt_file FROM queue").all(),s=new Map(o.map(l=>[l.id,l.prompt_file])),i=o.filter(l=>l.prompt_file.startsWith(n)),a=e.prepare("UPDATE queue SET prompt_file = ? WHERE id = ?");return e.transaction(l=>{for(let u of l){let d=r+u.prompt_file.slice(t.length);a.run(d,u.id)}})(i),{rewrittenCount:i.length,originalPathById:s}}async function Tv(e){let{sourceDir:t,targetDir:r,port:n=4173}=e,o=e.isDaemonAlive??BF,s=e.probeHttpAlive??WF,i=e.checkSiteLock??l_,a=Xe(t,"state.db"),c=Xe(r,"state.db"),l=i(a);if(l!==null)throw new fo(`${l.ownerLabel} pid ${l.pid} (site lock for ${a})`);let u=GF(t,o);if(u!==null)throw new fo(`pid ${u}, ${Xe(t,"serve.pid")}`);if(await s(n))throw new fo(`something is listening on port ${n}`);if(t===r||r.startsWith(t+hd))throw new Error(`migrate-home: target (${r}) must not be, or be nested inside, source (${t})`);let d=e.acquireSiteLock??sa,m=es(a),f=[];try{f.push(d(m,"migrate-home")),f.push(d(Xe(t,"site.lock"),"migrate-home"))}catch(p){for(let h of f.splice(0))h.release();throw p instanceof Wn?new fo(`${p.holder.ownerLabel} pid ${p.holder.pid}, ${p.lockPath}`):p}try{jF(r,{recursive:!0});let p=!1,h=!1;if(Hr(a)){let oe=Hr(c);if(oe&&e.replaceExistingTargetDb!==!0)throw new gd(c,hv(c).size);let V=new ht(a);try{if(V.prepare("SELECT COUNT(*) AS n FROM sqlite_master").get(),oe){process.stderr.write(`migrate-home: replacing existing target database ${c} (${hv(c).size} bytes) with a snapshot of ${a} (explicit replaceExistingTargetDb consent)
906
+ `);for(let se of["","-wal","-shm"])pv(c+se,{force:!0});h=!0}else for(let se of["-wal","-shm"])pv(c+se,{force:!0});V.prepare("VACUUM INTO ?").run(c)}finally{V.close()}p=!0}let w=Xe(t,"queue"),_=Xe(r,"queue"),T=_d(w);T>0&&La(w,_,{recursive:!0});let E=Xe(t,"prompts"),v=Xe(r,"prompts"),S=_d(E);S>0&&La(E,v,{recursive:!0});let N=Xe(t,"site-uuid"),$=Xe(r,"site-uuid"),L=!1,R=!1;Hr(N)&&(La(N,$),L=!0,R=pd(N,"utf8")!==pd($,"utf8"));let H=Xe(t,"lmt-peers.json"),C=Xe(r,"lmt-peers.json"),g=!1;Hr(H)&&(La(H,C),g=!0);let y=0,x=0,P=[],J=[],ee={};if(p){let oe=new ht(a,{readonly:!0});try{for(let se of gv)ee[se]={source:_v(oe,se),target:0}}finally{oe.close()}let V=new ht(c);try{for(let A of gv)ee[A].target=_v(V,A);let{rewrittenCount:se,originalPathById:k}=VF(V,w,_);y=se;let O=V.prepare("SELECT id, prompt_file FROM queue").all();x=O.length;for(let A of O){if(Hr(A.prompt_file))continue;let q=k.get(A.id);Hr(q)?P.push(`#${A.id} -> ${A.prompt_file}`):J.push(`#${A.id} -> ${A.prompt_file}`)}}finally{V.close()}}return{sourceDir:t,targetDir:r,stateDbCopied:p,replacedExistingTargetDb:h,queueFilesCopied:T,promptFilesCopied:S,rewrittenPromptPaths:y,queueRowCount:x,missingPromptFiles:P,preExistingMissingPromptFiles:J,siteIdentityCopied:L,siteIdentityMismatch:R,lmtPeersCopied:g,rowCountParity:ee}}finally{for(let p of f.splice(0))p.release()}}async function bv(e={}){let t=e.source??yv(),r=e.target??Ev(),n=await Tv({sourceDir:t,targetDir:r,replaceExistingTargetDb:e.replaceExistingTargetDb});return{output:YF(n),exitCode:JF(n)}}function JF(e){return e.missingPromptFiles.length>0||e.siteIdentityMismatch||KF(e)?1:0}function KF(e){return Object.values(e.rowCountParity).some(t=>t.source!==t.target)}function zF(e){let t=Object.entries(e).filter(([,r])=>r.source!==r.target);return t.length===0?` table row-count parity: OK (${Object.keys(e).length} table(s) checked, all match)`:` PARITY CHECK FAILED -- ${t.length} table(s) with a source/target row-count mismatch:
907
907
  `+t.map(([r,n])=>` ${r}: source=${n.source}, target=${n.target}`).join(`
908
- `)}function BF(e){return[`migrate-home: ${e.sourceDir} -> ${e.targetDir}`,e.replacedExistingTargetDb?" REPLACED an existing target database: the previous state.db in the target dir was DELETED (explicit --replace-existing-target-db consent) and replaced by the source snapshot":null,` state.db copied: ${e.stateDbCopied?"yes":"no (no source state.db found)"}`,` queue files copied: ${e.queueFilesCopied}`,` prompt files copied: ${e.promptFilesCopied}`,` prompt_file paths rewritten (new DB only): ${e.rewrittenPromptPaths}`,` queue rows in new DB: ${e.queueRowCount}`,e.missingPromptFiles.length>0?` PARITY CHECK FAILED -- ${e.missingPromptFiles.length} missing prompt file(s) that existed in source but not in the new copy:
908
+ `)}function YF(e){return[`migrate-home: ${e.sourceDir} -> ${e.targetDir}`,e.replacedExistingTargetDb?" REPLACED an existing target database: the previous state.db in the target dir was DELETED (explicit --replace-existing-target-db consent) and replaced by the source snapshot":null,` state.db copied: ${e.stateDbCopied?"yes":"no (no source state.db found)"}`,` queue files copied: ${e.queueFilesCopied}`,` prompt files copied: ${e.promptFilesCopied}`,` prompt_file paths rewritten (new DB only): ${e.rewrittenPromptPaths}`,` queue rows in new DB: ${e.queueRowCount}`,e.missingPromptFiles.length>0?` PARITY CHECK FAILED -- ${e.missingPromptFiles.length} missing prompt file(s) that existed in source but not in the new copy:
909
909
  `+e.missingPromptFiles.map(r=>` ${r}`).join(`
910
- `):" parity check: OK (every queue row's prompt_file that existed in source also exists in the new location)",e.preExistingMissingPromptFiles.length>0?` (${e.preExistingMissingPromptFiles.length} queue row(s) reference a file already missing in source too -- pre-existing, e.g. garbage-collected -- not a migration defect, not blocking)`:null,` site identity (site-uuid): ${e.siteIdentityCopied?e.siteIdentityMismatch?"PARITY CHECK FAILED -- copied bytes differ from source":"copied, verified byte-identical":"not present in source (remote mail was never enabled) -- nothing to copy"}`,` lmt peer registry (lmt-peers.json): ${e.lmtPeersCopied?"copied":"not present in source -- nothing to copy"}`,HF(e.rowCountParity),"",`Source (${e.sourceDir}) left fully intact -- this is your rollback path. Nothing has been`,"switched over yet: the running daemon and CLI defaults still point at the old location until a","separate, deliberate cutover step (stop the old daemon, flip defaults, start the new owner)."].filter(r=>r!==null).join(`
911
- `)}function hd(e){return{output:e,exitCode:0}}function mo(e){return{output:e,exitCode:1}}function gd(){return"usage: lmbee localweb passcode get | set | rotate"}var wv=32;async function WF(){let e=[],t=0;for await(let r of process.stdin){let n=Buffer.from(r);if(t+=n.length,t>4096)throw new Error("passcode input exceeds 4096 bytes");e.push(n)}return Buffer.concat(e).toString("utf8")}async function yv(e,t={}){let[r,n,...o]=e;if(r!=="passcode")return mo(gd());if(o.length)return mo(`unexpected argument; ${gd()}`);let s=wo(),i=Bn(s);if(i===null)return{output:`no passcode file for an in-memory DB (${s})`,exitCode:2};if(n==="get"){let a=d_(i);return a===null?{output:"no passcode set yet -- start the daemon or run `lmbee localweb passcode rotate`",exitCode:1}:hd(a)}if(n==="set"){let a=t.readStdin??WF,c;try{c=(await a()).trim()}catch{return mo("passcode input rejected")}let l=Buffer.byteLength(c,"utf8");return l===0||l>4096?mo("usage: lmbee localweb passcode set (reads a nonempty value of at most 4096 bytes from stdin)"):l<wv?mo(`passcode rejected: at least ${wv} bytes required (got ${l}) -- a short value meaningfully weakens the 256-bit guarantee rotate/startup generation otherwise provide; use \`lmbee localweb passcode rotate\` for a strong random value instead`):(zl(i,c),hd("passcode updated"))}return n==="rotate"?hd(na(i)):mo(gd())}import{randomUUID as GF}from"node:crypto";import{readFile as VF}from"node:fs/promises";function JF(e){try{let t=am(e);return KF(t.site),t}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function KF(e){return ad(e)?e.toLowerCase():$a(e,"peer alias")}function Ev(e,t,r,n,o=!1){let s=e??(t===void 0||t===""?r:t);return o&&s===""?s:$a(s,n)}async function zF(e,t){return e==="-"?t():VF(e,"utf8")}async function YF(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function QF(e,t,r){if(ad(e)){let s=tr(e,"site-uuid"),i=t[s];if(!i)throw new Error(`unknown peer site-uuid: ${s}; add it with lmbee peers add ${s} <mailbox>`);return{siteUuid:s,mailbox:_s(s,i.mailbox)}}let n=GS(e,t);if(n)return n;try{let s=await r.resolveSite(e);return{siteUuid:tr(s.site_uuid,"resolved site-uuid"),mailbox:s.mailbox}}catch(s){if(!(s instanceof Ft&&s.status===404))throw s}let o=Object.values(t).map(s=>s.alias).filter(s=>s!==void 0).sort();throw new Error(`unknown peer alias or site name: ${e}; registered local aliases: ${o.length?o.join(", "):"(none)"}; not found in the account's site registry either`)}function Tv(){return"usage: lmbee tell <site-uuid-or-alias:team-id:alias> (<prompt...> | --prompt-file <path|->) [--from-team <team>] [--from-alias <alias>]"}async function bv(e,t,r={}){let n=r.env??process.env,o=r.promptFile;if(!e||o===void 0&&t.length===0)throw new Me(Tv());if(o!==void 0&&t.length>0)throw new Me("positional prompt and --prompt-file are mutually exclusive");let s=JF(e),i=o===void 0?t.join(" "):await zF(o,r.readStdin??YF);if(!i.trim())throw new Me("tell prompt must be non-empty");let a=Ev(r.fromTeam,n.LMT_FROM_TEAM,"","from-team",!0),c=Ev(r.fromAlias,n.LMT_FROM_ALIAS,"operator","from-alias"),l=r.resolveAppkeyImpl??Se,u=r.createMailClientImpl??pt,{appkey:d}=l({env:n}),m=u({apiUrl:$t(n),appkey:d}),f=await ws(),{siteUuid:p,mailbox:h}=await QF(s.site,f,m),w={...s,site:p},_=await Us(ar()),E=GF(),T={v:1,msg_id:E,to:w,from:{site:_,team:a,alias:c},sent_at:new Date().toISOString(),payload:i},v=await m.sendMessage({mailbox:h,subject:`delivery ${E}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(T),"utf8")}});return`sent ${E} from ${_}:${a}:${c} to ${e} via ${h} (seq ${v})`}function hr(e){return{output:e,exitCode:0}}function rr(e){return{output:e,exitCode:1}}function _d(e){return{output:e instanceof Error?e.message:String(e),exitCode:e instanceof Me?1:2}}function XF(){return"usage: lmbee peers list | add <site-uuid> <mailbox> [--alias <name>] | remove <site-uuid>"}function nr(e,t){return co(e,t,r=>new Me(r))}async function Sv(e){let[t,...r]=e;try{if(t==="list"){if(r.length)throw new Me(`unexpected argument: ${r[0]}`);return hr(await VS())}if(t==="add"){let n=nr(r,"--alias");return r.length!==2?rr("usage: lmbee peers add <site-uuid> <mailbox> [--alias <name>]"):hr(await JS(r[0],r[1],n))}return t==="remove"?r.length!==1?rr("usage: lmbee peers remove <site-uuid>"):hr(await KS(r[0])):rr(XF())}catch(n){return _d(n)}}function ZF(e){let t=[...e];if(t.includes("--message-file"))throw new Me("unknown option --message-file; use --prompt-file");let r=nr(t,"--prompt-file"),n=nr(t,"--from-team"),o=nr(t,"--from-alias"),[s,...i]=t;return{rawAddress:s,messageParts:i,promptFile:r,fromTeam:n,fromAlias:o}}async function vv(e){try{let{rawAddress:t,messageParts:r,promptFile:n,fromTeam:o,fromAlias:s}=ZF(e);return hr(await bv(t,r,{promptFile:n,fromTeam:o,fromAlias:s}))}catch(t){return _d(t)}}async function Av(e){let[t,...r]=e;try{if(t==="register"){let n=nr(r,"--site-uuid"),o=nr(r,"--mailbox");return r.length!==1?rr(jr()):hr(await zS(r[0],{siteUuid:n,mailbox:o}))}if(t==="resolve")return r.length!==1?rr(jr()):await YS(r[0]);if(t==="list")return r.length?rr(jr()):hr(await XS());if(t==="set-name"){let n=nr(r,"--uuid"),o=nr(r,"--mailbox");return n===void 0==(o===void 0)||r.length!==1?rr(jr()):hr(await ev(r[0],{uuid:n,mailbox:o}))}if(t==="clear-name"){let n=nr(r,"--uuid"),o=nr(r,"--mailbox");return n===void 0==(o===void 0)||r.length!==0?rr(jr()):hr(await tv({uuid:n,mailbox:o}))}return t==="remove"?r.length!==1?rr(jr()):hr(await rv(r[0])):rr(jr())}catch(n){return _d(n)}}import{execFile as eq}from"node:child_process";import{promisify as tq}from"node:util";var rq=tq(eq),nq="lmbee.service";function oq(){return process.env.LMBEE_SYSTEMD_UNIT??nq}async function $v(e={}){let t=oq();if(!e.force)return{output:`lmbee shutdown: refusing to stop ${t} without --force -- this immediately stops queue delivery, mail polling, and anti-churn nudging. Re-run as \`lmbee shutdown --force\` to proceed.
912
- `,exitCode:1};let r=e.execFileImpl??rq;try{await r("systemctl",["--user","stop",t])}catch(o){let s=o instanceof Error?o.message:String(o);return{output:`lmbee shutdown: systemctl --user stop ${t} failed: ${s}
910
+ `):" parity check: OK (every queue row's prompt_file that existed in source also exists in the new location)",e.preExistingMissingPromptFiles.length>0?` (${e.preExistingMissingPromptFiles.length} queue row(s) reference a file already missing in source too -- pre-existing, e.g. garbage-collected -- not a migration defect, not blocking)`:null,` site identity (site-uuid): ${e.siteIdentityCopied?e.siteIdentityMismatch?"PARITY CHECK FAILED -- copied bytes differ from source":"copied, verified byte-identical":"not present in source (remote mail was never enabled) -- nothing to copy"}`,` lmt peer registry (lmt-peers.json): ${e.lmtPeersCopied?"copied":"not present in source -- nothing to copy"}`,zF(e.rowCountParity),"",`Source (${e.sourceDir}) left fully intact -- this is your rollback path. Nothing has been`,"switched over yet: the running daemon and CLI defaults still point at the old location until a","separate, deliberate cutover step (stop the old daemon, flip defaults, start the new owner)."].filter(r=>r!==null).join(`
911
+ `)}function wd(e){return{output:e,exitCode:0}}function po(e){return{output:e,exitCode:1}}function yd(){return"usage: lmbee localweb passcode get | set | rotate"}var Sv=32;async function QF(){let e=[],t=0;for await(let r of process.stdin){let n=Buffer.from(r);if(t+=n.length,t>4096)throw new Error("passcode input exceeds 4096 bytes");e.push(n)}return Buffer.concat(e).toString("utf8")}async function vv(e,t={}){let[r,n,...o]=e;if(r!=="passcode")return po(yd());if(o.length)return po(`unexpected argument; ${yd()}`);let s=Eo(),i=Gn(s);if(i===null)return{output:`no passcode file for an in-memory DB (${s})`,exitCode:2};if(n==="get"){let a=g_(i);return a===null?{output:"no passcode set yet -- start the daemon or run `lmbee localweb passcode rotate`",exitCode:1}:wd(a)}if(n==="set"){let a=t.readStdin??QF,c;try{c=(await a()).trim()}catch{return po("passcode input rejected")}let l=Buffer.byteLength(c,"utf8");return l===0||l>4096?po("usage: lmbee localweb passcode set (reads a nonempty value of at most 4096 bytes from stdin)"):l<Sv?po(`passcode rejected: at least ${Sv} bytes required (got ${l}) -- a short value meaningfully weakens the 256-bit guarantee rotate/startup generation otherwise provide; use \`lmbee localweb passcode rotate\` for a strong random value instead`):(Xl(i,c),wd("passcode updated"))}return n==="rotate"?wd(ia(i)):po(yd())}import{randomUUID as XF}from"node:crypto";import{readFile as ZF}from"node:fs/promises";function eq(e){try{let t=um(e);return tq(t.site),t}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function tq(e){return ud(e)?e.toLowerCase():Ra(e,"peer alias")}function Av(e,t,r,n,o=!1){let s=e??(t===void 0||t===""?r:t);return o&&s===""?s:Ra(s,n)}async function rq(e,t){return e==="-"?t():ZF(e,"utf8")}async function nq(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function oq(e,t,r){if(ud(e)){let s=tr(e,"site-uuid"),i=t[s];if(!i)throw new Error(`unknown peer site-uuid: ${s}; add it with lmbee peers add ${s} <mailbox>`);return{siteUuid:s,mailbox:Ts(s,i.mailbox)}}let n=YS(e,t);if(n)return n;try{let s=await r.resolveSite(e);return{siteUuid:tr(s.site_uuid,"resolved site-uuid"),mailbox:s.mailbox}}catch(s){if(!(s instanceof Ft&&s.status===404))throw s}let o=Object.values(t).map(s=>s.alias).filter(s=>s!==void 0).sort();throw new Error(`unknown peer alias or site name: ${e}; registered local aliases: ${o.length?o.join(", "):"(none)"}; not found in the account's site registry either`)}function kv(){return"usage: lmbee tell <site-uuid-or-alias:team-id:alias> (<prompt...> | --prompt-file <path|->) [--from-team <team>] [--from-alias <alias>]"}async function $v(e,t,r={}){let n=r.env??process.env,o=r.promptFile;if(!e||o===void 0&&t.length===0)throw new Me(kv());if(o!==void 0&&t.length>0)throw new Me("positional prompt and --prompt-file are mutually exclusive");let s=eq(e),i=o===void 0?t.join(" "):await rq(o,r.readStdin??nq);if(!i.trim())throw new Me("tell prompt must be non-empty");let a=Av(r.fromTeam,n.LMT_FROM_TEAM,"","from-team",!0),c=Av(r.fromAlias,n.LMT_FROM_ALIAS,"operator","from-alias"),l=r.resolveAppkeyImpl??Se,u=r.createMailClientImpl??pt,{appkey:d}=l({env:n}),m=u({apiUrl:kt(n),appkey:d}),f=await bs(),{siteUuid:p,mailbox:h}=await oq(s.site,f,m),w={...s,site:p},_=await Hs(ar()),T=XF(),E={v:1,msg_id:T,to:w,from:{site:_,team:a,alias:c},sent_at:new Date().toISOString(),payload:i},v=await m.sendMessage({mailbox:h,subject:`delivery ${T}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(E),"utf8")}});return`sent ${T} from ${_}:${a}:${c} to ${e} via ${h} (seq ${v})`}function gr(e){return{output:e,exitCode:0}}function rr(e){return{output:e,exitCode:1}}function Ed(e){return{output:e instanceof Error?e.message:String(e),exitCode:e instanceof Me?1:2}}function sq(){return"usage: lmbee peers list | add <site-uuid> <mailbox> [--alias <name>] | remove <site-uuid>"}function nr(e,t){return uo(e,t,r=>new Me(r))}async function xv(e){let[t,...r]=e;try{if(t==="list"){if(r.length)throw new Me(`unexpected argument: ${r[0]}`);return gr(await QS())}if(t==="add"){let n=nr(r,"--alias");return r.length!==2?rr("usage: lmbee peers add <site-uuid> <mailbox> [--alias <name>]"):gr(await XS(r[0],r[1],n))}return t==="remove"?r.length!==1?rr("usage: lmbee peers remove <site-uuid>"):gr(await ZS(r[0])):rr(sq())}catch(n){return Ed(n)}}function iq(e){let t=[...e];if(t.includes("--message-file"))throw new Me("unknown option --message-file; use --prompt-file");let r=nr(t,"--prompt-file"),n=nr(t,"--from-team"),o=nr(t,"--from-alias"),[s,...i]=t;return{rawAddress:s,messageParts:i,promptFile:r,fromTeam:n,fromAlias:o}}async function Rv(e){try{let{rawAddress:t,messageParts:r,promptFile:n,fromTeam:o,fromAlias:s}=iq(e);return gr(await $v(t,r,{promptFile:n,fromTeam:o,fromAlias:s}))}catch(t){return Ed(t)}}async function Nv(e){let[t,...r]=e;try{if(t==="register"){let n=nr(r,"--site-uuid"),o=nr(r,"--mailbox");return r.length!==1?rr(jr()):gr(await ev(r[0],{siteUuid:n,mailbox:o}))}if(t==="resolve")return r.length!==1?rr(jr()):await tv(r[0]);if(t==="list")return r.length?rr(jr()):gr(await nv());if(t==="set-name"){let n=nr(r,"--uuid"),o=nr(r,"--mailbox");return n===void 0==(o===void 0)||r.length!==1?rr(jr()):gr(await sv(r[0],{uuid:n,mailbox:o}))}if(t==="clear-name"){let n=nr(r,"--uuid"),o=nr(r,"--mailbox");return n===void 0==(o===void 0)||r.length!==0?rr(jr()):gr(await iv({uuid:n,mailbox:o}))}return t==="remove"?r.length!==1?rr(jr()):gr(await av(r[0])):rr(jr())}catch(n){return Ed(n)}}import{execFile as aq}from"node:child_process";import{promisify as cq}from"node:util";var lq=cq(aq),uq="lmbee.service";function dq(){return process.env.LMBEE_SYSTEMD_UNIT??uq}async function Lv(e={}){let t=dq();if(!e.force)return{output:`lmbee shutdown: refusing to stop ${t} without --force -- this immediately stops queue delivery, mail polling, and anti-churn nudging. Re-run as \`lmbee shutdown --force\` to proceed.
912
+ `,exitCode:1};let r=e.execFileImpl??lq;try{await r("systemctl",["--user","stop",t])}catch(o){let s=o instanceof Error?o.message:String(o);return{output:`lmbee shutdown: systemctl --user stop ${t} failed: ${s}
913
913
  `,exitCode:1}}let n;try{let{stdout:o}=await r("systemctl",["--user","is-active",t]);n=o.trim()}catch(o){let s=o&&typeof o=="object"&&"stdout"in o?String(o.stdout).trim():"";if(s.length===0){let i=o instanceof Error?o.message:String(o);return{output:`lmbee shutdown: ${t}: stop was issued, but its state could not be confirmed -- is-active check failed: ${i}
914
914
  `,exitCode:1}}n=s}switch(n){case"inactive":return{output:`lmbee shutdown: ${t} stopped (state: ${n})
915
915
  `,exitCode:0};case"active":return{output:`lmbee shutdown: stop reported success, but ${t} is active again (state: ${n})
916
916
  `,exitCode:1};case"activating":case"deactivating":case"reloading":return{output:`lmbee shutdown: ${t} stop not yet confirmed -- unit is in a transitional state (state: ${n})
917
917
  `,exitCode:1};default:return{output:`lmbee shutdown: ${t} stop not confirmed (state: ${n})
918
- `,exitCode:1}}}function sq(e,t,r){let n="";for(let o=0;o<e.length;o++){let s=e[o];t.atLineStart&&s!==`
918
+ `,exitCode:1}}}function mq(e,t,r){let n="";for(let o=0;o<e.length;o++){let s=e[o];t.atLineStart&&s!==`
919
919
  `&&(n+=`${r()} `,t.atLineStart=!1),n+=s,s===`
920
- `&&(t.atLineStart=!0)}return n}var kv=!1;function xv(e=()=>new Date().toISOString()){if(!kv){kv=!0;for(let t of[process.stdout,process.stderr]){let r=t.write.bind(t),n={atLineStart:!0};t.write=(o,...s)=>r(typeof o=="string"?sq(o,n,e):o,...s)}}}function fo(e){return`${e instanceof Error?e.message:String(e)}
921
- `}function dq(e){let t=wd(uq(),".lmbee");cq(t,{recursive:!0});let r=wd(t,"serve.log"),n=wd(t,"serve.pid"),o=aq(r,"a"),s=iq(process.execPath,[process.argv[1],...e],{detached:!0,stdio:["ignore",o,o]});s.unref(),s.pid!==void 0&&lq(n,`${s.pid}
920
+ `&&(t.atLineStart=!0)}return n}var Iv=!1;function Cv(e=()=>new Date().toISOString()){if(!Iv){Iv=!0;for(let t of[process.stdout,process.stderr]){let r=t.write.bind(t),n={atLineStart:!0};t.write=(o,...s)=>r(typeof o=="string"?mq(o,n,e):o,...s)}}}function ho(e){return`${e instanceof Error?e.message:String(e)}
921
+ `}function wq(e){let t=Td(_q(),".lmbee");hq(t,{recursive:!0});let r=Td(t,"serve.log"),n=Td(t,"serve.pid"),o=pq(r,"a"),s=fq(process.execPath,[process.argv[1],...e],{detached:!0,stdio:["ignore",o,o]});s.unref(),s.pid!==void 0&&gq(n,`${s.pid}
922
922
  `),process.stdout.write(`lmbee serve: started detached (pid ${s.pid??"?"}), log: ${r}, pidfile: ${n}
923
923
  Stop it with: kill ${s.pid??"<pid>"}
924
- `)}async function mq(){let e=process.argv.slice(2);if(NT(e))return process.stdout.write(`${Ur}
925
- `),0;if(e.length===1&&(e[0]==="--version"||e[0]==="-v"||e[0]==="-V")){let r=Dc();return process.stdout.write(`lmbee ${Pf()} (${r.sha}${r.dirty?".dirty":""})
926
- `),0}if(e[0]==="serve"){let{flags:r}=wt(e.slice(1),["daemon","auto-continue","miniplayer-verify","hung-holder-check","epic-review","orphan-reconciler","orphan-reconciler-dry-run","hang-probe-collect","auto-nudge-redirect-review","rate-limit-collect","rate-limit-policy","rate-limit-automation","remote-mail","exec-worker","exec-allow-anonymous","publish","help"]);if(r.help===!0)return process.stdout.write(`${Ur}
927
- `),0;if(r.daemon===!0)return dq(e.filter(ne=>ne!=="--daemon")),0;xv();let n;try{if(process.env.LMBEE_SITE_UUID!==void 0){let ne=vs(void 0,{readOnly:!0});try{En(ne.db,ar(),process.env.LMBEE_SITE_UUID)}finally{ne.close()}}n=pi()}catch(ne){return process.stderr.write(fo(ne)),1}let o=r["remote-mail"]===!0,s=typeof r["remote-allow"]=="string"?r["remote-allow"]:void 0;if(o&&s===void 0)return process.stderr.write(`error: --remote-mail requires --remote-allow <user_id1,user_id2,...>
924
+ `)}async function yq(){let e=process.argv.slice(2);if(DT(e))return process.stdout.write(`${Ur}
925
+ `),0;if(e.length===1&&(e[0]==="--version"||e[0]==="-v"||e[0]==="-V")){let r=Uc();return process.stdout.write(`lmbee ${qf()} (${r.sha}${r.dirty?".dirty":""})
926
+ `),0}if(e[0]==="serve"){let{flags:r}=yt(e.slice(1),["daemon","auto-continue","miniplayer-verify","hung-holder-check","epic-review","orphan-reconciler","orphan-reconciler-dry-run","hang-probe-collect","auto-nudge-redirect-review","rate-limit-collect","rate-limit-policy","rate-limit-automation","remote-mail","exec-worker","exec-allow-anonymous","publish","help"]);if(r.help===!0)return process.stdout.write(`${Ur}
927
+ `),0;if(r.daemon===!0)return wq(e.filter(ne=>ne!=="--daemon")),0;Cv();let n;try{if(process.env.LMBEE_SITE_UUID!==void 0){let ne=xs(void 0,{readOnly:!0});try{En(ne.db,ar(),process.env.LMBEE_SITE_UUID)}finally{ne.close()}}n=wi()}catch(ne){return process.stderr.write(ho(ne)),1}let o=r["remote-mail"]===!0,s=typeof r["remote-allow"]=="string"?r["remote-allow"]:void 0;if(o&&s===void 0)return process.stderr.write(`error: --remote-mail requires --remote-allow <user_id1,user_id2,...>
928
928
  `),n.db.close(),1;if(!o&&s!==void 0)return process.stderr.write(`error: --remote-allow requires --remote-mail
929
929
  `),n.db.close(),1;let i;if(o&&s!==void 0){let ne=s.split(",").map(j=>j.trim()).filter(j=>j.length>0);if(ne.length===0)return process.stderr.write(`error: --remote-allow must name at least one sender user_id
930
- `),n.db.close(),1;let D;try{D=En(n.db.db)}catch(j){return process.stderr.write(fo(j)),n.db.close(),1}try{let{appkey:j}=Se({env:process.env});i={client:pt({apiUrl:$t(process.env),appkey:j}),localSiteId:D,mailbox:zr(D),allowlist:ne}}catch(j){process.stderr.write(`[mail] --remote-mail setup failed, mail lane stays dormant this run: ${j instanceof Error?j.message:String(j)}
930
+ `),n.db.close(),1;let D;try{D=En(n.db.db)}catch(j){return process.stderr.write(ho(j)),n.db.close(),1}try{let{appkey:j}=Se({env:process.env});i={client:pt({apiUrl:kt(process.env),appkey:j}),localSiteId:D,mailbox:zr(D),allowlist:ne}}catch(j){process.stderr.write(`[mail] --remote-mail setup failed, mail lane stays dormant this run: ${j instanceof Error?j.message:String(j)}
931
931
  `)}}let a=r["exec-worker"]===!0,c=typeof r["exec-mailbox"]=="string"?r["exec-mailbox"]:void 0,l=typeof r["exec-admin"]=="string"?r["exec-admin"]:void 0,u=typeof r["exec-allow"]=="string"?r["exec-allow"]:void 0,d=r["exec-allow-anonymous"]===!0;if(!a&&c!==void 0)return process.stderr.write(`error: --exec-mailbox requires --exec-worker
932
932
  `),n.db.close(),1;let m;if(a){let ne=K=>(K??"").split(",").map(re=>re.trim()).filter(re=>re.length>0),D=new Set(ne(l)),j=new Set(ne(u));if(D.size===0&&j.size===0&&!d)return process.stderr.write(`error: --exec-worker requires at least one of --exec-admin, --exec-allow, or --exec-allow-anonymous
933
- `),n.db.close(),1;let Y;try{Y=En(n.db.db)}catch(K){return process.stderr.write(fo(K)),n.db.close(),1}try{let{appkey:K}=Se({env:process.env}),re=c??yn(Y);m={client:pt({apiUrl:$t(process.env),appkey:K}),mailbox:re,adminUsers:D,allowUsers:j,allowAnonymous:d}}catch(K){process.stderr.write(`[exec-worker] --exec-worker setup failed, exec stays dormant this run: ${K instanceof Error?K.message:String(K)}
933
+ `),n.db.close(),1;let Y;try{Y=En(n.db.db)}catch(K){return process.stderr.write(ho(K)),n.db.close(),1}try{let{appkey:K}=Se({env:process.env}),re=c??yn(Y);m={client:pt({apiUrl:kt(process.env),appkey:K}),mailbox:re,adminUsers:D,allowUsers:j,allowAnonymous:d}}catch(K){process.stderr.write(`[exec-worker] --exec-worker setup failed, exec stays dormant this run: ${K instanceof Error?K.message:String(K)}
934
934
  `)}}let f=typeof r.port=="string"?Number(r.port):void 0,p=r.publish===!0?!0:void 0,h=typeof r.hostname=="string"?r.hostname:void 0;if(h!==void 0&&!["127.0.0.1","::1","localhost"].includes(h)&&p===void 0)return process.stderr.write(`error: --hostname requires --publish for any non-loopback value
935
- `),1;let w=typeof r["web-dist"]=="string"?r["web-dist"]:void 0,_=typeof r.interval=="string"?Number(r.interval):void 0,E=an(r["queue-interval-ms"],"--queue-interval-ms");if(E instanceof Error)return process.stderr.write(`error: ${E.message}
936
- `),1;let T=typeof r["maintainer-team"]=="string"?r["maintainer-team"]:void 0,v=typeof r["maintainer-prompt-file"]=="string"?r["maintainer-prompt-file"]:void 0;if(T===void 0!=(v===void 0))return process.stderr.write(`error: --maintainer-team and --maintainer-prompt-file must be given together
937
- `),1;let S=typeof r["maintainer-session-alive-path"]=="string"?r["maintainer-session-alive-path"]:void 0;if(S!==void 0&&T===void 0)return process.stderr.write(`error: --maintainer-session-alive-path requires --maintainer-team and --maintainer-prompt-file
935
+ `),1;let w=typeof r["web-dist"]=="string"?r["web-dist"]:void 0,_=typeof r.interval=="string"?Number(r.interval):void 0,T=an(r["queue-interval-ms"],"--queue-interval-ms");if(T instanceof Error)return process.stderr.write(`error: ${T.message}
936
+ `),1;let E=typeof r["maintainer-team"]=="string"?r["maintainer-team"]:void 0,v=typeof r["maintainer-prompt-file"]=="string"?r["maintainer-prompt-file"]:void 0;if(E===void 0!=(v===void 0))return process.stderr.write(`error: --maintainer-team and --maintainer-prompt-file must be given together
937
+ `),1;let S=typeof r["maintainer-session-alive-path"]=="string"?r["maintainer-session-alive-path"]:void 0;if(S!==void 0&&E===void 0)return process.stderr.write(`error: --maintainer-session-alive-path requires --maintainer-team and --maintainer-prompt-file
938
938
  `),1;let N=an(r["maintainer-session-alive-freshness-ms"],"--maintainer-session-alive-freshness-ms");if(N instanceof Error)return process.stderr.write(`error: ${N.message}
939
939
  `),1;if(N!==void 0&&S===void 0)return process.stderr.write(`error: --maintainer-session-alive-freshness-ms requires --maintainer-session-alive-path
940
- `),1;let x=an(r["maintainer-stale-threshold-ms"],"--maintainer-stale-threshold-ms");if(x instanceof Error)return process.stderr.write(`error: ${x.message}
941
- `),1;let I=an(r["maintainer-activity-freshness-ms"],"--maintainer-activity-freshness-ms");if(I instanceof Error)return process.stderr.write(`error: ${I.message}
942
- `),1;if(I!==void 0&&T===void 0)return process.stderr.write(`error: --maintainer-activity-freshness-ms requires --maintainer-team and --maintainer-prompt-file
943
- `),1;let k=T!==void 0&&v!==void 0?{teamName:T,promptFile:v,...S!==void 0?{sessionAlivePath:S}:{},...N!==void 0?{sessionAliveFreshnessMs:N}:{},...I!==void 0?{activityFreshnessMs:I}:{},...x!==void 0?{maintainerStaleThresholdMs:x}:{}}:void 0,B=r["auto-continue"]===!0?{}:void 0,C=r["miniplayer-verify"]===!0?{}:void 0,g=r["hung-holder-check"]===!0?{}:void 0,y=r["epic-review"]===!0?{}:void 0,R=r["orphan-reconciler-dry-run"]===!0,P=r["orphan-reconciler"]===!0||R?{dryRun:R}:void 0,J=r["hang-probe-collect"]===!0?{}:void 0,ee=r["auto-nudge-redirect-review"]===!0?!0:void 0,oe=r["rate-limit-collect"]===!0?{}:void 0,V=r["rate-limit-policy"]===!0?{}:void 0,se=r["rate-limit-automation"]===!0?{}:void 0,$=an(r["idle-threshold-ms"],"--idle-threshold-ms"),O=an(r["cooldown-ms"],"--cooldown-ms");if($ instanceof Error)return process.stderr.write(`error: ${$.message}
940
+ `),1;let $=an(r["maintainer-stale-threshold-ms"],"--maintainer-stale-threshold-ms");if($ instanceof Error)return process.stderr.write(`error: ${$.message}
941
+ `),1;let L=an(r["maintainer-activity-freshness-ms"],"--maintainer-activity-freshness-ms");if(L instanceof Error)return process.stderr.write(`error: ${L.message}
942
+ `),1;if(L!==void 0&&E===void 0)return process.stderr.write(`error: --maintainer-activity-freshness-ms requires --maintainer-team and --maintainer-prompt-file
943
+ `),1;let R=E!==void 0&&v!==void 0?{teamName:E,promptFile:v,...S!==void 0?{sessionAlivePath:S}:{},...N!==void 0?{sessionAliveFreshnessMs:N}:{},...L!==void 0?{activityFreshnessMs:L}:{},...$!==void 0?{maintainerStaleThresholdMs:$}:{}}:void 0,H=r["auto-continue"]===!0?{}:void 0,C=r["miniplayer-verify"]===!0?{}:void 0,g=r["hung-holder-check"]===!0?{}:void 0,y=r["epic-review"]===!0?{}:void 0,x=r["orphan-reconciler-dry-run"]===!0,P=r["orphan-reconciler"]===!0||x?{dryRun:x}:void 0,J=r["hang-probe-collect"]===!0?{}:void 0,ee=r["auto-nudge-redirect-review"]===!0?!0:void 0,oe=r["rate-limit-collect"]===!0?{}:void 0,V=r["rate-limit-policy"]===!0?{}:void 0,se=r["rate-limit-automation"]===!0?{}:void 0,k=an(r["idle-threshold-ms"],"--idle-threshold-ms"),O=an(r["cooldown-ms"],"--cooldown-ms");if(k instanceof Error)return process.stderr.write(`error: ${k.message}
944
944
  `),1;if(O instanceof Error)return process.stderr.write(`error: ${O.message}
945
- `),1;let A=Zn(r["min-memory-percent"],"--min-memory-percent");if(A instanceof Error)return process.stderr.write(`error: ${A.message}
946
- `),1;let q=A??pc,M=$!==void 0||O!==void 0?{idleThresholdMs:$??pe.idleThresholdMs,cooldownMs:O??pe.cooldownMs}:void 0,Z;try{Z=await mE({context:n,...f!==void 0?{port:f}:{},...p!==void 0?{publish:p}:{},...h!==void 0?{hostname:h}:{},..._!==void 0?{intervalMs:_}:{},...E!==void 0?{queueIntervalMs:E}:{},...M!==void 0?{config:M}:{},...k!==void 0?{maintainerWake:k}:{},...y!==void 0?{epicReview:y}:{},...P!==void 0?{orphanReconciler:P}:{},...J!==void 0?{hangProbeCollect:J}:{},...ee!==void 0?{autoNudgeRedirectReview:ee}:{},...oe!==void 0?{rateLimitCollect:oe}:{},...V!==void 0?{rateLimitPolicy:V}:{},...se!==void 0?{rateLimitAutomation:se}:{},...B!==void 0?{autoContinue:B}:{},...C!==void 0?{miniplayerVerify:C}:{},...g!==void 0?{hungHolderCheck:g}:{},...i!==void 0?{remoteMail:i}:{},...m!==void 0?{execWorker:m}:{},...w!==void 0?{webDistDir:w}:{},minMemoryPercent:q})}catch(ne){return process.stderr.write(`${ne instanceof Error?ne.message:String(ne)}
945
+ `),1;let A=to(r["min-memory-percent"],"--min-memory-percent");if(A instanceof Error)return process.stderr.write(`error: ${A.message}
946
+ `),1;let q=A??_c,M=k!==void 0||O!==void 0?{idleThresholdMs:k??pe.idleThresholdMs,cooldownMs:O??pe.cooldownMs}:void 0,Z;try{Z=await _E({context:n,...f!==void 0?{port:f}:{},...p!==void 0?{publish:p}:{},...h!==void 0?{hostname:h}:{},..._!==void 0?{intervalMs:_}:{},...T!==void 0?{queueIntervalMs:T}:{},...M!==void 0?{config:M}:{},...R!==void 0?{maintainerWake:R}:{},...y!==void 0?{epicReview:y}:{},...P!==void 0?{orphanReconciler:P}:{},...J!==void 0?{hangProbeCollect:J}:{},...ee!==void 0?{autoNudgeRedirectReview:ee}:{},...oe!==void 0?{rateLimitCollect:oe}:{},...V!==void 0?{rateLimitPolicy:V}:{},...se!==void 0?{rateLimitAutomation:se}:{},...H!==void 0?{autoContinue:H}:{},...C!==void 0?{miniplayerVerify:C}:{},...g!==void 0?{hungHolderCheck:g}:{},...i!==void 0?{remoteMail:i}:{},...m!==void 0?{execWorker:m}:{},...w!==void 0?{webDistDir:w}:{},minMemoryPercent:q})}catch(ne){return process.stderr.write(`${ne instanceof Error?ne.message:String(ne)}
947
947
  `),n.db.close(),1}process.stdout.write(`lmbee serve: listening on http://${Z.hostname}:${Z.port}
948
- `);let W=Dc();process.stdout.write(`lmbee serve: build ${W.sha}${W.dirty?" (dirty)":""}, built ${W.builtAt}
948
+ `);let W=Uc();process.stdout.write(`lmbee serve: build ${W.sha}${W.dirty?" (dirty)":""}, built ${W.builtAt}
949
949
  `);let ae=!1,Ee=()=>{ae||(ae=!0,Z.shutdown().catch(ne=>{process.stderr.write(`lmbee serve: error during graceful shutdown: ${ne instanceof Error?ne.message:String(ne)}
950
- `)}).finally(()=>{n.db.close(),process.exit(0)}))};return process.on("SIGINT",Ee),process.on("SIGTERM",Ee),new Promise(()=>{})}if(e[0]==="whoami"){let{flags:r}=wt(e.slice(1),["json"]),{output:n,exitCode:o}=await my({json:r.json===!0});return n&&process.stdout.write(`${n}
951
- `),o}if(e[0]==="peers"||e[0]==="tell"||e[0]==="sites"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="peers"?await Sv(r):e[0]==="tell"?await vv(r):await Av(r);return n&&process.stdout.write(`${n}
952
- `),o}if(e[0]==="localweb"){let{output:r,exitCode:n}=await yv(e.slice(1));return r&&process.stdout.write(`${r}
953
- `),n}if(NS(e[0]??""))return await IS(e[0],e.slice(1));if(e[0]==="lmsound"){let{output:r,exitCode:n}=await LS(e.slice(1));return r&&process.stdout.write(`${r}
954
- `),n}if(e[0]==="exec"||e[0]==="fleet"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="exec"?await av(r):await cv(r);return n&&process.stdout.write(`${n}
955
- `),o}if(e[0]==="migrate-home"){let{flags:r,positionals:n}=wt(e.slice(1),["help","replace-existing-target-db"]);if(r.help===!0)return process.stdout.write(`${Ur}
950
+ `)}).finally(()=>{n.db.close(),process.exit(0)}))};return process.on("SIGINT",Ee),process.on("SIGTERM",Ee),new Promise(()=>{})}if(e[0]==="whoami"){let{flags:r}=yt(e.slice(1),["json"]),{output:n,exitCode:o}=await _y({json:r.json===!0});return n&&process.stdout.write(`${n}
951
+ `),o}if(e[0]==="peers"||e[0]==="tell"||e[0]==="sites"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="peers"?await xv(r):e[0]==="tell"?await Rv(r):await Nv(r);return n&&process.stdout.write(`${n}
952
+ `),o}if(e[0]==="localweb"){let{output:r,exitCode:n}=await vv(e.slice(1));return r&&process.stdout.write(`${r}
953
+ `),n}if(DS(e[0]??""))return await MS(e[0],e.slice(1));if(e[0]==="lmsound"){let{output:r,exitCode:n}=await PS(e.slice(1));return r&&process.stdout.write(`${r}
954
+ `),n}if(e[0]==="exec"||e[0]==="fleet"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="exec"?await mv(r):await fv(r);return n&&process.stdout.write(`${n}
955
+ `),o}if(e[0]==="migrate-home"){let{flags:r,positionals:n}=yt(e.slice(1),["help","replace-existing-target-db"]);if(r.help===!0)return process.stdout.write(`${Ur}
956
956
  `),0;if(n.length>0)return process.stderr.write(`lmbee migrate-home: does not accept positional arguments (got: ${n.join(" ")}). --replace-existing-target-db is a bare boolean flag: its presence alone grants consent to DELETE and replace an existing target database -- omit it entirely to keep the refusal.
957
- `),1;let o=typeof r.source=="string"?r.source:void 0,s=typeof r.target=="string"?r.target:void 0;try{let{output:i,exitCode:a}=await _v({source:o,target:s,replaceExistingTargetDb:r["replace-existing-target-db"]===!0});return i&&process.stdout.write(`${i}
958
- `),a}catch(i){return process.stderr.write(fo(i)),1}}if(e[0]==="shutdown"){let{flags:r}=wt(e.slice(1),["help","force"]);if(r.help===!0)return process.stdout.write(`${Ur}
959
- `),0;let{output:n,exitCode:o}=await $v({force:r.force===!0});return n&&process.stdout.write(n),o}if(e[0]==="cron"&&e[1]==="export")try{let{output:r,exitCode:n}=gE(e.slice(2));return r&&process.stdout.write(`${r}
960
- `),n}catch(r){return process.stderr.write(fo(r)),1}if(e[0]==="cron"&&e[1]==="import"){let{positionals:r,flags:n}=wt(e.slice(2),["json","help"]);if(n.help!==!0){let o=n.json===!0;try{ns("import",r,n);let s=r[0];if(s===void 0)throw new U("INVALID_ARGUMENT","an import PATH is required");yE(s)}catch(s){if(s instanceof U)return process.stdout.write(o?`${JSON.stringify({schema_version:1,ok:!1,error:{code:s.code,message:s.message}})}
957
+ `),1;let o=typeof r.source=="string"?r.source:void 0,s=typeof r.target=="string"?r.target:void 0;try{let{output:i,exitCode:a}=await bv({source:o,target:s,replaceExistingTargetDb:r["replace-existing-target-db"]===!0});return i&&process.stdout.write(`${i}
958
+ `),a}catch(i){return process.stderr.write(ho(i)),1}}if(e[0]==="shutdown"){let{flags:r}=yt(e.slice(1),["help","force"]);if(r.help===!0)return process.stdout.write(`${Ur}
959
+ `),0;let{output:n,exitCode:o}=await Lv({force:r.force===!0});return n&&process.stdout.write(n),o}if(e[0]==="cron"&&e[1]==="export")try{let{output:r,exitCode:n}=TE(e.slice(2));return r&&process.stdout.write(`${r}
960
+ `),n}catch(r){return process.stderr.write(ho(r)),1}if(e[0]==="cron"&&e[1]==="import"){let{positionals:r,flags:n}=yt(e.slice(2),["json","help"]);if(n.help!==!0){let o=n.json===!0;try{as("import",r,n);let s=r[0];if(s===void 0)throw new U("INVALID_ARGUMENT","an import PATH is required");vE(s)}catch(s){if(s instanceof U)return process.stdout.write(o?`${JSON.stringify({schema_version:1,ok:!1,error:{code:s.code,message:s.message}})}
961
961
  `:`${s.code}: ${s.message}
962
- `),s.exitCode;throw s}}}let t;try{t=pi({readOnly:IT(e)});let{output:r,exitCode:n}=await LT(t,e);return r&&process.stdout.write(`${r}
963
- `),n}catch(r){return process.stderr.write(fo(r)),1}finally{t?.db.close()}}mq().then(e=>{process.exitCode=e});
962
+ `),s.exitCode;throw s}}}let t;try{t=wi({readOnly:MT(e)});let{output:r,exitCode:n}=await PT(t,e);return r&&process.stdout.write(`${r}
963
+ `),n}catch(r){return process.stderr.write(ho(r)),1}finally{t?.db.close()}}yq().then(e=>{process.exitCode=e});