@lmctl-ai/lmctl 0.2.124 → 0.2.125

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 kv=Object.create;var La=Object.defineProperty;var xv=Object.getOwnPropertyDescriptor;var Rv=Object.getOwnPropertyNames;var Nv=Object.getPrototypeOf,Lv=Object.prototype.hasOwnProperty;var Pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Iv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),go=(e,t)=>{for(var r in t)La(e,r,{get:t[r],enumerable:!0})},Cv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Rv(t))!Lv.call(e,o)&&o!==r&&La(e,o,{get:()=>t[o],enumerable:!(n=xv(t,o))||n.enumerable});return e};var Ut=(e,t,r)=>(r=e!=null?kv(Nv(e)):{},Cv(t||!e||!e.__esModule?La(r,"default",{value:e,enumerable:!0}):r,e));var xt=Iv(ut=>{"use strict";function ra(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 AI(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 J_(e,t,r){let n=" ".repeat(Math.max(0,t-Ir(e)));return r?n+e:e+n}function $I(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 kI(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 xI(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 RI(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=RI(t),n=[],o=(s,i)=>{n[s]=Math.max(n[s]??0,i)};for(let s of e){let i=$I(s);i.headers!==void 0&&ra(i.headers).forEach((a,c)=>{o(c,Ir(a))});for(let a of i.rows.map(ra))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=z_;function NI(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 Y_(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=NI(i),u=AI(n),d=kI(c),m=t??z_([{rows:e,headers:r}],{max:a}),f=e.map(ra);r!==void 0&&f.unshift(ra(r));let p=f.map(h=>{let _=h.length-1;for(;_>=0&&h[_]==="";)_--;return h.slice(0,_+1).map((g,y)=>{let E=m[y]||0,v=o&&E>0&&(y!==_||s)?xI(g,E,d):g;return u[y]==="right"?J_(v,E,!0):y===_?v:J_(v,E,!1)}).join(" ")}).join(`
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(`
3
3
  `);return p===""||l===""?p:`${l}${p.split(`
4
4
  `).join(`
5
- ${l}`)}`}ut.renderGrid=Y_;function Q_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a}={}){return Y_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a})}function LI(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a,stream:c=process.stdout}={}){let l=Q_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a});l&&c.write(`${l}
6
- `)}ut.formatTable=Q_;ut.printTable=LI;function K_(e){return e instanceof Date?e.getTime():typeof e=="number"?e:typeof e=="string"&&e.trim()?Date.parse(e):NaN}function II(e,{now:t=Date.now()}={}){let r=K_(t);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=K_(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=II;function CI(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=CI;var ou=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function OI(e,{maxUnit:t="w",style:r="spaced"}={}){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let n=ou.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=ou.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 ou.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=OI;function X_(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 Z_(e){let t=X_(e);return Number.isNaN(t.getTime())?"unknown":`${Jt(t.getHours())}:${Jt(t.getMinutes())}:${Jt(t.getSeconds())}`}ut.formatClock=Z_;function DI(e){let t=X_(e);return Number.isNaN(t.getTime())?"unknown":`${`${t.getFullYear()}-${Jt(t.getMonth()+1)}-${Jt(t.getDate())}`} ${Z_(t)}`}ut.formatLocalTimestamp=DI;function MI(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e*100)}%`:"?%"}ut.formatPercent=MI;function PI(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=PI;function UI(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=UI;function FI(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=FI});import{createHash as uM,randomBytes as RT}from"node:crypto";function NT(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||os.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||os.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||os.scope,ports:os.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||os.authUrl).replace(/\/+$/,"")}}function LT(e=RT){let t=e(32).toString("base64url"),r=uM("sha256").update(t).digest("base64url");return{verifier:t,challenge:r}}function IT(e=RT){return e(16).toString("base64url")}function CT(e){return`http://127.0.0.1:${e}/callback`}function OT(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:CT(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 DT(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 MT(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:CT(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 UT(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function PT(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 UT(n)}`);return await n.json()}async function UT(e){try{return(await e.text()).slice(0,300)}catch{return""}}var os,FT=Pt(()=>{os={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var BT={};go(BT,{appkeyDir:()=>jT,persistCredentials:()=>HT,runLogin:()=>TM});import{createServer as dM}from"node:http";import{spawn as mM}from"node:child_process";import{hostname as fM}from"node:os";import{mkdir as pM,rename as hM,writeFile as gM}from"node:fs/promises";import{homedir as _M}from"node:os";import{join as pa}from"node:path";function jT(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||pa(_M(),".config");return pa(t,"lmctl")}async function HT(e,t,r,n=process.env){let o=jT(n);await pM(o,{recursive:!0,mode:448});let s=pa(o,"appkey.json"),i={version:1,appkey:e.appkey,user_id:e.user_id,label:e.label,issued_at:e.created_at};await qT(s,JSON.stringify(i,null,2)+`
8
- `);let a=null;if(t.refresh_token){a=pa(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 qT(a,JSON.stringify(c,null,2)+`
9
- `)}return{appkeyPath:s,identityPath:a}}async function qT(e,t){let r=`${e}.tmp-${process.pid}`;await gM(r,t,{mode:384}),await hM(r,e)}async function wM(e){let t,r=new Promise(o=>t=o),n=dM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=DT(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 yM(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 yM(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 EM(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=mM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
10
10
  If your browser didn't open, visit:
11
11
  ${e}
12
12
 
13
- `)}async function TM(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env,n=NT(r),o=e.fetchImpl??fetch,s=e.openBrowserFn??EM;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}=LT(),c=IT(),{server:l,port:u,wait:d}=await wM(n.ports);try{let m=OT(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 MT(n,{code:f.code,verifier:i,port:u},o),h=await PT(n,{idToken:p.id_token,label:fM()},o),{appkeyPath:_,identityPath:g}=await HT(h,p,n,r);return t.stdout.write(`
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(`
15
15
  \u2713 Signed in as ${h.user_id}
16
- \u2713 Appkey saved to ${_} (0600)
17
- `+(g?`\u2713 Refresh token saved to ${g} (0600, for silent re-mint)
16
+ \u2713 Appkey saved to ${w} (0600)
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 WT=Pt(()=>{FT()});import{createHash as HM,randomBytes as ZT}from"node:crypto";function eb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ss.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ss.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ss.scope,ports:ss.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ss.authUrl).replace(/\/+$/,"")}}function tb(e=ZT){let t=e(32).toString("base64url");return{verifier:t,challenge:HM("sha256").update(t).digest("base64url")}}function rb(e=ZT){return e(16).toString("base64url")}function nb(e){return`http://127.0.0.1:${e}/callback`}function ob(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:nb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function sb(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 ib(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:nb(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 cb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function ab(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 cb(n)}`);return n.json()}async function cb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ss,lb=Pt(()=>{ss={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var fb={};go(fb,{appkeyDir:()=>db,persistCredentials:()=>mb,runLogin:()=>ZM});import{spawn as BM}from"node:child_process";import{mkdir as WM,rename as GM,writeFile as VM}from"node:fs/promises";import{createServer as JM}from"node:http";import{homedir as KM,hostname as zM}from"node:os";import{join as _a}from"node:path";function db(e=process.env){return _a(e.XDG_CONFIG_HOME?.trim()||_a(KM(),".config"),"lmctl")}async function mb(e,t,r,n=process.env){let o=db(n);await WM(o,{recursive:!0,mode:448});let s=_a(o,"appkey.json");await ub(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=_a(o,"identity.json"),await ub(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 ub(e,t){let r=`${e}.tmp-${process.pid}`;await VM(r,t,{mode:384}),await GM(r,e)}async function YM(e){let t,r=new Promise(o=>{t=o}),n=JM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=sb(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 QM(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function QM(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 XM(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=BM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
24
24
  If your browser didn't open, visit:
25
25
  ${e}
26
26
 
27
- `)}async function ZM(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=eb(r),{verifier:o,challenge:s}=tb(),i=rb(),{server:a,port:c,wait:l}=await YM(n.ports);try{let u=ob(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
28
- `),(e.openBrowserFn??XM)(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 ib(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await ab(n,{idToken:m.id_token,label:zM()},e.fetchImpl??fetch),p=await mb(f,m,n,r);return t.stdout.write(`
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(`
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 pb=Pt(()=>{lb()});import{createHash as gP,randomBytes as yb}from"node:crypto";function Eb(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 Tb(e=yb){let t=e(32).toString("base64url");return{verifier:t,challenge:gP("sha256").update(t).digest("base64url")}}function bb(e=yb){return e(16).toString("base64url")}function Sb(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:Sb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Ab(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 $b(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Sb(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 xb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function kb(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 xb(n)}`);return n.json()}async function xb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var is,Rb=Pt(()=>{is={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var Cb={};go(Cb,{appkeyDir:()=>Lb,persistCredentials:()=>Ib,runLogin:()=>kP});import{spawn as _P}from"node:child_process";import{mkdir as wP,rename as yP,writeFile as EP}from"node:fs/promises";import{createServer as TP}from"node:http";import{homedir as bP,hostname as SP}from"node:os";import{join as ya}from"node:path";function Lb(e=process.env){return ya(e.XDG_CONFIG_HOME?.trim()||ya(bP(),".config"),"lmctl")}async function Ib(e,t,r,n=process.env){let o=Lb(n);await wP(o,{recursive:!0,mode:448});let s=ya(o,"appkey.json");await Nb(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=ya(o,"identity.json"),await Nb(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 Nb(e,t){let r=`${e}.tmp-${process.pid}`;await EP(r,t,{mode:384}),await yP(r,e)}async function vP(e){let t,r=new Promise(o=>{t=o}),n=TP((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Ab(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 AP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function AP(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 $P(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=_P(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
35
35
  If your browser didn't open, visit:
36
36
  ${e}
37
37
 
38
- `)}async function kP(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=Eb(r),{verifier:o,challenge:s}=Tb(),i=bb(),{server:a,port:c,wait:l}=await vP(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
39
- `),(e.openBrowserFn??$P)(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 $b(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await kb(n,{idToken:m.id_token,label:SP()},e.fetchImpl??fetch),p=await Ib(f,m,n,r);return t.stdout.write(`
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(`
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 Ob=Pt(()=>{Rb()});import{createHash as BP,randomBytes as Pb}from"node:crypto";function Ub(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 Fb(e=Pb){let t=e(32).toString("base64url");return{verifier:t,challenge:BP("sha256").update(t).digest("base64url")}}function qb(e=Pb){return e(16).toString("base64url")}function jb(e){return`http://127.0.0.1:${e}/callback`}function Hb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:jb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function Bb(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 Wb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:jb(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 Vb(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 Vb(n)}`);return n.json()}async function Vb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var us,Jb=Pt(()=>{us={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var Qb={};go(Qb,{appkeyDir:()=>zb,persistCredentials:()=>Yb,runLogin:()=>eU});import{spawn as WP}from"node:child_process";import{mkdir as GP,rename as VP,writeFile as JP}from"node:fs/promises";import{createServer as KP}from"node:http";import{homedir as zP,hostname as YP}from"node:os";import{join as Ea}from"node:path";function zb(e=process.env){return Ea(e.XDG_CONFIG_HOME?.trim()||Ea(zP(),".config"),"lmctl")}async function Yb(e,t,r,n=process.env){let o=zb(n);await GP(o,{recursive:!0,mode:448});let s=Ea(o,"appkey.json");await Kb(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=Ea(o,"identity.json"),await Kb(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 Kb(e,t){let r=`${e}.tmp-${process.pid}`;await JP(r,t,{mode:384}),await VP(r,e)}async function QP(e){let t,r=new Promise(o=>{t=o}),n=KP((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=Bb(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 XP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function XP(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 ZP(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=WP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
46
46
  If your browser didn't open, visit:
47
47
  ${e}
48
48
 
49
- `)}async function eU(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=Ub(r),{verifier:o,challenge:s}=Fb(),i=qb(),{server:a,port:c,wait:l}=await QP(n.ports);try{let u=Hb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
50
- `),(e.openBrowserFn??ZP)(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 Wb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await Gb(n,{idToken:m.id_token,label:YP()},e.fetchImpl??fetch),p=await Yb(f,m,n,r);return t.stdout.write(`
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(`
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 Xb=Pt(()=>{Jb()});import{createHash as aU,randomBytes as oS}from"node:crypto";function sS(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 iS(e=oS){let t=e(32).toString("base64url");return{verifier:t,challenge:aU("sha256").update(t).digest("base64url")}}function aS(e=oS){return e(16).toString("base64url")}function cS(e){return`http://127.0.0.1:${e}/callback`}function lS(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:cS(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function uS(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 dS(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:cS(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 fS(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function mS(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 fS(n)}`);return n.json()}async function fS(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ds,pS=Pt(()=>{ds={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var wS={};go(wS,{appkeyDir:()=>gS,persistCredentials:()=>_S,runLogin:()=>wU});import{spawn as cU}from"node:child_process";import{mkdir as lU,rename as uU,writeFile as dU}from"node:fs/promises";import{createServer as mU}from"node:http";import{homedir as fU,hostname as pU}from"node:os";import{join as Ta}from"node:path";function gS(e=process.env){return Ta(e.XDG_CONFIG_HOME?.trim()||Ta(fU(),".config"),"lmctl")}async function _S(e,t,r,n=process.env){let o=gS(n);await lU(o,{recursive:!0,mode:448});let s=Ta(o,"appkey.json");await hS(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=Ta(o,"identity.json"),await hS(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 hS(e,t){let r=`${e}.tmp-${process.pid}`;await dU(r,t,{mode:384}),await uU(r,e)}async function hU(e){let t,r=new Promise(o=>{t=o}),n=mU((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=uS(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 gU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function gU(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 _U(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=cU(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
57
57
  If your browser didn't open, visit:
58
58
  ${e}
59
59
 
60
- `)}async function wU(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=sS(r),{verifier:o,challenge:s}=iS(),i=aS(),{server:a,port:c,wait:l}=await hU(n.ports);try{let u=lS(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
61
- `),(e.openBrowserFn??_U)(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 dS(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await mS(n,{idToken:m.id_token,label:pU()},e.fetchImpl??fetch),p=await _S(f,m,n,r);return t.stdout.write(`
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(`
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 yS=Pt(()=>{pS()});import{spawn as tq}from"node:child_process";import{openSync as rq,mkdirSync as nq,writeFileSync as oq}from"node:fs";import{homedir as sq}from"node:os";import{join as _d}from"node:path";import{mkdirSync as mq,readFileSync as Ov,renameSync as fq,writeFileSync as pq}from"node:fs";import{homedir as Dv}from"node:os";import{dirname as _q,join as Ed}from"node:path";var lq=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}},ws=class extends Error{code="APPKEY_INVALID";source;constructor(t){super(`${t} resolved an invalid lmctl appkey`),this.name="AppkeyInvalidError",this.source=t}},ys=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 Mv="https://lmctl.ai/auth",Pv=1e4;function Ia(e){return e.length>0&&!e.includes(`
66
- `)}function Se(e={}){let t=e.env??process.env,r=e.fs??{readFileSync:(c,l)=>Ov(c,l)},n=e.homedir??Dv,o=t.LMCTL_APPKEY?.trim();if(o&&Ia(o))return{appkey:o,source:"env:LMCTL_APPKEY",envelope:null};let s=t.LMCTL_APPKEY_FILE?.trim();if(s){let c=Td(r,s,"env:LMCTL_APPKEY_FILE");if(c)return c}let i=Uv(t,n),a=Td(r,i,"file:default");if(a)return a;throw new Gr}async function Sd(e,t={}){let r=await jv("/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 Bv(r,"validate appkey response",sr);return{valid:!0,userId:bd(n,"user_id","validate appkey response",sr),label:bd(n,"label","validate appkey response",sr)}}function Td(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"&&Ia(i.appkey.trim())?{appkey:i.appkey.trim(),source:r,envelope:i}:null}}return Ia(o)?{appkey:o,source:r,envelope:null}:null}function Uv(e,t){let r=e.XDG_CONFIG_HOME?.trim()||Ed(t(),".config");return Ed(r,"lmctl","appkey.json")}function Fv(e){let t=e.env??process.env;return(e.authBaseUrl?.trim()||t.LMCTL_AUTH_BASE_URL?.trim()||Mv).replace(/\/+$/,"")}function qv(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 jv(e,t,r,n){return await Hv(e,t,r,n,r.timeoutMs)}async function Hv(e,t,r,n,o,s){let i=qv(r,n),a=`${Fv(r)}${e}`,c=o??Pv,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 Bv(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 bd(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 Eq={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,L={}){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(L.tolerate409!==!1&&kd(B)==="mailbox_exists")return;throw $d("create mailbox failed",k.status,B)}await R(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 L=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:vd(x.body),attachments:L.map(vd)})},"allocate message failed"),B=[{target:k.body,bytes:x.body.bytes},...k.attachments.map((C,w)=>({target:C,bytes:L[w].bytes}))];for(let{target:C,bytes:w}of B){let T=new FormData;for(let[U,J]of Object.entries(C.fields))T.append(U,J);T.append("file",new Blob([new Uint8Array(w)],{type:C.content_type}),C.name);let N=await r(C.upload_url,{method:"POST",body:T});await R(N,`upload failed for ${C.name}`)}return await S(Wv(t,k.finalize_url),{method:"POST",headers:n},"finalize message failed"),k.seq}async function c(x,L={}){let k=new URLSearchParams;if(L.status&&k.set("status",L.status),L.after!==void 0&&k.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");k.set("wait_s",String(L.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 L=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");L.set("limit",String(x.limit))}let k=L.size>0?`?${L.toString()}`:"";return S(`${t}/messages/recent${k}`,{headers:n},"get recent messages failed")}async function u(x,L){return S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${L}`,{headers:n},"get message failed")}async function d(x,L){let k=await u(x,L);return{...k,body:Ad(k.body),attachments:k.attachments.map(Ad)}}async function m(x,L){return S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${L}/thread`,{headers:n},"get thread failed")}async function f(x){let L=await r(x);return await R(L,"download failed"),new Uint8Array(await L.arrayBuffer())}async function p(x,L){await S(`${t}/mailboxes/${encodeURIComponent(x)}/messages/${L}`,{method:"DELETE",headers:n},"delete message failed")}async function h(x,L,k){return await S(`${t}/sites`,{method:"POST",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site_name:x,site_uuid:L,mailbox:k})},"register site failed")}async function _(x){return await S(`${t}/sites/${encodeURIComponent(x)}`,{headers:n},"resolve site failed")}async function g(x={}){let L=new URLSearchParams;if(x.cursor!==void 0&&L.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");L.set("limit",String(x.limit))}let k=L.size>0?`?${L.toString()}`:"";return S(`${t}/sites${k}`,{headers:n},"list sites failed")}async function y(x,L){return S(`${t}/sites/name`,{method:"PUT",headers:{...n,"content-type":"application/json"},body:JSON.stringify({site:x,name:L})},"set site name failed")}async function E(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,L,k){let B=await r(x,L);await R(B,k);try{return await B.json()}catch(C){throw new Error(`${k}: invalid JSON response: ${Gv(C)}`)}}async function R(x,L){if(x.ok)return;let k=await x.text().catch(()=>"");throw $d(L,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:_,listSites:g,setSiteName:y,deleteSiteName:E,deleteSite:v}}function vd(e){return{name:e.name,size:e.bytes.byteLength,content_type:e.contentType}}function Ad(e){return{name:e.name,size:e.size,content_type:e.content_type}}function $d(e,t,r){return new Ft(e,t,r,kd(r))}function kd(e){try{let t=JSON.parse(e);return typeof t.error=="string"?t.error:void 0}catch{return}}function Wv(e,t){return/^https?:\/\//i.test(t)?t:`${e}${t.startsWith("/")?"":"/"}${t}`}function Gv(e){return e instanceof Error?e.message:String(e)}import{execFile as EA}from"node:child_process";import{existsSync as TA}from"node:fs";import{join as bA}from"node:path";import{promisify as SA}from"node:util";import{existsSync as xd}from"node:fs";import{createRequire as Vv}from"node:module";import{dirname as Jv}from"node:path";var Ca=null;function Kv(){return Ca===null&&(Ca=Vv(import.meta.url)("node:sqlite").DatabaseSync),Ca}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"},Yv={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 Qv(e){return Yv[e]??zv[e&255]??`SQLITE_UNKNOWN_${e}`}var Xv="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=Qv(t.errcode),e;if(t.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(t.message)))throw new TypeError(Xv);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 Zv(){let e="unable to open database file";return Object.assign(new Error(e),{code:"SQLITE_CANTOPEN",errcode:14,errstr:e})}function Rd(e){return e instanceof Uint8Array&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function eA(e){if(e==null)return e;if(Array.isArray(e))return e.map(Rd);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=Rd(n);return t}return e}function tA(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 Es(e){return e.map((t,r)=>{if(t===void 0)return null;if(r===0&&tA(t)){let n={};for(let[o,s]of Object.entries(t))n[o]=s===void 0?null:s;return n}return t})}var Oa=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(...Es(t));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){qt(r)}}get(...t){try{return this.project(this.handle.get(...Es(t)))}catch(r){qt(r)}}all(...t){try{return this.handle.all(...Es(t)).map(r=>this.project(r))}catch(r){qt(r)}}*iterate(...t){let r;try{r=this.handle.iterate(...Es(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=eA(t);return this.pluckMode&&Array.isArray(r)?r[0]:r}},Da=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&&!xd(Jv(t)))throw new TypeError("Cannot open database because the directory does not exist");if(r.fileMustExist===!0&&!n&&!xd(t))throw Zv();this.name=t,this.memory=n,this.readonly=r.readonly===!0;try{this.handle=new(Kv())(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 Oa(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(!rA(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(!nA(i))throw i}throw s}}};function rA(e){return e instanceof Error&&/cannot rollback - no transaction is active/i.test(e.message)}function nA(e){return e instanceof Error&&/no such savepoint:/i.test(e.message)}var ht=Da;import{existsSync as Pa,lstatSync as oA,mkdirSync as sA,readFileSync as Od,realpathSync as Nd}from"node:fs";import{basename as iA,dirname as Ua,isAbsolute as aA,join as cA,relative as lA,resolve as Ld}from"node:path";import{fileURLToPath as uA}from"node:url";var Dd=cA(Ua(uA(import.meta.url)),"schema.sql");function _o(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 dA(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 mA(e,t){if(!(e===":memory:"||Pa(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 fA(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 pA(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 hA(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 gA(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 _A(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 Fa(e){let t=process.env.LMBEE_TEST_DB_ROOT;if(!t||e===":memory:")return;let r=[],n=Ld(e);for(;oA(n,{throwIfNoEntry:!1})===void 0;){r.unshift(iA(n));let i=Ua(n);if(i===n)throw new Error("Cannot resolve test database path");n=i}let o=Ld(Nd(n),...r),s=lA(Nd(t),o);if(s===".."||s.startsWith("../")||s.startsWith("..\\")||aA(s))throw new Error(`Database path is outside the test database root: ${e}`)}function Id(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 Ts=62;function Cd(e){let t=e.pragma("user_version",{simple:!0});if(t<=Ts)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)>Ts)n=`schema_meta.min_reader_version=${r} declares a breaking floor above ${Ts}`;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, ${Ts}, 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 Ma;function wA(){return Ma===void 0&&(Ma=[...Od(Dd,"utf8").matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/gi)].map(t=>t[1])),Ma}function yA(e,t){let r=new Set(e.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(o=>o.name)),n=wA().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 bs(e,t={}){let r=_o(e);dA(r);let n=!e&&typeof process.env.LMBEE_DB=="string"&&process.env.LMBEE_DB!=="";if(n&&mA(r,"LMBEE_DB"),Fa(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(!Pa(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{Id(a),Cd(a),a.pragma("busy_timeout = 5000"),yA(a,r)}catch(c){throw a.close(),c}return{path:r,db:a,close:()=>a.close()}}if(r!==":memory:"){let a=Ua(r);Pa(a)||sA(a,{recursive:!0})}let o=new ht(r,n?{fileMustExist:!0}:void 0);try{Id(o),Cd(o)}catch(a){throw o.close(),a}o.pragma("journal_mode = WAL"),o.pragma("busy_timeout = 5000");let s=Od(Dd,"utf8"),i=o.transaction(()=>{fA(o),pA(o),_A(o),gA(o),hA(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 Md(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 Ss(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 Pd(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 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)
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 qa(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 Ud(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 Fd(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 qd(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 jd(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 Hd(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 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)
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 Bd(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 ja(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 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)
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 Ha(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 Wa(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 Ba(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 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)
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 Wd(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 Gd(e,t){e.prepare("DELETE FROM auto_nudge_suspended WHERE team = ?").run(t)}function Vd(e){return e.prepare("SELECT * FROM auto_nudge_suspended ORDER BY team").all()}function Jd(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 Kd(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 Yd(e,t,r){e.prepare("UPDATE unresolvable_teamfile_watch SET surfaced_ts = ? WHERE team = ?").run(r,t)}function Qd(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_cli_activity_ts)
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)
107
107
  VALUES (?, ?)
108
- ON CONFLICT(team) DO UPDATE SET last_cli_activity_ts = excluded.last_cli_activity_ts`).run(t,r)}function Xd(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 Wa(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 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)
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 Ga(e,t,r,n){e.prepare("DELETE FROM orphan_watch WHERE target = ? AND started_at_ms = ? AND pid = ?").run(t,r,n)}function Zd(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 em(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 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)
114
114
  VALUES (?, ?, ?, ?, ?, ?)
115
- ON CONFLICT(target, started_at_ms, pid, observed_at) DO NOTHING`).run(t,r,n,o,s,i)}function tm(e,t){e.prepare("DELETE FROM hang_probe_observation WHERE observed_at < ?").run(t)}function rm(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 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)
116
116
  VALUES (?, ?, ?, ?, ?)
117
- ON CONFLICT(target, started_at_ms, pid) DO NOTHING`).run(t,r,n,o,s)}function nm(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 om(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 om(e,t){e.prepare("UPDATE team_progress SET quota_exhausted_last_seen_ts = NULL, quota_exhausted_message = NULL WHERE team = ?").run(t)}function sm(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 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)
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 vA=SA(EA);function AA(e){return TA(bA(e,".git"))}async function Va(e,t){try{let r=t.replace(/\.\d{3}Z$/,"Z"),{stdout:n}=await vA("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 $A(e,t){if(t===null)return"ACTIVE";for(let r of e)if(await Va(r,t))return"ACTIVE";return e.every(r=>!AA(r))?"NOT_A_REPO":"UNKNOWN"}async function Ja(e,t,r,n=Date.now()){let o=t.folders&&t.folders.length>0?t.folders:[t.repoPath],s=ie(e,r),i=await $A(o,s?.last_scan_ts??null);return Pd(e,r,i,new Date(n).toISOString(),new Date().toISOString()),ie(e,r)}import{existsSync as Za,readFileSync as hm,realpathSync as jA,statSync as HA}from"node:fs";import{join as fm,resolve as ks}from"node:path";var kA=/^[a-z0-9-]+$/;function Ka(e){if(e.length>128||!kA.test(e))throw new Error("site-id must match [a-z0-9-]+");return e}function im(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 Ka(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()||xA(e))throw new Error(`${t} must ${r?"":"be non-empty and "}contain no colons or control characters`);return e}function xA(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 LA,mkdir as IA,readFile as CA,rename as OA,unlink as DA,writeFile as MA}from"node:fs/promises";import{randomUUID as PA}from"node:crypto";import{homedir as RA}from"node:os";import{dirname as NA,join as am}from"node:path";function za(e=process.env){let t=e.LMAUTO_DB?.trim();return t?NA(t):am(e.HOME?.trim()||RA(),".lmauto")}function vs(e=process.env){return am(za(e),"site-uuid")}var cm=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,UA={readText:e=>CA(e,"utf8"),mkdir:async e=>{await IA(e,{recursive:!0})},writePrivate:(e,t)=>MA(e,t,{flag:"wx",mode:384}),link:LA,rename:OA,remove:DA};async function lm(e={}){let t=e.env??process.env,r=e.io??UA,n=vs(t),o=await $s(r,n);if(o.value)return o.value;await r.mkdir(za(t));let s={io:r,randomUuid:e.randomUuid??PA,pid:e.pid??process.pid,sleep:e.sleep??(i=>new Promise(a=>setTimeout(a,i)))};return o.exists?qA(s,n):FA(s,n)}async function FA(e,t){let r=await um(e,t);try{try{return await e.io.link(r.temporary,t),r.candidate}catch(n){if(n.code!=="EEXIST")throw n;return Ya(e,t)}}finally{await As(e.io,r.temporary)}}async function qA(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 Ya(e,t)}let n,o,s=!1;try{n=await um(e,t),o=`${t}.${e.pid}.${n.candidate}.corrupt`;let i=await $s(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 Ya(e,t);let c=await $s(e.io,t);throw s&&!c.exists&&(await e.io.rename(o,t),s=!1),a}}finally{n&&await As(e.io,n.temporary),s&&o&&await As(e.io,o),await As(e.io,r)}}async function um(e,t){let r=e.randomUuid().toLowerCase();if(!cm.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 Ya(e,t){for(let r=0;r<100;r+=1){let n=await $s(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 $s(e,t){try{let r=(await e.readText(t)).trim();return cm.test(r)?{exists:!0,value:r.toLowerCase()}:{exists:!0}}catch(r){if(r.code==="ENOENT")return{exists:!1};throw r}}async function As(e,t){try{await e.remove(t)}catch(r){if(r.code!=="ENOENT")throw r}}function Qa(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=Xa(r.bootId)?r.bootId:null;return{pid:r.pid,ownerLabel:r.ownerLabel,startedAt:r.startedAt,pidStartTicks:n,bootId:o}}function Xa(e){return typeof e=="string"&&/^[0-9a-f-]{36}$/i.test(e)}function hn(e){return`lmauto-site-${e}`}function dm(e){return`${hn(e)}-exec`}function mm(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 xs(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 wo(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?gm(i,f):[ks(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 gm(e,t){let r=new Set,n=[];for(let o of t){let s=ks(e,o);r.has(s)||(r.add(s),n.push(s))}return n}var BA=/^_TEAM_(\s|$)/,WA=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function GA(e){let t={};for(let m of e.matchAll(WA)){let f=m[1];f in t||(t[f]=m[2]!==void 0?m[2]:m[3])}if(t.channel==="lmmail")return VA(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?gm(n,u):[ks(n)];return{channel:"local",name:r,repoPath:n,leadAlias:o,promptName:l,description:i??"",autoNudge:l!=="on-demand",folders:d,coordinator:c==="true"}}function VA(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 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}
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 JA=/^(`{3,}|~{3,})/;function ec(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let o=n.trim(),s=JA.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||!BA.test(o))continue;let i=GA(o);i&&t.push(i)}return t}function pm(e){return e.toLowerCase().endsWith(".md")}function KA(e,t){let r=new Set,n=[];for(let o of[e,...t])if(!(!o||r.has(o))&&(r.add(o),!!Za(o))){try{if(!HA(o).isFile())continue}catch{continue}n.push(o)}return n}function zA(e,t=[]){let r=KA(e,t),n=new Map,o=s=>{try{return hm(s,"utf8")}catch{return null}};for(let s of r){if(!pm(s))continue;let i=o(s);if(i!==null)for(let a of ec(i))n.has(a.name)||n.set(a.name,a)}for(let s of r){if(pm(s))continue;let i=o(s);if(i!==null)for(let a of wo(i))n.has(a.name)||n.set(a.name,a)}return[...n.values()]}function Rs(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 tc(e){return e.prepare("SELECT * FROM sources ORDER BY id").all()}function Ns(e,t){e.prepare("DELETE FROM sources WHERE path = ?").run(t)}function YA(e){let t=ks(e);return Za(t)?jA(t):null}function Q(e){let t=YA(fm(e.repoPath,`${e.name}.lmctl`));if(t)return t;throw Za(e.repoPath)?new Error(`resolveTeamfilePath: cannot resolve a teamfile for team "${e.name}" -- expected "${fm(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 QA=/^_MEMBER_(\s|$)/,XA=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function jt(e,t){return nc(e).find(r=>r.alias===t)?.provider??null}function rc(e){return nc(e).filter(t=>t.sessionid!==void 0&&t.sessionid.length>0).length}function Vr(e){return nc(e).filter(t=>t.alias!==void 0).map(t=>({alias:t.alias,provider:t.provider??null}))}function nc(e){let t;try{t=hm(Q(e),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
130
- `)){if(!QA.test(n.trim()))continue;let o={};for(let s of n.matchAll(XA)){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=tc(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 _m(e,t,r){return r.running.some(n=>{let o=gn(n.target);return o!==null&&o.alias===t&&o.teamfilePath===e})}function ZA(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 Ls(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get("active");return t?JSON.parse(t.v):null}function e$(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 Is(e,t,r){let n=ZA(t,r,Ls(e));return e$(e,n.active),n}import{randomUUID as nf}from"node:crypto";import{existsSync as of,mkdirSync as w$,readFileSync as js,rmSync as y$,writeFileSync as sf}from"node:fs";import{homedir as E$}from"node:os";import{join as af,resolve as rf,sep as T$}from"node:path";var dj=64*1024;import{readFileSync as Cs,writeFileSync as r$}from"node:fs";function n$(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 wm(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=Cs(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 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(`
131
131
 
132
132
  --- addendum, ${d.created_ts} ---
133
- ${Cs(d.prompt_file,"utf8")}`)}catch{u=!1;break}if(!u){o.push(...s);continue}if(l.length>0){r$(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 sc(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=wm(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{Cs(c.prompt_file,"utf8")}catch{continue}if(!n$(e,c.id))continue;let d;try{d=Cs(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 Em}from"node:crypto";import{mkdtempSync as Tm,rmSync as bm,writeFileSync as Sm}from"node:fs";import{tmpdir as vm}from"node:os";import{join as Os}from"node:path";import{spawn as Am}from"node:child_process";var $m=50*6e4,km=5e3,Kr=["systemd-run","--user","--scope","--collect","--quiet","--","lmctl"];async function Ht(e,t,r={}){let n=r.timeoutMs??$m,o=r.sigkillGraceMs??km,s=Tm(Os(vm(),"lmauto-send-")),i=Os(s,`${Em()}.md`);Sm(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=Am(l,u,{detached:!0,stdio:["ignore","pipe","pipe"]});m.unref();let f="",p="",h=!1,_=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()}y({kind:"timeout"})}},n);function g(){clearTimeout(_);try{bm(s,{recursive:!0,force:!0})}catch{}}function y(E){h||(h=!0,g(),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 R of S){let x=ym(R);x&&y(x)}}),m.stderr?.on("data",E=>{p+=E.toString("utf8")}),m.on("error",E=>{y({kind:"error",message:E.message})}),m.on("close",(E,v)=>{if(!h){if(f.trim()){let S=ym(f);if(S){y(S);return}}if(E!==0||v!==null){y({kind:"error",message:`lctl exited ${v?`via signal ${v}`:`with code ${E}`} without a recognized status line: ${p.trim().slice(-2e3)}`});return}y({kind:"no-signal",rawOutput:p.trim()})}})})}function ym(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 xm(e,t,r={}){let n=Tm(Os(vm(),"lmauto-send-")),o=Os(n,`${Em()}.md`);Sm(o,t,{mode:384});let i=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",o,"--json"],[a,...c]=i,l=Am(a,c,{detached:!0,stdio:"ignore"});l.unref();function u(){try{bm(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??km).unref()},r.timeoutMs??$m);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 Rm(e,t){return e.prepare("SELECT 1 FROM kv WHERE k = ?").get(wn+t)!==void 0}function Nm(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:Nm(t,r.v)}function Im(e){return e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${wn}%`).map(r=>Nm(r.k.slice(wn.length),r.v))}function Cm(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 Om(e,t){return e.prepare("DELETE FROM kv WHERE k = ?").run(wn+t).changes>0}function o$(e){return{team:e.team,alias:e.alias,holderPid:e.holder_pid,reservedAt:e.reserved_at,leaseUntil:e.lease_until,reason:e.reason}}function Dm(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
+ ${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)
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 ic(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?o$(o):null}function Ds(e,t,r,n=Date.now()){return ic(e,t,r,n)!==null}function Mm(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 Pm(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 s$}from"node:os";import{readFileSync as i$}from"node:fs";import{join as a$}from"node:path";function Um(e){return{LMAUTO_DB:e}}function ar(){return process.env.LMAUTO_DB??a$(s$(),".lmbee","state.db")}function c$(e){return vs(Um(e))}function zr(e){return hn(e)}function yn(e){return dm(e)}async function Ms(e){return lm({env:Um(e)})}var l$="lmbee.site_uuid",u$=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function d$(e){let t=c$(e),r=i$(t,"utf8").trim();if(!u$.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=d$(t),o=e.prepare("SELECT v FROM kv WHERE k = ?").get(l$);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 m$(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 f$(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 Fm=64*1024;function yo(e){return JSON.stringify(m$(e))}function jm(e){if(Buffer.byteLength(e,"utf8")>Fm)throw new Error(`envelope body exceeds ${Fm} 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=Ps(r,"msg_id"),o=Ps(r,"sent_at"),s=Ps(r,"payload"),i=qm(r,"to"),a=qm(r,"from"),c=r.in_reply_to===void 0||r.in_reply_to===null?void 0:Ps(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 f$(l)}function Ps(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 ac(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 qm(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:ac(o,`${t}.site`,!1),team:ac(o,`${t}.team`,!0),alias:ac(o,`${t}.alias`,!1)}}function Hm(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 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(
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=cc(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 Bm(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'persisted' ORDER BY seq").all()}function cc(e,t){return e.prepare("SELECT * FROM mail_ledger WHERE msg_id = ?").get(t)??null}function Wm(e){return e.prepare("SELECT MAX(seq) as maxSeq FROM mail_ledger").get().maxSeq}function Gm(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 Vm(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=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
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 lc={baseMs:6e4,maxMs:30*6e4};function p$(e,t){let r=Math.max(0,e-1);return Math.min(t.baseMs*2**r,t.maxMs)}var Yr="PERMANENT: ";function uc(e){return e.prepare("SELECT * FROM mail_ledger WHERE state = 'failed' AND failed_ts IS NOT NULL ORDER BY seq").all()}function Us(e,t,r=lc){let n=Date.parse(t);return uc(e).filter(o=>{if(o.failure_reason?.startsWith(Yr))return!1;let s=Date.parse(o.failed_ts);return Number.isFinite(s)?n-s>=p$(o.retry_count,r):!1})}function Jm(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 Km(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 Ym(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 Qm(e){return e.prepare("SELECT COUNT(*) as n FROM mail_ledger WHERE delivery_error IS NOT NULL").get().n}function dc(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 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(
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 Xm(e,t){return e.prepare("SELECT * FROM mail_outbound_ledger WHERE msg_id = ?").get(t)??null}function Zm(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 ef(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 Fs(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 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
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 h$}from"node:fs";var g$=/^MemTotal:\s+(\d+)\s*kB/m,_$=/^MemAvailable:\s+(\d+)\s*kB/m;function qs(e){return e===null?null:`memory headroom: ${e.percentAvailable.toFixed(1)}% available (context only, not a wake trigger)`}function Eo(e="/proc/meminfo"){let t;try{t=h$(e,"utf8")}catch{return null}let r=g$.exec(t),n=_$.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 mc=10;function tf(e=mc,t=Eo){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 Hs(){return process.env.LMBEE_QUEUE_DIR?process.env.LMBEE_QUEUE_DIR:af(E$(),".lmbee","queue")}function b$(e,t,r){of(r)||w$(r,{recursive:!0});let n=af(r,`${e}.md`);return sf(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 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)
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=b$(m,n,o.queueDir??Hs());return e.prepare("UPDATE queue SET prompt_file = ? WHERE id = ?").run(f,m),m}).immediate()}function fc(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 cf(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 Bs(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 lf(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=$$(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 (
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 pc=["pending","sent","retrieved","escalating","merged"];function S$(e){let{escalation_claim_token:t,prompt_file:r,admission_fingerprint:n,...o}=e;return o}var v$=50,To=200;function hc(e,t={}){let r=t.limit??v$;if(!Number.isSafeInteger(r)||r<1||r>To)throw new I("INVALID_ARGUMENT",`limit must be a positive integer <= ${To}`);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(S$),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 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 $$(e){return`'${e.replaceAll("'","'\\''")}'`}function k$(e,t,r){return`${e}
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}
161
161
 
162
- [Delivery receipt: after reading this prompt, run \`lmbee queue retrieve ${$$(t)} --id ${r}\` to record that you received queue#${r}.]`}function x$(e,t,r,n,o){let i=(t.now??(()=>new Date().toISOString()))(),a={v:1,msgId:nf(),to:{site:r.peerSite,team:r.name,alias:r.alias},from:{site:t.localSiteId,team:"",alias:n.from_id},sentAt:i,payload:o};dc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:n.id},i);let c=zr(r.peerSite),l=new TextEncoder().encode(yo(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 R$(e,t,r,n,o,s=n.leadAlias){let i=t.now??(()=>new Date().toISOString()),a={v:1,msgId:nf(),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(yo(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();dc(e,{msgId:a.msgId,to:a.to,from:a.from,queueId:null},u),Vm(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 N$(e,t,r,n){if(!t.remoteMail)return!1;try{js(n.prompt_file,"utf8")}catch{return!1}if(!A$(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 x$(e,t.remoteMail,r,n,o),!0}function L$(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 gc(e){let t=e.expects_response?" (expects a response)":"";return`--- addendum from ${e.from_id}, ${e.created_ts}${t} ---`}function I$(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(`
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(`
166
166
 
167
- ${gc(d)}
168
- ${js(d.prompt_file,"utf8")}`)}catch{l=!1;break}if(!l||c.length===0)continue;sf(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??xm,n=t.sendAwaited??Ht,o=t.memoryCheck??tf,{refs:s,byName:i}=L$(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));I$(e,a);let c=sc(e,s,{teamName:t.teamName,isTeamBusy:d=>Fe(i.get(d.name),t.report)||Rm(e,d.name)||Mm(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?cc(e,d.dedupe_key):null,_=k$(p,m.name,d.id);if(!h||!t.remoteMail)return r(f,_),!0;let g=t.remoteMail,y=i.get(m.name);return n(f,_).then(E=>{E.kind==="ok"||E.kind==="stalled"?R$(e,g,h,y,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"&&Ym(e,h.msg_id,E.message,(g.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)}
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)}
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)||N$(e,t,f,d)&&c++}return c}function Ws(e,t,r){return r!==void 0?C$(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 C$(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 (
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 (
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 uf(e,t={}){let r=rf(t.queueDir??Hs()),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 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
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=rf(c.prompt_file);if(!(l!==r&&!l.startsWith(r+T$))&&of(l))try{y$(l,{force:!0}),a++}catch{}}return a}import{spawn as q$}from"node:child_process";import{lstatSync as O$,readlinkSync as D$,realpathSync as M$}from"node:fs";import{homedir as P$}from"node:os";import{basename as U$,dirname as df,isAbsolute as ff,join as F$,resolve as _c}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 I("INVALID_ARGUMENT",`${t} must not be blank`);return e}function wc(e){let t;try{t=O$(e)}catch{let r=df(e);return r===e?e:F$(wc(r),U$(e))}if(t.isSymbolicLink()){let r=D$(e),n=ff(r)?r:_c(df(e),r);return wc(n)}return M$(e)}function At(e){let t=e==="~"||e.startsWith("~/")?e.replace(/^~/,P$()):e,r=ff(t)?_c(t):_c(process.cwd(),t);return wc(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 Et(e){try{return e()}catch(t){if(t instanceof I)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 I("NOT_FOUND",`Entity ${t} does not exist`,3);return r}function pf(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 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 Gs(e,t){e.prepare("UPDATE entities SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}var Ne=1e4;function hf(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 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 gf(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 I("INVALID_ARGUMENT","Explicit owner and --unassigned are exclusive");try{pf(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 Le(e,Number(u.lastInsertRowid))}catch(u){if(u instanceof I)throw u;return bn(u)}});return Et(r)}function br(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"),hf(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 _f(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=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 (
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=_f(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 mf(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 I("INVALID_ARGUMENT","summary ID and --project are exclusive");if(t.id!==void 0)return mf(_f(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 mf(r)}function Vs(e,t,r){let n=e.transaction(()=>{let o=Le(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{pf(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({[Tr]:!0,from:o.status,to:s.status}),null,null,de()),Gs(e,t),Le(e,t)});return Et(n)}function wf(e,t,r){e.prepare("UPDATE entities SET delivered_ts = ? WHERE id = ? AND delivered_ts IS NULL").run(r,t)}function yf(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 Gs(e,t),{note:e.prepare("SELECT * FROM notes WHERE id = ?").get(i.lastInsertRowid),revision:Le(e,t).revision}});return Et(n)}function yc(e,t,r={}){return Le(e,t),hf(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 Js(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 Ef(e,t,r={}){let{rows:n,meta:o}=yc(e,t,r);return{rows:n.map(s=>({...s,noteType:Wt(s.body)===null?"authored":"system"})),meta:o}}function Tf(e,t,r){if(Le(e,t),Le(e,r),t===r)throw new I("SELF_DEPENDENCY","An entity cannot depend on itself")}function bf(e,t,r){let n=e.transaction(()=>{Tf(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&&Gs(e,t),{entity_id:t,depends_on_id:r,changed:o,revision:Le(e,t).revision}});return Et(n)}function Sf(e,t,r){let n=e.transaction(()=>{Tf(e,t,r);let s=e.prepare("DELETE FROM dependencies WHERE entity_id = ? AND depends_on_id = ?").run(t,r).changes>0;return s&&Gs(e,t),{entity_id:t,depends_on_id:r,changed:s,revision:Le(e,t).revision}});return Et(n)}var j$=new Set(["todo","in-progress"]),vn=new Set(["task","subtask"]),Gt="on-hold";function le(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}var Ys="blocked",An=new Set(["done","closed"]);function gt(e){return An.has(le(e))}function Zs(e){return e.kind==="epic"&&!gt(e.status)&&le(e.status)!==Gt}var Qs=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 Xs(e,t){return(ct(e,t.id,"outgoing").outgoing??[]).some(n=>le(n.status)!=="done")}var H$=45*6e4;function vf(e,t={}){let r=t.nowMs??Date.now(),n=t.staleInProgressThresholdMs??H$,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===Ys){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&&!Xs(e,i)&&s.push({...i,attentionReason:"dependency_ready"})}return s}function bc(e){let t=le(e);return t==="done"||t===Gt}function zs(e,t){return e.prepare("SELECT * FROM entities WHERE parent_id = ?").all(t).some(n=>!bc(n.status))}function Tc(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 bo(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=>Qs.has(le(u.status))),c=o!==void 0?At(o.team):null,l=[];for(let u of a){let d=Tc(e,u.id);if(d===null||!Qs.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 B$(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)===Ys&&!Vt(e,n,r))}var Sc=24*60*6e4,W$="DESIGN-FIRST:";function Af(e,t,r=Sc,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(W$)&&n-Date.parse(s.updated_at)>=r&&!Vt(e,s,o)&&!Xs(e,s)).map(s=>({id:s.id,title:s.title,updatedAt:s.updated_at}))}function $f(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 G$(e,t){return e.prepare("SELECT 1 FROM entities WHERE parent_id = ? LIMIT 1").get(t)!==void 0}function V$(e,t){return t.entities.filter(n=>n.kind==="epic"&&!gt(n.status)&&le(n.status)!==Gt).filter(n=>G$(e,n.id)&&!zs(e,n.id))}function Ks(e){return`'${e.replace(/'/g,"'\\''")}'`}var J$=3e4;function Ec(e,t={}){let r=t.timeoutMs??J$,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=q$(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 _=l.trim();if(!_){m("empty output");return}f(_)}),d.stdin.write(e),d.stdin.end()})}var K$="ollama/qwen2.5:14b",z$=5e3,Y$="deepseek/deepseek-flash";async function ei(e,t={}){if(t.model!==void 0)return Ec(e,t);let r=await Ec(e,{...t,model:K$,timeoutMs:t.timeoutMs??z$});return r!==null?r:Ec(e,{...t,model:Y$})}var Q$=15*6e4;function X$(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 kf(e,t,r={}){let n=r.backoffMs??Q$,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=>Qs.has(le(k.status))),c=null,l=!1;for(let k of a){let B=Tc(e,k.id);if(B===null||!Qs.has(le(B.status)))continue;l=!0;let C=Date.now(),w=typeof B.attrs?.expected_reset_ts=="string"?Date.parse(B.attrs.expected_reset_ts):NaN;if(!Number.isNaN(w)&&w>C)continue;let T=typeof B.attrs?.last_renudge_ts=="string"?Date.parse(B.attrs.last_renudge_ts):NaN;if(!(!Number.isNaN(T)&&C-T<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 N=Tc(e,k);N===null||N.epochId!==B||Bt(e,k,{body:JSON.stringify({...N.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 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?`
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=V$(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 ${Ks(f.owner_team_path)} --owner-alias ${Ks(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`,_=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=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?`
186
186
 
187
- (Also: ${m.length} epic(s) have all tasks done: ${m.map(h).join("; ")}.)`:"",g=i.filter(k=>le(k.status)==="done").map(k=>{let B=[];return Xs(e,k)&&B.push("still has an unmet dependency"),zs(e,k.id)&&B.push("still has an incomplete subtask"),{entity:k,reasons:B}}).filter(k=>k.reasons.length>0);if(g.length>0){let{entity:k,reasons:B}=g[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 y=i.filter(k=>le(k.status)==="done"&&!B$(e,k.id));if(y.length>0){let k=y[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+_}}let E=i.filter(k=>j$.has(le(k.status))&&le(k.status)!==Gt&&!zs(e,k.id));if(E.length===0){let k=i.filter(A=>{let q=le(A.status);return q!==Ys&&q!==Gt&&zs(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+_}}let B=i.filter(A=>le(A.status)===Gt),C=i.filter(A=>le(A.status)!==Gt&&le(A.status)!==Ys),w=t.entities.some(A=>A.kind==="epic"&&!gt(A.status)&&le(A.status)!==Gt);if(C.length===0&&!w)return null;if(m.length>1)return{message:`${m.length} of your open epics have all tasks done: ${m.map(h).join("; ")}.`};let T=X$(t.entities),N=t.entities[0],U=N?.owner_team_path,J=N?.owner_alias,ee=U!=null&&J!==null&&J!==void 0?` --owner-team ${Ks(U)} --owner-alias ${Ks(J)}`:"",oe=T!==null?String(T.id):"<epic-id>",V=T!==null?`lmauto tasks update ${T.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 T===null&&!w?{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(k=>!Xs(e,k));if(v.length===0){let k=E[0];return{message:`All ${E.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+_}}let S=v.filter(k=>le(k.status)==="in-progress"||k.delivered_ts!=null),R=S.length>0?S[0]:v[0],x=R.delivered_ts==null?()=>wf(e,R.id,new Date().toISOString()):void 0;if(v.length===1){let k=R.description.trim();return{message:`Continue task #${R.id}: "${R.title}" (status: ${R.status}).${k?`
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?`
188
188
 
189
- ${k}`:""}${d}${_}`,onSent:x}}let L=R.description.trim();return{message:`Continue task #${R.id}: "${R.title}" (status: ${R.status}).${L?`
189
+ ${k}`:""}${d}${w}`,onSent:x}}let I=N.description.trim();return{message:`Continue task #${N.id}: "${N.title}" (status: ${N.status}).${I?`
190
190
 
191
- ${L}`:""}
191
+ ${I}`:""}
192
192
 
193
- (${v.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+_,onSent:x}}var pe={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function Z$(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 vc(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 Ac(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&&!$c(a,n))}function $c(e,t){return e.hold_until!==null&&Date.parse(e.hold_until)>t}function kc(e,t){if(Ue(e,t.name)!==null||lf(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return xe(e,r,t.leadAlias)===null}function ek(e){return vc({...e,config:{...e.config,idleThresholdMs:0}})}function xf(e){return`last_nudged:${e}`}function xc(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(xf(t))?.v??null}function So(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(xf(t),r)}function Rf(e,t,r,n,o,s,i){if(Ue(e,t.name)?.status==="BLOCKED")return null;let c=kc(e,t),l=s?.progress_changed_ts==null?null:o-Date.parse(s.progress_changed_ts),u=xc(e,t.name),d=u===null?null:o-Date.parse(u);return{isCurrentlyActive:Fe(t,r),hasInFlightWorker:Z$(t,r),neverDispatched:c,progressStatus:s?.progress_status??null,progressAgeMs:l,isDeadReclaimable:Xr(t,r),hasStalePersistentInProgressWork:Ac(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 Nf(e,t,r,n,o,s,i){let a=Rf(e,t,r,o,s,i,n);return a!==null&&vc(a)}async function Rc(e,t,r,n,o=pe,s=Date.now()){let i=await Ja(e,t,t.name,s);return Nf(e,t,r,n,o,s,i)}function Nc(e,t,r,n,o=pe,s=Date.now()){return Nf(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?Nc(e,c,r,n,o,s):await Rc(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 Ja(e,c,c.name,s);if(ie(e,c.name)?.confirmed_done_ts)continue;let u=Rf(e,c,r,o,s,l,n);u!==null&&(vc(u)&&i.push(c.name),ek(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as If,readFileSync as Cf}from"node:fs";import{dirname as Ic,join as Of}from"node:path";import{fileURLToPath as Df}from"node:url";var Lc={sha:"unknown",dirty:!0,builtAt:"unknown"};function tk(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 Mf(){let e=Ic(Df(import.meta.url));for(let t=0;t<5;t+=1){let r=Of(e,"package.json");if(If(r))try{let n=JSON.parse(Cf(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=Ic(e)}return"unknown"}function Cc(){let e=Of(Ic(Df(import.meta.url)),"..","build-info.json");if(!If(e))return Lc;try{let t=JSON.parse(Cf(e,"utf8"));return tk(t)?t:Lc}catch{return Lc}}var rk="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()||rk).replace(/\/+$/,"")}import{createServer as nk}from"http";import{Http2ServerRequest as Ff,constants as ok}from"http2";import{Http2ServerRequest as Oc}from"http2";import{Readable as Pf}from"stream";import hk from"crypto";var Zr=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},sk=e=>e instanceof Zr?e:new Zr(e.message,{cause:e}),ik=global.Request,vo=class extends ik{constructor(e,t){typeof e=="object"&&Nn in e&&(e=e[Nn]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},ak=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)},qf=Symbol("wrapBodyStream"),ck=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new vo(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[qf]){let i;s.body=new ReadableStream({async pull(a){try{i||=Pf.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=Pf.toWeb(n);return new vo(t,s)},Nn=Symbol("getRequestCache"),jf=Symbol("requestCache"),ti=Symbol("incomingKey"),ri=Symbol("urlKey"),lk=Symbol("headersKey"),Rn=Symbol("abortControllerKey"),uk=Symbol("getAbortController"),Ao={get method(){return this[ti].method||"GET"},get url(){return this[ri]},get headers(){return this[lk]||=ak(this[ti])},[uk](){return this[Nn](),this[Rn]},[Nn](){return this[Rn]||=new AbortController,this[jf]||=ck(this.method,this[ri],this.headers,this[ti],this[Rn])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(Ao,e,{get(){return this[Nn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(Ao,e,{value:function(){return this[Nn]()[e]()}})});Object.defineProperty(Ao,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[jf]};return`Request (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Ao,vo.prototype);var dk=(e,t)=>{let r=Object.create(Ao);r[ti]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Oc)throw new Zr("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[ri]=a.href}catch(a){throw new Zr("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Oc?e.authority:e.headers.host)||t;if(!o)throw new Zr("Missing host header");let s;if(e instanceof Oc){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[ri]=i.href,r},Mc=Symbol("responseCache"),xn=Symbol("getResponseCache"),en=Symbol("cache"),Fc=global.Response,Ln=class Hf{#t;#e;[xn](){return delete this[en],this[Mc]||=new Fc(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof Hf){let o=r[Mc];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[Mc]};return`Response (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Ln,Fc);Object.setPrototypeOf(Ln.prototype,Fc.prototype);async function mk(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Bf(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 fk(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Bf(e.getReader(),t)}var Pc=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},pk="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=hk);var qc=Symbol("outgoingEnded"),Uf=Symbol("incomingDraining"),gk=500,_k=64*1024*1024,Dc=e=>{let t=e;if(e.destroyed||t[Uf])return;if(t[Uf]=!0,e instanceof Ff){try{e.stream?.close?.(ok.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,gk);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()},wk=()=>new Response(null,{status:400}),Wf=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Uc=(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))},Gf=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Vf=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=Pc(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Pc(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())):(Gf(t),await fk(n,t)?.catch(i=>Uc(i,t))),t[qc]?.()},yk=e=>typeof e.then=="function",Ek=async(e,t,r={})=>{if(yk(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(Wf);if(en in e)return Vf(e,t);let n=Pc(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 mk(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&&Gf(t),await Bf(o,t,a))}else n[pk]||(t.writeHead(e.status,n),t.end());t[qc]?.()},Tk=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==vo&&(Object.defineProperty(global,"Request",{value:vo}),Object.defineProperty(global,"Response",{value:Ln})),async(n,o)=>{let s,i;try{i=dk(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[qf]=!0,n.on("end",()=>{a=!0}),n instanceof Ff&&(o[qc]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Dc(n)})})}),o.on("finish",()=>{a||Dc(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(()=>{Dc(n)})})}),s=e(i,{incoming:n,outgoing:o}),en in s)return Vf(s,o)}catch(a){if(s)return Uc(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:sk(a)),!s)return}else i?s=Wf(a):s=wk()}try{return await Ek(s,o,t)}catch(a){return Uc(a,o)}}},bk=e=>{let t=e.fetch,r=Tk(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||nk)(e.serverOptions||{},r)},Jf=(e,t)=>{let r=bk(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var jc=(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 Kf=Symbol();var zf=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Yf=32,Sk=1e4,ni=e=>"headers"in e,Zf=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(ni(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?vk(e,{all:r,dot:n}):{}};async function vk(e,t){if(!ni(e)&&e.bodyCache.formData)return Qf(await e.bodyCache.formData,t);let r=ni(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=zf(n,r.get("Content-Type")||"");ni(e)||(e.bodyCache.formData=o);let s=await o;return s?Qf(s,t):{}}function Qf(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?Ak(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&($k(r,o,s,n),delete r[o])}),r}var Ak=(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},$k=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",Yf+2);s.length>Yf+1&&Xf(),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++>=Sk&&Xf(),o[i]=Object.create(null)),o=o[i])})},Xf=()=>{throw new Error("Nesting limit exceeded")};var Bc=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},ep=e=>{let{groups:t,path:r}=kk(e),n=Bc(r);return xk(n,t)},kk=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},xk=(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},oi={},tp=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return oi[n]||(r[2]?oi[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:oi[n]=[e,r[1],!0]),oi[n]}return null},rp=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Rk=e=>rp(e,decodeURI),Wc=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 Rk(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var np=e=>{let t=Wc(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}`}`),si=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)},ii=e=>e.indexOf("%")!==-1?rp(e,Nk):e,Hc=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),ii(e)),op=(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 Hc(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=Hc(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=Hc(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},sp=op,ip=(e,t)=>op(e,t,!0),Nk=decodeURIComponent;var ap=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&&ii(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]=ii(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return sp(this.url,e)}queries(e){return ip(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 Zf(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[Kf](){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 cp={Stringify:1,BeforeStream:2,Stream:3},Lk=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Gc=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=>Gc(c,t,!1,n,o))).then(()=>o[0]));return r?Lk(await i,s):i};var Ik="text/plain; charset=UTF-8",Vc=(e,t)=>({"Content-Type":e,...t}),$o=(e,t)=>new Response(e,t),Jc=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 ap(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||=$o(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=$o(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=$o(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 $o(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,Vc(Ik,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Vc("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Vc("text/html; charset=UTF-8",r));return typeof e=="object"?Gc(e,cp.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??=()=>$o(),this.#l(this))};var Ke="ALL",lp="all",up=["get","post","put","delete","options","patch","query"],ai="Can not add a route since the matcher is already built.",ci=class extends Error{};var dp="__COMPOSED_HANDLER";var Ck=e=>e.text("404 Not Found",404),mp=(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)},fp=class pp{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...up,lp].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??Wc:np}#e(){let t=new pp({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Ck;errorHandler=mp;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===mp?s=o.handler:(s=async(i,a)=>(await jc([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[dp]=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 Jc(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=jc(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 li=[];function Kc(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[[],li];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=n,n(e,t)}var In="[^/]+",xr=".*",cr="(?:|/.*)",kr=Symbol(),hp=new Set(".\\+*[^]$()");function Ok(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===In?1:t===In?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var gp=class zc{#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]:["","",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&&hp.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 zc}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 zc}i=d}if(i.#t!==void 0)throw kr;i.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(Ok).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:hp.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 Yc=class{#t={varIndex:0};#e=new gp;#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 _p=He();function wp(e){return _p[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?cr:t==="*"?xr:`/:${In}`)}$`)}function ui(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(wp(r).test(t))return[...e[r]]}var di=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[Ke]:He()},this.#e={[Ke]:He()},this.#r={[Ke]:new Yc}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===kr?new ci(t):r}}add(e,t,r){let n=this.#t,o=this.#e;if(!n)throw new Error(ai);if(!n[e]){this.#r[e]=new Yc;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=wp(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=ui(n[c],t)||ui(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=si(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=ui(n[c],a)||ui(n[Ke],a)||[]),o[c][a].push([r,a])}match=Kc;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,_p=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()]),li];continue}s[m[0]]=d.map(([f,p])=>[f,n.paths[p][1].reduceRight((h,[_],g)=>(h[_]=c[m[1][g][1]],h),He())])}return[i,a.map(l=>s[l]),o]}};var Qc=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(ai);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 ci)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 Xc=He(),Dk=0,yp=class Ep{#t=[];#e=He();#r=[];#s;#n=Xc;insert(t,r,n){let o=this,s=ep(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=tp(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 Ep;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:++Dk}})}#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=Xc;let s=[this],i=Bc(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,_=s.length;h<_;h++){let g=s[h],y=g.#e[d];y&&(y.#n=g.#n,m?(y.#e["*"]&&this.#o(n,y.#e["*"],t,g.#n),this.#o(n,y,t,g.#n)):f.push(y));for(let E of g.#r){let v=E.#s,S=g.#n===Xc?{}:{...g.#n};if(typeof v=="string"){(v==="*"||d.startsWith(v.slice(0,-1)))&&(this.#o(n,E,t,g.#n),v==="*"&&(E.#n=S,f.push(E)));continue}let[,R,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 L=r.slice(l[u]),k=x.exec(L);if(k){S[R]=k[0],this.#o(n,E,t,g.#n,S),k[0].length===L.length&&E.#e["*"]&&this.#o(n,E.#e["*"],t,g.#n,S);for(let B in E.#e){E.#n=S;let C=k[0].match(/\//g)?.length??0;(a[C]||=[]).push(E);break}continue}}(x===!0||x.test(d))&&(S[R]=d,m?(this.#o(n,E,t,S,g.#n),E.#e["*"]&&this.#o(n,E.#e["*"],t,S,g.#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 Zc=class{name="TrieRouter";#t=new yp;add(e,t,r){for(let n of si(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};var tn=class extends fp{constructor(e={}){super(e),this.router=e.router??new Qc({routers:[new di,new Zc]})}};import{join as Mk}from"node:path";function Pk(e){return e||(process.env.LMBEE_TEAMS_CONF?process.env.LMBEE_TEAMS_CONF:Mk(process.cwd(),"teams.conf"))}function Uk(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{Qd(e.db,r,new Date().toISOString())}catch{}}function mi(e={}){let t=bs(e.dbPath,{readOnly:e.readOnly??!1}),r=Pk(e.teamsConfPath),n=Jr(t.db,r);return e.readOnly||Uk(t,n),{db:t,teamsConfPath:r,teams:n}}import{existsSync as lL,readFileSync as uL,statSync as dL}from"node:fs";import{execFile as Fk}from"node:child_process";import{promisify as qk}from"node:util";var fi=qk(Fk),xo=3,ko="auto_nudge_redirect:",el=3,tl=5*60*6e4;function Tt(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(ko+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:el,hoursThresholdMs:typeof n.hoursThresholdMs=="number"&&n.hoursThresholdMs>0?n.hoursThresholdMs:tl,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 rl(e){return e.prepare("SELECT k FROM kv WHERE k LIKE ?").all(ko+"%").map(r=>r.k.slice(ko.length))}function pi(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(ko+t,JSON.stringify(r))}function Tp(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(ko+t)}async function bp(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 jk(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 Sp(e,t,r,n,o,s=fi){let i=r.shiftStartedTs!==null,a=i?r.shiftStartedSha:await bp(n,s);pi(e,t,{...r,turnsDispatched:r.turnsDispatched+1,shiftStartedTs:i?r.shiftStartedTs:o,shiftStartedSha:a})}async function vp(e,t,r=Date.now(),n=fi){let o=[];for(let s of rl(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 jk(a,i.shiftStartedSha,n):null,u=i.turnsDispatched<=xo&&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 Ap(e,t,r,n,o=fi){let s=Tt(e,t);if(s===null)return;let i=await bp(r,o);pi(e,t,{...s,shiftStartedTs:n,shiftStartedSha:i,lastReviewedTurn:s.turnsDispatched})}async function $p(e,t,r=fi){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: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?`
194
194
 
195
195
  Commits this shift:
196
- ${s}`:"";return e.isRampUp?`[auto-nudge-redirect] RAMP-UP turn ${e.turnNumber}/${xo} 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 Gk}from"node:child_process";import{existsSync as Vk,readdirSync as Np,readFileSync as Lp,statSync as Jk}from"node:fs";import{hostname as Kk}from"node:os";import{promisify as zk}from"node:util";import{existsSync as Hk,statSync as Bk}from"node:fs";var PB=15*6e4;function Wk(e,t,r={}){let n=r.existsSyncImpl??Hk,o=r.statSyncImpl??Bk,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 nl(e,t,r){if(e===null)return!1;let n=Date.parse(e);return Number.isNaN(n)?!1:r-n<=t}function kp(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&&Wk(e,t,o))return!0;if(n===void 0)return!1;let s=o.nowMs??Date.now();return nl(r,n,s)}var Yk=zk(Gk),Qk=45*6e4,Ip=100,xp=Ip,Xk=3;async function Zk(e,t=3e4){try{let{stdout:r}=await Yk("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 hi(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 Cp(e,t="/proc"){let r=hi(e,t);return r===null?null:r.utime+r.stime}function Rp(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 ol(e,t="/proc"){let r=hi(e,t);if(r===null)return null;let n;try{n=Np(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=hi(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 Op(e,t="/proc"){let r=Rp(e,t);if(r===null)return null;let n;try{n=Np(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=hi(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=Rp(c,t);l!==null&&(s+=l),i.push(...o.get(c)??[])}return s}function ex(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 tx(e,t,r,n){let o=n.fetchHealthImpl??Zk,s=n.readProcStatImpl??ol,i=n.hostnameImpl??Kk,a=n.wallClockThresholdMs??Qk,c=n.requiredLowCpuStreak??Xk,l=await o(r);if(l===null)return;let u=l.members.find(R=>R.alias===t.leadAlias);if(u===void 0)return;let d=ex(u.liveness,i());if(d===null){let R=ie(e,t.name);(R?.holder_watch_pid!==null&&R?.holder_watch_pid!==void 0||R?.hung_holder_flagged_ts!==null&&R?.hung_holder_flagged_ts!==void 0)&&Ba(e,t.name);return}let m=new Date().toISOString(),f=s(d.pid);if(f===null){Ha(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)){ja(e,t.name,d.pid,d.startedAt,f,m,0);return}let _=Date.now()-Date.parse(d.startedAt),g=p.holder_watch_cpu_ticks!==null?f-p.holder_watch_cpu_ticks:null,y=g!==null&&g<xp,E=p.holder_watch_low_cpu_streak??0,v=y?E+1:0;if(ja(e,t.name,d.pid,d.startedAt,f,m,v),_<a||v<c)return;let S=Math.round(_/6e4);Ha(e,t.name,`${t.leadAlias} has held its servicing lock for ~${S}m with under ${xp/Ip}s of CPU time across ${v} consecutive checks -- possibly hung, not just slow.`,m)}async function Dp(e,t,r={}){let n=r.existsSyncImpl??Vk,o=r.statSyncImpl??Jk,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})){Ba(e,i.name);continue}let a;try{a=Q(i)}catch{continue}try{await tx(e,i,a,r)}catch{continue}}}var Ro="provider_disabled:";function Mp(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 gi(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(Ro+t);return r===void 0?null:Mp(t,r.v)}function _i(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(Ro+t,JSON.stringify(n))}function Pp(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(Ro+t)}function No(e){let t=e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${Ro}%`),r=[];for(let n of t){let o=n.k.slice(Ro.length),s=Mp(o,n.v);s!==null&&r.push(s)}return r}function rt(e,t,r=Date.now()){let n;try{n=gi(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 rx,readFileSync as nx,readdirSync as ox,statSync as Up}from"node:fs";import{basename as wi}from"node:path";var il="orphan_would_reap",sx=5e3,ix=6e4,ax=100,cx=3,lx=45*6e4;function Fp(e,t){try{let n=nx(`${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 qp(e,t){try{return Up(`${e}/${t}`).mtime.getTime()}catch{return null}}function al(e){let t;try{t=ox(e)}catch{return[]}let r=[];for(let n of t){if(!/^\d+$/.test(n))continue;let o=Number(n),s=Fp(e,o);if(s===null)continue;let i=qp(e,o);i!==null&&r.push({pid:o,target:s,startedAtMs:i})}return r.sort((n,o)=>n.pid-o.pid),r}function sl(e){let t=e.lastIndexOf(":");return t===-1?null:{teamfilePath:e.slice(0,t),alias:e.slice(t+1)}}function ux(e,t){if(t===null)return!1;let r=sl(e),n=sl(t);return r===null||n===null?!1:r.alias===n.alias&&wi(r.teamfilePath)===wi(n.teamfilePath)}function dx(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"&&ux(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 mx(e,t,r,n,o,s,i,a){let c=s(t.pid,a);if(c===null)return!1;let l=Xd(e,t.target,t.startedAtMs,t.pid);if(l===null||l.cpu_ticks===null)return Wa(e,t.target,t.startedAtMs,t.pid,c,i,0),!1;let m=c-l.cpu_ticks<ax?l.low_cpu_streak+1:0;return Wa(e,t.target,t.startedAtMs,t.pid,c,i,m),o-t.startedAtMs<n?!1:m>=r}function fx(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 px(e,t){let r=sl(t);if(r===null)return t;for(let n of e)if(H(n))try{let o=Q(n);if(wi(o)===wi(r.teamfilePath))return n.name}catch{continue}return t}async function hx(e,t,r,n,o){if(Fp(e,t.pid)!==t.target||qp(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 jp(e,t,r,n={}){let o=n.procPath??"/proc",s=n.safetyMarginMs??ix,i=n.sigkillGraceMs??sx,a=n.requiredLowCpuStreak??cx,c=n.minCorroborationWallClockMs??lx,l=n.existsSyncImpl??rx,u=n.statSyncImpl??Up,d=n.killImpl??process.kill.bind(process),m=n.sleepImpl??(R=>new Promise(x=>setTimeout(x,R))),f=n.readProcCpuTicksImpl??Cp,p=n.insertEventImpl??tt,h=n.dryRun??!1,_=n.nowMs??Date.now(),g=new Date(_).toISOString(),y=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:_}),E=y?fx(t,n.sessionAliveExemptTeamName):null;y&&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=al(o)}catch{return}Zd(e,v.map(R=>({target:R.target,startedAtMs:R.startedAtMs,pid:R.pid})));let S=v.filter(R=>_-R.startedAtMs>=s);for(let R of v){if(_-R.startedAtMs<s)continue;if(E!==null){let L=R.target.lastIndexOf(":");if(R.target.slice(0,L)===E)continue}let x=dx(R,S,r);if(x.action!=="reap"){Ga(e,R.target,R.startedAtMs,R.pid);continue}if(!(x.requiresCpuCorroboration&&!mx(e,R,a,c,_,f,g,o))){if(h){try{try{p(e,px(t,R.target),il,_,{note:`pid ${R.pid} (${R.target}): ${x.reason}`})}catch{}n.onWouldReap?.({pid:R.pid,target:R.target,reason:x.reason}),process.stderr.write(`[orphan-reconciler] WOULD REAP pid ${R.pid} (${R.target}) [dry-run]: ${x.reason}
198
- `)}catch{}continue}try{let L=await hx(o,R,i,d,m);if(Ga(e,R.target,R.startedAtMs,R.pid),!L)continue;n.onReap?.({pid:R.pid,target:R.target,reason:x.reason}),process.stderr.write(`[orphan-reconciler] reaped pid ${R.pid} (${R.target}): ${x.reason}
199
- `)}catch{continue}}}}import{existsSync as gx}from"node:fs";import{homedir as _x}from"node:os";import{join as wx}from"node:path";function yx(e){return e||(process.env.LCTL_STATE_DB?process.env.LCTL_STATE_DB:wx(_x(),".lmctl","state.db"))}function On(e){let t=yx(e);if(!gx(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 Ex(e){return e==="done"?"done":e==="error"||e==="aborted"?"failed":e==="busy"||e==="running"||e==="cancelled"?"contention":null}function Hp(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=Ex(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 Tx=30*24*60*6e4;function bx(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 Bp(e,t={}){let r=t.procPath??"/proc",n=t.nowMs??Date.now(),o=new Date(n).toISOString(),s=t.retentionMs??Tx,i=t.openLctlDbImpl??On,a;try{a=al(r)}catch{return}for(let u of a)try{let d=ol(u.pid,r),m=Op(u.pid,r);em(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=bx(i,t.lctlStateDbPath,u.pid);rm(e,u.target,u.started_at_ms,u.pid,d,o)}catch{}try{tm(e,new Date(n-s).toISOString())}catch{}}import{createHash as Sx}from"node:crypto";var vx=24*60*6e4,Ax=200,$x=new Set(["all_good","needs_review"]),kx=24*60*6e4;function xx(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 Rx(e,t){return xx(e,t).map(r=>{let n=Sn(e,r.id),o=Js(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 Nx(e,t){let r=JSON.stringify([e.status,e.title,e.description,t.map(n=>[n.id,n.status,n.latestNoteId])]);return Sx("sha256").update(r,"utf8").digest("hex")}function Lx(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}/${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(`
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 Ix(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"||!$x.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,Ax)}}async function Cx(e,t,r,n){let o=n.decompositionGraceMs??kx;if(r.length===0&&Date.now()-Date.parse(t.created_at)<o)return;let s=Nx(t,r),i=n.cooldownMs??vx,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 ei(Lx(t,r),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),u=Ix(l);if(u===null)return;let d=new Date().toISOString();yf(e,t.id,d,s,u.label==="needs_review"?{needsReview:!0,reason:u.reason}:{needsReview:!1})}async function Wp(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(Zs)){let a=Rx(e,i.id);try{await Cx(e,i,a,r)}catch{continue}}}}import{createHash as Fx}from"node:crypto";import{execFile as Ox}from"node:child_process";import{promisify as Dx}from"node:util";var Gp=Dx(Ox),Mx=/^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) )?([A-Za-z0-9_]+): (.*)$/,Px="\u2026 [truncated older output \u2014 raise with --max-bytes]";function Ux(e){let t=[],r=!1;for(let n of e.split(`
220
- `)){if(n.length===0)continue;if(n===Px){r=!0;continue}if(/^\s/.test(n)){let s=t[t.length-1];s&&(s.text+=`
221
- ${n.replace(/^ {2}/,"")}`);continue}let o=Mx.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 yi(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 Gp(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 Ux(i)}async function Ei(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 Gp(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 qx=200,jx=new Set(["genuinely_done","blocked","stalled_needs_nudge","produced_output_no_report"]),Hx=2*60*6e4;function Bx(e,t,r){let n=xe(e,t,r);return n===null?[]:n.entities.filter(o=>!bc(o.status)).map(o=>({id:o.id,title:o.title,status:o.status}))}function Wx(e,t,r,n){let o=xe(e,t,r);return o===null?[]:o.entities.filter(s=>(s.kind==="task"||s.kind==="subtask")&&$c(s,n)).map(s=>({id:s.id,title:s.title,holdUntil:s.hold_until}))}function Vp(e,t,r=null,n=[]){let o=Fx("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 Gx(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 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(`
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 Vx(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"||!jx.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,qx)}}function Jx(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 Kx(e,t,r,n){let o=n.fetchTailJsonImpl??Ei,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=Bx(e,r,t.leadAlias),a=Wx(e,r,t.leadAlias,Date.now())}catch{return}let c=ie(e,t.name),l=Vp(s,i,c,a),u=Vp("",i,c,a),d=n.cooldownMs??Hx,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 ei(Gx(t.name,s,i,c,a),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),_=Vx(h);if(_===null)return;let g=_.label==="stalled_needs_nudge"&&a.length>0&&i.length===0?{label:"blocked",reason:Jx(a)}:_;Hd(e,t.name,g.label,g.reason,new Date().toISOString(),l,u)}async function Jp(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 Kx(e,s,i,n)}catch{continue}}}import{execFileSync as VR}from"node:child_process";var P=class extends Error{code;exitCode;constructor(t,r,n=2){super(r),this.code=t,this.exitCode=n}};function ll(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:cl(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:cl(l[0],t,r,s),d=a==="*"?r:l[1]!==void 0?cl(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 cl(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 Kp(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 Yx}from"node:child_process";import{closeSync as Qx,existsSync as Xx,mkdirSync as Zx,openSync as eR,readdirSync as tR,unlinkSync as rR}from"node:fs";import{homedir as nR}from"node:os";import{join as Ti}from"node:path";var zp=["systemd-run","--user","--scope","--collect","--quiet"],oR=10,sR=50*6e4,iR=5e3;function bi(){return process.env.LMBEE_CRON_LOG_DIR?process.env.LMBEE_CRON_LOG_DIR:Ti(nR(),".lmbee","cron-logs")}function aR(e,t){try{let r=tR(e).sort();for(let n of r.slice(0,Math.max(0,r.length-t)))try{rR(Ti(e,n))}catch{}}catch{}}function cR(e,t){return[...t.spawnPrefix??(t.systemdUnitName!==void 0?[...zp,"--unit",t.systemdUnitName,"--"]:[...zp,"--"]),"sh","-c",e]}function Io(e,t={}){let r=Ti(t.logDir??bi(),String(e.id));Xx(r)||Zx(r,{recursive:!0});let n=Ti(r,`${new Date().toISOString().replace(/[:.]/g,"-")}.log`),o=eR(n,"a"),s=cR(e.action_payload,t),[i,...a]=s,c;try{c=Yx(i,a,{detached:!0,stdio:["ignore",o,o],...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{}})}finally{Qx(o)}c.unref();let l=c.pid??null,u=!1,d=t.timeoutMs??sR,m=t.sigkillGraceMs??iR,f=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);f.unref();let p=(h,_)=>{u||(u=!0,clearTimeout(f),aR(r,oR),t.onExit?.(h,_,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 lR,randomUUID as uR}from"node:crypto";var rn=16*1024,Oo=16*1024,ul=512,Si=100,dl=4096,ml=1024*1024,Do="('pending','running')",dR="execution_state != 'gone' OR (status = 'escalated' AND escalation_resolved_at IS NULL)";function Mo(e){let{run_token_hash:t,...r}=e;return r}function Yp(e){return lR("sha256").update(e,"utf8").digest("hex")}function bt(e){try{return e()}catch(t){if(t instanceof P)throw t;if(t instanceof I)throw new P(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 P("DB_BUSY","Database busy; retry after the current writer completes",5):r!==void 0&&r.startsWith("SQLITE_CONSTRAINT")?new P("STRUCTURAL_ERROR",n,2):new P("STORAGE_ERROR",n,1)}}function Qp(e,t){return bt(()=>e.prepare("SELECT * FROM cron_runs WHERE id = ?").get(t)??null)}function ze(e,t){let r=Qp(e,t);if(r===null)throw new P("NOT_FOUND",`Cron run ${t} does not exist`,3);return r}function mR(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 (${dR}) ORDER BY id DESC LIMIT 1`).get(t)??null)}function fl(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=uR(),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,Yp(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 vi(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 pl(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 fR(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 Po(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 Co(e,t,r){let n=ye(e,t);if(Buffer.byteLength(n,"utf8")>r)throw new P("INVALID_ARGUMENT",`${t} exceeds ${r} bytes`);return n}function pR(e){if(e===void 0)return[];if(!Array.isArray(e))throw new P("INVALID_ARGUMENT","artifacts must be an array");if(e.length>Si)throw new P("INVALID_ARGUMENT",`at most ${Si} artifacts are allowed`);return e.map(t=>{if(typeof t!="string")throw new P("INVALID_ARGUMENT","artifacts must be strings");return Co(t,"artifact",dl)})}function Xp(e,t){if(e.status!=="succeeded"&&e.status!=="failed"&&e.status!=="escalated")throw new P("INVALID_ARGUMENT",'status must be "succeeded", "failed", or "escalated"');let r=Co(e.summary,"summary",rn),n=pR(e.artifacts),o=null,s=null,i=null;if(e.status==="escalated"){o=Co(e.action??"","requested action",Oo),i=e.reason!==void 0?Co(e.reason,"escalation reason",Oo):r;let a=e.owner!==void 0?Co(e.owner,"owner",ul):t;if(a===null||a.trim().length===0)throw new P("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 Zp(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 eh(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 hl(e,t,r){let n=Xp(r,eh(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 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 = ?,
266
266
  escalation_owner = ?, reported_at = ?, finished_at = ?, updated_at = ?
267
- WHERE id = ? AND status IN ${Do} 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(Zp(i,n))return i;throw new P("CONFLICTING_REPORT",`Cron run ${t.id} already has a different terminal report`,4)}return ze(e,t.id)}function th(e,t,r){return bt(()=>{let n=mR(e,Yp(t));if(n===null)throw new P("NOT_FOUND","No cron run matches the supplied report token",3);if(n.reported_at!==null||n.status!=="pending"&&n.status!=="running"){let o=Xp(r,eh(n));if(Zp(n,o))return n;throw new P("CONFLICTING_REPORT",`Cron run ${n.id} already has a different terminal report`,4)}return hl(e,n,r)})}function rh(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&&hl(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 ${Do} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return fR(e,t),ze(e,t)});return bt(()=>n.immediate())}function nh(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&&hl(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 ${Do} 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 gl(e,t,r){return bt(()=>{let n=Qp(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 ${Do} AND reported_at IS NULL`).run(o,r.summary.slice(0,rn),de(),de(),n.id),ze(e,n.id)})}function oh(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 P("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 ${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,
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 ${Do} 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 P("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 Ai(e,t){if(!Number.isSafeInteger(t.limit)||t.limit<1||t.limit>Ne)throw new P("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 _l}from"node:child_process";import{createHash as hR}from"node:crypto";import{existsSync as gR,mkdirSync as _R,mkdtempSync as wR,readFileSync as yR,rmSync as sh,writeFileSync as lh}from"node:fs";import{homedir as ER,tmpdir as TR}from"node:os";import{isAbsolute as bR,join as qo,resolve as Dn}from"node:path";var SR=["lmctl"],vR=["miniplayer"],AR=10*6e4,$R=50*6e4,kR=50*6e4,ih=24*60*6e4,uh=5e3,$i=1024*1024;function Uo(){return{text:"",overflow:!1}}function Fo(e,t){if(e.overflow)return;let r=e.text+t.toString("utf8");r.length>$i?(e.text=r.slice(0,$i),e.overflow=!0):e.text=r}function Ye(e){return e instanceof Error?e.message:String(e)}function xR(e,t,r){try{Po(e,t,r)}catch{}}function Be(e,t,r){try{return rh(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){xR(e,t,r);try{nh(e,t,n)}catch(o){process.stderr.write(`[lmcron] run ${t} outcome could not be persisted (fence retained): ${Ye(o)}
272
- `)}}function wl(e,t,r){let n=e??t;if(!Number.isFinite(n)||n<=0||n>ih)throw new Error(`${r} must be a positive number of milliseconds <= ${ih}`);return n}var ah=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","ClaudeMock"]),RR=/^[A-Za-z0-9][A-Za-z0-9._:@/+~-]*$/;function El(e){if(!ah.has(e))throw new P("INVALID_ARGUMENT",`provider "${e}" is not one of lmctl's supported providers (${[...ah].join(", ")})`);return e}function Tl(e){if(!RR.test(e))throw new P("INVALID_ARGUMENT",`model "${e}" is not a safe lmctl model token (no whitespace, quotes, '=' or control characters)`);return e}function ki(e){if(!bR(e))throw new P("INVALID_ARGUMENT",`sessiondir "${e}" must be an absolute path`);if(/["\u0000-\u001f\u007f]/.test(e))throw new P("INVALID_ARGUMENT",`sessiondir contains a quote, newline, or control character that lmctl cannot represent: ${JSON.stringify(e)}`);return e}function NR(e){let t=["_MEMBER_",`alias=${e.alias}`,`provider=${El(e.provider)}`];return e.model!==null&&e.model!==void 0&&t.push(`model=${Tl(e.model)}`),t.push(`sessiondir="${ki(e.sessiondir)}"`),t.join(" ")}function LR(e){let t=e.name,r=t!==void 0&&t.length>0?Dn(t):":memory:";return hR("sha256").update(r,"utf8").digest("hex").slice(0,16)}function IR(){return process.env.LMBEE_CRON_SESSION_DIR?process.env.LMBEE_CRON_SESSION_DIR:qo(ER(),".lmbee","cron-sessions")}function CR(e){return`'${e.replace(/'/g,"'\\''")}'`}function OR(e){let t=e.name;return t!==void 0&&t.length>0&&t!==":memory:"?`LMBEE_DB=${CR(Dn(t))} `:""}function DR(e,t,r){let n=OR(r);return`${e}
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}
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 MR(e,t){return`${e}
282
+ required. Never report succeeded unless the work actually succeeded.`}function FR(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 PR=new Set(["run_token","status","summary","artifacts","escalation"]),UR=new Set(["owner","reason","requestedAction"]);function dh(e,t){if(e===null)return{ok:!1,reason:"no output"};if(Buffer.byteLength(e,"utf8")>ml)return{ok:!1,reason:`result exceeds ${ml} 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(!PR.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>Si)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")>dl)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(!UR.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")>Oo)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")>Oo)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>ul)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 FR(e,t,r){let n=t.session_alias??"Worker";if(t.working_directory===null||t.provider===null)throw new P("INVALID_ARGUMENT",`session job ${t.id} requires provider and an absolute working_directory`);let o=qo(r??IR(),LR(e)),s=t.session_generation??0,i=t.session_teamfile??qo(o,`job-${t.id}-g${s}.lmctl`);if(t.session_teamfile!==null)return{teamfile:t.session_teamfile,alias:n};if(gR(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};_R(o,{recursive:!0});let a=NR({alias:n,provider:t.provider,model:t.model,sessiondir:t.working_directory});return lh(i,`#teamfile: ${i}
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}
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 bl(e){try{return process.kill(-e,0),!0}catch{return!1}}function yl(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 qR(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 jR(e,t){try{let r=yR(e,"utf8").trim();return r.length>t?r.slice(-t):r}catch{return""}}var HR=500,ch=75;function BR(e){let{db:t,job:r,run:n}=e;try{vi(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{Io({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===ch,l=jR(a,HR),u=o===ch?`script no-op (exit ${o})${l?`: ${l}`:""}`:`script exited with code ${o}${l?`: ${l}`:""}`;i!==null&&bl(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 WR(e){let{db:t,job:r,run:n}=e,o,s,i,a;try{o=wl(e.timeoutMs,AR,"timeoutMs"),s=e.sigkillGraceMs??uh,i=[...e.spawnPrefixes?.miniplayer??vR,"run",...r.model!==null?["-m",r.model]:[]],a=MR(r.action_payload,e.runToken)}catch(_){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer setup failed before spawn: ${Ye(_)}`}});return}let[c,...l]=i,u;try{u=_l(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(_){Be(t,n.id,{fallback:{ok:!1,summary:`miniplayer spawn error: ${Ye(_)}`}});return}u.unref();let d=Uo(),m=Uo(),f=!1,p=!1,h=setTimeout(()=>{f||(f=!0,yl(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",_=>Fo(d,_)),u.stderr?.on("data",_=>Fo(m,_)),u.stdin?.on("error",()=>{}),u.on("error",_=>{if(f)return;f=!0,clearTimeout(h);let g={fallback:{ok:!1,summary:`miniplayer spawn error: ${_.message}`}};p?_t(t,n.id,`miniplayer post-spawn error: ${_.message}`,g):Be(t,n.id,g)}),u.on("close",(_,g)=>{if(f)return;f=!0,clearTimeout(h);let y=u.pid??null,E=y!==null&&bl(y),v=d.overflow?{ok:!1,reason:`output exceeded the ${$i}-byte capture limit`}:dh(d.text,e.runToken),S=v.ok?{report:v.result}:{fallback:{ok:!1,summary:`miniplayer produced no valid structured result (${v.reason})`+(_!==0||g!==null?`; exit ${g??_}: ${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{vi(t,n.id,{kind:"miniplayer",model:r.model},u.pid??null)}catch(_){process.stderr.write(`[lmcron] miniplayer run ${n.id} state write failed after spawn: ${Ye(_)}
297
- `)}try{u.stdin?.write(a),u.stdin?.end()}catch(_){process.stderr.write(`[lmcron] miniplayer run ${n.id} stdin write failed: ${Ye(_)}
298
- `)}}function GR(e){let{db:t,job:r,run:n}=e,o,s,i;try{o=wl(e.timeoutMs,$R,"timeoutMs"),s=wl(e.seedTimeoutMs,kR,"seedTimeoutMs"),i=e.sigkillGraceMs??uh}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}=FR(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,R;try{let J=DR(r.action_payload,e.runToken,t);v=wR(qo(TR(),"lmbee-cron-session-")),S=qo(v,`${n.id}.md`),lh(S,J,{mode:384}),R=[...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[x,...L]=R,k;try{k=_l(x,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:Dn(t.name)}}:{}})}catch(J){try{sh(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=Uo(),C=Uo(),w=!1,T=!1,N=()=>{try{sh(v,{recursive:!0,force:!0})}catch{}},U=setTimeout(()=>{w||(w=!0,yl(k,i),_t(t,n.id,`session timed out after ${o}ms`,{fallback:{ok:!1,summary:`session timed out after ${o}ms`}}))},o);U.unref(),k.on("spawn",()=>T=!0),k.stdout?.on("data",J=>Fo(B,J)),k.stderr?.on("data",J=>Fo(C,J)),k.on("error",J=>{if(w)return;w=!0,clearTimeout(U);let ee={fallback:{ok:!1,summary:`session dispatch spawn error: ${J.message}`}};T?_t(t,n.id,`session post-spawn error: ${J.message}`,ee):(N(),Be(t,n.id,ee))}),k.on("close",J=>{if(w)return;w=!0,clearTimeout(U);let ee=k.pid??null,oe=ee!==null&&bl(ee),V=B.overflow?{kind:"overflow"}:qR(B.text),se=V.kind==="completed"?dh(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 ${$i}-byte capture limit`:"session ended without positive completion")+(J!==0?` (exit ${J}: ${C.text.trim().slice(-300)})`:"")}};if($){if(se!==null&&!se.ok){N(),Be(t,n.id,O);return}if(Be(t,n.id,O)){N();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{vi(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{pl(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??SR,"seed",a],m=d[0],f=d.slice(1),p;try{p=_l(m,f,{detached:!0,stdio:["ignore","ignore","pipe"],...t.name!==void 0&&t.name!==":memory:"?{env:{...process.env,LMBEE_DB:Dn(t.name)}}:{}})}catch(E){Be(t,n.id,{fallback:{ok:!1,summary:`session seed spawn error: ${Ye(E)}`}});return}p.unref();let h=Uo(),_=!1,g=!1,y=setTimeout(()=>{_||(_=!0,yl(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);y.unref(),p.on("spawn",()=>g=!0),p.stderr?.on("data",E=>Fo(h,E)),p.on("error",E=>{if(_)return;_=!0,clearTimeout(y);let v={fallback:{ok:!1,summary:`session seed spawn error: ${E.message}`}};g?_t(t,n.id,`session seed post-spawn error: ${E.message}`,v):Be(t,n.id,v)}),p.on("close",E=>{if(!_){if(_=!0,clearTimeout(y),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{pl(t,n.id,{kind:"session",phase:"seed",teamfile:a,alias:c},p.pid??null)}catch{}}function Sl(e){try{switch(e.job.action_kind){case"script":BR(e);return;case"miniplayer":WR(e);return;case"session":GR(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 JR(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}function KR(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 P("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 P("STRUCTURAL_ERROR",r,2):new P("STORAGE_ERROR",r,1)}function lr(e){try{return e()}catch(t){if(t instanceof P)throw t;if(t instanceof I)throw new P(t.code,t.message,t.exitCode);return Mn(t)}}function xi(e,t){e.prepare("UPDATE cron_jobs SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}function Ri(e,t){return lr(()=>e.prepare("SELECT * FROM cron_jobs WHERE id = ?").get(t)??null)}function Ie(e,t){let r=Ri(e,t);if(r===null)throw new P("NOT_FOUND",`Cron job ${t} does not exist`,3);return r}function zR(e){let t;try{t=JSON.parse(e)}catch{throw new P("INVALID_ARGUMENT","enqueue action_payload must be valid JSON")}if(typeof t!="object"||t===null)throw new P("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 P("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "to"');if(typeof n!="string"||n.trim().length===0)throw new P("INVALID_ARGUMENT",'enqueue action_payload requires a nonblank "prompt"');if(o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new P("INVALID_ARGUMENT",'enqueue action_payload "from", if given, must be a nonblank string')}function ph(e,t){ye(t,"action_payload"),e==="enqueue"&&zR(t)}function hh(e){let{actionKind:t}=e;if(t==="session"){if(e.provider===void 0||e.provider===null||e.provider.trim().length===0)throw new P("INVALID_ARGUMENT","a session job requires a nonblank provider");if(El(e.provider),e.workingDirectory===void 0||e.workingDirectory===null||e.workingDirectory.trim().length===0)throw new P("INVALID_ARGUMENT","a session job requires an absolute working_directory (--cwd)");ki(e.workingDirectory)}else if(e.provider!==void 0&&e.provider!==null&&e.provider.trim().length>0)throw new P("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 P("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 P("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&&Tl(e.model),e.workingDirectory!==void 0&&e.workingDirectory!==null&&e.workingDirectory.trim().length>0&&t==="enqueue")throw new P("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 P("INVALID_ARGUMENT","working_directory, if given, must be nonblank");if(e.escalationOwner!==void 0&&e.escalationOwner!==null&&e.escalationOwner.trim().length===0)throw new P("INVALID_ARGUMENT","escalation_owner, if given, must be nonblank")}function gh(e){let t=ye(e,"timezone");try{new Intl.DateTimeFormat(void 0,{timeZone:t})}catch{throw new P("INVALID_ARGUMENT",`timezone "${t}" is not a recognized IANA zone name`)}return t}function _h(e){let t=ll(e);if(!t.ok){let r=t.error.field?` (field: ${t.error.field})`:"";throw new P("INVALID_SCHEDULE",`${t.error.message}${r}`)}}function Ni(e,t){let r=e.transaction(()=>{if(t.id!==void 0&&(!Number.isSafeInteger(t.id)||t.id<1))throw new P("INVALID_ARGUMENT","id, if given, must be a positive safe integer");let n=ye(t.title,"title");if(!JR(t.actionKind))throw new P("INVALID_ARGUMENT",'action_kind must be "enqueue", "command", "script", "session", or "miniplayer"');_h(t.scheduleExpr),ph(t.actionKind,t.actionPayload),hh({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?gh(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,
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)}
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,
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 P("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 wh(e,t,r){let n=e.transaction(()=>{let o=Ie(e,t);if(r.ifRevision!==void 0&&o.revision!==r.ifRevision)throw new P("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&&(_h(r.scheduleExpr),s.schedule_expr=r.scheduleExpr),r.actionPayload!==void 0&&(ph(o.action_kind,r.actionPayload),s.action_payload=r.actionPayload),r.timezone!==void 0&&(s.timezone=r.timezone===null?null:gh(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 P("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)&&hh({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 P("INVALID_ARGUMENT","working_directory is not valid for enqueue jobs");if(r.workingDirectory===null){if(o.action_kind==="session")throw new P("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"&&ki(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 P("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 xi(e,t),Ie(e,t)});return lr(n)}function yh(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 xi(e,t),Ie(e,t)});return lr(n)}function Eh(e,t){let r=e.transaction(()=>{let n=Ie(e,t);if(Rr(e,t)!==null)throw new P("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 Th(e,t){let r=e.transaction(()=>{if(Ie(e,t).action_kind!=="session")throw new P("INVALID_ARGUMENT",`Cron job ${t} is not a session job`);if(Rr(e,t)!==null)throw new P("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),xi(e,t),Ie(e,t)});return lr(r)}var YR=24*60*60*1e3;function bh(e,t=VR){try{return t("systemctl",["--user","is-active","--quiet",e]),"active"}catch(r){return r.status===3?"confirmed-gone":"unknown"}}async function Sh(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Io,i=n.isUnitStillRunningImpl??bh,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{QR(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??Sl})}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 mh(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 QR(e,t,r,n,o,s,i,a,c,l,u,d){let m=ll(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 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 = ?,
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),_=new Date(n);if(n-p>YR){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, last_fire_status = ?, updated_at = ?",[o,"skipped_stale",o],t);return}let g=t.timezone!==null?mh(h,t.timezone):h,y=t.timezone!==null?mh(_,t.timezone):_;if(!Kp(f,g,y)){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ?",[o,o],t);return}let v=Ri(e,t.id);if(!(v===null||v.enabled===0||v.revision!==t.revision)){if(KR(t.action_kind)){XR(e,t,o,l,u,d);return}if(t.action_kind==="enqueue")try{let S=JSON.parse(t.action_payload),R={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,R),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,R=`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,R,o,t.id,t.revision,t.last_checked_ts,t.running_since_ts).changes===0)return;let L={logDir:c,systemdUnitName:R,onExit:(k,B)=>{let C=k===0?"ok":"error",w=C==="ok"?null:B?St(B):`Command exited with code ${k} -- see ${c??bi()}/${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,w,new Date().toISOString(),t.id,S)}catch{}}};try{i({id:t.id,action_payload:t.action_payload},L),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 fh(e,t){for(;!e();)await new Promise(r=>setTimeout(r,t))}async function vl(e,t,r,n={}){let o=n.enqueueImpl??_e,s=n.spawnCommandImpl??Io,i=n.isUnitStillRunningImpl??bh,a=n.executeRunImpl??Sl,c=n.logDir,l=n.pollMs??250,u=Ie(e,t);if(u.enabled===0)throw new P("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 vl(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 g={logDir:c,systemdUnitName:h,onExit:(y,E)=>{let v=y===0?"ok":"error",S=v==="ok"?null:E?St(E):`Command exited with code ${y} -- see ${c??bi()}/${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},g)}catch(y){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(y),d,u.id,p)}catch{}throw new P("SPAWN_FAILED",`manual trigger of job ${t} failed to spawn: ${St(y)}`,1)}return await fh(()=>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=fl(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 P("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{Po(e,f.run.id,`worker dispatch threw: ${St(p)}`),gl(e,f.run.id,{ok:!1,summary:`worker dispatch error: ${St(p)}`})}catch{}throw new P("SPAWN_FAILED",`manual trigger of job ${t} failed to dispatch: ${St(p)}`,1)}return await fh(()=>{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 XR(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=fl(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{Po(e,a.run.id,`worker dispatch threw: ${St(c)}`),gl(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 vh(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 xi(e,t),Ie(e,t)});return lr(r)}import{execFileSync as ZR}from"node:child_process";import{existsSync as eN,readFileSync as Ah}from"node:fs";import{homedir as $h}from"node:os";import{join as kh}from"node:path";function Un(){return process.env.LMBEE_HEAVY_STATUS??kh($h(),".lmbee","heavy.status")}function Fn(){return process.env.LMBEE_HEAVY_LOCK??kh($h(),".lmbee","heavy.lock")}var Pn=class extends Error{};function tN(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 rN(e){let t;try{t=Ah(e,"utf8")}catch{return null}try{let r=JSON.parse(t);return tN(r)?r:null}catch{return null}}function nN(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 oN(e){try{let t=Ah(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[0]==="Z"}catch{return!1}}function sN(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return!oN(e)}function iN(e,t=ZR){if(!eN(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 Pn(`heavy-lock probe failed (flock did not run or exited abnormally): ${o}`)}}function Al(e=Un(),t=Fn(),r=rN,n=iN,o=sN){for(let s=0;s<3;s++){let i=r(e),a=n(t),c=r(e);if(i!==null&&nN(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=Un(),t=Fn(),r=Al,n){try{return r(e,t)}catch(o){if(!(o instanceof Pn))throw o;return n?.(o),{held:!0,holder:null}}}var Ii={observedAt:null,report:null,lastErrorAt:null,lastError:null};function xh(e,t){Ii={observedAt:t,report:e,lastErrorAt:null,lastError:null}}function Rh(e,t){Ii={...Ii,lastErrorAt:t,lastError:e}}function jo(){return Ii}import{execFile as aN}from"node:child_process";import{promisify as cN}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 lN=cN(aN);function uN(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 dN(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(uN))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 lN("lmctl",["running","--json"],{timeout:e});return dN(t)}function $l(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 mN}from"node:fs";import{randomUUID as fN}from"node:crypto";var kl={staleThresholdMs:2*60*6e4,escalationCooldownMs:60*6e4,digestTimeoutMs:9e4,leaseTimeoutMs:10*6e4,providerQuotaBackoffMs:24*60*6e4,operatorStaleThresholdMs:6e4,operatorEscalationCooldownMs:6e4};function pN(e){return/usage limit/i.test(e)&&/quota/i.test(e)}function hN(e){let t=[];for(let r of e)try{t.push({row:r,content:mN(r.prompt_file,"utf8")})}catch{continue}return t}function gN(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);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} ---
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 _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 wN(e,t){let r=new Set,n=new Date().toISOString(),o=fN();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 Ci(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 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
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 Nh(e,t,r=kl,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,_=d[0];if(n-Date.parse(_.created_ts)<p)continue;let y=ie(e,u),E=y?.last_escalation_attempt_ts?Date.parse(y.last_escalation_attempt_ts):null;if(E!==null&&n-E<h)continue;let v=y?.quota_exhausted_last_seen_ts?Date.parse(y.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(Ds(e,u,m.leadAlias,n))continue;let S;try{S=Q(m)}catch{continue}let R=hN(d);if(R.length===0)continue;let{claimed:x,token:L}=wN(e,R.map(C=>C.row.id)),k=R.filter(C=>x.has(C.row.id));if(k.length===0)continue;let B=!1;try{let C=gN(k);sm(e,u,new Date().toISOString());let w=await s({teamfilePath:S,alias:m.leadAlias},C,{timeoutMs:r.digestTimeoutMs});if(w.kind==="ok"||w.kind==="stalled")Ci(e,x,L,!0,()=>om(e,u)),B=!0,i.push(u);else if(w.kind==="error"&&pN(w.message)){let T=new Date().toISOString();Ci(e,x,L,!1,()=>nm(e,u,T,w.message)),B=!0}else Ci(e,x,L,!1),B=!0}catch{}finally{if(!B)try{Ci(e,x,L,!1)}catch{}}}return i}var xl={minStaleMs:12e5,maxTotalAgeMs:144e5};function Lh(e,t,r=xl,n=Date.now()){return[]}var Rl={staleMs:72e5,maxAgeMs:864e5,cooldownMs:36e5};function Ih(e,t,r,n=Rl,o=Date.now()){return[]}import{execFile as SN}from"node:child_process";import{promisify as vN}from"node:util";var yN=["ok","provider_unavailable","auth_expired","not_applicable","reader_throttled"];function EN(e){return typeof e=="string"&&yN.includes(e)}function Nl(e){return typeof e=="object"&&e!==null}function TN(e){if(!Nl(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 bN(e){if(!Nl(e))return null;let t=e.provider,r=e.status,n=e.read_at;if(typeof t!="string"||t.length===0||!EN(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(TN).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 Ch(e){let t;try{t=JSON.parse(e)}catch{return null}return!Nl(t)||!Array.isArray(t.readings)?null:t.readings.map(bN).filter(r=>r!==null)}var AN=vN(SN);function Oh(){return process.env.LMBEE_RATE_LIMIT_BIN??"lmctl"}async function $N(e=Oh(),t=AN){try{let{stdout:r}=await t(e,["ratelimit","--json"]);return Ch(r)}catch{return null}}function kN(e){return e==null?null:typeof e=="string"?e:JSON.stringify(e)}function xN(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 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)
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,kN(i.raw_value),i.raw_scale??null,i.is_exhausted===!0?1:i.is_exhausted===!1?0:null,t.read_at)}}var Dh="rate_limit_collect:last_run_ms",RN=5*6e4;function NN(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(Dh);if(n===void 0)return!0;let o=Number(n.v);return Number.isFinite(o)?t-o>=r:!0}function LN(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Dh,String(t))}async function Mh(e,t={}){let r=t.nowMs??Date.now(),n=t.cooldownMs??RN;if(!NN(e,r,n))return{outcome:"skipped-cooldown"};let s=await(t.fetchImpl??$N)(t.binPath??Oh());if(s===null)return{outcome:"fetch-failed"};let i=Math.floor(r/1e3);return e.transaction(c=>{for(let l of c)xN(e,l,i)})(s),LN(e,r),{outcome:"collected",readingsStored:s.length}}var Ll={five_hour:9e5,weekly:36e5},Oi={five_hour:"five_hour_15m",weekly:"weekly_1h"};function Di(e,t){if(e.length<3)return{kind:"insufficient_data",reason:`only ${e.length} sample(s), need >= 3`};let r=[...e].sort((g,y)=>g.readAt-y.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((g,y)=>g+y.readAt,0)/a,l=r.reduce((g,y)=>g+y.usedFraction,0)/a,u=0,d=0;for(let g of r){let y=g.readAt-c;u+=y*(g.usedFraction-l),d+=y*y}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 Ph(e,t,r){return e.kind!=="forecast"?!1:e.forecastAtMs-r<=Ll[t]}var IN=new Set(["claude:week-scoped-Fable","codex:codex_bengalfox-5h","codex:codex_bengalfox-weekly"]);function Uh(e,t){return IN.has(`${e}:${t}`)}var CN=Ll.weekly;function ON(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 DN(e){return new Date(e*1e3).toISOString()}function MN(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=${Oi[r]}`}function qn(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 Mi(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 PN(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 UN(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,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)
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 Fh(e,t={}){let r=t.nowMs??Date.now(),n=t.dryRun??!0,o=t.checkProviderDisabledImpl??rt,s=t.setProviderDisableImpl??_i,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(Uh(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)Mi(e,c,l,L.resetsAt),qn(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),_=h.map(L=>({readAt:L.readAt,usedFraction:L.usedFraction})),g=Di(_,r);if(g.kind==="insufficient_data"){a.push({provider:c,bucketId:l,windowType:u,outcome:"insufficient-data",detail:g.reason});continue}let y=PN(e,c,l,m);if(g.kind==="no_forecast"||!Ph(g,u,r)){y!==null&&(Mi(e,c,l,m),qn(e,r,c,l,u,"disarmed",`forecast no longer crosses the ${Oi[u]} threshold`)),a.push({provider:c,bucketId:l,windowType:u,outcome:g.kind==="no_forecast"?"no-forecast":"below-threshold",detail:""});continue}let E=_[_.length-1].usedFraction;if(y===null){UN(e,c,l,m,Oi[u],r,g.latestReadAtMs,E,g.forecastAtMs);let L=`armed on first crossing, forecast ${new Date(g.forecastAtMs).toISOString()}`;qn(e,r,c,l,u,"armed",L),a.push({provider:c,bucketId:l,windowType:u,outcome:"armed",detail:L});continue}if(g.latestReadAtMs<=y.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<=y.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 (${y.armed_used_fraction}) -- awaiting real movement to confirm`});continue}let v=o(e,c,r),S=ON(_),R=MN(c,l,u,g,S,r);if(v.disabled){let L=v.config?`reason=${JSON.stringify(v.config.reason)}, expiresAt=${v.config.expiresAt??"indefinite"}`:"fail-closed (read error)",k=`would have fired (${R}) but ${c} is already disabled (${L}) -- deferring, never shortening or overwriting an existing hold`;qn(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){Mi(e,c,l,m);let L=`would have fired (policy step is disabled -- collection only): ${R}`;qn(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 x=u==="weekly"?new Date(r+CN).toISOString():h[h.length-1]?.resetsAtIso??DN(m);s(e,c,{reason:R,expiresAt:x}),Mi(e,c,l,m),qn(e,r,c,l,u,"confirmed_fired",R),a.push({provider:c,bucketId:l,windowType:u,outcome:"confirmed-fired",detail:R})}return FN(e,r,a),a}var qh="rate_limit_policy_heartbeat";function FN(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(qh,JSON.stringify(o))}function Ui(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(qh);if(t===void 0)return null;try{return JSON.parse(t.v)}catch{return null}}var qN=15*6e4;function jh(e,t=Date.now(),r=qN){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=Ui(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 jN=.85;function Hh(e,t=jN){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 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
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=>!Uh(n.provider,n.bucketId)&&n.usedFraction>=t)}var Il="auto_scan_paused";function Lr(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Il);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 HN=3*24*60*6e4;function Bh(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>=HN?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!1}:null}function Wh(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Il,JSON.stringify(t))}function Gh(e){e.prepare("DELETE FROM kv WHERE k = ?").run(Il)}var BN=/usage limit|rate limit|too many requests|quota exceeded|insufficient_quota/i;function Fi(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||!BN.test(o.error))return!1;let s=Date.parse(o.ended_at);return Number.isFinite(s)?n-s<r:!1}import{existsSync as Cl,mkdirSync as WN,readFileSync as GN,writeFileSync as VN}from"node:fs";import{homedir as JN}from"node:os";import{join as Vh}from"node:path";var KN=`# Autopilot check-in -- advance your work, then report status
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
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 qi(e){return e||(process.env.LMBEE_PROMPTS_DIR?process.env.LMBEE_PROMPTS_DIR:Vh(JN(),".lmbee","prompts"))}function Jh(e,t){return Vh(e,`${t}.md`)}function zN(e){Cl(e)||WN(e,{recursive:!0});let t=Jh(e,"default");Cl(t)||VN(t,KN)}function YN(e,t){let r=Jh(e,t);if(!Cl(r))if(t==="default")zN(e);else throw new Error(`loadPromptTemplate: no prompt file for "${t}" at ${r} -- prepare it (S1) before this team can be auto-nudged`);return GN(r,"utf8")}function ji(e,t){return YN(e,t.promptName)}import{existsSync as QN,readFileSync as zh,rmSync as XN}from"node:fs";import{resolve as Kh,sep as ZN}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 Yh(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? ORDER BY created_at ASC, id ASC").all(t)}var e0=`q.status != 'merged'
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'
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 Qh(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 Xh(e,t){return e.prepare(`SELECT q.* FROM queue q
353
353
  WHERE q.to_id = ?
354
- AND ${e0}
355
- ORDER BY q.id`).all(t)}function Xh(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 Zh(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 Ol(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 Dl(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=zh(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function nn(e,t){return 1+Ol(e,t).length}function Ho(e,t){return(t.retracted_ts!==null?1:0)+Ol(e,t).filter(n=>n.retracted_ts!==null).length}function eg(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=Ol(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=Kh(Hs()),p=Kh(a.prompt_file);if((p===f||p.startsWith(f+ZN))&&QN(p))try{XN(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 Bo(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 t0=5;function r0(e,t,r){let n=new Set([t.from_id,t.to_id]);if(r.length>0){let a="";try{a=zh(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,t0)}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=r0(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 tg(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 rg(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 Hi(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 ng(e,t,r){e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ?").run(r,t)}function og(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&&(Vs(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),ng(e,t,c),og(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 sg(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),ng(e,t,c),og(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 ig(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 cg(e,t,o)}).immediate()}function ag(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 cg(e,t,`[resolved by proxy ${r}]: ${o}`)}).immediate()}function cg(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 n0=/standing by|standby|\bready\b|on-call/i,o0=4*60*6e4,ug=5;function s0(e,t){if(e.length===0)return"";let r=e.slice(0,ug),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 ${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)`),`
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 lg=140,i0=4*60*6e4;function a0(e){let t=e.trim().split(`
362
- `)[0]??"";return t.length>lg?`${t.slice(0,lg)}\u2026`:t}function c0(e){if(e.length===0)return"";let t=e.slice(0,ug).map(({row:r,answer:n,ageMs:o})=>` #${r.id} to ${r.to_id} (${me(o)} ago) -- "${a0(n.answer_text)}"`);return e.length>t.length&&t.push(` ...and ${e.length-t.length} more`),`
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`),`
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 l0(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 u0(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 dg(e,t,r,n={}){let o=n.config??pe,s=n.nowMs??Date.now(),i=n.fetchTailImpl??yi,a=qi(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 _=Ue(e,h.name);if(_===null||_.status==="BLOCKED"||ie(e,h.name)?.confirmed_done_ts||qe(e,h.name,{fromAutopilot:!0}).length>0)return!1;let g=l();if(g.held&&(g.holder===null||g.holder.holder===h.name))return!1;try{let y=`${Q(h)}:${h.leadAlias}`;if(Fi(r,y,n.providerExhaustionBackoffMs))return!1}catch{}return!0}let f=n.clearAutoNudgeSuspendedImpl??Gd,p=n.recordAutoNudgeSuspendedImpl??Wd;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 _=await l0(h,i);if(_!==null&&n0.test(_.text)&&!u0(_.ts,n.standbyStaleMs??o0,s)){p(e,h.name,"standby_reply_active",`last reply matches the standby pattern and is not yet stale: "${_.text.slice(0,200)}"`,new Date(s).toISOString());continue}if(!m(h))continue;let g=n.loadTeamTaskStateImpl??xe,y=n.deriveTaskAwareNudgeImpl??kf,E=null;try{E=g(e,Q(h),h.leadAlias)}catch{}let v,S;if(E!==null){let oe=await y(e,E,{backoffMs:o.cooldownMs});if(oe===null||(v=oe.message,S=oe.onSent,!m(h)))continue}else try{v=ji(a,h)}catch{continue}let x=(n.findOwedResponsesImpl??on)(e,h.name,s);v+=s0(x,h.name);let k=(n.findRecentlyAnsweredForSenderImpl??Hi)(e,h.name,i0,s);v+=c0(k);let C=(n.loadAutoNudgeRedirectImpl??Tt)(e,h.name),w=C===null?h.name:`${C.companionTeam}:${C.workerAlias}`,T=C===null?h.name:C.companionTeam,N=C===null?h.leadAlias:C.workerAlias,U=C===null?h.repoPath:t.find(oe=>oe.name===T)?.repoPath??h.repoPath,ee=(n.resolveMemberProviderImpl??jt)({repoPath:U,name:T},N);if(!(ee!==null&&(n.checkProviderDisabledImpl??rt)(e,ee,s).disabled)){if(_e(e,t,w,v,{from:"autopilot"}),C!==null){let oe=n.recordRedirectedDispatchImpl??Sp;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 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)}
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
- `)}So(e,h.name,new Date().toISOString()),d.push(h.name)}}return d}import{readFileSync as d0}from"node:fs";function mg(e){return`last_maintainer_wake:${e}`}function m0(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(mg(t))?.v??null}function f0(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(mg(t),r)}function p0(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 fg(e,t,r,n,o=a=>d0(a,"utf8"),s=Date.now(),i){let a=t.find(m=>m.name===n.teamName);if(!a||!H(a)||!(i??p0(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=m0(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"}),f0(e,n.teamName,new Date(s).toISOString()),!0}function Bi(e){return`blocked:${e}`}function pg(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 hg(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 _ of m)if(_.blocked_on!=="operator"){if(_.blocked_on===null){f.push(_);continue}if(n.some(g=>g.name===_.blocked_on)){let g=p.get(_.blocked_on)??[];g.push(_),p.set(_.blocked_on,g)}else f.push(_)}let h=!1;f.length>0&&(new Set(qe(e,r).map(g=>g.subject_id).filter(g=>g!==null)).has(Bi(a.name))||(_e(e,n,r,pg(e,a.name,f,"your decision"),{from:"autopilot",subject:Bi(a.name)}),h=!0));for(let[_,g]of p)new Set(qe(e,_).map(E=>E.subject_id).filter(E=>E!==null)).has(Bi(a.name))||(_e(e,n,_,pg(e,a.name,g,"your decision"),{from:"autopilot",subject:Bi(a.name)}),h=!0);h&&(Fd(e,a.name,new Date().toISOString()),i.push(a.name))}return i}var h0=30*6e4;function g0(e){return`unresolvable-teamfile:${e}`}async function gg(e,t,r,n,o=pe,s=Date.now(),i=h0,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),Kd(e,l.name);continue}catch{}Jd(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=g0(l.name);if(qe(e,r).map(g=>g.subject_id).filter(g=>g!==null).includes(f))continue;let h=Math.round(d/6e4),_=`[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,_,{from:"autopilot",subject:f}),Yd(e,l.name,a()),c.push(l.name)}return c}var Ml="epic_closed_surfaced_ts";function Wi(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[Ml]=="string"&&(s=!0)}}return{entity:n,status:n.status,alreadySurfacedThisEpisode:s}})()}function _g(e){return`epic-closed:${e}`}async function wg(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(_g(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 _=At(Q(u)),g=!1;e.transaction(()=>{let E=[];for(let x of h){let L=Wi(e,x.id);if(L===null)continue;let k=L.entity;An.has(le(k.status))&&(k.owner_team_path!==_||k.owner_alias!==u.leadAlias||L.alreadySurfacedThisEpisode||E.push(k))}if(E.length===0)return;let v=E.map(x=>`#${x.id} ("${x.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:_g(u.name),escalationOnly:!0});let R=new Date().toISOString();for(let x of E)Bt(e,x.id,{body:JSON.stringify({[Ml]:R})});jd(e,u.name,R),g=!0}).immediate(),g&&l.push(u.name)}return l}function yg(e){return`done-check:${e}`}var Tg="consistency_alert_ts";function Eg(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[Tg]=="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 Va(o,n))return!0;return!1}async function bg(e,t,r,n,o=pe,s={}){let i=s.hasEvidenceAroundDoneImpl??_0,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(yg(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],_=[];for(let S of p){let R=Eg(e,S.id);if(R===null||R.alreadyAlertedThisEpisode)continue;await i(h,R.doneTransitionIso,o.idleThresholdMs)||_.push({entity:S,epochId:R.epochId})}if(_.length===0)continue;let g=At(d),y=new Date().toISOString(),E=!1;e.transaction(()=>{let S=[];for(let{entity:L,epochId:k}of _){let B=Eg(e,L.id);if(B===null)continue;let C=B.entity;le(C.status)==="done"&&(C.owner_team_path!==g||C.owner_alias!==u.leadAlias||Vt(e,C,new Map)||B.epochId!==k||B.alreadyAlertedThisEpisode||S.push(C))}if(S.length===0)return;let R=S.map(L=>`#${L.id} ("${L.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: ${R.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:yg(u.name),escalationOnly:!0});for(let L of S)Bt(e,L.id,{body:JSON.stringify({[Tg]:y})});E=!0}).immediate(),E&&l.push(u.name)}return l}function Sg(e){return`fault:${e}`}async function vg(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(Sg(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=bo(e,f,o.cooldownMs,s);if(p.length===0)continue;i.beforeRevalidate?.();let h=!1;e.transaction(()=>{let g=[];for(let v of p){let S=at(e,v.id);if(S===null)continue;let R=bo(e,{entities:[S]},o.cooldownMs,s,{team:Q(l),alias:l.leadAlias});R.length!==0&&g.push(R[0])}if(g.length===0)return;let y=g.map(v=>{let S=Sn(e,v.id),R=S!==null?`note: "${S.body}"`:"no note recorded";return`#${v.id} ("${v.title}", ${v.status}, ${R})`}),E=`Team "${l.name}" has ${g.length} task(s) stuck in a fault state past expected recovery: ${y.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:Sg(l.name)}),qd(e,l.name,new Date().toISOString()),h=!0}).immediate(),h&&c.push(l.name)}return c}function Ag(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
+ `)}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(
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 $g(e){return`unknown:${e}`}async function kg(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 w0(e,t,r,n,o,s,c)}finally{a!==void 0&&a.close()}}async function w0(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($g(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!==""&&Ag(i(),v,f.leadAlias,o.idleThresholdMs,s))continue}let p=a.get(u),h=p?.repoPath!==void 0&&p?.leadAlias!==void 0,_=h?kc(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias}):Ue(e,u)===null,g=d===null||d.progress_status==="ACTIVE",y=!_&&h&&g&&Ac(e,{name:u,repoPath:p.repoPath,leadAlias:p.leadAlias},o.idleThresholdMs,s);if(!_&&!y)continue;let E=_?`[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:$g(u)}),Ud(e,u,new Date().toISOString()),l.push(u)}return l}import{execFile as y0}from"node:child_process";import{promisify as E0}from"node:util";function Wo(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 Gi(e,t,r,n,o={}){let s=o.resolveMemberProviderImpl??jt,i=o.checkProviderDisabledImpl??rt,a=o.isProviderExhaustedImpl??Fi,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(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 xg=E0(y0),T0=new Set(["ENV-ERROR","NO-OUTPUT"]),b0=24*60*6e4,S0=3;async function Go(e,t,r=xg){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 Rg(e,t,r,n,o,s={}){let i=s.execImpl??xg,a=s.whyNotObservedImpl??Gi,c=s.flappingWindowMs??b0,l=s.flappingOccurrenceThreshold??S0,u=s.listRecentEventsByStatusImpl??Ss,d=[],m=[];for(let f of t){let p=Md(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:_,observedAt:g,changedAt:y}=p,E=n-Date.parse(g),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)),R=S.length>=l,x=T0.has(_.status)&&!Number.isNaN(E)&&E>=o;if(!x&&!R)continue;if(R&&!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:g,ageMs:E,suspension:h});continue}let L=_.status;if(h.kind==="no_continuous_observer"){let k=null;if(L==="NO-OUTPUT")try{k=await Go(Q(f),f.leadAlias,i)}catch{k=null}d.push({kind:"continuous",team:f.name,status:L,changedAt:y,observedAt:g,ageMs:E,cause:k})}else m.push({team:f.name,status:L,changedAt:y,observedAt:g,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 v0}from"node:child_process";import{promisify as A0}from"node:util";var $0=A0(v0);async function Ng(e,t=$0){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 k0}from"node:child_process";import{promisify as x0}from"node:util";var R0=x0(k0);async function Ig(e,t=R0){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 Pl}from"node:fs";function Ul(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=Ul(e,n,r);return o===null?null:{...o,explicit:!1}}function Vi(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 Cg(e){return e.prepare("SELECT * FROM entities WHERE kind = 'epic' AND owner_team_path IS NULL").all().filter(r=>!gt(r.status))}function Og(e,t,r=Pl){return Vi(e,t)!==null?"registered":r(t)?"on_demand":"dangling"}function Dg(e,t,r={}){let n=r.existsSyncImpl??Pl,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=Ul(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}Og(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 Mg(e){return e.prepare("SELECT * FROM entities WHERE status = 'blocked'").all().filter(r=>(ct(e,r.id,"outgoing").outgoing??[]).length===0)}function N0(e,t){return e.prepare("SELECT 1 FROM queue WHERE to_id = ? LIMIT 1").get(t)!==void 0}function Pg(e,t,r,n=Pl){let o=Ul(e,r);if(o===null)return{ownerKind:"dangling",everContacted:null};let s=Og(t,o.ownerTeamPath,n);if(s==="dangling")return{ownerKind:s,everContacted:null};if(s==="on_demand")return{ownerKind:s,everContacted:!1};let i=Vi(t,o.ownerTeamPath);return{ownerKind:s,everContacted:N0(e,i)}}function Fg(e,t){let r=ct(e,t,"outgoing").outgoing??[];return new Set(r.filter(n=>!gt(n.status)).map(n=>n.id))}function Ji(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(...Ji(e,a.id,r));let i=new Set;return s.filter(a=>i.has(a.id)?!1:(i.add(a.id),!0))}function L0(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 Ug(e){let t=e.trim().toLowerCase();return t==="todo"?0:t==="in_progress"||t==="in-progress"?1:2}function qg(e,t,r){let n=new Map;for(let s of t)for(let i of Ji(e,s.id))n.set(i.id,i);let o=[];for(let s of n.values()){let i=L0(e,s.id),a=new Set;for(let l of i){let u=Vi(r,l.owner_team_path);u!==null&&a.add(u)}let c=Pg(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=Ug(s.entity.status)-Ug(i.entity.status);return a!==0?a:s.entity.id-i.entity.id}),o}import{execFile as I0}from"node:child_process";import{readFileSync as C0}from"node:fs";import{basename as O0,resolve as D0}from"node:path";import{promisify as M0}from"node:util";var Fl=M0(I0),P0=[/\.env\.(example|sample|template)$/i],U0=[/\.pem$/,/\.key$/,/(^|\/)id_rsa$/,/(^|\/)id_ed25519$/,/(^|\/)id_ecdsa$/],F0=[/(^|\/)\.env(\..+)?$/,/(^|\/)\.mcp\.json$/,/(^|\/)\.netrc$/,/(^|\/)\.npmrc$/],Hg=[/\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,}/],q0=[...Hg,/\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],Ki=20*1024*1024;async function Bg(e,t){try{let{stdout:r}=await t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Ki});return r.split(`
382
- `).filter(n=>n.length>0)}catch{return null}}async function ql(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"show",`HEAD:${t}`],{timeout:1e4,maxBuffer:Ki});return n}catch{return null}}async function Wg(e,t=Fl){let r=await Bg(e,t);if(r===null)return null;let n=a=>!P0.some(c=>c.test(a)),o=r.filter(a=>U0.some(c=>c.test(a))&&n(a)),s=r.filter(a=>F0.some(c=>c.test(a))&&n(a)),i=[];for(let a of s){let c=await ql(e,a,t);c!==null&&q0.some(l=>l.test(c))&&i.push(a)}return[...o,...i]}async function Gg(e,t=Fl){let r=await Bg(e,t);if(r===null)return null;let n=r.filter(s=>s.endsWith(".lmctl")),o=[];for(let s of n){let i=await ql(e,s,t);if(i===null)continue;let a=Hg.reduce((c,l)=>c+(l.test(i)?1:0),0);a>0&&o.push({path:s,matchCount:a})}return o}var j0=[/(^|\/)template\.lmctl$/i,/(^|\/)examples\/.*\.lmctl$/i],jg=/_MEMBER_\b|\bsessionid\s*=\s*\S/;async function Vg(e,t=Fl){try{let[r,n]=await Promise.all([t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Ki}),t("git",["-C",e,"ls-files","--others","--exclude-standard"],{timeout:1e4,maxBuffer:Ki})]),o=u=>!j0.some(d=>d.test(u)),s=u=>O0(u).includes(".lmctl")&&o(u),i=r.stdout.split(`
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(`
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 ql(e,u,t);d!==null&&jg.test(d)&&c.push(u)}let l=[];for(let u of a){let d;try{d=C0(D0(e,u),"utf8")}catch{continue}jg.test(d)&&l.push(u)}return{tracked:c,unprotected:l}}catch{return null}}import{execFile as H0}from"node:child_process";import{statSync as Jg}from"node:fs";import{homedir as B0}from"node:os";import{join as Kg}from"node:path";import{promisify as W0}from"node:util";var jl=W0(H0);var G0="mike.ma@lmctl.com",Hl="mike-lmctl";async function zg(e,t=jl){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===G0}}var V0=6e4,zi;async function Yi(e=jl,t=Date.now(),r=Jg){let n=e===jl&&r===Jg;if(n&&zi!==void 0&&t-zi.atMs<V0)return zi.result;let o=await K0(e,r);return n&&(zi={result:o,atMs:t}),o}function J0(){let e=process.env.GH_CONFIG_DIR;return e?Kg(e,"hosts.yml"):Kg(B0(),".config","gh","hosts.yml")}async function K0(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(J0()).mtime.toISOString()}catch{c=null}return{account:a,matchesPolicy:a===Hl,hostsFileChangedAt:c}}var z0=7*24*60*6e4,Y0=500,Q0=3*60*6e4,X0=3*60*6e4,Vo=4*60*6e4,Z0=24*60*6e4,eL=48*60*6e4,tL=24*60*6e4,rL=20,Wl=24*60*6e4;function nL(e,t){let r=me(t);return`${t>Wl?`possible ${e}`:e} as of ${r} ago (not re-observed)`}var oL=7*24*60*6e4,sL=24*60*6e4;function iL(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<=sL)return null}else return o!==void 0&&rc(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>oL?{kind:"self-report",status:t.status,changedTs:t.changed_ts}:null}function aL(e,t){let r=e.teams.filter(H);return t===void 0?r:r.filter(n=>n.name===t)}function cL(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 Qi(e,t={}){let r=e.db.db,n=t.config??pe,o=t.nowMs??Date.now(),s=aL(e,t.team),i=t.awaitingReviewThresholdMs??Sc,a=[],c=[],l=[],u=[],d=[],m=new Set(Bo(r,o).map(F=>F.row.subject_id).filter(F=>F!==null)),f=[],p=[],h=[],_=[],g=[],y=[],E=t.countDirtyGitFilesImpl??Ng,v=[],S=t.lintTeamfileWarningsImpl??Ig,R=[],x=[],L=[],k=[],B=[],C=t.findNeverTrackFilesImpl??Wg,w=t.findSecretBearingTeamfilesImpl??Gg,T=t.checkTeamfileTrackingImpl??Vg,N=t.checkRepoGitIdentityImpl??zg,U=t.resolveMemberProviderImpl??jt,J=t.listTeamMembersImpl??Vr,ee=[],oe=!1;try{ee=No(r).filter(F=>rt(r,F.provider,o).disabled)}catch{oe=!0}let V=jh(r,o),se=Hh(r),$=null;try{$=Bh(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&&R.push({team:F.name,files:it});let fn=await w(F.repoPath);fn!==null&&fn.length>0&&x.push({team:F.name,files:fn});let Ot=await T(F.repoPath);Ot!==null&&(Ot.tracked.length>0&&L.push({team:F.name,files:Ot.tracked}),Ot.unprotected.length>0&&k.push({team:F.name,files:Ot.unprotected}));let Br=await N(F.repoPath);Br!==null&&!Br.matchesPolicy&&B.push({team:F.name,identity:{name:Br.name,email:Br.email}});let Dt=O.size>0?cL(F,O,J):null;if(O.size>0){let ce=Tt(r,F.name),Mt=ce===null?F.name:ce.companionTeam,Na=ce===null?F.leadAlias:ce.workerAlias,po=ce===null?F.repoPath:q.find(ho=>ho.name===Mt)?.repoPath??F.repoPath,Wr=U({repoPath:po,name:Mt},Na);if(Wr!==null&&O.has(Wr)){let ho=ee.find($v=>$v.provider===Wr)?.expiresAt??null;A.push({team:F.name,provider:Wr,expiresAt:ho,totalMembers:Dt?.totalMembers??1,liveMembers:Dt?.liveMembers??[]})}}let xa=on(r,F.name,o,M);xa.length>0&&l.push({team:F.name,rows:xa,...Dt!==null&&Dt.quiescedMembers.length>0?{quiescedMembers:Dt.quiescedMembers,totalMembers:Dt.totalMembers}:{}});let wd=xa.filter(ce=>ce.row.status==="sent"||ce.row.status==="retrieved");if(wd.length>0){let ce=r.prepare("SELECT MAX(created_ts) AS ts FROM queue WHERE from_id = ?").get(F.name),Mt=iL(ie(r,F.name),Ue(r,F.name),ce.ts,o,F);Mt!==null&&d.push({team:F.name,rows:wd,reason:Mt})}let yd=Hi(r,F.name,Vo,o);yd.length>0&&u.push({team:F.name,rows:yd});let wr=xe(r,ge,F.leadAlias);if(wr===null)continue;for(let ce of $n(r,wr)){let Mt;try{let po=Fg(r,ce.id),Wr=Ji(r,ce.id).filter(ho=>!po.has(ho.id));Wr.length>0&&(Mt=Wr)}catch{Mt=void 0}let Na=Js(r,ce.id);a.push({team:F.name,entity:ce,blockedSinceTs:Na,...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(po=>po.name===ce.blocked_on)&&c.push({team:F.name,entity:ce,blockedOn:ce.blocked_on,reason:"team-unresolvable"})}for(let ce of bo(r,wr,n.cooldownMs,o))f.push({team:F.name,entity:ce});for(let ce of Af(r,wr,i,o))p.push({team:F.name,task:ce});for(let ce of $f(r,wr,o))h.push({team:F.name,task:ce});for(let ce of wr.entities)ce.kind==="epic"&&ce.needs_review===1&&Zs(ce)&&_.push({team:F.name,entity:ce});for(let ce of wr.entities)ce.kind!=="epic"||!An.has(le(ce.status))||Wi(r,ce.id)?.alreadySurfacedThisEpisode||g.push({team:F.name,entity:ce});let Ra=wr.entities.filter(ce=>le(ce.status)==="todo");if(Ra.length>0){let ce=await E(F.repoPath);ce!==null&&ce>0&&y.push({team:F.name,dirtyCount:ce,todoCount:Ra.length,exampleEntity:Ra[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??Rg,{unreachable:Y,notObserved:K}=await j(r,s,W,o,Vo),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=Vd(r).map(F=>({team:F.team,reason:F.reason,detail:F.detail,suspendedAt:F.suspended_at})),$e=t.blockedSelfReportUrgentThresholdMs??Z0,be=t.blockedSelfReportUnconfirmedThresholdMs??eL,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??z0,Ge=new Date(o-Te).toISOString(),Ct=Ss(r,il,Ge,Y0).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),...Bs(r,t.maintainer)].sort((F,ge)=>F.id-ge.id).filter(F=>F.from_id!=="autopilot"),we=t.maintainer===void 0?[]:Zh(r,t.maintainer,o).map(F=>({row:F.row,constituentCount:nn(r,F.row)})),st=t.maintainer===void 0?[]:Bo(r,o).map(F=>{let ge=nn(r,F.row),Pe=Ho(r,F.row),it=F.ageMs>=Vo||ge>=2&&F.row.sent_ts===null;return{row:F.row,constituentCount:ge,retractedCount:Pe,urgent:it}}),Ze=t.maintainerStaleThresholdMs??Q0,ft=[];if(t.maintainer!==void 0&&G!==null){let ge=ie(r,t.maintainer)?.last_cli_activity_ts??null,Pe=kp(ge,o),it=!nl(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=qg(r,Ve,e.teams),gr=Cg(r),or=Dg(r,e.teams),et=Mg(r),_r=[];for(let F of e.teams.filter(H)){try{Q(F)}catch{continue}rc(F)===0&&_r.push({team:F.name,repoPath:F.repoPath})}let fo=t.stuckProcessingThresholdMs??X0,_s=t.stuckProcessingMaxAgeMs??tL,ka=t.maintainer!==void 0&&t.stuckProcessingFleetWide!==!0?t.maintainer:void 0,Av=Xh(r,{minAgeMs:fo,maxAgeMs:_s,fromId:ka},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:_,closedEpicsToReview:g,orphanReapCandidates:Ct,maintainerStale:ft,blockingRoots:mn,epicsWithoutOwner:gr,unresolvableOwnerEntities:or,untrackedBlockers:et,unseededTeams:_r,stuckProcessing:Av,inbox:G,memory:(t.readMemoryAvailabilityImpl??Eo)(),operatorPrompts:we,operatorEscalations:st,uncommittedWork:y,teamfileLintWarnings:v,expiredHolds:h,neverTrackFiles:R,secretBearingTeamfiles:x,trackedTeamfiles:L,unprotectedTeamfiles:k,gitIdentityMismatches:B,activeGhAccount:await(t.checkActiveGhAccountImpl??Yi)(),disabledProviders:ee,providerDisableReadFailed:oe,quiescedByProviderDisable:A,staleAutoScanPause:$,persistentDispatchFailures:Y,notObserved:K,rateLimitPolicyHealth:V,rateLimitLevelWarnings:se}}function Bl(e){return` ${e.team}: #${e.entity.id} ("${e.entity.title}")`}function Yg(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 Jo(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 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}):
387
387
  ${l.join(`
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,_)=>h+_.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:
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=nL(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=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}):
393
393
  ${c.join(`
394
- `)}`)}if(e.notObserved.length>0){let c=e.notObserved.map(l=>{let u=me(l.ageMs),d=l.ageMs>Wl?`possible ${l.status}`:l.status;return` ${l.team}: last checked ${u} ago, ${d} then -- ${Wo(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>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}):
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(`
@@ -411,19 +411,19 @@ ${c.join(`
411
411
  ${c.join(`
412
412
  `)}`)}if(e.providerDisableReadFailed&&r.push("PROVIDER-DISABLE STATE UNREADABLE -- failing toward disabled (epic #197's own fail-safe direction): every team's auto-nudge may be silently quiescing right now, not by operator choice. Investigate the `kv` table/DB access immediately; `lmbee provider status` will not be trustworthy until this clears."),e.disabledProviders.length>0){let c=e.disabledProviders.map(l=>{let u=l.reason?` (${l.reason})`:"",d=l.expiresAt!==null?`, auto-re-enables at ${l.expiresAt}`:", indefinite";return` ${l.provider}: disabled since ${he(l.disabledAt)}${u}${d}`});r.push(`PROVIDER DISABLED FOR AUTO-NUDGE (${e.disabledProviders.length}):
413
413
  ${c.join(`
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 _=h.provider??"(no provider set)",g=f.get(_)??[];g.push(h.alias),f.set(_,g)}m=`; ${[...f.entries()].map(([h,_])=>`${_.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:
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=Bl(l),d=l.blockedSinceTs===null?" (blocked-since unknown)":(()=>{let f=Date.now()-Date.parse(l.blockedSinceTs),p=me(f);return f>Wl?` -- 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=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}):
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(_=>!_.hasReplyTrafficSince)?0:1,h=f.rows.some(_=>!_.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(_=>!_.hasReplyTrafficSince),p=m.rows.filter(_=>_.hasReplyTrafficSince),h=[];if(f.length>0){let _=f.filter(y=>y.row.status!=="retrieved"),g=f.filter(y=>y.row.status==="retrieved");if(_.length>0){let y=_[0];h.push(`${_.length} NEVER RECEIVED (undelivered-to-inbox, not a decision delay) -- oldest #${y.row.id} from ${y.row.from_id} (${me(y.ageMs)} ago), status ${y.row.status}`+Yg(y.laterRelatedTraffic))}if(g.length>0){let y=g[0];h.push(`${g.length} unanswered -- no reply traffic from ${m.team} since the prompt, oldest #${y.row.id} from ${y.row.from_id} (${me(y.ageMs)} ago)`+Yg(y.laterRelatedTraffic))}}if(p.length>0){let _=p.map(g=>`#${g.row.id}`).join(", ");h.push(`${p.length} likely answered in prose (reply traffic exists since the prompt), row(s) unclosed: needs queue answer ${_}`)}if(m.quiescedMembers!==void 0&&m.totalMembers!==void 0){let _=new Map;for(let y of m.quiescedMembers){let E=_.get(y.provider)??[];E.push(y.alias),_.set(y.provider,E)}let g=[..._.entries()].map(([y,E])=>`${y}: ${E.join(", ")}`).join("; ");h.push(`${m.quiescedMembers.length}/${m.totalMembers} members quiesced by a disabled provider (${g})`)}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(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:
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(Bl).join(`
426
+ ${e.awaitingDecision.map(Wl).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(Bl).join(`
440
+ ${e.closedEpicsToReview.map(Wl).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,rL),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,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?`
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=qs(e.memory),s=o===null?n:`${n}
468
+ `),o=Hs(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 Qg(e,t,r,n={}){let o={db:{path:"",db:e,close:()=>{}},teamsConfPath:"",teams:[...t]},s=await Qi(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??Eo)(),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=qs(i),l=c===null?Jo(s):`${Jo(s)}
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)}
473
473
 
474
- ${c}`;return{attention:s,memory:i,isEmpty:a,rendered:l}}var mL=18e5,fL={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 Xg(e){let t=e.fetchReport??Ae,r=e.readHeavyLockStatusImpl??lt,n=e.heavyLockStatusPath??Un(),o=e.heavyLockPath??Fn(),s=e.maintainerWakeImpl??fg,i=e.autoContinueImpl??dg,a=e.surfaceUnknownImpl??kg,c=e.surfaceBlockedImpl??hg,l=e.surfaceDoneConsistencyImpl??bg,u=e.surfaceUnresolvableTeamfilesImpl??gg,d=e.surfaceFaultImpl??vg,m=e.surfaceClosedEpicsImpl??wg,f=e.escalateImpl??Nh,p=e.autoRedeliverImpl??Lh,h=e.wakeImpl??Ih,_=e.evaluateCronJobsImpl??Sh,g=e.miniplayerVerifyImpl??Jp,y=e.hungHolderCheckImpl??Dp,E=e.epicReviewImpl??Wp,v=e.orphanReconcilerImpl??jp,S=e.hangProbeCollectImpl??Bp,R=e.rateLimitCollectImpl??Mh,x=e.rateLimitPolicyImpl??Fh,L=e.assembleWakeReportImpl??Qg,k=e.existsSyncImpl??lL,B=e.statSyncImpl??dL,C=e.config??pe,w=e.escalation??kl,T=e.autoRedeliver??xl,N=e.wake??Rl,U=e.intervalMs??mL,J=null,ee=!1;async function oe(){if(ee)return fL;ee=!0;try{let V=e.getTeams(),se=V.filter(H),$;try{$=await t(),xh($,new Date().toISOString())}catch(G){throw Rh(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=Is(e.db,se,$),{stalled:M,continueEligible:Z}=await Lf(e.db,se,$,A,C,O);if(e.miniplayerVerify)try{await g(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&&Bd(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 y(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??vp,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??$p,Ve=e.resetShiftImpl??Ap,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 fo=st.get(et.team),_s=fo===void 0?null:or(fo,fo.leadAlias);if(_s!==null&&gr(e.db,_s,O).disabled)continue;let ka=await ft(et,_r);mn(e.db,V,et.team,ka,{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 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:k,statSyncImpl:B,nowMs:O}),st,Ze;try{let Ve=await L(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=>`${uL(Ve,"utf8")}
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")}
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&&Lr(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 _(e.db,V,O,{onJobError:(G,we)=>e.onError?.(we)})}catch(G){e.onError?.(G)}let ue=[];try{ue=await f(e.db,se,w,O)}catch(G){e.onError?.(G)}let $e=[];try{$e=p(e.db,se,T,O)}catch(G){e.onError?.(G)}let be=[];try{be=h(e.db,se,$,N,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 R(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(()=>{})},U),J.unref())},stop(){J&&(clearInterval(J),J=null)},runTickNow:oe,isRunning:()=>J!==null,isTicking:()=>ee}}import{closeSync as pL,linkSync as hL,openSync as gL,readdirSync as _L,readFileSync as Zi,readlinkSync as wL,realpathSync as yL,renameSync as Zg,unlinkSync as Vl,writeSync as EL}from"node:fs";import{dirname as TL,join as bL}from"node:path";var jn=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 Ko(e){return e===":memory:"?null:`${e}.lock`}function n_(e){let t=zo(e);return t.kind==="held"?t.identity:null}function e_(e){let t;try{t=Zi(e,"utf8")}catch(o){return o.code==="ENOENT"?{kind:"free"}:{kind:"unknown"}}let r=Qa(t);if(!r)return{kind:"unknown"};let n={...r,bootId:r.bootId??null};return Gl(n)?{kind:"held",identity:n}:{kind:"free"}}function SL(e,t){let r;try{r=yL(t)}catch{return!1}let n;try{n=_L(`/proc/${e}/fd`)}catch{return!1}for(let o of n)try{if(wL(`/proc/${e}/fd/${o}`)===r)return!0}catch{}return!1}function zo(e){let t=Ko(e);if(t===null)return{kind:"free"};let r=e_(t);if(r.kind==="held")return r;let n=bL(TL(e),"site.lock");if(n===t)return r;let o=e_(n);return o.kind==="held"&&SL(o.identity.pid,e)?o:r}function Xi(e){try{let t=Qa(Zi(e,"utf8"));return t?{...t,bootId:t.bootId??null}:null}catch{return null}}function o_(){try{let e=Zi("/proc/sys/kernel/random/boot_id","utf8").trim();return Xa(e)?e:null}catch{return null}}function s_(e){try{let t=Zi(`/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 Gl(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=o_();if(n!==null&&n!==e.bootId)return!1}if(e.pidStartTicks===null)return!0;let r=s_(e.pid);return r===null?!0:r===e.pidStartTicks}function t_(e,t){let r=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,n=gL(r,"wx");try{EL(n,JSON.stringify(t))}finally{pL(n)}try{return hL(r,e),!0}catch(o){if(o.code!=="EEXIST")throw o;return!1}finally{Vl(r)}}function ea(e,t){let r={pid:process.pid,ownerLabel:t,startedAt:new Date().toISOString(),pidStartTicks:s_(process.pid),bootId:o_()};if(t_(e,r))return r_(e,r);let n=Xi(e);if(n!==null&&Gl(n))throw new jn(n,e);let o=`${e}.reclaim.${process.pid}.${Math.random().toString(36).slice(2)}`,s=!1;try{Zg(e,o);let a=Xi(o);n===null&&a===null||n!==null&&a!==null&&a.pid===n.pid&&a.startedAt===n.startedAt?(Vl(o),s=!0):Zg(o,e)}catch{}if(s&&t_(e,r))return r_(e,r);let i=Xi(e);throw i!==null&&Gl(i)?new jn(i,e):new Error(`failed to acquire site lock at ${e} (lost a reclaim race)`)}function r_(e,t){let r=!1;return{release(){if(!r){r=!0;try{let n=Xi(e);n!==null&&n.pid===t.pid&&n.startedAt===t.startedAt&&Vl(e)}catch{}}}}}import{closeSync as Jl,existsSync as vL,fstatSync as AL,mkdirSync as $L,openSync as i_,readFileSync as a_,renameSync as kL,unlinkSync as xL,writeSync as RL}from"node:fs";import{dirname as c_,join as NL}from"node:path";import{createHash as LL,randomBytes as IL}from"node:crypto";var CL=32;function Hn(e){return e===":memory:"?null:NL(c_(e),"localweb-passcode")}function OL(){return IL(CL).toString("base64url")}function Kl(e,t){let r=c_(e);vL(r)||$L(r,{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,o;try{o=i_(n,"wx",384);let s=Buffer.from(t,"utf8"),i=0;for(;i<s.length;){let a=RL(o,s,i,s.length-i);if(a<=0)throw new Error("passcode file write made no progress");i+=a}Jl(o),o=void 0,kL(n,e)}catch(s){if(o!==void 0)try{Jl(o)}catch{}try{xL(n)}catch{}throw s}}function l_(e){let t;try{t=i_(e,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=AL(t,{bigint:!0}),n=a_(t,"utf8"),o=LL("sha256").update(`${r.dev}:${r.ino}:${r.ctimeNs}:${r.mtimeNs}:${r.size}:`).update(n,"utf8").digest("base64url");return{passcode:n,generation:o}}finally{Jl(t)}}function u_(e){try{return a_(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function ta(e){let t=OL();return Kl(e,t),t}import{randomUUID as DL}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 d_(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:zl(r),dedupeKey:r.msgId})}var ML=new Set(["dispatched","queued","failed"]);function PL(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"&&ML.has(r)}var UL="reply-surfaced:";function FL(e,t,r,n){let o=r.inReplyTo;if(!o)throw new Error("recordReplyOrAck: envelope has no in_reply_to");let s=Xm(e,o);if(!s)return"orphan";if(PL(r.payload))return Zm(e,o,n),"acked";ef(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:zl(r),dedupeKey:`${UL}${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 qL(e,t,r,n,o){let s=e.now??(()=>new Date().toISOString()),i={v:1,msgId:DL(),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(yo(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 m_(e,t,r,n){if(r.inReplyTo){FL(e,t,r,(n.now??(()=>new Date().toISOString()))());return}let o;try{d_(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;qL(n,r.from,r.msgId,o?"failed":"dispatched",i)}if(o)throw o}var g_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,jL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,HL="text/plain; charset=utf-8",Yl="exec",__="exec-result";var BL="exec-result";var WL=`
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=`
480
480
  ... [lmexec output truncated; middle elided, see attachment] ...
481
- `;function w_(e){return Ql(b_(e))}function y_(e){return E_(b_(e))}function Ql(e){let t=S_(e),r=v_(t.type,"type",Yl),n=A_(t.id,"id"),o=Zl(t.command,"command"),s=zL(t.timeout_s,"timeout_s"),i=KL(t.reply_to,"reply_to"),a=VL(t.from,"from");return{v:1,type:r,id:n,command:o,timeout_s:s,reply_to:i,...a===void 0?{}:{from:a}}}function E_(e){let t=S_(e),r=GL(t.v),n=v_(t.type,"type",__),o=A_(t.id,"id"),s=QL(t.exit_code,"exit_code"),i=p_(t.stdout,"stdout"),a=p_(t.stderr,"stderr"),c=YL(t.duration_ms,"duration_ms"),l=h_(t.timed_out,"timed_out"),u=h_(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=JL(t.sender_trust),f=Zl(t.sender,"sender");return{v:r,...d,sender_trust:m,sender:f}}function Xl(e){if(!g_.test(e))throw new Error(`invalid exec id: ${e}`);return`${BL} ${e}`}function f_(e,t,r){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),o=r?.capBytes??49152,s=r?.marker??WL;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:`${XL(a,l)}${s}${ZL(a,u)}`,truncated:!0,attachment:{name:e==="stdout"?"stdout.txt":"stderr.txt",content_type:HL,data:n}}}function T_(e,t){let r=f_("stdout",e.stdout,t),n=f_("stderr",e.stderr,t),o=E_({v:2,type:__,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:Xl(e.id),envelope:o,attachments:[r.attachment,n.attachment].filter(s=>s!==void 0)}}function b_(e){try{return JSON.parse(e)}catch(t){throw new Error(`invalid JSON: ${eI(t)}`)}}function S_(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("expected object");return e}function v_(e,t,r){if(e!==r)throw new Error(`invalid ${t}: expected ${r}`);return r}function GL(e){if(e===void 0||e===1)return 1;if(e===2)return 2;throw new Error("invalid v: expected 1 or 2")}function A_(e,t){if(typeof e!="string"||!g_.test(e))throw new Error(`invalid ${t}: expected UUID v4`);return e}function Zl(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`invalid ${t}: expected non-empty string`);return e}function VL(e,t){if(e!==void 0)return Zl(e,t)}function JL(e){if(e==="admin"||e==="registered"||e==="anonymous")return e;throw new Error("invalid sender_trust: expected admin, registered, or anonymous")}function KL(e,t){if(typeof e!="string"||e.includes("/")||e.includes("\\")||e.includes("..")||e.endsWith(".")||/[\u0000-\u001f\u007f]/.test(e)||!jL.test(e))throw new Error(`invalid ${t}: expected mailbox name`);return e}function p_(e,t){if(typeof e!="string")throw new Error(`invalid ${t}: expected string`);return e}function zL(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<1)throw new Error(`invalid ${t}: expected positive integer`);return e}function YL(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer`);return e}function QL(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 h_(e,t){if(typeof e!="boolean")throw new Error(`invalid ${t}: expected boolean`);return e}function XL(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 ZL(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 eI(e){return e instanceof Error&&e.message?e.message:String(e)}var tI=/[;&|`$<>(){}\\]/,$_=/[\x00-\x1f\x7f]/;function x_(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($_.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($_.test(e[r])||tI.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 eu(e){if(!e.includes("--json"))return"requires --json when run via exec (plain-text output has no machine-readable contract)"}function rI(e){return e.includes("--watch")?"tail --watch is a long-running stream, not a fit for a single bounded exec call":e.includes("--lines")?eu(e):"tail requires --lines N when run via exec (unbounded --max-bytes/no-limit output is not allowed)"}var nI=[{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:eu},{prefix:["lmctl","running"],validate:eu},{prefix:["lmctl","tail"],validate:rI}],oI=[{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 sI(e,t){return e.length<t.prefix.length?!1:t.prefix.every((r,n)=>e[n]===r)}function k_(e,t){return t.find(r=>sI(e,r))}function R_(e,t){let r=k_(e,nI);if(r){let o=r.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:{allowed:!0}}let n=k_(e,oI);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 N_}from"node:child_process";var iI=5e3,aI="/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??iI;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 I_(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,tu(e.pid,"SIGTERM"),r>0?m=setTimeout(()=>{tu(e.pid,"SIGKILL")},r):tu(e.pid,"SIGKILL")},t)})}async function C_(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??aI,s=N_(o,["-c",e],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return I_(s,t.timeoutMs,r,n)}async function O_(e,t){if(e.length===0)throw new Error("argv must be non-empty");let{killGraceMs:r,now:n}=L_(t),o=N_(e[0],e.slice(1),{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return I_(o,t.timeoutMs,r,n)}function tu(e,t){if(e)try{process.kill(-e,t)}catch(r){if(!cI(r))throw r}}function cI(e){return!!e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH"}var D_=1e3,uI=6e4,dI=20,mI=1e3;async function P_(e,t){let r=t.runCommand??C_,n=t.runCommandArgv??O_,o=t.sleep??pI,s=t.pollNow??Date.now,i=t.now??(()=>new Date),a=t.stderr??(d=>process.stderr.write(`${d}
482
- `)),c=t.shouldStop??(()=>!1),l=D_,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:dI}}),f=Math.max(0,s()-d);for(let p of m.messages){if(c())break;let h=fI(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 _=await t.client.getMessage(e.mailbox,p.seq),g=Buffer.from(await t.client.download(_.body.download_url)).toString("utf8"),y;try{y=w_(g)}catch(x){kt(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"malformed_request",error:ru(x)});continue}let E=e.execAllowlist?x_(y.command):void 0,v=e.execAllowlist?E?R_(E,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:y.id,sender:p.sender,sender_trust:h,...y.from===void 0?{}:{asserted_from:y.from},code:v.code,seq:p.seq}),await M_(t.client,y.reply_to,{id:y.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:y.id,sender:p.sender,sender_trust:h,...y.from===void 0?{}:{asserted_from:y.from},seq:p.seq});let S;try{S=E?await n(E,{timeoutMs:Math.min(y.timeout_s,e.timeoutCapSeconds)*1e3}):await r(y.command,{timeoutMs:Math.min(y.timeout_s,e.timeoutCapSeconds)*1e3})}catch(x){kt(a,i,"error","command_failed",{id:y.id,sender:p.sender,sender_trust:h,...y.from===void 0?{}:{asserted_from:y.from},error:ru(x)});continue}let R=await M_(t.client,y.reply_to,{id:y.id,...S,sender_trust:h,sender:p.sender});kt(a,i,"info","command_finished",{id:y.id,sender:p.sender,sender_trust:h,...y.from===void 0?{}:{asserted_from:y.from},duration_ms:S.duration_ms,exit_code:S.exit_code,timed_out:S.timed_out,truncated:R.envelope.truncated})}if(l=D_,e.once||c())break;m.messages.length===0&&f<mI&&(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:ru(d),retry_ms:l}),c())break;await o(l),l=Math.min(l*2,uI)}kt(a,i,"info","daemon_stopped",{mailbox:e.mailbox})}function fI(e,t){return e.adminUsers.has(t)?"admin":e.allowUsers.has(t)?"registered":"anonymous"}async function M_(e,t,r){let n=T_(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 pI(e){return new Promise(t=>setTimeout(t,e))}function ru(e){return e instanceof Error?e.message:String(e)}var hI=5e3,gI=300;async function U_(e,t){await e.createMailbox(t,{tolerate409:!0})}function F_(e){let t=!1,r=!1,n=Promise.resolve(),o=e.stderr??(c=>process.stderr.write(`${c}
483
- `)),s=e.runDaemonLoopImpl??P_,i={mailbox:e.mailbox,allowUsers:e.allowUsers,adminUsers:e.adminUsers,allowAnonymous:e.allowAnonymous,apiUrl:"",pollIntervalMs:e.pollIntervalMs??hI,timeoutCapSeconds:e.timeoutCapSeconds??gI,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 q_(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 nu(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),Gm(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 Bm(e))i.recovered++,await nu(e,n,q_(d),d.sender_user_id,o,i);let a=n.retryPolicy??lc;for(let d of Us(e,o(),a))Km(e,d.msg_id)&&(i.retriedFailed++,await nu(e,n,q_(d),d.sender_user_id,o,i));let c=Wm(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=jm(Buffer.from(f).toString("utf8"))}catch{i.stoppedEarly=!0;break}let h=o(),_=Hm(e,{msgId:p.msgId,seq:d.seq,to:p.to,from:p.from,senderUserId:m.sender,sentAt:p.sentAt,payload:p.payload},h);if(_!=="duplicate"){if(_==="conflict"){i.rejected++;continue}i.recorded++,await nu(e,n,p,m.sender,o,i)}}return i}async function H_(e,t){await e.createMailbox(t,{tolerate409:!0})}var wI=6e4,yI={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};function B_(e){let t=e.intervalMs??wI,r=null,n=!1;async function o(){if(n)return yI;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 EI=5e3;function W_(e){let t=e.intervalMs??EI,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{readFileSync as UO}from"node:fs";var TI=10*6e4,bI=60*6e4;function G_(e,t,r={},n=Date.now()){let o=r.ackDeadlineMs??TI,s=r.replyThresholdMs??bI,i=[];for(let a of t){let c=Fs(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 SI=[/^\S+'s turn has finished and exited; resubmit/i,/^resubmit .*lmctl chat/i];function vI(e){let t=e.split(/\r?\n/).filter(n=>n.trim().length>0).filter(n=>!SI.some(o=>o.test(n.trim()))),r=(t[t.length-1]??"").trim();return r==="BLOCKED"?"BLOCKED":r==="DONE"?"DONE":null}function V_(e){if(e.trim()==="")return{status:"NO-OUTPUT",wake:"env"};let t=vI(e);return t==="BLOCKED"?{status:"BLOCKED",wake:"blocked"}:t==="DONE"?{status:"DONE",wake:null}:{status:"IDLE",wake:null}}function Bn(e){switch(e.kind){case"ok":return V_(e.replyText);case"stalled":{let t=V_(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 Wn=Ut(xt(),1);function ke(e,t){return{error:{code:e,message:t}}}var ew=1e4;function su(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>ew)return ke("invalid_limit",`invalid limit "${r}" -- must be an integer from 0 to ${ew}`);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 tw(e,t,r,n={}){let o=su(e,t,r);return n.json?JSON.stringify(o):"error"in o?o.error.message:(0,Wn.formatTable)([["ID","TS","TEAM","STATUS","NOTE"],...o.events.map(s=>[String(s.id),he(s.ts),(0,Wn.escapeCell)(s.team),(0,Wn.escapeCell)(s.status),(0,Wn.escapeCell)(s.note??"")])])}var rw=Ut(xt(),1);function iu(e){let t=e.db.db,r=Jm(t),n=uc(t),o=n.filter(c=>c.failure_reason?.startsWith(Yr)).length,s=n.length-o,i=Us(t,new Date().toISOString()).length,a=Qm(t);return{counts:r,retryEligibleCount:s,permanentCount:o,dueNowCount:i,deliveryErrorCount:a}}function nw(e,t={}){let r=iu(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,rw.formatTable)([["STATE","COUNT"],...n]),s=r.deliveryErrorCount>0?`
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?`
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 eC,existsSync as tC,openSync as rC,readFileSync as gu,readSync as nC,realpathSync as oC,statSync as sC}from"node:fs";var qI="member_health:";function au(e,t){return`${qI}${e}:${t}`}function ow(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(au(t,r),JSON.stringify(o))}function Yo(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(au(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 sw(e,t,r){e.prepare("DELETE FROM kv WHERE k = ?").run(au(t,r))}function iw(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 Qo(e,t){return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(t)??null}function aw(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 cw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE task_id = ? ORDER BY id ASC").all(t)}function lw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id ASC").all(t)}function uw(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 dw(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 mw(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(Qo(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 fw(e,t){return e.prepare("SELECT * FROM prompt_task_reassignments WHERE prompt_id = ? ORDER BY id ASC").all(t)}function pw(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 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
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=Qo(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 jI}from"node:fs";function HI(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 BI(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=gc(t);for(let o of r){let s;try{s=jI(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function cu(e,t){return HI(e,t).map(r=>({row:r,verifiedTarget:BI(e,r)}))}function hw(e,t){let r=cu(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 gw(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 lu="operator";function WI(e){if(e===lu)throw new Error(`logical_names: "${lu}" is reserved for the real operator entity (epic #162's #164) -- never a re-routable logical name`)}function _w(e,t,r,n,o=new Date().toISOString()){WI(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 na(e,t){return t===lu?null:e.prepare("SELECT teamfile_path AS teamfilePath, alias FROM logical_names WHERE name = ?").get(t)??null}function ww(e){return e.prepare("SELECT name, teamfile_path AS teamfilePath, alias, updated_at AS updatedAt FROM logical_names ORDER BY name").all()}function yw(e,t){e.prepare("DELETE FROM logical_names WHERE name = ?").run(t)}function Xo(e,t,r){let n=na(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 GI,mkdirSync as VI,readFileSync as JI,renameSync as KI,writeFileSync as zI}from"node:fs";import{homedir as YI}from"node:os";import{dirname as QI,join as Ew}from"node:path";function uu(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 du(e,t,r){let n=`
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=`
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 Tw(e){return e.filter(t=>t.answer===null&&t.row.retracted_ts===null&&t.row.merged_into_id===null)}function bw(e,t){let r=t??process.env.LMBEE_SENDER_PULL_SEEN_DIR??Ew(YI(),".lmbee","sender-pull-seen");return Ew(r,`${e}.json`)}function mu(e){try{let t=JSON.parse(JI(e,"utf8"));return new Map(Object.entries(t).map(([r,n])=>[Number(r),n]))}catch{return new Map}}function Sw(e,t){let r=QI(e);GI(r)||VI(r,{recursive:!0});let n={};for(let[s,i]of t)n[String(s)]=i;let o=`${e}.tmp`;zI(o,JSON.stringify(n,null,1)),KI(o,e)}var XI=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],fu=XI.join(", ");function ZI(e,t){return e.prepare(`SELECT ${fu} FROM team_progress WHERE team = ?`).get(t)??null}function vw(e,t){let r=e-Date.parse(t);return Number.isFinite(r)?r:null}function Aw(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 _=p.get(h.to_id);_?_.push(h.ts):p.set(h.to_id,[h.ts])}return p}let s=f=>{let p=f.reduce((h,_)=>h===null||_!==null&&_<h?_:h,null);return p===null?null:vw(r,p)},i=f=>{let p=f.filter(_=>_!==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?vw(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(ZI(e,f))}}),m=t?e.prepare(`SELECT ${fu} FROM team_progress WHERE team = ? AND escalation_attempt_count > 0`).all(t):e.prepare(`SELECT ${fu} 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 iC=[".md",".txt",".json",".log",".yaml",".yml",".csv",".html",".htm",".xml"];function aC(e){if(/\s/.test(e)||!(e.startsWith("/")||e.startsWith("./")||iC.some(r=>e.toLowerCase().endsWith(r))))return!1;try{return tC(e)}catch{return!1}}function cC(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 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}"
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 gu(t.slice(1),"utf8");if(!r&&aC(t))throw cC(e,t);return t}async function Rw(e,t,r,n){let{baseId:o,alias:s}=Qr(t);if(o!=="operator"&&!e.teams.some(E=>E.name===o)){let E=Xo(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&&H(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&&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??zo)(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)?lC(e,a,s??a.leadAlias,t):"",g=(n.inReplyTo===void 0?yr(e.db.db,d):null)?.expects_response===1&&!uC(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
- `:"",y=p+h+g;if(a&&H(a))try{let v=await(n.fetchReport??Ae)();if(Fe(a,v))return`${y}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`${y}queued#${d} -> ${t} (${i})`}function lC(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=Yo(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:Yo(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 uC(e){return e.includes("?")}function _u(e,t){return{queue:fc(e.db.db,t)}}function Nw(e,t,r={}){if(r.json)return JSON.stringify(_u(e,t));let n=fc(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 Gn(e,t){return yr(e.db.db,t)}function Lw(e,t,r={}){let n=Gn(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 pu=64*1024;function $w(e){if(e===null)return null;let t=Buffer.byteLength(e.answer_text,"utf8");if(t<=pu)return{...e,byteLength:t,totalBytes:t,truncated:!1};let r=Buffer.from(e.answer_text,"utf8").subarray(0,pu).toString("utf8");for(;Buffer.byteLength(r,"utf8")>pu;)r=r.slice(0,-1);return{...e,answer_text:r,byteLength:Buffer.byteLength(r,"utf8"),totalBytes:t,truncated:!0}}function Zo(e,t){let r=yr(e.db.db,t);if(r===null)return null;let n=Ce(e.db.db,t),o=Yh(e.db.db,t).map(s=>$w(s)).filter(s=>s!==null);return{id:r.id,createdAt:r.created_ts,answer:$w(n),answerHistory:o,mergedInto:r.status==="merged"?Dl(e.db.db,r)?.id??null:null,...vt(r,n)}}function Iw(e,t,r={}){let n=Zo(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 _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=`
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 Cw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=Xo(e.db.db,e.teams,r),a=i!==null?i.team:r;try{let c=o.amend?ig(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(ke(c.code,c.message)):`${c.code}: ${c.message}`,exitCode:c.exitCode};throw c}}function Ow(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=Xo(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 Dw(e,t,r,n,o={}){let s=Cr("queue resolve",n,o.literal);try{let i=o.amend?ag(e.db.db,t,r,s):sg(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(ke(i.code,i.message)):`${i.code}: ${i.message}`,exitCode:i.exitCode};throw i}}function Mw(e,t,r,n,o={}){try{let s=eg(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(ke(s.code,s.message)):`${s.code}: ${s.message}`,exitCode:s.exitCode};throw s}}function Pw(e,t,r={}){let n=Date.now(),o=tg(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 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):
507
507
  ${s.join(`
508
- `)}`,exitCode:0}}function Uw(e,t,r,n={}){try{let o=rg(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(ke(o.code,o.message)):`${o.code}: ${o.message}`,exitCode:o.exitCode};throw o}}function Fw(e,t,r,n={}){let o=new Date().toISOString();return Cm(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 qw(e,t,r={}){let n=Om(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 jw(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=Im(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 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}):
509
509
  ${o.join(`
510
- `)}`,exitCode:0}}function oa(e,t={}){let{rows:r,meta:n}=hc(e.db.db,t);return{rows:r.map(o=>({...o,...vt(o,Ce(e.db.db,o.id))})),meta:n}}function wu(e,t={}){return hc(e.db.db,t)}var hu=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=oC(r.prompt_file)}catch(u){return o(s(u)?"missing":"unreadable")}let a,c;try{let u=sC(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=rC(i,"r")}catch{return o("unreadable")}try{let u=Buffer.alloc(hu),d=nC(l,u,0,hu,0);return{id:t,status:"available",text:u.subarray(0,d).toString("utf8"),byteLength:d,truncated:a>hu,sourceModifiedAt:c,fetchedAt:n}}catch{return o("unreadable")}finally{eC(l)}}async function Hw(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 Bw(e,t,r={}){let n=Ws(e.db.db,t,r.id),o=r.id===void 0?uw(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=gu(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 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}):
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 dC(e,t){if(t==="operator"||e.teams.some(n=>n.name===t))return t;let r=Xo(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 yu(e,t){let r=dC(e,t),n=[...Qh(e.db.db,r),...Bs(e.db.db,r)];n.sort((s,i)=>s.id-i.id);let o=lw(e.db.db,r);return{pending:n,taskPrompts:o}}function Ww(e,t,r={}){let n=yu(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=Dl(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 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)
517
517
  ${i.map(a=>a.text).join(`
518
- `)}`}function Gw(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 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):
519
519
  ${o.join(`
520
- `)}`}function Vw(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 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:
521
521
  ${o.join(`
522
522
  `)}
523
- close with: queue answer ${n.map(s=>s.row.id).join(",")} <text|@file> --from ${t}`}function kw(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 xw=600;function Jw(e,t,r={}){let n=r.seenPath??bw(t);if(r.mark!==void 0){let c=mu(n),l=Array.isArray(r.mark)?r.mark:du(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 Sw(n,c),`marked ${l.length} pulled`}let o=mu(n),s=r.ids!==void 0&&r.ids.length>0,i=du(e.db.db,t,r.ids);if(!s&&!r.all&&(i=r.open?Tw(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:uu(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} ${uu(c)}`;if(c.answer!==null?(l+=` answered ${kw(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 ${kw(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>xw&&(u=`${u.slice(0,xw)}
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)}
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 Eu(e,t,r=Date.now()){return{stats:Aw(e.db.db,t,r)}}function mC(e){let t=e/36e5;return t<24?`${Math.round(t)}h ago`:`${Math.round(t/24)}d ago`}function Kw(e,t,r={}){let n=Eu(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?mC(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 ${uf(e.db.db,{retentionMs:r})} prompt file(s) older than ${t??7} day(s)`}function fC(e,t,r){let n=gw(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=gu(s.prompt_file,"utf8").split(`
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(`
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 Yw(e,t,r={}){if(r.swallowed===!0)return fC(e,t,r.json);if(r.repair===!0){let l=hw(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=cu(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 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(`
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 pC,statSync as hC}from"node:fs";var Vn=Ut(xt(),1);function sa(e,t,r){let n;try{n=hC(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=pC(t,"utf8")}catch(l){return{output:`error: could not read source ${t}: ${l instanceof Error?l.message:String(l)}`,ok:!1}}let a=s?ec(i):wo(i);if(a.length===0)return{output:`error: source parsed to zero teams, not registered: ${t}`,ok:!1};Rs(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 Tu(e){return{defaultTeamsConfPath:e.teamsConfPath,sources:tc(e.db.db)}}function Qw(e,t={}){let r=Tu(e);if(t.json)return JSON.stringify(r);let n=["-",(0,Vn.escapeCell)(r.defaultTeamsConfPath),"(default, always scanned)"],o=r.sources.map(s=>[String(s.id),(0,Vn.escapeCell)(s.path),(0,Vn.escapeCell)(s.label??"")]);return(0,Vn.formatTable)([["ID","PATH","LABEL"],n,...o])}function Xw(e,t){return Ns(e.db.db,t),`source removed: ${t}`}import{execFile as gC}from"node:child_process";import{promisify as _C}from"node:util";var Jn=Ut(xt(),1);var wC=_C(gC);function Zw(e,t){return{team:t,state:Ue(e.db.db,t),progress:ie(e.db.db,t),last_nudged:xc(e.db.db,t)}}function bu(e){let t=e.teams.map(n=>Zw(e,n.name)),r=Ls(e.db.db)??[];return{teams:t,active:r}}function Su(e,t){return{team:Zw(e,t)}}var yC=new Set(["DONE"]);function ey(e,t={}){let r=bu(e),n=t.nonDone?r.teams.filter(i=>!yC.has(i.state?.status??"")):r.teams;if(t.json)return JSON.stringify({...r,teams:n});let o=n.map(i=>[(0,Jn.escapeCell)(i.team),(0,Jn.escapeCell)(i.state?.status??"?"),i.state?.changed_ts?he(i.state.changed_ts):"-",i.state?.last_ts?he(i.state.last_ts):"-",(0,Jn.escapeCell)(i.progress?.progress_status??"?"),i.progress?.confirmed_done_ts?"yes":"-"]);return`${(0,Jn.formatTable)([["TEAM","STATUS(self-report)","CHANGED","LAST","PROGRESS","CONFIRMED-DONE"],...o])}
533
- active: ${r.active.length?r.active.join(","):"(none)"}`}function ty(e,t,r={}){let{team:n}=Su(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 ry(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 ny(e,t,r,n=Date.now()){let o=new Date(n).toISOString();return qa(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 oy(e,t,r,n=Date.now(),o=wC){let s=ie(e.db.db,t)?.confirmed_done_ts!=null;qa(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 Go(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 vu(e){return{active:Ls(e.db.db)??[]}}function sy(e,t={}){let r=vu(e);return t.json?JSON.stringify(r):`active: ${r.active.length?r.active.join(","):"(none)"}`}var Kn=Ut(xt(),1);function EC(e,t){return H(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead(reclaimable)":"Idle":"remote -- delivery only"}async function Au(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=cf(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=EC(u,r)),f}),s=await(t.checkActiveGhAccountImpl??Yi)(),i=s!==null&&!s.matchesPolicy?s:null,c=(t.readSiteLockStateImpl??zo)(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 iy(e,t={}){let r=await Au(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,Kn.escapeCell)(a.team),(0,Kn.escapeCell)(a.status??"?"),a.changedTs===null?"-":he(a.changedTs),String(a.pending)];return r.live?[...c,(0,Kn.escapeCell)(a.live??"")]:c}),s=(0,Kn.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 "${Hl}". DO NOT PUSH until this is switched back. !!!`),i.push(s),i.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(`
536
536
 
537
- `)}var Dr=Ut(xt(),1);function $u(e){return{teams:e.teams}}function ay(e,t={}){if(t.json)return JSON.stringify($u(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 TC(e){let t=e.LMCTL_AUTH_URL?.trim()||e.LMCTL_AUTH_BASE_URL?.trim();return t?t.replace(/\/+$/,""):void 0}async function ku(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.validateAppkeyImpl??Sd,o=TC(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 cy(e={}){let{data:t,exitCode:r}=await ku(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 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}
538
538
  label: ${t.label}
539
- appkey source: ${t.appkeySource}`,exitCode:r}}import{execFile as bC}from"node:child_process";import{promisify as SC}from"node:util";var vC=SC(bC);async function ly(e,t=3e4){let r=e.trim().split(/\s+/).filter(Boolean),{stdout:n}=await vC("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 AC}from"node:child_process";import{existsSync as $C}from"node:fs";import{promisify as kC}from"node:util";var xC=kC(AC),ia=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 xu(e){let t=e.cliPath??process.env.LMBI_SUBSCRIPTION_CLI;if(t===void 0||t==="")throw new ia;let r=e.execFileImpl??xC,{stdout:n}=await r("node",[t,e.configPath,"--json"],{timeout:e.timeoutMs??3e4});return JSON.parse(n)}async function uy(e={}){let t=e.configPath??process.env.LMBI_SUBSCRIPTION_CONFIG_PATH;if(t===void 0||t===""||!$C(t))return{status:200,body:{needs_configuration:!0}};try{return{status:200,body:await xu({configPath:t,cliPath:e.cliPath,execFileImpl:e.execFileImpl})}}catch(r){return r instanceof ia?{status:500,body:{error:r.message}}:{status:502,body:{error:r instanceof Error?r.message:String(r)}}}}import{createHash as hy,randomBytes as LC,timingSafeEqual as IC}from"node:crypto";var dy=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 my}from"node:crypto";import{basename as RC}from"node:path";function b(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}var fy="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}}",NC=`default-src 'none'; style-src 'sha256-${my("sha256").update(fy).digest("base64")}'; form-action 'self'`;function Re(e,t){return`<a href="${b(e)}">${b(t)}</a>`}function zn(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=NC+`; base-uri '${a?"self":"none"}'`+(o.length?`; script-src ${o.map(d=>`'sha256-${my("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 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">
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>${fy}</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 py(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=`${RC(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 aa="localweb_session",CC=8*1024,OC=1024,DC=30*24*60*60,MC=10,PC=6e4,UC=6e4,FC=1024;function by(e,t){let r=qC(t.mountPath),n=`${r}/login`||"/login",o=`${r}/`||"/",s=r||"/",i=t.allowedOrigins,a=new Map,c=new Map,l=t.remoteKey??KC,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=jC(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 _=d();if(_===null)return es(m,p,n,r,"unavailable");let g=m.req.header("authorization");if(g!==void 0){let E=l(m),v=Date.now();if(yy(c,E,v))return es(m,p,n,r,"locked_out");let S=g.startsWith("Bearer ")?g.slice(7):"";if(!wy(S,_.passcode))return Ey(c,E,v),es(m,p,n,r);Ty(c,E),await f();return}let y=_y(m.req.header("cookie"));if(y===null||a.get(y)!==_.generation)return es(m,p,n,r,y===null?"missing":"expired");if(GC(m.req.method)&&!gy(m.req.url,m.req.header("host"),h,i))return es(m,p,n,r);await f()}),e.get("/healthz",m=>m.json({ok:!0})),e.get("/login",m=>m.html(HC(Ay(m,n,r),r))),e.post("/login",async m=>{if(!gy(m.req.url,m.req.header("host"),m.req.header("origin"),i))return Ru(m,n,r);let f=l(m),p=Date.now();if(yy(c,f,p))return BC(m,r);let h=d();if(h===null)return Ru(m,n,r);let _=await WC(m.req.raw).catch(()=>null);if(_===null||!wy(_,h.passcode))return Ey(c,f,p),Ru(m,n,r);Ty(c,f),a.size>=OC&&a.delete(a.keys().next().value);let g=LC(32).toString("base64url");return a.set(g,h.generation),m.header("Set-Cookie",VC(g,s,new URL(m.req.url).protocol==="https:")),m.redirect(vy(m,r)??o,303)}),e.post("/logout",m=>{let f=_y(m.req.header("cookie"));return f!==null&&a.delete(f),m.header("Set-Cookie",JC(s,new URL(m.req.url).protocol==="https:")),m.redirect(n,303)})}function qC(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 jC(e,t){return t&&(e===t||e.startsWith(`${t}/`))?e.slice(t.length)||"/":e}function es(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"?Sy(`${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 HC(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 Ru(e,t,r){return e.html(ve("Login failed",`<p>Invalid credentials.</p><a href="${b(Ay(e,t,r))}">Try again</a>`,r),401)}function BC(e,t){return e.html(ve("Login failed","<p>Too many failed attempts from this source. Try again shortly.</p>",t),429)}function Sy(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 vy(e,t){let r=new URL(e.req.url).searchParams.getAll("next");return r.length===1?Sy(r[0],t):null}function Ay(e,t,r){let n=vy(e,r);return n===null?t:`${t}?next=${encodeURIComponent(n)}`}async function WC(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>CC)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 gy(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 GC(e){return e!=="GET"&&e!=="HEAD"&&e!=="OPTIONS"}function _y(e){let t=(e??"").split(";").map(r=>r.trim()).filter(r=>r.startsWith(`${aa}=`)).map(r=>r.slice(aa.length+1));return t.length===1&&/^[A-Za-z0-9_-]{43}$/.test(t[0])?t[0]:null}function VC(e,t,r){return`${aa}=${e}; Path=${t}; HttpOnly; SameSite=Strict; Max-Age=${DC}${r?"; Secure":""}`}function JC(e,t){return`${aa}=; Path=${e}; HttpOnly; SameSite=Strict; Max-Age=0${t?"; Secure":""}`}function wy(e,t){let r=hy("sha256").update(e,"utf8").digest(),n=hy("sha256").update(t,"utf8").digest();return IC(r,n)}function KC(e){try{return dy(e).remote.address??"unknown"}catch{return"unknown"}}function yy(e,t,r){let n=e.get(t);return n!==void 0&&r<n.lockedUntilMs}function Ey(e,t,r){let n=e.get(t);if(n===void 0||r-n.windowStartMs>PC){e.size>=FC&&e.delete(e.keys().next().value),e.set(t,{count:1,windowStartMs:r,lockedUntilMs:0});return}n.count+=1,n.count>=MC&&(n.lockedUntilMs=r+UC)}function Ty(e,t){e.delete(t)}import{createHash as zC}from"node:crypto";var $y=64*1024,YC=new Set(["math"]);function QC(e,t){return zC("sha256").update(e,"utf8").update("\0","utf8").update(t,"utf8").digest("hex")}function ca(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")>$y)throw new I("INVALID_ARGUMENT",`prompt exceeds the ${$y}-byte comm-flow cap`,2);if(!YC.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||!H(i))throw new I("INVALID_ARGUMENT",`"${n}" is not a registered local team`,2);let a=QC(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 XC,readFileSync as ZC}from"node:fs";import{dirname as xy,join as Nu}from"node:path";import{fileURLToPath as Ry}from"node:url";var eO=Nu(xy(Ry(import.meta.url)),"public"),tO={"/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"}},rO=Nu(xy(Ry(import.meta.url)),"vendor-webui"),nO={"/":{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 oO(e){return e.endsWith("/")?e.slice(0,-1):e}function sO(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 ky(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=Nu(t,i.file);if(!XC(a))return s.notFound();let c=ZC(a);return n!==void 0&&i.contentType.startsWith("text/html")&&(c=sO(c.toString("utf8"),n)),s.body(c,200,{"content-type":i.contentType})})}function Ny(e,t={}){let r=oO(t.mountPath??""),n=t.webDistDir??rO;ky(e,n,nO,r!==""?`${r}/`:void 0),ky(e,eO,tO,`${r}/legacy/`)}import{createHash as Cu,createHmac as dO,randomBytes as Lu,timingSafeEqual as mO}from"node:crypto";import{basename as fO}from"node:path";import{existsSync as iO}from"node:fs";import{homedir as aO}from"node:os";import{join as cO}from"node:path";function lO(e){return e||(process.env.LMTEAM_DB_PATH?process.env.LMTEAM_DB_PATH:cO(aO(),".lmteam","lmteam.db"))}function la(e){let t=lO(e);if(!iO(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 Ly(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 Iy(e){return e.prepare("SELECT * FROM asks WHERE status = 'open' ORDER BY raised_at ASC").all()}function Cy(e,t){return e.prepare("SELECT * FROM asks WHERE id = ?").get(t)??null}function Oy(e){return e.prepare("SELECT * FROM blocked WHERE status = 'open' ORDER BY raised_at ASC").all()}function uO(){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??"",_,g=null,y=0,E=f?.dataset.lifecycle==="finished";function v(){if(clearTimeout(_),!(!f||!c(p)||e||document.hidden||E||g)){if(y>=60){s("comm-poll-notice","Automatic checks paused after 60 reads. Use Refresh state to check again.");return}_=setTimeout(()=>void S(),Math.min(1e3*1.5**y,1e4))}}async function S(){if(!f||g||e||document.hidden||E||y>=60)return;let A=new AbortController,q=t;g=A,y++;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{g===A&&(g=null),v()}}let R=o("comm-composer-container"),x=o("comm-draft-form"),L=null,k=!1,B=!1,C=!1,w=null,T=null,N=A=>Array.from(A.querySelectorAll("input, textarea")),U=(A,q)=>{let M=N(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=N(A).map(Z=>({input:Z,value:Z.value}));w=A,T=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),T&&(T.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()}),R&&x&&o("compose")){let A=Array.from(R.childNodes),q=x.querySelector('textarea[name="prompt"]'),M=x.querySelector('button[type="submit"]');x.addEventListener("submit",async Z=>{if(!q||(Z.preventDefault(),L||C||e||document.hidden))return;let W=q.value.replace(/\r\n?/g,`
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,`
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;L=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 N(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=U(Ze,"csrf").value)}catch{}if(!ft)throw G;U(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=U(re,"confirmation").value;if(re.method.toLowerCase()!=="post"||te.origin!==ne.origin||te.pathname!==`${D}/prompts`||te.search||te.hash||!ue||ue.length>4096||U(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,R.replaceChildren(...A),w=null)}),J(be,je),R.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{L===Ee&&(L=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(){L&&(k=!0),t++,clearTimeout(_);for(let A of r)A.abort()}let V=()=>{if(!L&&!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,w&&B&&(B=!1,T&&(T.disabled=!1,T.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 ua=`(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;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 () {
548
548
  function __name(value) { return value; }
549
- return (${uO.toString()})();
550
- })();`;var Dy=ve("","","").match(/<style>([\s\S]*?)<\/style>/),pO=Cu("sha256").update(Dy?Dy[1]:"").digest("base64"),hO=Cu("sha256").update(ua).digest("base64"),gO=`default-src 'none'; style-src 'sha256-${pO}'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; script-src 'sha256-${hO}'; connect-src 'self'`,Iu="lmbee_comm_browser",_O=64*1024,wO=256*1024,Yn=class extends Error{};function My(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=$=>Cu("sha256").update($).digest("hex"),l=$=>dO("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||!mO(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(`${Iu}=`));if(A.length===1)try{let M=d(A[0].slice(Iu.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",`${Iu}=${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 _($){for(let O of $.split(`
551
- `)){let A=O.trim();if(A)return A}return""}let g=80,y=2e3;function E($,O){return $.length>O?`${$.slice(0,O)}\u2026`:$}function v($){let O=_($);return O?E(O,g):"(empty prompt)"}function S($){return E($.trim(),y)}function R($){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 L($){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(L($))}</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(`${fO(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 w(){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 T="<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 N($,O,A,q=200){return $.html(ve(O,`${A}<script>${ua}</script>`,n,{},[ua]),q)}function U($,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>
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
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=la(),M;try{M=Cy(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=Gn(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($){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>wO)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)>_O)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",gO),$.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 N($,"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=U(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 N($,"Invalid page","<p>Invalid prompt cursor.</p>",400);let q=oa(r,{toId:"math",limit:20,...A?{after:Number(A)}:{}});return N($,"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>${T}<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>${w()}<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>${R(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 N($,"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 Yn(ae.message)}A=M;let Z;try{Z=d(q.get("csrf")??"")}catch(ae){throw new Yn(ae.message)}if(Z.browser!==M||Z.purpose!=="review")throw new Yn("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 N($,"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">
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">
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>${U(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 Yn?409:400;return N($,"Review unavailable",`<p>${b(q.message)}</p>${A?U(A,O):`<pre>
556
- ${b(O)}</pre>`}<a href="${o}">Math inbox</a>`,M)}}),t.post("/comm/math/prompts",async $=>{if(!e.enabled)return N($,"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 N($,"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=ca(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 N($,"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 N($,"Not found","<p>Invalid prompt ID.</p>",404);let q=Gn(r,A);if(!q||q.to_id!=="math")return N($,"Not found","<p>No Math inbox prompt at this address.</p>",404);let M=Zo(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 N($,"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>${U(m($,!0))}</section>`}catch{}return N($,`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>${T}<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 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>
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">${w()}</div>`)}),t}import{basename as yO}from"node:path";var Ou=50,EO=e=>e.trim().toLowerCase().replace(/[\s_]+/g,"-"),Du=e=>["blocked","error","on-hold","rate-limited"].includes(EO(e));function jy(e){if(!/^[1-9]\d*$/.test(e)||!Number.isSafeInteger(Number(e)))throw new I("INVALID_ARGUMENT","Invalid positive integer ID");return Number(e)}function TO(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&&jy(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 Py(e,t){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==""));return e+(r.size?`?${r}`:"")}function bO(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||Du(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)*Ou,s*Ou),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*Ou,byId:a}}function Qn(e,t){return Re(`${t}/tasks/${e.id}`,`#${e.id} ${e.title}`)}function Hy(e,t,r){if(e.owner_team_path===null)return"Unassigned";let n=`${yO(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 By(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 Uy(e,t,r,n,o="Task ledger"){return zn(["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=>Qn(u,r)).join(" / ");return[`${l?`${l}<br>`:""}${Qn(s,r)}${s.context?" <strong>(ancestor context)</strong>":""}<br>${b(s.kind)}`,b(s.project),b(s.status),By(s),Hy(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 Fy(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 qy(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 Wy(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=TO(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 I("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>'+Fy(a,d,n),503);let m=bO(l.rows,a,p=>Sr(t.db.db,p),c),f=`<nav aria-label="Task pages">${m.pageNumber>1?Re(Py(`${n}/tasks`,{...a,page:String(m.pageNumber-1)}),"Previous page"):""} ${m.more?Re(Py(`${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>'+qy({total:l.rows.length,by_kind:l.rows.reduce((p,h)=>(p[h.kind]=(p[h.kind]??0)+1,p),{})})+Fy(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+Uy(m.rows,m.byId,n,u)+f)}catch(a){return s(i,a)}}),e.get("/tasks/:id",i=>{try{let a=jy(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(R=>`<li>${Qn(R,n)} \u2014 ${b(R.status)}</li>`).join("")}</ul>`:"<p>None recorded.</p>",_=`<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>`,g=u.at(-1),y=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"?y?`This is a task in epic ${Qn(y,n)}.`:"This is a task with no parent epic.":`This is a subtask${g?` of task ${Qn(g,n)}`:""}${y?`, part of epic ${Qn(y,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>`+_+`<p>Kind: ${b(c.kind)}; project: ${b(c.project)}; recorded status: <strong>${b(c.status)}</strong>.</p><p>Recorded owner: ${Hy(c,f,n)}.</p><p>Blocked / hold: ${By(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("")+qy(Ar(t.db.db,{id:a}))+"<h2>Children</h2>"+Uy(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 SO}from"node:path";var Gy=50,Vy='<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>',vO={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),Jy=e=>e.last_fire_status===null?"Not recorded":`${b(vO[e.last_fire_status]??e.last_fire_status)} <small>(${b(e.last_fire_status)})</small>`;function Ky(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 P("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=`${SO(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 Yy(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 Mu(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function AO(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 $O(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>"+Mu([["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>`+Mu([["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>`+AO(e.artifacts)+s+"</article>"}function Qy(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 P?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=Ky(a),l=Li(t.db.db,{limit:Gy,after:c}),u=Mr(t.teams),d=l.rows.map(f=>({job:f,flags:Yy(f,Rr(t.db.db,f.id))})),m=(f,p)=>zn(["Job","Schedule / timezone","Action kind","Enabled","Last fire status","Last fired","Scheduler last looked at","Last fire error","Session"],f.map(({job:h,flags:_})=>[Re(`${n}/cron/${h.id}`,`#${h.id} ${h.title}`)+(_.length?`<p class="warning"><strong>${_.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",Jy(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",Vy+"<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 P("INVALID_ARGUMENT","Invalid positive job ID");let l=Ky(a),u=Ie(t.db.db,Number(c)),d=Ai(t.db.db,{jobId:u.id,limit:Gy,after:l}),m=Rr(t.db.db,u.id),f=Yy(u,m),p=Mu([["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",Jy(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>`:"",_=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}`,Vy+`<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($O).join(""):_)+i(`${n}/cron/${u.id}`,l,d.next_cursor))}catch(c){return s(a,c)}})}function kO(e,t){return t===null&&e.retracted_ts===null&&(e.status==="pending"||e.status==="escalating"||e.status==="sent"||e.status==="retrieved")}var Zy=64*1024;async function xO(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>Zy)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 eE(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 tE(e,t){let r=[];t.retracted_ts!==null&&t.retracted_reason&&r.push(t.retracted_reason);let n=eE(e,t);for(let o of n)o.retracted_ts!==null&&o.retracted_reason&&r.push(o.retracted_reason);return r}function Pu(e,t=Date.now()){return Bo(e,t).map(n=>{let o=n.row,s=nn(e,o),i=Ho(e,o),a=n.ageMs>=Vo||s>=2&&o.sent_ts===null,c=tE(e,o);return{row:o,constituentCount:s,retractedCount:i,urgent:a,retractedReasons:c}})}function rE(e){return e===1?"1 of 1":`${e} merged into this one`}function RO(e){return e==="merged"||e==="informational"||e==="retracted"}function NO(e){return e.lifecycle==="queued"?"queued":e.lifecycle==="processing"?"processing":RO(e.lifecycleBasis)?"muted":"replied"}function LO(e){return e.lifecycle==="queued"?"Queued":e.lifecycle==="processing"?"Processing":e.lifecycleBasis==="merged"?"Combined":e.lifecycleBasis==="informational"?"Informational":e.lifecycleBasis==="retracted"?"Retracted":"Replied"}function nE(e){return`<span class="status-chip status-${NO(e)}" title="${b(Uu(e))}">${b(LO(e))}</span>`}function Uu(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 IO(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function CO(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 OO(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 DO(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 Xy(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=rE(i.constituentCount),p=i.retractedCount>0?`${i.retractedCount} retracted${i.retractedReasons.length>0?`: ${i.retractedReasons.map(_=>`\u201C${b(_)}\u201D`).join("; ")}`:""}`:"\u2014",h=`${nE(l)} \xB7 ${b(Uu(l))}`;return[u,d,m,f,p,h]});return zn(o,s,t)}function oE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/operator",o=>{try{let s=Pu(t.db.db,Date.now()),i=s.filter(_=>_.urgent),a=s.filter(_=>!_.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>${Xy(i,"Urgent escalations",n,t.db.db)}</section>`,u=`<section aria-label="Routine escalations"><h2>Routine escalations</h2>${Xy(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 _=la(),g,y,E;try{g=Oy(_),y=Iy(_),E=Ly(_)}finally{_.close()}m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${OO(g)}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${DO(y,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>${CO(E)}</section>`}catch(_){let g=`<p class="warning">lmteam data unavailable: ${b(_ instanceof Error?_.message:String(_))}</p>`;m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${g}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${g}</section>`,p=`<section aria-label="Decisions"><h2>Decisions</h2>${g}</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=Ho(t.db.db,a),f=tE(t.db.db,a),p=[["From",b(a.from_id)],["To",b(a.to_id)],["Queued",fe(a.created_ts)],["Lifecycle",`${nE(u)} \xB7 ${b(Uu(u))}`],["Constituents",b(rE(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 _="";l?_=`<section><h2>Answer</h2><p>Recorded ${fe(l.answered_at)}</p><pre>${b(l.answer_text)}</pre></section>`:kO(a,l)&&(_=`<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="${Zy}" required></textarea><button>Send answer</button></form></section>`);let g=eE(t.db.db,a),y="";g.length>0&&(y=`<section><h3>Merged constituents (${g.length})</h3><p>Additional escalations folded into this message:</p><ul>${g.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>
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>
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>${IO(p)}</section>
562
+ <section aria-label="Escalation metadata"><h2>Metadata</h2>${PO(p)}</section>
563
563
  <article aria-label="Prompt content"><h2>Prompt content</h2>${h}</article>
564
- ${_}
565
- ${y}`;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 xO(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 sE(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((g,[y,E])=>g+(Du(y)?E:0),0),c=Pu(t.db.db,Date.now()).filter(g=>g.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(g=>Re(`${n}/tasks?kind=${g}`,`${i.by_kind[g]??0} ${g}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 g=u.report,y=[...g.running,...g.dead,...g.idle],E=p.filter(v=>!y.some(S=>_n(v,S.target)));if(E.length>0){let v=E.map(S=>`<li>${b(S.name)}: ${b(Wo(Gi(t.db.db,S,g,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 _=`${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>
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>
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",_,n,{},[],!0))}catch(s){return Oe(o,ve("Overview unavailable",`<p>${b(s instanceof Error?s.message:String(s))}</p>`,n,{},[],!0),500)}})}function MO(e,t,r){return`${r.replace(/\/$/,"")}/api/session/${encodeURIComponent(e)}/${encodeURIComponent(t)}?limit=20`}function iE(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(MO(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 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))}">
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 (${PO.toString()})();
589
- })();</script>`}function PO(){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,_=0,g=0,y=null,E=null,v=D=>!m&&!document.hidden&&D===f,S=()=>{},R=[],x=!1;function L(D){let j=u("span",D),Y=R.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(L(D),u("span"," \u2192 "),L(j)),Y}let B=D=>`${n}/sessions/${encodeURIComponent(t)}/${encodeURIComponent(r)}?queue=${D}`,C=D=>D instanceof Error?D.message:String(D);async function w(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 T(D){return D==="merged"||D==="informational"||D==="retracted"}function N(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 U=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||U===f||m||document.hidden)return;let D=f;U=D,c("session-refresh").disabled=!0;try{let j=await w(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{U===D&&(U=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 w(`${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(y===_||h===null||m||document.hidden)return;y=_;let D=h,j=_,Y=f;try{let K=await w(`${n}/api/queue/${D}/state`);if(j!==_||!v(Y))return;if(K.id!==D)throw new Error("Queue identity mismatch");if(K.lifecycle==="finished"&&!T(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}: ${N(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"&&++g<60?p=setTimeout(()=>void $(),5e3):K.lifecycle!=="finished"&&l("comm-state",`Queue #${D}: observation stalled \u2014 automatic checks paused after 60 reads; last state ${N(K)}. Check again manually. This does not establish execution failure.`)}catch(K){j===_&&v(Y)&&l("comm-state",`State check failed; last content may be stale. ${C(K)}. Check again manually.`)}finally{y===j&&(y=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,_++,g=0;let Y=_,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 w(`${n}/api/queue/${D}`);if(Y!==_||!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: "),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 $e=await w(`${n}/api/queue/${D}/preview`);if(Y!==_||!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===_&&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 w(`${n}/api/teams`).catch(()=>null);if(!v(D))return;R=j?.teams??[],x=j!==null;let Y=R.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 w(`${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":T(z.lifecycleBasis)?"muted":"replied"}`,G.title=N(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"&&!T(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 gr=await w(`${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?`
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
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 w(`${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),g=0,$()});let Z=D=>{f++,_++,clearTimeout(p),U=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 aE(e){let{context:t}=e,r=e.config??pe,n=e.remoteStalledConfig??{},o=e.fetchReport??Ae,s=e.send??Ht,i=e.whoami??ku,a=e.fetchHealth??ly,c=e.heavyLockStatusPath??Un(),l=e.heavyLockPath??Fn(),u=e.tail??yi,d=e.tailJson??Ei,m=new tn;if(e.publish===!0){let w=e.passcodeFilePath!==void 0?e.passcodeFilePath:Hn(t.db.path),T=e.readPasscodeAuthority??(()=>w===null?null:l_(w));by(m,{allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,readAuthority:T,...e.remoteKey!==void 0?{remoteKey:e.remoteKey}:{}})}else m.use("*",async(w,T)=>{w.header("Cache-Control","no-store");let N=w.req.header("origin");if(N!==void 0&&!e.allowedOrigins.includes(N))return w.json({error:"origin not allowed"},403);await T()});m.route("/",My({context:t,allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,enabled:!0})),sE(m,t,e.mountPath),Ny(m,{webDistDir:e.webDistDir,mountPath:e.mountPath}),Wy(m,t,e.mountPath),Qy(m,t,e.mountPath),oE(m,t,e.mountPath),m.get("/api/teams",w=>w.json($u(t))),m.get("/api/identities/:key",w=>w.json(xs(t.teams,w.req.param("key")))),m.get("/api/state",w=>{let T=w.req.query("team");return T!==void 0?w.json(Su(t,T)):w.req.query("active")!==void 0?w.json(vu(t)):w.json(bu(t))}),m.get("/api/status",async w=>{let T=w.req.query("live")==="1"||w.req.query("live")==="true",N=await Au(t,{live:T,fetchReport:o});return w.json(N)}),m.get("/api/liveness",async w=>{let T=await o(),N=t.teams.map(U=>{let J=H(U)?null:Fs(t.db.db,{site:U.peerSite,team:U.name,alias:U.alias});return{team:U.name,running:H(U)?Fe(U,T):!1,deadReclaimable:H(U)?Xr(U,T):!1,remoteOutbound:J?{state:J.state,sentTs:J.sent_ts,ackedTs:J.acked_ts,repliedTs:J.replied_ts}:null}});return w.json({report:T,teams:N})}),m.get("/api/stalled",async w=>{let T=await o(),N=lt(c,l,void 0,ee=>{process.stderr.write(`[api/stalled] heavy-lock probe failed, treating conservatively as held: ${ee.message}
594
- `)}),U=await kn(t.db.db,t.teams.filter(H),T,N,r,void 0,{readOnly:!0}),J=G_(t.db.db,t.teams.filter(ee=>!H(ee)),n);return w.json({stalled:U,remoteStalled:J})});function f(w){let T=t.teams.find(U=>U.name===w);if(!T)return{error:`unknown team "${w}"`,status:404};if(!H(T))return{error:`team "${w}" is a remote team (channel=lmmail) -- not reachable via lctl`,status:400};let N;try{N=Q(T)}catch(U){return{error:U instanceof Error?U.message:String(U),status:500}}return{teamfilePath:N}}function p(w,T,N,U){return d(w,T,{lines:N?Number(N):20,...U?{since:U}:{}})}let h=(e.mountPath??"").replace(/\/$/,"");m.get("/running",w=>{try{let T=jo(),N=T.report===null?"<p>Activity has not yet been observed; running, dead, and idle counts are unknown.</p>":`<p>Cached observation taken ${T.observedAt?fe(T.observedAt):"at an unknown time"}. Refreshing this page does not run a new activity scan.</p>`,U=T.lastError?`<p class="warning">Observer failed${T.lastErrorAt?` ${fe(T.lastErrorAt)}`:""}: ${b(T.lastError)}. ${T.report?"Showing the last successful observation.":"No successful observation is available."}</p>`:"",J=T.report===null?"":py($l(T.report),Mr(t.teams),h);return Oe(w,ve("Running","<p>This page loaded just now; activity data comes from a separate scheduled observation and may be older.</p>"+N+U+J,h))}catch(T){return Oe(w,ve("Running unavailable",`<p>${b(T instanceof Error?T.message:String(T))}</p>`,h),502)}}),m.get("/sessions/:team/:alias",w=>{let T=w.req.param("team"),N=w.req.param("alias"),U=`Session: ${T} / ${N}`,J={"data-page":"session","data-team":T,"data-alias":N},ee=f(T);if("error"in ee)return Oe(w,ve(U,`<p role="alert">${b(ee.error)}</p>`,h,J),ee.status);let oe=iE(T,N,h,{canonicalTeamfile:ee.teamfilePath,commPageEnabled:!0}),V=Array.from(oe.matchAll(/<script>([\s\S]*?)<\/script>/g),se=>se[1]);return Oe(w,ve(U,oe,h,J,V))}),m.get("/api/session/:team/:alias",async w=>{let T=w.req.param("team"),N=w.req.param("alias"),U=f(T);if("error"in U)return w.json({error:U.error},U.status);let{teamfilePath:J}=U,ee=w.req.query("since"),oe=w.req.query("limit");try{let V=await p(J,N,oe,ee);return w.json(V)}catch(V){return w.json({error:V instanceof Error?V.message:String(V)},404)}}),m.get("/api/transcript",async w=>{let T=w.req.query("team");if(!T)return w.json({error:"team is required"},400);let N=t.teams.find(V=>V.name===T);if(!N)return w.json({error:`unknown team "${T}"`},404);if(!H(N))return w.json({error:`team "${T}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let U=w.req.query("alias")??N.leadAlias,J;try{J=Q(N)}catch(V){return w.json({error:V instanceof Error?V.message:String(V)},500)}let ee=w.req.query("lines"),oe=w.req.query("since");try{let V=await u(J,U,{...ee?{lines:Number(ee)}:{},...oe?{since:oe}:{}});return w.json({team:T,alias:U,...V})}catch(V){return w.json({error:V instanceof Error?V.message:String(V)},502)}}),m.get("/api/queue",w=>{let T=w.req.query("to");return w.json(_u(t,T))}),m.get("/api/queue/stats",w=>{try{let T=x(w.req.query("to"),"to");return w.json(Eu(t,T))}catch(T){return g(w,T)}});let _=w=>{try{let T=w.req.query(),N={fromId:x(T.from,"from"),toId:x(T.to,"to"),status:k(T.status),since:B(T.since,"since"),until:B(T.until,"until"),after:E(T.after,"after"),limit:E(T.limit,"limit",200)};return w.json(oa(t,N))}catch(T){return g(w,T)}};m.get("/api/queue/prompts",_),m.get("/api/queue/:id",w=>{let T=Number(w.req.param("id")),N=Gn(t,T);return N?w.json({queue:N}):w.json(ke("queue_not_found",`no queue entry ${T}`),404)}),m.get("/api/queue/:id/state",w=>{let T=Number(w.req.param("id")),N=Zo(t,T);return N?w.json(N):w.json(ke("queue_not_found",`no queue entry ${T}`),404)}),m.post("/api/queue/:id/answer",async w=>{try{let T=S(w.req.param("id"),"id"),N=await w.req.json().catch(()=>({})),U=x(N.from,"from"),J=x(N.text,"text");if(U===void 0||J===void 0)return w.json(ke("invalid_argument","from and text are required"),400);let ee=sn(t.db.db,T,U,J);return w.json({answer:ee},202)}catch(T){return g(w,T)}}),m.get("/api/queue/:id/preview",w=>{try{let T=S(w.req.param("id"),"id"),N=Or(t,T);return N?w.json(N):w.json(ke("queue_not_found",`no queue entry ${T}`),404)}catch(T){return g(w,T)}}),m.post("/api/enqueue",async w=>{let T=await w.req.json().catch(()=>({})),N=T.prompt;if(!T.to||!N||!T.from)return w.json({error:"to, prompt, and from are required"},400);if(T.from==="autopilot")return w.json({error:"from: 'autopilot' is reserved for the tool's own automated enqueues"},400);try{let U=e.publish===!0&&T.from==="operator",J=_e(t.db.db,t.teams,T.to,N,{from:T.from,...U?{operatorPriority:!0}:{}});return w.json({id:J})}catch(U){return w.json({error:U instanceof Error?U.message:String(U)},400)}}),m.post("/api/comm/send",async w=>{try{let T=await w.req.json().catch(()=>({})),N=x(T.to,"to"),U=x(T.prompt,"prompt"),J=x(T.dedupeKey,"dedupeKey");if(N===void 0||U===void 0||J===void 0)return w.json(ke("invalid_argument","to, prompt, and dedupeKey are required"),400);let ee=ca(t.db.db,t.teams,{to:N,prompt:U,dedupeKey:J});return w.json(ee,ee.replayed?200:202)}catch(T){return g(w,T)}}),m.post("/api/queue/deliver",async w=>{let T=await o(),N=Er(t.db.db,{teams:t.teams,report:T,...e.remoteMail?{remoteMail:e.remoteMail}:{}});return w.json({delivered:N})}),m.post("/api/queue/retrieve",async w=>{let T=await w.req.json().catch(()=>({}));if(!T.to)return w.json({error:"to is required"},400);if(T.id!==void 0&&(!Number.isInteger(T.id)||T.id<=0))return w.json({error:"id must be a positive integer"},400);try{let U=Ws(t.db.db,T.to,T.id).map(J=>{let ee;try{ee=UO(J.prompt_file,"utf8")}catch{ee="(could not read prompt file)"}return{...J,content:ee}});return w.json({retrieved:U})}catch(N){return g(w,N)}}),m.get("/api/inbox",w=>{let T=w.req.query("to");return T?w.json(yu(t,T)):w.json(ke("to_required","to is required"),400)});function g(w,T){if(T instanceof I){let N=T.code==="NOT_FOUND"?404:T.code==="CONFLICT"?409:T.code==="DB_BUSY"?503:T.code==="STORAGE_ERROR"?500:400;return w.json(ke(T.code,T.message),N)}return w.json(ke("internal_error",T instanceof Error?T.message:String(T)),500)}let y=new Set(["epic","task","subtask"]);function E(w,T,N){if(w===void 0)return;let U=Number(w);if(!/^[1-9]\d*$/.test(w)||!Number.isSafeInteger(U)||N!==void 0&&U>N)throw new I("INVALID_ARGUMENT",N!==void 0?`${T} must be a positive integer <= ${N}`:`${T} must be a positive integer`);return U}function v(w,T){if(w===void 0)return;let N=Number(w);if(!/^\d+$/.test(w)||!Number.isSafeInteger(N))throw new I("INVALID_ARGUMENT",`${T} must be a nonnegative integer`);return N}function S(w,T){let N=Number(w);if(!/^[1-9]\d*$/.test(w)||!Number.isSafeInteger(N))throw new I("INVALID_ARGUMENT",`${T} must be a positive integer`);return N}function R(w){if(w!==void 0){if(!y.has(w))throw new I("INVALID_ARGUMENT","kind must be 'epic', 'task', or 'subtask'");return w}}function x(w,T){if(w!==void 0){if(w.trim()==="")throw new I("INVALID_ARGUMENT",`${T} must not be blank`);return w}}function L(w,T){if(w!==void 0){if(w==="1"||w==="true")return!0;if(w==="0"||w==="false")return!1;throw new I("INVALID_ARGUMENT",`${T} must be '1'/'true' or '0'/'false'`)}}function k(w){if(w!==void 0){if(!pc.includes(w))throw new I("INVALID_ARGUMENT",`status must be one of: ${pc.join(", ")}`);return w}}function B(w,T){if(w===void 0)return;let N=w.trim()===""?NaN:Date.parse(w);if(Number.isNaN(N))throw new I("INVALID_ARGUMENT",`${T} must be a valid ISO8601 date-time string`);return new Date(N).toISOString()}function C(w,T){let N=x(w,"ownerTeam"),U=x(T,"ownerAlias");if(!(N===void 0&&U===void 0)){if(N===void 0||U===void 0)throw new I("INVALID_ARGUMENT","ownerTeam and ownerAlias must both be given");return{team:N,alias:U}}}return m.get("/api/tasks",w=>{let T=w.req.query();try{let N={project:x(T.project,"project"),kind:R(T.kind),status:x(T.status,"status"),parentId:E(T.parentId,"parentId"),owner:C(T.ownerTeam,T.ownerAlias),unassigned:L(T.unassigned,"unassigned"),limit:E(T.limit,"limit",Ne),after:v(T.after,"after")};return w.json(br(t.db.db,N))}catch(N){return g(w,N)}}),m.get("/api/tasks/summary",w=>{try{let T=E(w.req.query("id"),"id"),N=x(w.req.query("project"),"project");return w.json(Ar(t.db.db,{id:T,project:N}))}catch(T){return g(w,T)}}),m.get("/api/tasks/:id",w=>{try{let T=S(w.req.param("id"),"id");return w.json(Sr(t.db.db,T))}catch(T){return g(w,T)}}),m.get("/api/tasks/:id/tree",w=>{try{let T=S(w.req.param("id"),"id");return w.json(vr(t.db.db,T))}catch(T){return g(w,T)}}),m.get("/api/tasks/:id/notes",w=>{try{let T=S(w.req.param("id"),"id"),N=v(w.req.query("after"),"after"),U=E(w.req.query("limit"),"limit",Ne);return w.json(Ef(t.db.db,T,{limit:U,after:N}))}catch(T){return g(w,T)}}),m.post("/api/send",async w=>{let T=await w.req.json().catch(()=>({})),N=T.prompt;if(!T.team||!N)return w.json({error:"team and prompt are required"},400);let U=t.teams.find(V=>V.name===T.team);if(!U)return w.json({error:`unknown team "${T.team}"`},404);if(!H(U))return w.json({error:`team "${T.team}" is a remote team (channel=lmmail) -- not reachable via lctl`},400);let J=await s({teamfilePath:Q(U),alias:U.leadAlias},N),ee=Bn(J),oe=Date.now();return ir(t.db.db,U.name,ee.status,oe),tt(t.db.db,U.name,ee.status,oe,{note:"web send"}),w.json({status:ee.status,outcome:J})}),m.get("/api/history",w=>{let T=w.req.query("team"),N=w.req.query("limit"),U=su(t,T,N);return"error"in U?w.json(U,400):w.json(U)}),m.get("/api/sources",w=>w.json(Tu(t))),m.get("/api/mail/status",w=>w.json(iu(t))),m.get("/api/subscriptions",async w=>{let{status:T,body:N}=await uy();return w.json(N,T)}),m.get("/api/whoami",async w=>{let{data:T,exitCode:N}=await i();return"error"in T?w.json(T,N===4?502:400):w.json(T)}),m.get("/api/running",async w=>w.json(await o())),m.get("/api/running/humanized",async w=>w.json($l(await o()))),m.get("/api/running/observed",w=>w.json(jo())),m.get("/api/heavy-lock",w=>{try{return w.json(Al(c,l))}catch(T){if(T instanceof Pn)return w.json(ke("heavy_lock_probe_failed",T.message),502);throw T}}),m.get("/api/health",async w=>{let T=w.req.query("target");if(!T)return w.json(ke("target_required","target is required"),400);try{let N=await a(T);return w.json(N)}catch(N){return w.json(ke("health_fetch_failed",N instanceof Error?N.message:String(N)),502)}}),m.post("/api/sources",async w=>{let T=await w.req.json().catch(()=>({}));if(!T.path)return w.json({error:"path is required"},400);let N=sa(t,T.path,T.label??void 0);return N.ok?(t.teams=Jr(t.db.db,t.teamsConfPath),w.json({ok:!0})):w.json({error:N.output},400)}),m.delete("/api/sources",w=>{let T=w.req.query("path");return T?(Ns(t.db.db,T),t.teams=Jr(t.db.db,t.teamsConfPath),w.json({ok:!0})):w.json({error:"path is required"},400)}),m}function Fu(e){return e.teams=Jr(e.db.db,e.teamsConfPath),e.teams}var FO=4173,qO="127.0.0.1";function cE(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??FO,r=e.hostname??qO,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=Ko(e.context.db.path),i=null;if(s!==null)try{i=ea(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??Hn(e.context.db.path);n&&h!==null&&ta(h),l=aE({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 _=e.mountPath?.endsWith("/")?e.mountPath.slice(0,-1):e.mountPath;if(_?u=new tn().route(_,l).get(`${_}/`,async g=>{let y=new URL(g.req.url);y.pathname="/",y.search="";let E=await l.fetch(new Request(y,{method:"GET",headers:g.req.raw.headers}));return E.ok?g.redirect(_,302):E}):u=l,d=Xg({db:e.context.db.db,getTeams:()=>Fu(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:g=>{process.stderr.write(`[cron] tick: watch=${g.watch.why}, ${g.stalled.length} stalled (${g.stalled.join(", ")||"none"})${g.maintainerWoken?", maintainer woken":""}${g.autoContinued.length?`, auto-continued (${g.autoContinued.join(", ")})`:""}
595
- `)},onError:g=>{process.stderr.write(`[cron] tick failed: ${g instanceof Error?g.stack??g.message:String(g)}
596
- `)}}),m=W_({db:e.context.db.db,getTeams:()=>Fu(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:g=>{g>0&&process.stderr.write(`[queue] delivered ${g}
597
- `)},onError:g=>{process.stderr.write(`[queue] delivery pass failed: ${g instanceof Error?g.stack??g.message:String(g)}
598
- `)}}),e.remoteMail){let g=e.remoteMail;f=B_({db:e.context.db.db,client:g.client,mailbox:g.mailbox,worker:{localSiteId:g.localSiteId,allowlist:g.allowlist,dispatch:y=>m_(e.context.db.db,Fu(e.context),y,{client:g.client,localSiteId:g.localSiteId})},...g.intervalMs!==void 0?{intervalMs:g.intervalMs}:{},onPoll:y=>{if(g.onPoll?.(y),y.recorded>0||y.retriedFailed>0){let E=e.fetchReport??Ae,v=e.deliverImpl??Er;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:g.onMailError??(y=>{process.stderr.write(`[mail] poll failed: ${y instanceof Error?y.stack??y.message:String(y)}
600
- `)})})}if(e.execWorker){let g=e.execWorker;p=(g.createExecWorkerImpl??F_)({client:g.client,mailbox:g.mailbox,adminUsers:g.adminUsers,allowUsers:g.allowUsers,allowAnonymous:g.allowAnonymous,...g.pollIntervalMs!==void 0?{pollIntervalMs:g.pollIntervalMs}:{},...g.timeoutCapSeconds!==void 0?{timeoutCapSeconds:g.timeoutCapSeconds}:{}})}}catch(h){throw i?.release(),h}return new Promise((h,_)=>{let g=!1,y;try{y=Jf({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}`),g=!0,d.start(),m.start(),f&&e.remoteMail){let v=e.remoteMail;(v.ensureMailboxImpl??H_)(v.client,v.mailbox).then(()=>f?.start()).catch(R=>{process.stderr.write(`[mail] mailbox provisioning failed, mail lane stays dormant this run: ${R instanceof Error?R.stack??R.message:String(R)}
601
- `),v.onMailError?.(R)})}if(p&&e.execWorker){let v=e.execWorker;(v.ensureExecMailboxImpl??U_)(v.client,v.mailbox).then(()=>p?.start()).catch(R=>{process.stderr.write(`[exec-worker] mailbox provisioning failed, exec stays dormant this run: ${R instanceof Error?R.stack??R.message:String(R)}
602
- `)})}h({app:l,scheduler:d,queueScheduler:m,mailScheduler:f,execWorker:p,server:y,port:E.port,hostname:r,close(){d.stop(),m.stop(),f?.stop(),p?.stop(),y.close(),i?.release()},async shutdown(){d.stop(),m.stop(),f?.stop(),p?.stop();let v=new Promise((R,x)=>{y.close(L=>L?x(L):R())}),S=(async()=>{for(;d.isTicking()||m.isDelivering()||(f?.isPolling()??!1);)await new Promise(R=>setTimeout(R,50))})();await Promise.all([v,S,p?.whenIdle()??Promise.resolve()]),i?.release()}})})}catch(E){i?.release(),_(E instanceof Error?E:new Error(String(E)));return}y.on("error",E=>{if(g){process.stderr.write(`[serve] post-bind server error (ignored -- lock/scheduler untouched): ${E instanceof Error?E.stack??E.message:String(E)}
603
- `);return}g=!0,i?.release(),_(E instanceof Error?E:new Error(String(E)))})})}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 Xn(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 jO,readFileSync as HO,writeFileSync as BO}from"node:fs";var qu="lmbee-cron-export",lE=["schema_version","kind","exported_at","exported_from","jobs"],uE=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","timezone","enabled"],WO=["provider","model","working_directory","escalation_owner","timezone"];function GO(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 VO(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("SQLITE_BUSY")}function JO(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 VO(n)?new P("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 P("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:qu,exported_at:new Date().toISOString(),exported_from:t,jobs:r.map(GO)}}function KO(e,t,r){let n=JO(e,r);try{BO(t,`${JSON.stringify(n,null,2)}
604
- `,{flag:"wx"})}catch(o){throw o&&typeof o=="object"&&"code"in o&&o.code==="EEXIST"?new P("INVALID_ARGUMENT",`export path already exists: ${t} (rm it first; there is no --force)`):new P("INVALID_ARGUMENT",`cannot write export to ${t}: ${o instanceof Error?o.message:String(o)}`)}return n}function zO(e){let t=_o(e);Fa(t);let r=new ht(t,{readonly:!0,fileMustExist:!0});return r.pragma("busy_timeout = 0"),{db:r,path:t,close:()=>r.close()}}var dE=`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 ts(e,t,r){if(t.length>1)throw new P("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 P("INVALID_ARGUMENT",`cron ${e} does not know flag "--${n}" (only --json and --help)`)}function mE(e){let{positionals:t,flags:r}=wt(e,["json","help"]),n=r.json===!0;try{if(r.help===!0)return{output:dE,exitCode:0};ts("export",t,r);let o=t[0];if(o===void 0)throw new P("INVALID_ARGUMENT",`an export PATH is required
606
- ${dE}`);let s=zO();try{let i=KO(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 P)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 P("INVALID_ARGUMENT",`jobs[${e}]: ${t}`)}function YO(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))uE.includes(l)||yt(t,`unknown key "${l}"`);for(let l of uE)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 WO){let u=r[l];u!==null&&typeof u!="string"&&yt(t,`${l} must be a string or null`)}return r}function fE(e){let t;try{t=HO(e,"utf8")}catch(i){throw new P("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 P("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 P("INVALID_ARGUMENT","import document must be a JSON object");let n=r;for(let i of Object.keys(n))if(!lE.includes(i))throw new P("INVALID_ARGUMENT",`unknown top-level key "${i}"`);for(let i of lE)if(!(i in n))throw new P("INVALID_ARGUMENT",`missing top-level key "${i}"`);if(n.schema_version!==1)throw new P("INVALID_ARGUMENT",`schema_version must be 1, got ${JSON.stringify(n.schema_version)}`);if(n.kind!==qu)throw new P("INVALID_ARGUMENT",`kind must be "${qu}", got ${JSON.stringify(n.kind)}`);for(let i of["exported_at","exported_from"])if(typeof n[i]!="string")throw new P("INVALID_ARGUMENT",`${i} must be a string, got ${JSON.stringify(n[i])}`);if(!Array.isArray(n.jobs))throw new P("INVALID_ARGUMENT","jobs must be an array");let o=n.jobs.map((i,a)=>YO(i,a)),s=new Set;for(let i of o){if(s.has(i.id))throw new P("INVALID_ARGUMENT",`duplicate id ${i.id} within the document`);s.add(i.id)}return o}function pE(e){return{...e,title:e.title.trim(),timezone:e.timezone===null?null:e.timezone.trim()}}function QO(e,t){let r=pE(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 XO(e){let t=pE(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 hE(e){fE(e)}function gE(e,t){let r=fE(t),n=[],o=[];e.transaction(()=>{for(let a of r){let c=Ri(e,a.id);if(c!==null){if(QO(c,a)){n.push({id:a.id,title:a.title});continue}throw new P("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)}Ni(e,XO(a)),o.push(a)}}).immediate();let i=[];for(let a of o)a.working_directory!==null&&!jO(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 _E(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 wE(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:Nc(e.db.db,c,o,s,a,i)}))}}var da=Ut(xt(),1);import{readFileSync as ZO}from"node:fs";function cn(e,t,r={}){if(e===void 0)return;if(typeof e!="string"||!/^\d+$/.test(e))throw new P("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 P("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 P("INVALID_ARGUMENT",`${t} is required`);return r}function eD(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}var tD=["pending","running","succeeded","failed","escalated"];function rD(e){return tD.includes(e)}function yE(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 P("INVALID_ARGUMENT","provide only one of --payload, --prompt, or --prompt-file");if(n!==void 0){if(typeof n!="string")throw new P("INVALID_ARGUMENT","--prompt-file requires a path");try{return ZO(n,"utf8")}catch(s){throw new P("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}):nD(t,r)}function EE(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 nD(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,da.formatTable)([["ID","ENABLED","KIND","SCHEDULE","TITLE"],...e.map(s=>["id","enabled","action_kind","schedule_expr","title"].map(i=>(0,da.escapeCell)(String(s[i]??""))))]):e.map(s=>JSON.stringify(s)).join(`
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(", ")})`:""}
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 ${_}
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(`
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 TE=`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 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]
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 bE(e,t,r,n,o=[]){try{let[s,...i]=t;switch(s){case"create":{let a=r.title;if(typeof a!="string")throw new P("INVALID_ARGUMENT","--title is required");let c=r.schedule;if(typeof c!="string")throw new P("INVALID_ARGUMENT","--schedule is required");let l=r.kind;if(typeof l!="string"||!eD(l))throw new P("INVALID_ARGUMENT",'--kind must be "enqueue", "command", "script", "session", or "miniplayer"');let u=yE(r);if(u===void 0)throw new P("INVALID_ARGUMENT",l==="session"||l==="miniplayer"?"--prompt or --prompt-file is required":"--payload is required");let d=Ni(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 P("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=yE(r),l=wh(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=yh(e,a,s==="enable");return{output:dt(n,c),exitCode:0}}case"remove":{let a=ur(i[0],"id"),c=Eh(e,a);return{output:dt(n,c),exitCode:0}}case"reset":{let a=ur(i[0],"id"),c=vh(e,a);return{output:dt(n,c),exitCode:0}}case"reset-session":{let a=ur(i[0],"id"),c=Th(e,a);return{output:dt(n,c),exitCode:0}}case"runs":{let a=r.status;if(a!==void 0&&(typeof a!="string"||!rD(a)))throw new P("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}=Ai(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(Mo),{next_cursor:u}),exitCode:0}}case"run":{let a=ur(i[0],"id");return{output:dt(n,Mo(ze(e,a))),exitCode:0}}case"trigger":{let a=ur(i[0],"id"),c=await vl(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 P("INVALID_ARGUMENT","a run token is required");let c=r.status;if(typeof c!="string"||c!=="succeeded"&&c!=="failed"&&c!=="escalated")throw new P("INVALID_ARGUMENT",'--status must be "succeeded", "failed", or "escalated"');let l=r.summary;if(typeof l!="string")throw new P("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=th(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,Mo(f)),exitCode:0}}case"import":{ts("import",i,r);let a=i[0];if(a===void 0)throw new P("INVALID_ARGUMENT","an import PATH is required");let c=gE(e,a);return{output:n?dt(!0,c):_E(c),exitCode:0}}case"resolve":{let a=ur(i[0],"id"),c=oh(e,a,{resolution:We(r.resolution),actor:We(r.actor),note:We(r.note),confirmStopped:r["confirm-stopped"]===!0});return{output:dt(n,Mo(c)),exitCode:0}}default:return n?EE(n,new P("INVALID_ARGUMENT",TE)):{output:TE,exitCode:1}}}catch(s){if(s instanceof P)return EE(n,s);throw s}}var SE=["disabled","confirm-stopped"];async function vE(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 oD(i,o,async l=>{if(!await Rc(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 _=h instanceof Error?h.message:String(h);return ir(e.db,l.name,"ENV-ERROR",n),So(e.db,l.name,new Date(n).toISOString()),tt(e.db,l.name,"ENV-ERROR",n,{note:_}),{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(Ds(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=Bn(f);return ir(e.db,l.name,p.status,n),So(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 oD(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 rs(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=qi(r.promptsDir);return(r.scanOnceImpl??vE)({db:e,teams:t.filter(H),report:o,heavyLock:i,readHeavyLockStatusImpl:s,resolveNudgeMessage:l=>ji(a,l)})}function ns(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 AE(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 rs(e.db.db,n,r);return ns(o)}function $E(e,t,r){let n=Tt(e.db.db,t),o={companionTeam:r.companionTeam,workerAlias:r.workerAlias??"Worker",commitThreshold:r.commitThreshold??el,hoursThresholdMs:r.hoursThresholdMs??tl,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 pi(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 kE(e,t,r={}){let n=Tt(e.db.db,t)!==null;return Tp(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 sD(e,t){let r=t!==void 0?[t]:rl(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 xE(e,t,r={}){let n=sD(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<xo?`, ramp-up turn ${o.config.turnsDispatched}/${xo} (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 iD=new Set(["operator","lmauto"]),aD=new Set(["autopilot"]);function cD(e,t){return aD.has(e)?t:e}function RE(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&&iD.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=iw(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=Qo(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=cD(n.from,t);o=dw(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#${aw(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 NE(e,t,r={}){let n=pw(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 $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}:
618
618
  ${o.join(`
619
- `)}`}function LE(e,t,r={}){let n=Qo(e.db.db,t);if(n===null)return`prompt log: task #${t} does not exist`;let o=cw(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 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}):
620
620
  ${i.prompt}`);return`prompt log #${t} ("${n.title}"):
621
621
 
622
622
  ${s.join(`
623
623
 
624
- `)}`}function IE(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=mw(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 CE(e,t,r={}){let n=fw(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 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}:
625
625
  ${o.join(`
626
- `)}`}function OE(e,t,r={}){if(_i(e.db.db,t,{reason:r.reason??null,expiresAt:r.expiresAt??null}),r.json)return JSON.stringify(gi(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 DE(e,t,r={}){let n=gi(e.db.db,t)!==null;return Pp(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 lD(e,t,r=Date.now()){return(t!==void 0?No(e.db.db).filter(o=>o.provider===t):No(e.db.db)).map(o=>({provider:o.provider,config:o,expired:!rt(e.db.db,o.provider,r).disabled}))}function ME(e,t,r={}){let n=lD(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 dD(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 mD(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=Di(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 PE(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 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
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=Ui(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,...dD(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(y=>y.provider===f.provider&&y.bucketId===f.bucketId&&y.resetsAt===f.resetsAt),h=p?` [ARMED rule=${p.rule}, forecast ${new Date(p.forecastAt).toISOString()}]`:"",_=f.stale?` [STALE, read ${me(f.ageMs)} ago]`:"",g=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"}${_}${g}${h}`),u.push(` ${mD(r,f.provider,f.bucketId,f.resetsAt)}`)}}return u.join(`
643
- `)}function UE(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=Ui(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 fD=[7,30],ju=3,pD=20,hD="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 gD(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 _D(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 wD(e){return(e.tokens_in_cached??0)+(e.tokens_in_uncached??0)+(e.tokens_cache_write??0)+(e.tokens_out??0)}function yD(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=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
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+wD(s),0)}function ED(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}function FE(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<pD}}function qE(e){let t=e.nowMs??Date.now(),r=[],n={},o=ED(e.lmautoDb,"lmbi_session_responses");for(let s of fD){let i=new Date(t-s*24*60*60*1e3).toISOString(),{rows:a,skippedUnattributable:c}=Hp(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-ju*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,R)=>S-R),f=FE(d.invocations),{doneCount:p,failedCount:h,contentionCount:_}=f,g=d.invocations.filter(S=>Date.parse(S.startedAtIso)>=u),y=FE(g),E=0,v=0;for(let S of d.invocations){if(S.outcome!=="done")continue;let R=yD(e.lmautoDb,S,o);R===null?v++:E+=R}r.push({provider:d.provider,model:d.model,windowDays:s,sampleSize:f.sampleSize,lowConfidence:f.lowConfidence,recentCompletionRate:y.completionRate,recentSampleSize:y.sampleSize,recentLowConfidence:y.lowConfidence,medianDurationMs:gD(m),p90DurationMs:_D(m),completionRate:f.completionRate,doneCount:p,failedCount:h,contentionCount:_,totalTokens:E,tokenJoinMisses:v,costUnavailableReason:hD})}}return{rows:r.sort((s,i)=>s.windowDays-i.windowDays||s.provider.localeCompare(i.provider)||(s.model??"").localeCompare(i.model??"")),skippedUnattributableByWindow:n}}function jE(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 ${ju}d unknown (n=${i.recentSampleSize})`:`last ${ju}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+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(`
649
649
  (${s.join("; ")} -- see tracked_invocation's own meta shape)`),n.join(`
650
- `).trimStart()}function HE(e,t={}){let r=On(t.lctlDbPath);try{let{rows:n,skippedUnattributableByWindow:o}=qE({lctlDb:r,lmautoDb:e.db.db});return t.json?JSON.stringify({rows:n,skippedUnattributableByWindow:o}):jE(n,o)}finally{r.close()}}async function BE(e,t={}){let r=await xu({configPath:e});return t.json?JSON.stringify(r):JSON.stringify(r,null,2)}import{execFile as TD}from"node:child_process";import{basename as bD}from"node:path";import{promisify as SD}from"node:util";var vD=SD(TD),AD=["lmplayer run","opencode run"];function $D(){return Kr[Kr.length-1]??"lmctl"}function kD(e){let t=e.lastIndexOf(":");if(t===-1)return[e];let r=e.slice(0,t),n=e.slice(t+1);return[e,`${bD(r)} ${n}`]}async function WE(e,t=Ae,r=vD){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=$D(),c=[`${a} chat`,`${a} terminal`,...AD],l=n.flatMap(kD),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 GE(e){return(e.otherTeamsRunning?.length??0)>0||e.externalWrapperProcessLines.length>0}function xD(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 VE(e,t={}){let r=t.exclude===void 0?[]:typeof t.exclude=="string"?t.exclude.split(","):t.exclude,n=xD(e),o=n===null?r:[n,...r],i=await(t.checkInFlightDispatchImpl??WE)(o),a=GE(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 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:
652
652
  ${c.join(`
653
- `)}${l}`}import{readFileSync as RD,statSync as JE}from"node:fs";function ma(e,t=RD){try{let r=t(`/proc/${e}/stat`,"utf8");return r.slice(r.lastIndexOf(")")+2).trim().split(/\s+/)[19]??null}catch{return null}}function ND(e,t=process.kill,r=ma){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 LD(e,t=JE){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 KE(e,t,r=process.kill,n=ma,o=JE){let s=ND(e,r,n),i=LD(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=ma(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 ID(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 YE(e,t,r={}){let n=KE({pid:e,startTicks:r.startTicks??null},t);return r.json?JSON.stringify({pid:e,...n}):ID(e,n)}function QE(e,t,r,n,o={}){return _w(e.db.db,t,r,n),o.json?JSON.stringify({name:t,teamfilePath:r,alias:n}):`logical name "${t}" -> ${r}:${n}`}function XE(e,t,r={}){let n=na(e.db.db,t);return r.json?JSON.stringify(n):n===null?`"${t}" is not registered`:`"${t}" -> ${n.teamfilePath}:${n.alias}`}function ZE(e,t={}){let r=ww(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 eT(e,t,r={}){let n=na(e.db.db,t)!==null;return yw(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 CD}from"node:child_process";import{promisify as OD}from"node:util";var dr=Ut(xt(),1),tT=OD(CD);async function DD(e){try{let[{stdout:t},{stdout:r}]=await Promise.all([tT("git",["-C",e,"log","--oneline","-1"],{timeout:1e4}),tT("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 MD(e,t){return H(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead":"Idle":"remote -- delivery only"}async function rT(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 DD(c.repoPath):{head:"(remote)",dirty:"-"},m=u?.confirmed_done_ts?"DONE(confirmed)":u?.progress_status??"?";return[(0,dr.escapeCell)(c.name),(0,dr.escapeCell)(MD(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 PD=8,UD=18e5;function Hu(e){return e.teams.filter(H).filter(t=>t.autoNudge)}function FD(e){let t=Hu(e);return t.length>0&&t.every(r=>ie(e.db.db,r.name)?.confirmed_done_ts)}async function nT(e,t={}){let r=await rs(e.db.db,Hu(e),t);return ns(r)}async function oT(e,t={}){let r=t.maxScans??PD,n=t.scanIntervalMs??UD,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i))),s="(no scans ran)";for(let i=1;i<=r;i++){let a=await rs(e.db.db,Hu(e),t);if(s=ns(a),a.wake)return`AUTOPILOT WAKE [${a.wake}]:
657
- ${s}`;if(FD(e))return`AUTOPILOT WAKE [all-done]:
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]:
658
658
  ${s}`;i<r&&await o(n)}return`AUTOPILOT WAKE [heartbeat]: exhausted ${r} scans with no wake condition
659
- ${s}`}function qD(e){let t=Lr(e.db.db);return{paused:t!==null,state:t}}function sT(e,t={}){let r=qD(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 iT(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(Wh(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 aT(e,t={}){let r=Lr(e.db.db)!==null;return Gh(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 cT(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=e.teams.find(y=>y.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(y=>y.alias===a))throw new Error(`send: "${a}" is not a configured member of team "${o}" -- actual members: ${l.map(y=>y.alias).join(", ")}`);let u=Cr("send",r,n.literal),d=n.send??Ht,m=n.probe??Go,f=n.nowMs??Date.now(),p=await d({teamfilePath:c,alias:a},u),h=Bn(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||ow(e.db.db,c,a,{kind:"evicted",remedy:`lctl refresh ${c} ${a}`})}catch{}else Yo(e.db.db,c,a)!==null&&sw(e.db.db,c,a);let _=p.kind==="ok"?p.replyText.split(`
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(`
662
662
  `).slice(-6).join(`
663
- `):"";return`${a===i.leadAlias?i.name:`${i.name}:${a}`}: ${h.status}${_?`
664
- ${_}`:""}`}import{spawnSync as HD}from"node:child_process";var BD=2e3,WD=3e4;async function lT(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(w=>w.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??BD,f=n.leaseMs??6e4,p=n.maxWaitMs??WD,h=n.fetchReport??Ae,_=n.spawnSyncImpl??HD,g=n.sleep??(C=>new Promise(w=>setTimeout(w,C))),y=n.now??Date.now,E=n.reason??null,v=n.pid??process.pid,S=y();if(Dm(e.db.db,a,u,v,new Date(S).toISOString(),E,f)===null){let C=ic(e.db.db,a,u,S),w=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 -- ${w}`,exitCode:1}}let x=[`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(!_m(d,u,C))break;if(y()-S>=p){L=!0;break}await g(m)}}finally{Pm(e.db.db,a,u,v)}if(L)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=_("lmctl",["terminal",d,u],{stdio:"inherit"}),B=k.status??(k.error?1:0);return{output:x.join(`
667
- `),exitCode:B}}import{readFileSync as pT}from"node:fs";import{basename as zD}from"node:path";import{execFileSync as uT}from"node:child_process";import{dirname as GD}from"node:path";var VD=new Set(["done","closed","cancelled"]);function JD(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}function KD(e){return GD(e)}function dT(e,t,r=uT){let n=Le(e,t);return mT(n,r)}function mT(e,t){let r={id:e.id,title:e.title,status:e.status};if(VD.has(JD(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=KD(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 fT(e,t,r=uT){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=>mT(i,r))}var _T=["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 pT(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 pT(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 fa(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 hT(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&&zD(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 gT(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}):QD(t,r)}function YD(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 QD(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(`
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(`
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 XD(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 ZD="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 wT(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||!gT(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=fa(r,"owner"),d=hT(r,o,u?.team),m=typeof r.status=="string"?r.status:void 0,f=gf(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=vf(e,{project:m});return{output:Rt(n,f),exitCode:0}}let c=fa(r,"owner"),l=r.kind;if(l!==void 0&&(typeof l!="string"||!gT(l)))throw new I("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 I("INVALID_ARGUMENT","audit requires exactly one of: an id, or --epic ID");let u=c!==void 0?fT(e,c):[dT(e,zt(l,"id"))];return n?{output:JSON.stringify({schema_version:1,ok:!0,data:u}),exitCode:0}:{output:XD(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=fa(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:Le(e,c).owner_team_path),m=hT(r,o,d),f=typeof r.status=="string"?r.status:void 0,p=Vs(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=fa(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}=yc(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"?bf(e,u,d):Sf(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 Le(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:ZD,exitCode:n?2:1}}}catch(s){if(s instanceof I)return YD(n,s);throw s}}var mt=Ut(xt(),1);var eM=20;function tM(e,t,r={}){let n=xs(e.teams,t),o=r.limit??eM,s=wu(e,{toId:t,limit:o}).rows,i=wu(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 yT(e,t,r={}){let n=tM(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 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(`
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 rM,readFileSync as nM,statSync as oM,writeFileSync as sM}from"node:fs";import{homedir as iM}from"node:os";import{basename as ET,dirname as TT,join as aM}from"node:path";function cM(){return aM(iM(),".lmbee","on-demand-teams.conf")}function bT(e,t,r,n={}){let o;try{o=oM(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(ET(r)!==`${t}.lmctl`)return{output:`error: teamfile must be named "${t}.lmctl" to match team name "${t}" (got "${ET(r)}") -- resolveTeamfilePath's own convention, not a new rule`,ok:!1};let s=n.alias??"Lead",i=TT(r),a=n.confPath??cM(),c="";try{c=nM(a,"utf8")}catch{}let l=c.split(/\r?\n/).filter(_=>_.trim().length>0&&!_.trim().startsWith("#")),u=_=>_.split(/\t+/)[0]?.trim()===t,d=l.some(u),m=l.filter(_=>!u(_)),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 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(`
680
680
  `)+`
681
- `;return rM(TT(a),{recursive:!0}),sM(a,p),Rs(e.db.db,a,"on-demand teams (lmbee team register)"),wo(p).some(_=>_.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 ST(e,t={}){let n=await(t.fetchReport??Ae)(),o=Is(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 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]
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 $T(e){if(e.length===0)return!0;let[t,r]=e;return t==="-h"||t==="--help"||t==="help"?!0:r==="-h"||r==="--help"}var lM=new Set(["status","oversee","history","teams","attention","stalled","in-flight"]);function kT(e){let[t,r]=e;return lM.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 vT=`usage: lmbee queue <command> [args]
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]
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".`,AT={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 xT(e,t){if(t.length===0)return{output:`${Ur}
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
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 oT(e),exitCode:0};case"once":return{output:await nT(e),exitCode:0};case"watch":{let a=await ST(e);return{output:a.text,exitCode:a.changed?10:0}}case"status":return{output:await iy(e,{live:s.live===!0,json:i}),exitCode:0};case"oversee":return{output:await rT(e,{only:o}),exitCode:0};case"state":{let[a,...c]=o;return a==="list"?{output:ey(e,{json:i,nonDone:s["non-done"]===!0}),exitCode:0}:a==="get"?c[0]===void 0?X("usage: lmbee state get <team>"):{output:ty(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:ry(e,c[0],c[1],c.slice(2).join(" ")),exitCode:0}:a==="active"?{output:sy(e,{json:i}),exitCode:0}:a==="confirm-done"?c[0]===void 0?X("usage: lmbee state confirm-done <team> [note]"):{output:ny(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 oy(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 Rw(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:NE(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:LE(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 _=typeof s.task=="string"?Number(s.task):NaN;if(typeof s.task!="string"||!Number.isInteger(_)||_<=0)return X(`prompt reassign: --task must be a positive integer task id; ${a}`);let g=typeof s.by=="string"?s.by:void 0;return g===void 0?X(`prompt reassign: --by is required; ${a}`):{output:IE(e,h,_,{by:g}),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:CE(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:RE(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?AT[a]:void 0;if(l!==void 0){if(s.help===!0)return{output:`${l.usage}
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}
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:Nw(e,c[0],{json:i}),exitCode:0};if(a==="get")return c[0]===void 0?X("usage: lmbee queue get <id>"):{output:Lw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="deliver")return{output:await Hw(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:Bw(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:Ww(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:Kw(e,c[0],{json:i}),exitCode:0};if(a==="doctor")return{output:Yw(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:Iw(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 _=u.split(",").map(Number);return Ow(e,_,f,d.join(" "),{json:i,literal:p})}return Cw(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):Mw(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):Dw(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 Fw(e,c[0],u,{json:i})}if(a==="resume")return c[0]===void 0?X("usage: lmbee queue resume <team>"):qw(e,c[0],{json:i});if(a==="pause-status")return jw(e,c[0],{json:i});if(a==="owed")return c[0]===void 0?X("usage: lmbee queue owed <team> [--ids]"):{output:Gw(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="pull"){let u=AT.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: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
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:Jw(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:Vw(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>"):Pw(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):Uw(e,Number(u),p,{json:i})}return s.help===!0?{output:`${vT}
868
- `,exitCode:0}:X(vT)}case"nudge":return o.length===0?X("usage: lmbee nudge <team> [team2 ...]"):{output:await AE(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 cT(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 lT(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:tw(e,c,l,{json:i}),exitCode:0}}case"teams":return{output:ay(e,{json:i}),exitCode:0};case"in-flight":{let a=typeof s.exclude=="string"?s.exclude:void 0;return{output:await VE(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:YE(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:QE(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:XE(e,c,{json:i}),exitCode:0}:a==="list"?{output:ZE(e,{json:i}),exitCode:0}:a==="clear"?c===void 0?X("usage: lmbee logical-name clear <name>"):{output:eT(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 Qi(e,{team:a,maintainer:c,stuckProcessingFleetWide:l});return{output:Jo(u,{json:i}),exitCode:0}}case"stalled":{if(o.length>1)return X("usage: lmbee stalled [team] [--json]");let a=Xn(s["idle-threshold-ms"],"--idle-threshold-ms"),c=Xn(s["cooldown-ms"],"--cooldown-ms");if(a instanceof Error)return X(a.message);if(c instanceof Error)return X(c.message);let l=await wE(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=bT(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=Xn(s.limit,"--limit");return c instanceof Error?{output:`error: ${c.message}`,exitCode:1}:c!==void 0&&(c<1||c>To)?{output:`error: --limit must be a positive integer <= ${To}`,exitCode:1}:{output:yT(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=sa(e,c[0],c.slice(1).join(" ")||void 0);return{output:l.output,exitCode:l.ok?0:1}}return a==="list"?{output:Qw(e,{json:i}),exitCode:0}:a==="remove"?c[0]===void 0?X("usage: lmbee source remove <path>"):{output:Xw(e,c[0]),exitCode:0}:X("usage: lmbee source add <path> [label...] | list | remove <path>")}case"mail":{let[a]=o;return a==="status"?{output:nw(e,{json:i}),exitCode:0}:X("usage: lmbee mail status")}case"scan":{let[a]=o;if(a==="status")return{output:sT(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:iT(e,{...c!==void 0?{actor:c}:{},...l!==void 0?{note:l}:{},...u!==void 0?{resumeAfter:u}:{},json:i}),exitCode:0}}return a==="start"?{output:aT(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:xE(e,c,{json:i}),exitCode:0};if(a==="clear")return c===void 0?X("usage: lmbee auto-nudge-redirect clear <team>"):{output:kE(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:$E(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:ME(e,c,{json:i}),exitCode:0};if(a==="enable")return c===void 0?X("usage: lmbee provider enable <name>"):{output:DE(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:OE(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:PE(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:UE(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:HE(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 BE(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",..._T]),c=wT(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",...SE]),c=await bE(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 NU,readFile as LU,stat as IU,writeFile as CU}from"node:fs/promises";import{mkdir as bM,readFile as GT,stat as SM,writeFile as vM}from"node:fs/promises";import{readFileSync as AM}from"node:fs";import{homedir as $M}from"node:os";import{dirname as kM,extname as xM}from"node:path";var KT="https://lmctl.ai/tools/lmchat";async function zT(e,t={}){let r=jM(t),n=Vu(e);if(n.kind==="whoami"){r.stdout(qM(r.env,n.api));return}if(n.kind==="login"){let{runLogin:s}=await Promise.resolve().then(()=>(WT(),BT));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=PM(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 VT(r,o,n),n.kind==="post"){let s=await RM(r,o,n);r.stdout(String(s));return}if(n.kind==="say"){let s=await NM(r,o,n);r.stdout(String(s));return}if(n.kind==="list"){await VT(r,o,{...n,kind:"read"});return}if(n.kind==="get"){await IM(r,o,n),r.stdout(`saved ${n.out}`);return}if(n.kind==="delete"){let s=await CM(r,o,n);r.stdout(`deleted ${s}`);return}if(n.kind==="delete-room"){let s=await OM(r,o,n);r.stdout(`deleted room ${s}`);return}}function Vu(e){let t=[...e],r=De(t,"--api"),n=t.shift();if(!n||n==="help"||n==="--help"||n==="-h")throw new Qt(JT());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=ha(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=ha(t,"--follow"),u=ha(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=Wu(t,"--name"),a=Wu(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=ha(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=Wu(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}
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}
871
871
 
872
- ${JT()}`)}async function RM(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??FM(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 NM(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 VT(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 LM(e,t,r.roomName,n,r.limit);r.follow?r.json?c.files.length>0&&e.stdout(JSON.stringify(c.files)):(i||(QT(e.stdout),i=!0),XT(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)):UM(e.stdout,a);return}await DM(s)}}}async function LM(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 IM(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 Gu(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 Gu(s,"presigned download failed");let i=new Uint8Array(await s.arrayBuffer());await e.mkdir(kM(r.out),{recursive:!0}),await e.writeFile(r.out,i)}async function CM(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 OM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}`,{method:"DELETE",headers:mr(e.env)})).room_name}function DM(e){return new Promise(t=>setTimeout(t,e))}async function Fr(e,t,r){let n=await e(t,r);return await Gu(n,"API request failed"),await n.json()}async function Gu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function MM(e){return YT(e).appkey}function YT(e){if(ga(e.LMCTL_APPKEY))return{appkey:e.LMCTL_APPKEY,source:"LMCTL_APPKEY"};let t=e.LMCTL_APPKEY_FILE?.trim();if(t){let s=Bu(t);if(s)return{appkey:s,source:"LMCTL_APPKEY_FILE"}}let r=e.XDG_CONFIG_HOME?.trim()||`${$M()}/.config`,n=Bu(`${r}/lmctl/appkey.json`);if(n)return{appkey:n,source:"~/.config/lmctl/appkey.json"};let o=Bu(`${r}/lmctl/lmchat-apikey`);if(o)return{appkey:o,source:"~/.config/lmctl/lmchat-apikey (legacy)"};if(ga(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 ga(e){return!!(e&&e===e.trim()&&!/[\u0000-\u001f\u007f]/.test(e))}function Bu(e){let t;try{t=AM(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 ga(o)?o:void 0}catch{return}return ga(r)?r:void 0}}function mr(e){return{authorization:`Bearer ${MM(e)}`}}function PM(e,t){return(e??t.LMCHAT_API_URL??KT).replace(/\/+$/,"")}function UM(e,t){QT(e),XT(e,t)}function QT(e){e("seq name size content_type created_at")}function XT(e,t){for(let r of t)e(`${r.seq} ${r.name} ${r.size} ${r.content_type} ${r.created_at}`)}function FM(e){let t=xM(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 qM(e,t){let r="unset";try{r=YT(e).source}catch{r="unset"}return[`API: ${t??e.LMCHAT_API_URL??KT}`,`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 ha(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 Wu(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 jM(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?GT(t,{encoding:r}):GT(t)),writeFile:e.writeFile??((t,r)=>vM(t,r)),mkdir:e.mkdir??((t,r)=>bM(t,r)),stat:e.stat??(t=>SM(t))}}function JT(){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 eP,readFile as tP,stat as rP,writeFile as nP}from"node:fs/promises";import{basename as oP,extname as sP,join as iP}from"node:path";async function _b(e,t={}){let r=hP(t),n=Ju(e);if(n.kind==="whoami"){r.stdout(dP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:a}=await Promise.resolve().then(()=>(pb(),fb));if(await a({env:r.env})!==0)throw new Error("login failed");return}let o=uP(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(()=>aP(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:cP(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=hb(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=iP(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,hb(n.seq))),r.stdout(`deleted ${n.seq}`))}function Ju(e){let t=[...e],r=eo(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new fr(gb());if(n==="login"||n==="whoami"||n==="mailboxes")return Zn(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=un(t,"mailbox");return Zn(t),{kind:"create",mailbox:o,...r?{api:r}:{}}}if(n==="send"){let o=un(t,"mailbox"),s=pP(t,"--file"),i=eo(t,"--subject"),a=fP(t,"--attach");return Zn(t),{kind:"send",mailbox:o,file:s,attachments:a,...i?{subject:i}:{},...r?{api:r}:{}}}if(n==="list"){let o=un(t,"mailbox"),s=eo(t,"--status"),i=eo(t,"--after");return Zn(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=eo(t,"--out")??".";return Zn(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 Zn(t),{kind:"delete",mailbox:o,seq:s,...r?{api:r}:{}}}throw new fr(`unknown command: ${n}
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}
875
875
 
876
- ${gb()}`)}async function aP(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:oP(s),contentType:mP(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 wb(o,r.status,r.responseBody)}}function hb(e){if(!/^[1-9]\d*$/.test(e))throw wa("seq_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw wa("seq_invalid");return t}function cP(e){if(!/^(0|[1-9]\d*)$/.test(e))throw wa("after_invalid");let t=Number(e);if(!Number.isSafeInteger(t))throw wa("after_invalid");return t}function wa(e){return wb("API request failed",400,JSON.stringify({error:e}))}function wb(e,t,r){return new Error(`${e}: ${t}${r?` ${r}`:""}`)}function lP(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 uP(e,t){let r=e??t.LMMAIL_API_URL;if(!r)throw new Error("missing LMMAIL_API_URL or --api");return r.replace(/\/+$/,"")}function dP(e,t){return[`API: ${t??e.LMMAIL_API_URL??"unset (set --api or LMMAIL_API_URL)"}`,`appkey source: ${lP(e)}`,"identity: derived server-side from the shared appkey"].join(`
877
- `)}function mP(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"}[sP(e).toLowerCase()]??"application/octet-stream"}function eo(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 fP(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 pP(e,t){let r=eo(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 Zn(e){if(e.length)throw new fr(`unexpected argument: ${e[0]}`)}function hP(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>tP(t)),writeFile:e.writeFile??((t,r)=>nP(t,r)),mkdir:e.mkdir??((t,r)=>eP(t,r)),stat:e.stat??(t=>rP(t))}}function gb(){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 xP,readFile as RP,stat as NP,writeFile as LP}from"node:fs/promises";import{dirname as IP,extname as CP}from"node:path";async function Mb(e,t={}){let r=HP(t),n=zu(e);if(n.kind==="whoami"){r.stdout(FP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(Ob(),Cb));if(await i({env:r.env})!==0)throw new Error("login failed");return}let o=PP(n.api,r.env),s=UP(r.env);if(n.kind==="push"||n.kind==="update"){await OP(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 ls(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 ls(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"GET",headers:s}),a=await r.fetch(i.download_url);await Yu(a,"presigned download failed");let c=new Uint8Array(await a.arrayBuffer());n.out?(await r.mkdir(IP(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 ls(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"DELETE",headers:s}),r.stdout(`deleted ${n.name}`))}function zu(e){let t=[...e],r=cs(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new qr(Db());if(n==="login"||n==="whoami")return as(t),{kind:n,...r?{api:r}:{}};if(n==="push"||n==="update"){let o=Ku(t,"name"),s=jP(t,"--file");return as(t),{kind:n,name:o,file:s,...r?{api:r}:{}}}if(n==="list"){let o=cs(t,"--after"),s=cs(t,"--limit");return as(t),{kind:"list",...o?{after:o}:{},...s?{limit:s}:{},...r?{api:r}:{}}}if(n==="read"){let o=Ku(t,"name"),s=cs(t,"--out");return as(t),{kind:"read",name:o,...s?{out:s}:{},...r?{api:r}:{}}}if(n==="delete"){let o=Ku(t,"name");return as(t),{kind:"delete",name:o,...r?{api:r}:{}}}throw new qr(`unknown command: ${n}
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}
879
879
 
880
- ${Db()}`)}async function OP(e,t,r,n){let o=await e.stat(n.file);if(!o.isFile())throw new Error(`not a file: ${n.file}`);let s=qP(n.file),i=n.kind==="push"?`${t}/notes`:`${t}/notes/${encodeURIComponent(n.name)}`,a=await ls(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 Yu(u,"S3 upload failed");let d=a.finalize_url.startsWith("http")?a.finalize_url:`${t}${a.finalize_url.startsWith("/")?"":"/"}${a.finalize_url}`;await ls(e.fetch,d,{method:"POST",headers:{...r,"content-type":"application/json"},body:JSON.stringify({operation_token:a.operation_token})})}function DP(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 MP(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 PP(e,t){let r=e??t.LMNOTE_API_URL;if(!r)throw new Error("missing LMNOTE_API_URL or --api");return r.replace(/\/+$/,"")}function UP(e){return{authorization:`Bearer ${DP(e)}`}}function FP(e,t){return[`API: ${t??e.LMNOTE_API_URL??"unset (set --api or LMNOTE_API_URL)"}`,`appkey source: ${MP(e)}`,"notebook identity: derived server-side from the shared appkey"].join(`
881
- `)}function qP(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"}[CP(e).toLowerCase()]??"application/octet-stream"}async function ls(e,t,r){let n=await e(t,r);return await Yu(n,"API request failed"),n.json()}async function Yu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function cs(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 jP(e,t){let r=cs(e,t);if(!r)throw new qr(`missing required ${t}`);return r}function Ku(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new qr(`missing ${t}`);return r}function as(e){if(e.length)throw new qr(`unexpected argument: ${e[0]}`)}function HP(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>RP(t)),writeFile:e.writeFile??((t,r)=>LP(t,r)),mkdir:e.mkdir??((t,r)=>xP(t,r)),stat:e.stat??(t=>NP(t))}}function Db(){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 nS(e,t={}){let r=t.fetch??fetch,n=t.env??process.env,o=t.stdout??(l=>console.log(l)),s=Qu(e);if(s.kind==="whoami"){o(sU(n,s.api));return}if(s.kind==="login"){let{runLogin:l}=await Promise.resolve().then(()=>(Xb(),Qb));if(await l({env:n})!==0)throw new Error("login failed");return}let i=nU(s.api,n),a=oU(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} ${Zb(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 ${Zb(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 Qu(e){let t=[...e],r=to(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new er(rS());if(n==="login"||n==="whoami"||n==="sheets")return Zt(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=ot(t,"name"),s=iU(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=to(t,"--after"),i=to(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=to(t,"--row"),i=eS(tS(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=eS(tS(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
+ ${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}
883
883
 
884
- ${rS()}`)}function tU(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 rU(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 nU(e,t){let r=e??t.LMSHEET_API_URL;if(!r)throw new Error("missing LMSHEET_API_URL or --api");return r.replace(/\/+$/,"")}function oU(e){return{authorization:`Bearer ${tU(e)}`}}function sU(e,t){return[`API: ${t??e.LMSHEET_API_URL??"unset (set --api or LMSHEET_API_URL)"}`,`appkey source: ${rU(e)}`,"sheet identity: derived server-side from the shared appkey"].join(`
885
- `)}function Zb(e){return e.map(t=>`${t.letter}:${t.label}`).join(",")}function eS(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 to(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 tS(e,t){let r=[];for(;e.includes(t);){let n=to(e,t);n!==void 0&&r.push(n)}return r}function iU(e,t){let r=to(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 rS(){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 yU,stat as EU}from"node:fs/promises";import{basename as ES,extname as TU}from"node:path";async function TS(e,t={}){let r=RU(t);if(!e.length||["help","-h","--help"].includes(e[0]??"")){r.stdout(Zu());return}let n=ed(e);if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(yS(),wS));if(await i({env:r.env})!==0)throw new Error("login failed");return}if(n.kind==="whoami"){let i=bU(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=SU(n.api,r.env),s=vU(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=kU(n.file),c=await ro(r.fetch,`${o}/transcriptions`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({file_name:ES(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}),ES(n.file));let d=await r.fetch(c.upload_url,{method:"POST",body:u});if(await $U(d,"S3 upload failed"),await ro(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 ro(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 ro(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 ro(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 ro(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"DELETE",headers:s});r.stdout(JSON.stringify(i,null,2));return}}function ed(e){let t=[...e],r=ms(t,"--api"),n=t.shift();if(!n||["help","-h","--help"].includes(n))throw new dn(Zu());if(n==="login"||n==="whoami")return fs(t),{kind:n,...r?{api:r}:{}};if(n==="transcribe"){let o=Xu(t,"file"),s=ms(t,"--language"),i=xU(t,"--wait");return fs(t),{kind:"transcribe",file:o,...s?{language:s}:{},wait:i,...r?{api:r}:{}}}if(n==="list"){let o=ms(t,"--status"),s=ms(t,"--after"),i=ms(t,"--limit");return fs(t),{kind:"list",...o?{status:o}:{},...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="get"){let o=Xu(t,"id");return fs(t),{kind:"get",id:o,...r?{api:r}:{}}}if(n==="delete"){let o=Xu(t,"id");return fs(t),{kind:"delete",id:o,...r?{api:r}:{}}}throw new dn(`unknown command: ${n}
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}
887
887
 
888
- ${Zu()}`)}function bU(e){try{return{source:Se({env:e}).source}}catch(t){return t instanceof Gr?{source:"unset"}:{source:"unset"}}}function SU(e,t){let r=e??t.LMTEXT_API_URL;if(!r)throw new Error("missing LMTEXT_API_URL or --api");return r.replace(/\/+$/,"")}function vU(e){return{authorization:`Bearer ${AU(e)}`}}function AU(e){return Se({env:e}).appkey}async function ro(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 $U(e,t){if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status} ${r}`)}}function kU(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"}[TU(e).toLowerCase()]??"application/octet-stream"}function ms(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 xU(e,t){let r=e.indexOf(t);return r<0?!1:(e.splice(r,1),!0)}function Xu(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new dn(`missing ${t}`);return r}function fs(e){if(e.length)throw new dn(`unexpected argument: ${e[0]}`)}function Zu(){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 RU(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>process.stdout.write(`${t}
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}
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=>yU(t)),stat:e.stat??(t=>EU(t))}}var dn=class extends Error{};var ps=class extends Error{status;responseBody;constructor(t,r){super(`HTTP ${t}${r?` ${r}`:""}`),this.status=t,this.responseBody=r,this.name="HttpResponseError"}},no=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"}},oo=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"}},so=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 ba(e){if(!e.ok)throw new ps(e.status,await e.text().catch(()=>""))}var bS=Object.freeze({lmchat:io("https://lmctl.ai/tools/lmchat","LMCTL_LMCHAT_API_URL","LMCHAT_API_URL"),lmmail:io("https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMMAIL_API_URL","LMMAIL_API_URL"),lmnote:io("https://vijni9tfxh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMNOTE_API_URL","LMNOTE_API_URL"),lmsheet:io("https://9zdvg8wfjh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMSHEET_API_URL","LMSHEET_API_URL"),lmtext:io("https://bxdbjn5k90.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMTEXT_API_URL","LMTEXT_API_URL"),lmsound:io("https://lmctl.ai/tools/lmsound","LMCTL_LMSOUND_API_URL")});function td(e,t){let r=bS[e];return(t[r.overrideEnv]?.trim()||r.defaultUrl).replace(/\/+$/,"")}function SS(e,t){let r=bS[e];return{...t,[r.serviceEnv]:td(e,t)}}function io(e,t,r){return{defaultUrl:e,overrideEnv:t,...r?{serviceEnv:r}:{}}}var OU={lmchat:(e,t)=>zT(e,t),lmmail:(e,t)=>_b(e,t),lmnote:(e,t)=>Mb(e,t),lmsheet:(e,t)=>nS(e,t),lmtext:(e,t)=>TS(e,t)},DU={lmchat:Vu,lmmail:Ju,lmnote:zu,lmsheet:Qu,lmtext:ed},MU=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 vS(e,t,r={}){let n=r.env??process.env,o=r.stdout??(g=>process.stdout.write(g)),s=r.stderr??(g=>process.stderr.write(g)),i=r.resolveAppkeyImpl??Se,a=r.serviceRunners??OU,c=r.serviceParsers??DU,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 g=m[0];if(g!==void 0&&MU[e].has(g)&&!d)return o(`lmbee ${e}: refusing to run "${g}" without --force -- this permanently deletes data. Re-run with --force to proceed.
892
- `),1}let p=m.length===0?["--help"]:m,h=process.exitCode,_;try{let g=SS(e,n);if(!f){try{c[e](p)}catch(S){throw S instanceof Error&&S.constructor.name==="UsageError"?new oo(e,S):S}g.LMCTL_APPKEY=i({env:n}).appkey}let E=PU(g,o,s,async(S,R)=>{let x=await l(S,R);return x.ok||(_=x.status),x});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 so(e,S)}return 0}catch(g){if(f)return o(`${FU(g)}
893
- `),0;throw _!==void 0&&!UU(g)?new no(e,_,g):g}finally{process.exitCode=h}}function PU(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=>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}
894
894
  `),stderr:o=>r(`${o}
895
- `),sleep:o=>new Promise(s=>setTimeout(s,o)),readFile:(o,s)=>LU(o,s),writeFile:(o,s)=>CU(o,s),mkdir:(o,s)=>NU(o,s),stat:o=>IU(o)}}function UU(e){return!!(e&&typeof e=="object"&&"status"in e&&typeof e.status=="number")}function FU(e){return e instanceof Error?e.message:String(e)}import{writeFile as qU}from"node:fs/promises";function ao(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 jU(){return["usage:",' lmbee lmsound speak "text" [--voice ID] [--engine ENGINE] [--format FORMAT] [--out FILE]'," lmbee lmsound voices"].join(`
896
- `)}function Sa(e,t){return ao(e,t,r=>new pr(r))}function HU(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=Sa(t,"--voice"),s=Sa(t,"--engine"),i=Sa(t,"--format"),a=Sa(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 AS(e,t={}){if(e.length===0||e.length===1&&(e[0]==="--help"||e[0]==="-h"))return jU();let r=t.env??process.env,n=t.resolveAppkeyImpl??Se,o=t.fetchImpl??fetch,s=t.writeFileImpl??qU,i=HU(e),a=n({env:r}).appkey,c=td("lmsound",r),l={authorization:`Bearer ${a}`};if(i.kind==="voices"){let f=await o(`${c}/voices`,{headers:l});await ba(f);let p=await f.json(),h=["id name language gender engines"];for(let _ of p.voices??[])h.push(`${_.id} ${_.name} ${_.language_code} ${_.gender} ${_.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 ba(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 ba(m),await s(i.out,new Uint8Array(await m.arrayBuffer())),`saved ${i.out}`}var BU=new Set(["lmchat","lmmail","lmnote","lmsheet","lmtext"]);function $S(e){return BU.has(e)}async function kS(e,t){try{return await vS(e,[...t])}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
898
- `),RS(r)}}async function xS(e){try{return{output:await AS(e),exitCode:0}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:RS(t)}}}function RS(e){if(e instanceof oo||e instanceof pr)return 2;if(e instanceof so)return WU(e.exitCode);if(e instanceof Gr||e instanceof ws)return 3;if(e instanceof sr||e instanceof ys)return 4;let t=e instanceof ps||e instanceof no?e.status:void 0;return t===401||t===403?3:GU(e)?4:1}function WU(e){return Number.isInteger(e)&&e>0&&e<=255?e:1}function GU(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 EF}from"node:crypto";import{randomUUID as JU}from"node:crypto";import{hostname as KU,userInfo as zU}from"node:os";var YU=120,NS=60,QU=20,XU=1e3,ZU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function rd(e,t,r){try{await e.createMailbox(t,{tolerate409:!1});return}catch(o){if(!eF(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 eF(e){if(!e||typeof e!="object")return!1;let t=e;return t.status===409&&t.code==="mailbox_exists"}async function nd(e,t){let r=Ql({v:1,type:Yl,id:t.id,command:t.command,timeout_s:t.timeoutSeconds??NS,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 od(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 tF(e,t,l,d,c);for(let f of m.messages){let p=sF(f.subject,i);if(p)try{let h=await oF(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(XU,u))}return a}async function tF(e,t,r,n,o){let s=o.supported?Math.min(QU,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||!rF(a))throw a;return o.supported=!1,await e.listMessages(t,{status:"unread",after:r})}}function rF(e){let t=e;return t?.status===400&&t.code==="wait_s_invalid"}function LS(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 IS(e){return LS(e,"fleet")}function nF(e){return ZU.test(e)?yn(e.toLowerCase()):e}async function oF(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=y_(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 sF(e,t){for(let r of t)if(e===Xl(r))return r}var It=class extends Error{};async function CS(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(R=>setTimeout(R,S))),c=r.username??(()=>zU().username),l=r.hostname??KU,u=r.waitSeconds??YU;if(!Number.isFinite(u)||u<=0)throw new It("--wait-s must be positive");let d=r.replyMailbox??(n.LMEXEC_REPLY_MAILBOX?.trim()||LS(c(),l())),{appkey:m}=o({env:n}),f=s({apiUrl:$t(n),appkey:m}),p=JU();await rd(f,d,a),await nd(f,{id:p,daemonMailbox:nF(e),command:t,replyMailbox:d,timeoutSeconds:NS});let h=[],_=i()+Math.round(u*1e3),y=(await od(f,d,new Set([p]),_,{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(!y)return{stdout:"",stderr:`${h.join("")}[lmbee exec] timed out waiting for a reply
900
- `,exitCode:124};let E=y.result.v===2?` trust=${y.result.sender_trust} sender=${y.result.sender}`:"",v=`[lmbee exec] exit=${y.result.exit_code===null?"timeout":y.result.exit_code} duration_ms=${y.result.duration_ms} truncated=${y.result.truncated}${E}
901
- `;return{stdout:y.stdout,stderr:`${y.stderr}${v}`,exitCode:y.result.exit_code??124}}import{randomUUID as iF}from"node:crypto";import{mkdir as aF,readFile as cF,rename as lF,rm as uF,writeFile as dF}from"node:fs/promises";import{dirname as MS,join as mF}from"node:path";var PS=2,fF=/^[A-Za-z0-9_-]+$/,sd=/^[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 US(){return mF(MS(ar()),"lmt-peers.json")}function tr(e,t){if(!sd.test(e))throw new Me(`${t} must be a UUID`);return e.toLowerCase()}function id(e){return sd.test(e)}function FS(e){return va(e,"peer alias")}function va(e,t){if(e.length>128||!fF.test(e))throw new Me(`${t} must match [A-Za-z0-9_-]+`);if(sd.test(e))throw new Me(`${t} must not be a UUID`);return e}function hs(e,t){try{return mm(e,t)}catch(r){throw new Me(r instanceof Error?r.message:String(r))}}function OS(){return Object.create(null)}async function gs(){let e=US(),t;try{t=await cF(e,"utf8")}catch(i){if(i.code==="ENOENT")return OS();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!==PS||!n.peers||typeof n.peers!="object"||Array.isArray(n.peers))throw new Error(`peer registry is invalid: ${e}`);let o=OS(),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=hs(l,DS(c.mailbox,`peer registry has invalid mailbox for ${i}`)),d=c.alias===void 0?void 0:FS(DS(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 qS(e){let t=US(),r={v:PS,peers:e},n=`${t}.${process.pid}.${iF()}.tmp`;await aF(MS(t),{recursive:!0});let o=!1;try{await dF(n,`${JSON.stringify(r,null,2)}
902
- `),await lF(n,t),o=!0}finally{if(!o)try{await uF(n)}catch(s){if(s.code!=="ENOENT")throw s}}}function pF(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 jS(e,t){for(let[r,n]of Object.entries(t))if(n.alias===e)return{siteUuid:tr(r,"wire site-uuid"),mailbox:hs(r,n.mailbox)}}function DS(e,t){if(typeof e!="string")throw new Error(t);return e}async function HS(){let e=await gs(),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 BS(e,t,r){let n=tr(e,"site-uuid"),o=hs(n,t),s=await gs(),i=s[n],a=r===void 0?i?.alias:FS(r);return pF(s,n,a),s[n]=a===void 0?{mailbox:o}:{mailbox:o,alias:a},await qS(s),`peer ${n}${a?` (${a})`:""} -> ${o}`}async function WS(e){let t=tr(e,"site-uuid"),r=await gs();if(!Object.hasOwn(r,t))throw new Error(`unknown peer site-uuid: ${t}`);return delete r[t],await qS(r),`removed peer ${t}`}function co(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 cd(e){try{return Ka(e)}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function hF(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 GS(e,t={}){let r=cd(e),n=t.siteUuid===void 0?await Ms(ar()):tr(t.siteUuid,"--site-uuid"),o=t.mailbox??hn(n),s=co(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 VS(e,t={}){let r=cd(e),n=co(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 Aa(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=JS(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 JS(e){return e.site_uuid?`uuid#${e.site_uuid.toLowerCase()}`:`mailbox#${e.mailbox}#${e.owner_user_id}`}function gF(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 _F(e,t){let r=new Set(e.flatMap(gF));return t.filter(n=>!r.has(JS(n))&&!r.has(`mailbox#${n.mailbox}#${n.owner_user_id}`))}function ad(e){return e.display_name??e.registered_name??e.site_name}function wF(e,t){let r=["REGISTERED","display-name registered-name site-uuid content-mailbox exec-mailbox"];for(let n of e.sort((o,s)=>ad(o).localeCompare(ad(s))))r.push([ad(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 KS(e={}){let t=co(e),r=await Aa(t);return wF(r.sites,_F(r.sites,r.discovered))}async function yF(e,t){let r=await Aa(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 yF(e,hF(r))}async function YS(e,t){let r=e.trim();if(!r)throw new Me("site display name must be non-empty");let n=co(t),o=await zS(n,t.uuid,t.mailbox),s=await n.setSiteName(o,r);return`named ${s.site_key} -> ${s.name}`}async function QS(e){let t=co(e),r=await zS(t,e.uuid,e.mailbox);return`cleared ${(await t.deleteSiteName(r)).site_key}`}async function XS(e,t={}){let r=cd(e);return await co(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 TF=15,bF=60,SF="lmbee status --live --json";async function ZS(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??TF;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 Aa(l)).sites.sort((m,f)=>m.site_name.localeCompare(f.site_name)),d=IS(i());await rd(l,d,s);try{let m=u.map(v=>({site:v,execMailbox:yn(v.site_uuid),id:EF(),sentAt:o()}));await Promise.all(m.map(async v=>{try{await nd(l,{id:v.id,daemonMailbox:v.execMailbox,command:SF,replyMailbox:d,timeoutSeconds:bF})}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 od(l,d,p,f,{now:o,sleep:s}),_=m.filter(v=>v.sendError===void 0).length,g=h.size,y=u.length===0?"empty":g===u.length?"all":g===0?"none":"partial";return{verdict:y,exit_code:y==="none"?2:y==="partial"?3:0,sent:_,answered:g,sites:m.map(v=>vF(v,h.get(v.id))),generated_at:new Date(o()).toISOString()}}finally{await l.deleteMailbox(d)}}function vF(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=AF(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 AF(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 ev(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??"-",$F(r.status)??"-",kF(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 $F(e){return Array.isArray(e?.teams)?e.teams.length:void 0}function kF(e){return typeof e?.live=="boolean"?`live:${e.live}`:void 0}function tv(){return"usage: lmbee exec <site-uuid-or-mailbox> [--wait-s N] <command...> | lmbee exec <site-uuid-or-mailbox> [--wait-s N] -- <literal command...>"}function ld(){return"usage: lmbee fleet status [--json] [--wait-s N]"}function rv(e,t){return ao(e,t,r=>new It(r))}function xF(e){let t=e.indexOf("--"),r=t<0?[...e]:[...e.slice(0,t)],n=t<0?void 0:e.slice(t+1),o=rv(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(tv());let a=n??r;if(n&&r.length>0)throw new It(`unexpected argument before --: ${r[0]}`);if(a.length===0)throw new It(tv());return{target:i,command:a.join(" "),...s===void 0?{}:{waitSeconds:s}}}async function nv(e){try{let{target:t,command:r,waitSeconds:n}=xF(e),o=await CS(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 ov(e){let[t,...r]=e;if(t!=="status")return{output:ld(),exitCode:1};let n=r.includes("--json");try{let o=[...r],s=o.indexOf("--json");n&&o.splice(s,1);let i=rv(o,"--wait-s"),a=i===void 0?void 0:Number(i);if(a!==void 0&&(!Number.isFinite(a)||a<=0))return{output:ld(),exitCode:1};if(o.length>0)return{output:ld(),exitCode:1};let c=await ZS({waitSeconds:a});return{output:n?JSON.stringify(c,null,2):ev(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 $a,existsSync as Hr,mkdirSync as RF,readFileSync as ud,readdirSync as NF,rmSync as sv,statSync as iv}from"node:fs";import{homedir as lv}from"node:os";import{join as Xe,sep as dd}from"node:path";var lo=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"}},md=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 uv(){return Xe(lv(),".lmauto")}function dv(){return Xe(process.env.LMCTL_HOME??Xe(lv(),".lmctl"),"lmauto")}function LF(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function IF(e){try{return(await fetch(`http://127.0.0.1:${e}/api/teams`,{signal:AbortSignal.timeout(1e3)})).body?.cancel(),!0}catch{return!1}}function CF(e,t){let r=Xe(e,"serve.pid");if(!Hr(r))return null;let n=ud(r,"utf8").trim(),o=Number(n);return!Number.isInteger(o)||o<=0?null:t(o)?o:null}var av=["team_state","kv","events","queue","sources","team_progress","mail_ledger","mail_outbound_ledger"];function cv(e,t){return e.prepare(`SELECT COUNT(*) as n FROM ${t}`).get().n}function fd(e){if(!Hr(e))return 0;let t=0;for(let r of NF(e,{withFileTypes:!0}))r.isDirectory()?t+=fd(Xe(e,r.name)):t+=1;return t}function OF(e,t,r){let n=t.endsWith(dd)?t:t+dd,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 mv(e){let{sourceDir:t,targetDir:r,port:n=4173}=e,o=e.isDaemonAlive??LF,s=e.probeHttpAlive??IF,i=e.checkSiteLock??n_,a=Xe(t,"state.db"),c=Xe(r,"state.db"),l=i(a);if(l!==null)throw new lo(`${l.ownerLabel} pid ${l.pid} (site lock for ${a})`);let u=CF(t,o);if(u!==null)throw new lo(`pid ${u}, ${Xe(t,"serve.pid")}`);if(await s(n))throw new lo(`something is listening on port ${n}`);if(t===r||r.startsWith(t+dd))throw new Error(`migrate-home: target (${r}) must not be, or be nested inside, source (${t})`);let d=e.acquireSiteLock??ea,m=Ko(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 jn?new lo(`${p.holder.ownerLabel} pid ${p.holder.pid}, ${p.lockPath}`):p}try{RF(r,{recursive:!0});let p=!1,h=!1;if(Hr(a)){let oe=Hr(c);if(oe&&e.replaceExistingTargetDb!==!0)throw new md(c,iv(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} (${iv(c).size} bytes) with a snapshot of ${a} (explicit replaceExistingTargetDb consent)
906
- `);for(let se of["","-wal","-shm"])sv(c+se,{force:!0});h=!0}else for(let se of["-wal","-shm"])sv(c+se,{force:!0});V.prepare("VACUUM INTO ?").run(c)}finally{V.close()}p=!0}let _=Xe(t,"queue"),g=Xe(r,"queue"),y=fd(_);y>0&&$a(_,g,{recursive:!0});let E=Xe(t,"prompts"),v=Xe(r,"prompts"),S=fd(E);S>0&&$a(E,v,{recursive:!0});let R=Xe(t,"site-uuid"),x=Xe(r,"site-uuid"),L=!1,k=!1;Hr(R)&&($a(R,x),L=!0,k=ud(R,"utf8")!==ud(x,"utf8"));let B=Xe(t,"lmt-peers.json"),C=Xe(r,"lmt-peers.json"),w=!1;Hr(B)&&($a(B,C),w=!0);let T=0,N=0,U=[],J=[],ee={};if(p){let oe=new ht(a,{readonly:!0});try{for(let se of av)ee[se]={source:cv(oe,se),target:0}}finally{oe.close()}let V=new ht(c);try{for(let A of av)ee[A].target=cv(V,A);let{rewrittenCount:se,originalPathById:$}=OF(V,_,g);T=se;let O=V.prepare("SELECT id, prompt_file FROM queue").all();N=O.length;for(let A of O){if(Hr(A.prompt_file))continue;let q=$.get(A.id);Hr(q)?U.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:y,promptFilesCopied:S,rewrittenPromptPaths:T,queueRowCount:N,missingPromptFiles:U,preExistingMissingPromptFiles:J,siteIdentityCopied:L,siteIdentityMismatch:k,lmtPeersCopied:w,rowCountParity:ee}}finally{for(let p of f.splice(0))p.release()}}async function fv(e={}){let t=e.source??uv(),r=e.target??dv(),n=await mv({sourceDir:t,targetDir:r,replaceExistingTargetDb:e.replaceExistingTargetDb});return{output:UF(n),exitCode:DF(n)}}function DF(e){return e.missingPromptFiles.length>0||e.siteIdentityMismatch||MF(e)?1:0}function MF(e){return Object.values(e.rowCountParity).some(t=>t.source!==t.target)}function PF(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)=>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:
907
907
  `+t.map(([r,n])=>` ${r}: source=${n.source}, target=${n.target}`).join(`
908
- `)}function UF(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 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:
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"}`,PF(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 pd(e){return{output:e,exitCode:0}}function uo(e){return{output:e,exitCode:1}}function hd(){return"usage: lmbee localweb passcode get | set | rotate"}var pv=32;async function FF(){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 hv(e,t={}){let[r,n,...o]=e;if(r!=="passcode")return uo(hd());if(o.length)return uo(`unexpected argument; ${hd()}`);let s=_o(),i=Hn(s);if(i===null)return{output:`no passcode file for an in-memory DB (${s})`,exitCode:2};if(n==="get"){let a=u_(i);return a===null?{output:"no passcode set yet -- start the daemon or run `lmbee localweb passcode rotate`",exitCode:1}:pd(a)}if(n==="set"){let a=t.readStdin??FF,c;try{c=(await a()).trim()}catch{return uo("passcode input rejected")}let l=Buffer.byteLength(c,"utf8");return l===0||l>4096?uo("usage: lmbee localweb passcode set (reads a nonempty value of at most 4096 bytes from stdin)"):l<pv?uo(`passcode rejected: at least ${pv} 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`):(Kl(i,c),pd("passcode updated"))}return n==="rotate"?pd(ta(i)):uo(hd())}import{randomUUID as qF}from"node:crypto";import{readFile as jF}from"node:fs/promises";function HF(e){try{let t=im(e);return BF(t.site),t}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function BF(e){return id(e)?e.toLowerCase():va(e,"peer alias")}function gv(e,t,r,n,o=!1){let s=e??(t===void 0||t===""?r:t);return o&&s===""?s:va(s,n)}async function WF(e,t){return e==="-"?t():jF(e,"utf8")}async function GF(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function VF(e,t,r){if(id(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:hs(s,i.mailbox)}}let n=jS(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 _v(){return"usage: lmbee tell <site-uuid-or-alias:team-id:alias> (<prompt...> | --prompt-file <path|->) [--from-team <team>] [--from-alias <alias>]"}async function wv(e,t,r={}){let n=r.env??process.env,o=r.promptFile;if(!e||o===void 0&&t.length===0)throw new Me(_v());if(o!==void 0&&t.length>0)throw new Me("positional prompt and --prompt-file are mutually exclusive");let s=HF(e),i=o===void 0?t.join(" "):await WF(o,r.readStdin??GF);if(!i.trim())throw new Me("tell prompt must be non-empty");let a=gv(r.fromTeam,n.LMT_FROM_TEAM,"","from-team",!0),c=gv(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 gs(),{siteUuid:p,mailbox:h}=await VF(s.site,f,m),_={...s,site:p},g=await Ms(ar()),y=qF(),E={v:1,msg_id:y,to:_,from:{site:g,team:a,alias:c},sent_at:new Date().toISOString(),payload:i},v=await m.sendMessage({mailbox:h,subject:`delivery ${y}`,body:{name:"body.txt",contentType:"text/plain; charset=utf-8",bytes:Buffer.from(JSON.stringify(E),"utf8")}});return`sent ${y} from ${g}:${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 gd(e){return{output:e instanceof Error?e.message:String(e),exitCode:e instanceof Me?1:2}}function JF(){return"usage: lmbee peers list | add <site-uuid> <mailbox> [--alias <name>] | remove <site-uuid>"}function nr(e,t){return ao(e,t,r=>new Me(r))}async function yv(e){let[t,...r]=e;try{if(t==="list"){if(r.length)throw new Me(`unexpected argument: ${r[0]}`);return hr(await HS())}if(t==="add"){let n=nr(r,"--alias");return r.length!==2?rr("usage: lmbee peers add <site-uuid> <mailbox> [--alias <name>]"):hr(await BS(r[0],r[1],n))}return t==="remove"?r.length!==1?rr("usage: lmbee peers remove <site-uuid>"):hr(await WS(r[0])):rr(JF())}catch(n){return gd(n)}}function KF(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 Ev(e){try{let{rawAddress:t,messageParts:r,promptFile:n,fromTeam:o,fromAlias:s}=KF(e);return hr(await wv(t,r,{promptFile:n,fromTeam:o,fromAlias:s}))}catch(t){return gd(t)}}async function Tv(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 GS(r[0],{siteUuid:n,mailbox:o}))}if(t==="resolve")return r.length!==1?rr(jr()):await VS(r[0]);if(t==="list")return r.length?rr(jr()):hr(await KS());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 YS(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 QS({uuid:n,mailbox:o}))}return t==="remove"?r.length!==1?rr(jr()):hr(await XS(r[0])):rr(jr())}catch(n){return gd(n)}}import{execFile as zF}from"node:child_process";import{promisify as YF}from"node:util";var QF=YF(zF),XF="lmbee.service";function ZF(){return process.env.LMBEE_SYSTEMD_UNIT??XF}async function bv(e={}){let t=ZF();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??QF;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"}`,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}
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 eq(e,t,r){let n="";for(let o=0;o<e.length;o++){let s=e[o];t.atLineStart&&s!==`
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!==`
919
919
  `&&(n+=`${r()} `,t.atLineStart=!1),n+=s,s===`
920
- `&&(t.atLineStart=!0)}return n}var Sv=!1;function vv(e=()=>new Date().toISOString()){if(!Sv){Sv=!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"?eq(o,n,e):o,...s)}}}function mo(e){return`${e instanceof Error?e.message:String(e)}
921
- `}function iq(e){let t=_d(sq(),".lmbee");nq(t,{recursive:!0});let r=_d(t,"serve.log"),n=_d(t,"serve.pid"),o=rq(r,"a"),s=tq(process.execPath,[process.argv[1],...e],{detached:!0,stdio:["ignore",o,o]});s.unref(),s.pid!==void 0&&oq(n,`${s.pid}
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}
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 aq(){let e=process.argv.slice(2);if($T(e))return process.stdout.write(`${Ur}
925
- `),0;if(e.length===1&&(e[0]==="--version"||e[0]==="-v"||e[0]==="-V")){let r=Cc();return process.stdout.write(`lmbee ${Mf()} (${r.sha}${r.dirty?".dirty":""})
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
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 iq(e.filter(ne=>ne!=="--daemon")),0;vv();let n;try{if(process.env.LMBEE_SITE_UUID!==void 0){let ne=bs(void 0,{readOnly:!0});try{En(ne.db,ar(),process.env.LMBEE_SITE_UUID)}finally{ne.close()}}n=mi()}catch(ne){return process.stderr.write(mo(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,...>
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,...>
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(mo(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(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)}
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(mo(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(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)}
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 _=typeof r["web-dist"]=="string"?r["web-dist"]:void 0,g=typeof r.interval=="string"?Number(r.interval):void 0,y=an(r["queue-interval-ms"],"--queue-interval-ms");if(y instanceof Error)return process.stderr.write(`error: ${y.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
- `),1;let R=an(r["maintainer-session-alive-freshness-ms"],"--maintainer-session-alive-freshness-ms");if(R instanceof Error)return process.stderr.write(`error: ${R.message}
939
- `),1;if(R!==void 0&&S===void 0)return process.stderr.write(`error: --maintainer-session-alive-freshness-ms requires --maintainer-session-alive-path
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
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
+ `),1;if(N!==void 0&&S===void 0)return process.stderr.write(`error: --maintainer-session-alive-freshness-ms requires --maintainer-session-alive-path
940
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 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 k=E!==void 0&&v!==void 0?{teamName:E,promptFile:v,...S!==void 0?{sessionAlivePath:S}:{},...R!==void 0?{sessionAliveFreshnessMs:R}:{},...L!==void 0?{activityFreshnessMs:L}:{},...x!==void 0?{maintainerStaleThresholdMs:x}:{}}:void 0,B=r["auto-continue"]===!0?{}:void 0,C=r["miniplayer-verify"]===!0?{}:void 0,w=r["hung-holder-check"]===!0?{}:void 0,T=r["epic-review"]===!0?{}:void 0,N=r["orphan-reconciler-dry-run"]===!0,U=r["orphan-reconciler"]===!0||N?{dryRun:N}: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}
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}
944
944
  `),1;if(O instanceof Error)return process.stderr.write(`error: ${O.message}
945
- `),1;let A=Xn(r["min-memory-percent"],"--min-memory-percent");if(A instanceof Error)return process.stderr.write(`error: ${A.message}
946
- `),1;let q=A??mc,M=$!==void 0||O!==void 0?{idleThresholdMs:$??pe.idleThresholdMs,cooldownMs:O??pe.cooldownMs}:void 0,Z;try{Z=await cE({context:n,...f!==void 0?{port:f}:{},...p!==void 0?{publish:p}:{},...h!==void 0?{hostname:h}:{},...g!==void 0?{intervalMs:g}:{},...y!==void 0?{queueIntervalMs:y}:{},...M!==void 0?{config:M}:{},...k!==void 0?{maintainerWake:k}:{},...T!==void 0?{epicReview:T}:{},...U!==void 0?{orphanReconciler:U}:{},...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}:{},...w!==void 0?{hungHolderCheck:w}:{},...i!==void 0?{remoteMail:i}:{},...m!==void 0?{execWorker:m}:{},..._!==void 0?{webDistDir:_}:{},minMemoryPercent:q})}catch(ne){return process.stderr.write(`${ne instanceof Error?ne.message:String(ne)}
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)}
947
947
  `),n.db.close(),1}process.stdout.write(`lmbee serve: listening on http://${Z.hostname}:${Z.port}
948
- `);let W=Cc();process.stdout.write(`lmbee serve: build ${W.sha}${W.dirty?" (dirty)":""}, built ${W.builtAt}
948
+ `);let W=Dc();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 cy({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 yv(r):e[0]==="tell"?await Ev(r):await Tv(r);return n&&process.stdout.write(`${n}
952
- `),o}if(e[0]==="localweb"){let{output:r,exitCode:n}=await hv(e.slice(1));return r&&process.stdout.write(`${r}
953
- `),n}if($S(e[0]??""))return await kS(e[0],e.slice(1));if(e[0]==="lmsound"){let{output:r,exitCode:n}=await xS(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 nv(r):await ov(r);return n&&process.stdout.write(`${n}
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
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}
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 fv({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(mo(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 bv({force:r.force===!0});return n&&process.stdout.write(n),o}if(e[0]==="cron"&&e[1]==="export")try{let{output:r,exitCode:n}=mE(e.slice(2));return r&&process.stdout.write(`${r}
960
- `),n}catch(r){return process.stderr.write(mo(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{ts("import",r,n);let s=r[0];if(s===void 0)throw new P("INVALID_ARGUMENT","an import PATH is required");hE(s)}catch(s){if(s instanceof P)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 _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}})}
961
961
  `:`${s.code}: ${s.message}
962
- `),s.exitCode;throw s}}}let t;try{t=mi({readOnly:kT(e)});let{output:r,exitCode:n}=await xT(t,e);return r&&process.stdout.write(`${r}
963
- `),n}catch(r){return process.stderr.write(mo(r)),1}finally{t?.db.close()}}aq().then(e=>{process.exitCode=e});
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});