@lmctl-ai/lmctl 0.2.68 → 0.2.70

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,87 +1,87 @@
1
1
  #!/usr/bin/env node
2
- var Av=Object.create;var La=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var kv=Object.getOwnPropertyNames;var xv=Object.getPrototypeOf,Rv=Object.prototype.hasOwnProperty;var Pt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nv=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ho=(e,t)=>{for(var r in t)La(e,r,{get:t[r],enumerable:!0})},Lv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of kv(t))!Rv.call(e,o)&&o!==r&&La(e,o,{get:()=>t[o],enumerable:!(n=$v(t,o))||n.enumerable});return e};var Ut=(e,t,r)=>(r=e!=null?Av(xv(e)):{},Lv(t||!e||!e.__esModule?La(r,"default",{value:e,enumerable:!0}):r,e));var xt=Nv(lt=>{"use strict";function ta(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 vI(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 V_(e,t,r){let n=" ".repeat(Math.max(0,t-Ir(e)));return r?n+e:e+n}function AI(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 $I(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 kI(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 xI(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 K_(e,{max:t}={}){if(!Array.isArray(e))throw new TypeError("grids must be an array of grids");let r=xI(t),n=[],o=(s,i)=>{n[s]=Math.max(n[s]??0,i)};for(let s of e){let i=AI(s);i.headers!==void 0&&ta(i.headers).forEach((a,c)=>{o(c,Ir(a))});for(let a of i.rows.map(ta))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)})}lt.measureColumns=K_;function RI(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 z_(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=RI(i),u=vI(n),d=$I(c),m=t??K_([{rows:e,headers:r}],{max:a}),f=e.map(ta);r!==void 0&&f.unshift(ta(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)?kI(g,E,d):g;return u[y]==="right"?V_(v,E,!0):y===_?v:V_(v,E,!1)}).join(" ")}).join(`
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(`
3
3
  `);return p===""||l===""?p:`${l}${p.split(`
4
4
  `).join(`
5
- ${l}`)}`}lt.renderGrid=z_;function Y_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a}={}){return z_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a})}function NI(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a,stream:c=process.stdout}={}){let l=Y_(e,{headers:t,align:r,truncate:n,truncateTrailing:o,margin:s,max:i,ellipsis:a});l&&c.write(`${l}
6
- `)}lt.formatTable=Y_;lt.printTable=NI;function J_(e){return e instanceof Date?e.getTime():typeof e=="number"?e:typeof e=="string"&&e.trim()?Date.parse(e):NaN}function LI(e,{now:t=Date.now()}={}){let r=J_(t);if(!Number.isFinite(r))throw new TypeError("now must be a valid timestamp");let n=J_(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":""}`}lt.formatRelativeTime=LI;function II(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`}lt.formatCount=II;var nu=[["w",604800],["d",86400],["h",3600],["m",60],["s",1]];function CI(e,{maxUnit:t="w",style:r="spaced"}={}){if(typeof e!="number"||!Number.isFinite(e))return"unknown";let n=nu.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=nu.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 nu.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(" ")}lt.formatDuration=CI;function Q_(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 X_(e){let t=Q_(e);return Number.isNaN(t.getTime())?"unknown":`${Jt(t.getHours())}:${Jt(t.getMinutes())}:${Jt(t.getSeconds())}`}lt.formatClock=X_;function OI(e){let t=Q_(e);return Number.isNaN(t.getTime())?"unknown":`${`${t.getFullYear()}-${Jt(t.getMonth()+1)}-${Jt(t.getDate())}`} ${X_(t)}`}lt.formatLocalTimestamp=OI;function DI(e){return typeof e=="number"&&Number.isFinite(e)?`${Math.round(e*100)}%`:"?%"}lt.formatPercent=DI;function MI(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)}`}lt.formatBar=MI;function PI(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}lt.formatTimer=PI;function UI(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")}`)}lt.escapeCell=UI});import{createHash as lM,randomBytes as kT}from"node:crypto";function xT(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ns.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ns.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ns.scope,ports:ns.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ns.authUrl).replace(/\/+$/,"")}}function RT(e=kT){let t=e(32).toString("base64url"),r=lM("sha256").update(t).digest("base64url");return{verifier:t,challenge:r}}function NT(e=kT){return e(16).toString("base64url")}function LT(e){return`http://127.0.0.1:${e}/callback`}function IT(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:LT(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 CT(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 OT(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:LT(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 MT(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function DT(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 MT(n)}`);return await n.json()}async function MT(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ns,PT=Pt(()=>{ns={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var jT={};ho(jT,{appkeyDir:()=>FT,persistCredentials:()=>qT,runLogin:()=>EM});import{createServer as uM}from"node:http";import{spawn as dM}from"node:child_process";import{hostname as mM}from"node:os";import{mkdir as fM,rename as pM,writeFile as hM}from"node:fs/promises";import{homedir as gM}from"node:os";import{join as pa}from"node:path";function FT(e=process.env){let t=e.XDG_CONFIG_HOME?.trim()||pa(gM(),".config");return pa(t,"lmctl")}async function qT(e,t,r,n=process.env){let o=FT(n);await fM(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 UT(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 UT(a,JSON.stringify(c,null,2)+`
9
- `)}return{appkeyPath:s,identityPath:a}}async function UT(e,t){let r=`${e}.tmp-${process.pid}`;await hM(r,t,{mode:384}),await pM(r,e)}async function _M(e){let t,r=new Promise(o=>t=o),n=uM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=CT(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 wM(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 wM(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 yM(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=dM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
10
10
  If your browser didn't open, visit:
11
11
  ${e}
12
12
 
13
- `)}async function EM(e={}){let t=e.io??{stdout:process.stdout,stderr:process.stderr},r=e.env??process.env,n=xT(r),o=e.fetchImpl??fetch,s=e.openBrowserFn??yM;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}=RT(),c=NT(),{server:l,port:u,wait:d}=await _M(n.ports);try{let m=IT(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 OT(n,{code:f.code,verifier:i,port:u},o),h=await DT(n,{idToken:p.id_token,label:mM()},o),{appkeyPath:_,identityPath:g}=await qT(h,p,n,r);return t.stdout.write(`
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(`
15
15
  \u2713 Signed in as ${h.user_id}
16
16
  \u2713 Appkey saved to ${_} (0600)
17
17
  `+(g?`\u2713 Refresh token saved to ${g} (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 HT=Pt(()=>{PT()});import{createHash as jM,randomBytes as QT}from"node:crypto";function XT(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 ZT(e=QT){let t=e(32).toString("base64url");return{verifier:t,challenge:jM("sha256").update(t).digest("base64url")}}function eb(e=QT){return e(16).toString("base64url")}function tb(e){return`http://127.0.0.1:${e}/callback`}function rb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:tb(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function nb(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 ob(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:tb(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 ib(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function sb(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 ib(n)}`);return n.json()}async function ib(e){try{return(await e.text()).slice(0,300)}catch{return""}}var os,ab=Pt(()=>{os={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var db={};ho(db,{appkeyDir:()=>lb,persistCredentials:()=>ub,runLogin:()=>XM});import{spawn as HM}from"node:child_process";import{mkdir as BM,rename as WM,writeFile as GM}from"node:fs/promises";import{createServer as VM}from"node:http";import{homedir as JM,hostname as KM}from"node:os";import{join as _a}from"node:path";function lb(e=process.env){return _a(e.XDG_CONFIG_HOME?.trim()||_a(JM(),".config"),"lmctl")}async function ub(e,t,r,n=process.env){let o=lb(n);await BM(o,{recursive:!0,mode:448});let s=_a(o,"appkey.json");await cb(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 cb(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 cb(e,t){let r=`${e}.tmp-${process.pid}`;await GM(r,t,{mode:384}),await WM(r,e)}async function zM(e){let t,r=new Promise(o=>{t=o}),n=VM((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=nb(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 YM(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}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 QM(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=HM(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
24
24
  If your browser didn't open, visit:
25
25
  ${e}
26
26
 
27
- `)}async function XM(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=XT(r),{verifier:o,challenge:s}=ZT(),i=eb(),{server:a,port:c,wait:l}=await zM(n.ports);try{let u=rb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
28
- `),(e.openBrowserFn??QM)(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 ob(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await sb(n,{idToken:m.id_token,label:KM()},e.fetchImpl??fetch),p=await ub(f,m,n,r);return t.stdout.write(`
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(`
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 mb=Pt(()=>{ab()});import{createHash as hP,randomBytes as _b}from"node:crypto";function wb(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 yb(e=_b){let t=e(32).toString("base64url");return{verifier:t,challenge:hP("sha256").update(t).digest("base64url")}}function Eb(e=_b){return e(16).toString("base64url")}function Tb(e){return`http://127.0.0.1:${e}/callback`}function bb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:Tb(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 vb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Tb(t.port),code_verifier:t.verifier}),o=await r(`https://${e.domain}/oauth2/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:n.toString()});if(!o.ok)throw new Error(`token exchange failed: HTTP ${o.status} ${await $b(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function 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 $b(n)}`);return n.json()}async function $b(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ss,kb=Pt(()=>{ss={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var Lb={};ho(Lb,{appkeyDir:()=>Rb,persistCredentials:()=>Nb,runLogin:()=>$P});import{spawn as gP}from"node:child_process";import{mkdir as _P,rename as wP,writeFile as yP}from"node:fs/promises";import{createServer as EP}from"node:http";import{homedir as TP,hostname as bP}from"node:os";import{join as ya}from"node:path";function Rb(e=process.env){return ya(e.XDG_CONFIG_HOME?.trim()||ya(TP(),".config"),"lmctl")}async function Nb(e,t,r,n=process.env){let o=Rb(n);await _P(o,{recursive:!0,mode:448});let s=ya(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)+`
33
- `);let i=null;return t.refresh_token&&(i=ya(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)+`
34
- `)),{appkeyPath:s,identityPath:i}}async function xb(e,t){let r=`${e}.tmp-${process.pid}`;await yP(r,t,{mode:384}),await wP(r,e)}async function SP(e){let t,r=new Promise(o=>{t=o}),n=EP((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 vP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function vP(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 AP(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=gP(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
35
35
  If your browser didn't open, visit:
36
36
  ${e}
37
37
 
38
- `)}async function $P(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=wb(r),{verifier:o,challenge:s}=yb(),i=Eb(),{server:a,port:c,wait:l}=await SP(n.ports);try{let u=bb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
39
- `),(e.openBrowserFn??AP)(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 vb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await Ab(n,{idToken:m.id_token,label:bP()},e.fetchImpl??fetch),p=await Nb(f,m,n,r);return t.stdout.write(`
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(`
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 Ib=Pt(()=>{kb()});import{createHash as HP,randomBytes as Db}from"node:crypto";function Mb(e=process.env){return{domain:e.LMCTL_AUTH_DOMAIN?.trim()||ls.domain,clientId:e.LMCTL_CLI_CLIENT_ID?.trim()||ls.clientId,scope:e.LMCTL_AUTH_SCOPE?.trim()||ls.scope,ports:ls.ports,authUrl:(e.LMCTL_AUTH_URL?.trim()||ls.authUrl).replace(/\/+$/,"")}}function Pb(e=Db){let t=e(32).toString("base64url");return{verifier:t,challenge:HP("sha256").update(t).digest("base64url")}}function Ub(e=Db){return e(16).toString("base64url")}function Fb(e){return`http://127.0.0.1:${e}/callback`}function qb(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:Fb(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 Hb(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:Fb(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 Wb(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function Bb(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 Wb(n)}`);return n.json()}async function Wb(e){try{return(await e.text()).slice(0,300)}catch{return""}}var ls,Gb=Pt(()=>{ls={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var zb={};ho(zb,{appkeyDir:()=>Jb,persistCredentials:()=>Kb,runLogin:()=>ZP});import{spawn as BP}from"node:child_process";import{mkdir as WP,rename as GP,writeFile as VP}from"node:fs/promises";import{createServer as JP}from"node:http";import{homedir as KP,hostname as zP}from"node:os";import{join as Ea}from"node:path";function Jb(e=process.env){return Ea(e.XDG_CONFIG_HOME?.trim()||Ea(KP(),".config"),"lmctl")}async function Kb(e,t,r,n=process.env){let o=Jb(n);await WP(o,{recursive:!0,mode:448});let s=Ea(o,"appkey.json");await Vb(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 Vb(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 Vb(e,t){let r=`${e}.tmp-${process.pid}`;await VP(r,t,{mode:384}),await GP(r,e)}async function YP(e){let t,r=new Promise(o=>{t=o}),n=JP((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 QP(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function QP(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 XP(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(`
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(`
46
46
  If your browser didn't open, visit:
47
47
  ${e}
48
48
 
49
- `)}async function ZP(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=Mb(r),{verifier:o,challenge:s}=Pb(),i=Ub(),{server:a,port:c,wait:l}=await YP(n.ports);try{let u=qb(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
50
- `),(e.openBrowserFn??XP)(u,t);let d=await l;if(d.error)throw new Error(`authorization failed: ${d.error}`);if(!d.code)throw new Error("no authorization code returned");if(d.state!==i)throw new Error("state mismatch (possible CSRF); aborting");let m=await Hb(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await Bb(n,{idToken:m.id_token,label:zP()},e.fetchImpl??fetch),p=await Kb(f,m,n,r);return t.stdout.write(`
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(`
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 Yb=Pt(()=>{Gb()});import{createHash as iU,randomBytes as rS}from"node:crypto";function nS(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 oS(e=rS){let t=e(32).toString("base64url");return{verifier:t,challenge:iU("sha256").update(t).digest("base64url")}}function sS(e=rS){return e(16).toString("base64url")}function iS(e){return`http://127.0.0.1:${e}/callback`}function aS(e,t){let r=new URLSearchParams({response_type:"code",client_id:e.clientId,redirect_uri:iS(t.port),scope:e.scope,state:t.state,code_challenge:t.challenge,code_challenge_method:"S256"});return`https://${e.domain}/oauth2/authorize?${r}`}function cS(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 lS(e,t,r=fetch){let n=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t.code,redirect_uri:iS(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 dS(o)}`);let s=await o.json();if(!s.id_token)throw new Error("token exchange returned no id_token");return s}async function uS(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 dS(n)}`);return n.json()}async function dS(e){try{return(await e.text()).slice(0,300)}catch{return""}}var us,mS=Pt(()=>{us={domain:"auth.lmctl.ai",clientId:"lpla33du6p451g9ohb0su9c5u",scope:"openid email profile",ports:[8976,8977,8978,8979],authUrl:"https://lmctl.ai/auth"}});var gS={};ho(gS,{appkeyDir:()=>pS,persistCredentials:()=>hS,runLogin:()=>_U});import{spawn as aU}from"node:child_process";import{mkdir as cU,rename as lU,writeFile as uU}from"node:fs/promises";import{createServer as dU}from"node:http";import{homedir as mU,hostname as fU}from"node:os";import{join as Ta}from"node:path";function pS(e=process.env){return Ta(e.XDG_CONFIG_HOME?.trim()||Ta(mU(),".config"),"lmctl")}async function hS(e,t,r,n=process.env){let o=pS(n);await cU(o,{recursive:!0,mode:448});let s=Ta(o,"appkey.json");await fS(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 fS(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 fS(e,t){let r=`${e}.tmp-${process.pid}`;await uU(r,t,{mode:384}),await lU(r,e)}async function pU(e){let t,r=new Promise(o=>{t=o}),n=dU((o,s)=>{if(!o.url?.startsWith("/callback")){s.writeHead(404).end();return}let i=cS(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 hU(n,o))return{server:n,port:o,wait:r};throw new Error(`could not bind any loopback port (${e.join(", ")})`)}function hU(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 gU(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=aU(r,n,{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}t.stdout.write(`
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(`
57
57
  If your browser didn't open, visit:
58
58
  ${e}
59
59
 
60
- `)}async function _U(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=nS(r),{verifier:o,challenge:s}=oS(),i=sS(),{server:a,port:c,wait:l}=await pU(n.ports);try{let u=aS(n,{port:c,state:i,challenge:s});t.stdout.write(`Opening your browser to sign in with lmctl.ai\u2026
61
- `),(e.openBrowserFn??gU)(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 lS(n,{code:d.code,verifier:o,port:c},e.fetchImpl??fetch),f=await uS(n,{idToken:m.id_token,label:fU()},e.fetchImpl??fetch),p=await hS(f,m,n,r);return t.stdout.write(`
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(`
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 _S=Pt(()=>{mS()});import{spawn as eq}from"node:child_process";import{openSync as tq,mkdirSync as rq,writeFileSync as nq}from"node:fs";import{homedir as oq}from"node:os";import{join as gd}from"node:path";import{mkdirSync as dq,readFileSync as Iv,renameSync as mq,writeFileSync as fq}from"node:fs";import{homedir as Cv}from"node:os";import{dirname as gq,join as yd}from"node:path";var cq=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}},_s=class extends Error{code="APPKEY_INVALID";source;constructor(t){super(`${t} resolved an invalid lmctl appkey`),this.name="AppkeyInvalidError",this.source=t}},ws=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 Ov="https://lmctl.ai/auth",Dv=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)=>Iv(c,l)},n=e.homedir??Cv,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=Ed(r,s,"env:LMCTL_APPKEY_FILE");if(c)return c}let i=Mv(t,n),a=Ed(r,i,"file:default");if(a)return a;throw new Gr}async function bd(e,t={}){let r=await Fv("/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:Td(n,"user_id","validate appkey response",sr),label:Td(n,"label","validate appkey response",sr)}}function Ed(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 Mv(e,t){let r=e.XDG_CONFIG_HOME?.trim()||yd(t(),".config");return yd(r,"lmctl","appkey.json")}function Pv(e){let t=e.env??process.env;return(e.authBaseUrl?.trim()||t.LMCTL_AUTH_BASE_URL?.trim()||Ov).replace(/\/+$/,"")}function Uv(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 Fv(e,t,r,n){return await qv(e,t,r,n,r.timeoutMs)}async function qv(e,t,r,n,o,s){let i=Uv(r,n),a=`${Pv(r)}${e}`,c=o??Dv,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 Td(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 yq={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 ft(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 H=await k.text().catch(()=>"");if(L.tolerate409!==!1&&$d(H)==="mailbox_exists")return;throw Ad("create mailbox failed",k.status,H)}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:Sd(x.body),attachments:L.map(Sd)})},"allocate message failed"),H=[{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 H){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(Hv(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 H=k.size>0?`?${k.toString()}`:"",C=await S(`${t}/mailboxes/${encodeURIComponent(x)}/messages${H}`,{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:vd(k.body),attachments:k.attachments.map(vd)}}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 H=await r(x,L);await R(H,k);try{return await H.json()}catch(C){throw new Error(`${k}: invalid JSON response: ${Bv(C)}`)}}async function R(x,L){if(x.ok)return;let k=await x.text().catch(()=>"");throw Ad(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 Sd(e){return{name:e.name,size:e.bytes.byteLength,content_type:e.contentType}}function vd(e){return{name:e.name,size:e.size,content_type:e.content_type}}function Ad(e,t,r){return new Ft(e,t,r,$d(r))}function $d(e){try{let t=JSON.parse(e);return typeof t.error=="string"?t.error:void 0}catch{return}}function Hv(e,t){return/^https?:\/\//i.test(t)?t:`${e}${t.startsWith("/")?"":"/"}${t}`}function Bv(e){return e instanceof Error?e.message:String(e)}import{execFile as wA}from"node:child_process";import{existsSync as yA}from"node:fs";import{join as EA}from"node:path";import{promisify as TA}from"node:util";import{existsSync as kd}from"node:fs";import{createRequire as Wv}from"node:module";import{dirname as Gv}from"node:path";var Ca=null;function Vv(){return Ca===null&&(Ca=Wv(import.meta.url)("node:sqlite").DatabaseSync),Ca}var Jv={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"},Kv={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 zv(e){return Kv[e]??Jv[e&255]??`SQLITE_UNKNOWN_${e}`}var Yv="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=zv(t.errcode),e;if(t.code==="ERR_INVALID_ARG_TYPE"&&/cannot be bound/.test(String(t.message)))throw new TypeError(Yv);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 Qv(){let e="unable to open database file";return Object.assign(new Error(e),{code:"SQLITE_CANTOPEN",errcode:14,errstr:e})}function xd(e){return e instanceof Uint8Array&&!Buffer.isBuffer(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function Xv(e){if(e==null)return e;if(Array.isArray(e))return e.map(xd);if(typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))t[r]=xd(n);return t}return e}function Zv(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 ys(e){return e.map((t,r)=>{if(t===void 0)return null;if(r===0&&Zv(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(...ys(t));return{changes:Number(r.changes),lastInsertRowid:Number(r.lastInsertRowid)}}catch(r){qt(r)}}get(...t){try{return this.project(this.handle.get(...ys(t)))}catch(r){qt(r)}}all(...t){try{return this.handle.all(...ys(t)).map(r=>this.project(r))}catch(r){qt(r)}}*iterate(...t){let r;try{r=this.handle.iterate(...ys(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=Xv(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&&!kd(Gv(t)))throw new TypeError("Cannot open database because the directory does not exist");if(r.fileMustExist===!0&&!n&&!kd(t))throw Qv();this.name=t,this.memory=n,this.readonly=r.readonly===!0;try{this.handle=new(Vv())(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(!eA(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(!tA(i))throw i}throw s}}};function eA(e){return e instanceof Error&&/cannot rollback - no transaction is active/i.test(e.message)}function tA(e){return e instanceof Error&&/no such savepoint:/i.test(e.message)}var pt=Da;import{existsSync as Pa,lstatSync as rA,mkdirSync as nA,readFileSync as Cd,realpathSync as Rd}from"node:fs";import{basename as oA,dirname as Ua,isAbsolute as sA,join as iA,relative as aA,resolve as Nd}from"node:path";import{fileURLToPath as cA}from"node:url";var Od=iA(Ua(cA(import.meta.url)),"schema.sql");function go(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 lA(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 uA(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 dA(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 mA(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 fA(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 pA(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 hA(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=Nd(e);for(;rA(n,{throwIfNoEntry:!1})===void 0;){r.unshift(oA(n));let i=Ua(n);if(i===n)throw new Error("Cannot resolve test database path");n=i}let o=Nd(Rd(n),...r),s=aA(Rd(t),o);if(s===".."||s.startsWith("../")||s.startsWith("..\\")||sA(s))throw new Error(`Database path is outside the test database root: ${e}`)}function Ld(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 Es=62;function Id(e){let t=e.pragma("user_version",{simple:!0});if(t<=Es)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:s!==void 0&&s.value!==null&&(r=String(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)>Es)n=`schema_meta.min_reader_version=${r} declares a breaking floor above ${Es}`;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, ${Es}, 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 gA(){return Ma===void 0&&(Ma=[...Cd(Od,"utf8").matchAll(/CREATE TABLE IF NOT EXISTS (\w+)/gi)].map(t=>t[1])),Ma}function _A(e,t){let r=new Set(e.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(o=>o.name)),n=gA().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 Ts(e,t={}){let r=go(e);lA(r);let n=!e&&typeof process.env.LMBEE_DB=="string"&&process.env.LMBEE_DB!=="";if(n&&uA(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 pt(r,{readonly:!0,fileMustExist:!0});try{Ld(a),Id(a),a.pragma("busy_timeout = 5000"),_A(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)||nA(a,{recursive:!0})}let o=new pt(r,n?{fileMustExist:!0}:void 0);try{Ld(o),Id(o)}catch(a){throw o.close(),a}o.pragma("journal_mode = WAL"),o.pragma("busy_timeout = 5000");let s=Cd(Od,"utf8"),i=o.transaction(()=>{dA(o),mA(o),hA(o),pA(o),fA(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 Dd(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 bs(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 Md(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 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:s!==void 0&&s.value!==null&&(r=String(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)
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
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 Pd(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 Ud(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 Fd(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 qd(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 jd(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)
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)
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 Hd(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 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)
85
85
  VALUES (?, ?, ?, ?, ?, ?)
86
86
  ON CONFLICT(team) DO UPDATE SET
87
87
  holder_watch_pid = excluded.holder_watch_pid,
@@ -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 Bd(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 Wd(e,t){e.prepare("DELETE FROM auto_nudge_suspended WHERE team = ?").run(t)}function Gd(e){return e.prepare("SELECT * FROM auto_nudge_suspended ORDER BY team").all()}function Vd(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 Jd(e,t){e.prepare("DELETE FROM unresolvable_teamfile_watch WHERE team = ?").run(t)}function Kd(e,t){return e.prepare("SELECT * FROM unresolvable_teamfile_watch WHERE team = ?").get(t)??null}function zd(e,t,r){e.prepare("UPDATE unresolvable_teamfile_watch SET surfaced_ts = ? WHERE team = ?").run(r,t)}function Yd(e,t,r){e.prepare(`INSERT INTO team_progress(team, last_cli_activity_ts)
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)
107
107
  VALUES (?, ?)
108
- ON CONFLICT(team) DO UPDATE SET last_cli_activity_ts = excluded.last_cli_activity_ts`).run(t,r)}function Qd(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 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)
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 Xd(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 Zd(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 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)
114
114
  VALUES (?, ?, ?, ?, ?, ?)
115
- ON CONFLICT(target, started_at_ms, pid, observed_at) DO NOTHING`).run(t,r,n,o,s,i)}function em(e,t){e.prepare("DELETE FROM hang_probe_observation WHERE observed_at < ?").run(t)}function tm(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 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)
116
116
  VALUES (?, ?, ?, ?, ?)
117
- ON CONFLICT(target, started_at_ms, pid) DO NOTHING`).run(t,r,n,o,s)}function rm(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 nm(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 nm(e,t){e.prepare("UPDATE team_progress SET quota_exhausted_last_seen_ts = NULL, quota_exhausted_message = NULL WHERE team = ?").run(t)}function om(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 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)
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 bA=TA(wA);function SA(e){return yA(EA(e,".git"))}async function Va(e,t){try{let r=t.replace(/\.\d{3}Z$/,"Z"),{stdout:n}=await bA("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 vA(e,t){if(t===null)return"ACTIVE";for(let r of e)if(await Va(r,t))return"ACTIVE";return e.every(r=>!SA(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 vA(o,s?.last_scan_ts??null);return Md(e,r,i,new Date(n).toISOString(),new Date().toISOString()),ie(e,r)}import{existsSync as Za,readFileSync as pm,realpathSync as FA,statSync as qA}from"node:fs";import{join as mm,resolve as $s}from"node:path";var AA=/^[a-z0-9-]+$/;function Ka(e){if(e.length>128||!AA.test(e))throw new Error("site-id must match [a-z0-9-]+");return e}function sm(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()||$A(e))throw new Error(`${t} must ${r?"":"be non-empty and "}contain no colons or control characters`);return e}function $A(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 RA,mkdir as NA,readFile as LA,rename as IA,unlink as CA,writeFile as OA}from"node:fs/promises";import{randomUUID as DA}from"node:crypto";import{homedir as kA}from"node:os";import{dirname as xA,join as im}from"node:path";function za(e=process.env){let t=e.LMAUTO_DB?.trim();return t?xA(t):im(e.HOME?.trim()||kA(),".lmauto")}function Ss(e=process.env){return im(za(e),"site-uuid")}var am=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,MA={readText:e=>LA(e,"utf8"),mkdir:async e=>{await NA(e,{recursive:!0})},writePrivate:(e,t)=>OA(e,t,{flag:"wx",mode:384}),link:RA,rename:IA,remove:CA};async function cm(e={}){let t=e.env??process.env,r=e.io??MA,n=Ss(t),o=await As(r,n);if(o.value)return o.value;await r.mkdir(za(t));let s={io:r,randomUuid:e.randomUuid??DA,pid:e.pid??process.pid,sleep:e.sleep??(i=>new Promise(a=>setTimeout(a,i)))};return o.exists?UA(s,n):PA(s,n)}async function PA(e,t){let r=await lm(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 vs(e.io,r.temporary)}}async function UA(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 lm(e,t),o=`${t}.${e.pid}.${n.candidate}.corrupt`;let i=await As(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 As(e.io,t);throw s&&!c.exists&&(await e.io.rename(o,t),s=!1),a}}finally{n&&await vs(e.io,n.temporary),s&&o&&await vs(e.io,o),await vs(e.io,r)}}async function lm(e,t){let r=e.randomUuid().toLowerCase();if(!am.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 As(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 As(e,t){try{let r=(await e.readText(t)).trim();return am.test(r)?{exists:!0,value:r.toLowerCase()}:{exists:!0}}catch(r){if(r.code==="ENOENT")return{exists:!1};throw r}}async function vs(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 um(e){return`${hn(e)}-exec`}function dm(e,t){let r=hn(e);if(t!==r)throw new Error(`peer mailbox mismatch for ${e}: registered ${t}, expected ${r}`);return r}function B(e){return e.channel==="local"}function ks(e,t){let r=e.find(n=>n.name===t);return r?B(r)?{key:t,kind:"local",name:r.name,repoPath:r.repoPath,leadAlias:r.leadAlias,channel:r.channel,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"remote",name:r.name,channel:r.channel,peerSite:r.peerSite,alias:r.alias,currentSession:null,historicalCoverage:"unavailable"}:{key:t,kind:"unresolved",currentSession:null,historicalCoverage:"unavailable"}}function _o(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?hm(i,f):[$s(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 hm(e,t){let r=new Set,n=[];for(let o of t){let s=$s(e,o);r.has(s)||(r.add(s),n.push(s))}return n}var jA=/^_TEAM_(\s|$)/,HA=/(\w+)=(?:"([^"]*)"|([\S]*))/g;function BA(e){let t={};for(let m of e.matchAll(HA)){let f=m[1];f in t||(t[f]=m[2]!==void 0?m[2]:m[3])}if(t.channel==="lmmail")return WA(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?hm(n,u):[$s(n)];return{channel:"local",name:r,repoPath:n,leadAlias:o,promptName:l,description:i??"",autoNudge:l!=="on-demand",folders:d,coordinator:c==="true"}}function WA(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 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}
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 GA=/^(`{3,}|~{3,})/;function ec(e){let t=[],r=null;for(let n of e.split(/\r?\n/)){let o=n.trim(),s=GA.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=BA(o);i&&t.push(i)}return t}function fm(e){return e.toLowerCase().endsWith(".md")}function VA(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(!qA(o).isFile())continue}catch{continue}n.push(o)}return n}function JA(e,t=[]){let r=VA(e,t),n=new Map,o=s=>{try{return pm(s,"utf8")}catch{return null}};for(let s of r){if(!fm(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(fm(s))continue;let i=o(s);if(i!==null)for(let a of _o(i))n.has(a.name)||n.set(a.name,a)}return[...n.values()]}function xs(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 Rs(e,t){e.prepare("DELETE FROM sources WHERE path = ?").run(t)}function KA(e){let t=$s(e);return Za(t)?FA(t):null}function Q(e){let t=KA(mm(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 "${mm(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 zA=/^_MEMBER_(\s|$)/,YA=/(\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=pm(Q(e),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
130
- `)){if(!zA.test(n.trim()))continue;let o={};for(let s of n.matchAll(YA)){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 JA(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 gm(e,t,r){return r.running.some(n=>{let o=gn(n.target);return o!==null&&o.alias===t&&o.teamfilePath===e})}function QA(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 Ns(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get("active");return t?JSON.parse(t.v):null}function XA(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 Ls(e,t,r){let n=QA(t,r,Ns(e));return XA(e,n.active),n}import{randomUUID as rf}from"node:crypto";import{existsSync as nf,mkdirSync as g$,readFileSync as qs,rmSync as _$,writeFileSync as of}from"node:fs";import{homedir as w$}from"node:os";import{join as sf,resolve as tf,sep as y$}from"node:path";var uj=64*1024;import{readFileSync as Is,writeFileSync as e$}from"node:fs";function t$(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 _m(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=Is(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 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(`
131
131
 
132
132
  --- addendum, ${d.created_ts} ---
133
- ${Is(d.prompt_file,"utf8")}`)}catch{u=!1;break}if(!u){o.push(...s);continue}if(l.length>0){e$(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=_m(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{Is(c.prompt_file,"utf8")}catch{continue}if(!t$(e,c.id))continue;let d;try{d=Is(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 ym}from"node:crypto";import{mkdtempSync as Em,rmSync as Tm,writeFileSync as bm}from"node:fs";import{tmpdir as Sm}from"node:os";import{join as Cs}from"node:path";import{spawn as vm}from"node:child_process";var Am=50*6e4,$m=5e3,Kr=["systemd-run","--user","--scope","--collect","--quiet","--","lmctl"];async function Ht(e,t,r={}){let n=r.timeoutMs??Am,o=r.sigkillGraceMs??$m,s=Em(Cs(Sm(),"lmauto-send-")),i=Cs(s,`${ym()}.md`);bm(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=vm(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{Tm(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=wm(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=wm(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 wm(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 km(e,t,r={}){let n=Em(Cs(Sm(),"lmauto-send-")),o=Cs(n,`${ym()}.md`);bm(o,t,{mode:384});let i=[...r.spawnPrefix??Kr,"chat",`${e.teamfilePath}:${e.alias}`,"--prompt-file",o,"--json"],[a,...c]=i,l=vm(a,c,{detached:!0,stdio:"ignore"});l.unref();function u(){try{Tm(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??$m).unref()},r.timeoutMs??Am);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 xm(e,t){return e.prepare("SELECT 1 FROM kv WHERE k = ?").get(wn+t)!==void 0}function Rm(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 Nm(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(wn+t);return r===void 0?null:Rm(t,r.v)}function Lm(e){return e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${wn}%`).map(r=>Rm(r.k.slice(wn.length),r.v))}function Im(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 Cm(e,t){return e.prepare("DELETE FROM kv WHERE k = ?").run(wn+t).changes>0}function r$(e){return{team:e.team,alias:e.alias,holderPid:e.holder_pid,reservedAt:e.reserved_at,leaseUntil:e.lease_until,reason:e.reason}}function Om(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
+ ${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)
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?r$(o):null}function Os(e,t,r,n=Date.now()){return ic(e,t,r,n)!==null}function Dm(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 Mm(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 n$}from"node:os";import{readFileSync as o$}from"node:fs";import{join as s$}from"node:path";function Pm(e){return{LMAUTO_DB:e}}function ar(){return process.env.LMAUTO_DB??s$(n$(),".lmbee","state.db")}function i$(e){return Ss(Pm(e))}function zr(e){return hn(e)}function yn(e){return um(e)}async function Ds(e){return cm({env:Pm(e)})}var a$="lmbee.site_uuid",c$=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function l$(e){let t=i$(e),r=o$(t,"utf8").trim();if(!c$.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=l$(t),o=e.prepare("SELECT v FROM kv WHERE k = ?").get(a$);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 u$(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 d$(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 Um=64*1024;function wo(e){return JSON.stringify(u$(e))}function qm(e){if(Buffer.byteLength(e,"utf8")>Um)throw new Error(`envelope body exceeds ${Um} 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=Ms(r,"msg_id"),o=Ms(r,"sent_at"),s=Ms(r,"payload"),i=Fm(r,"to"),a=Fm(r,"from"),c=r.in_reply_to===void 0||r.in_reply_to===null?void 0:Ms(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 d$(l)}function Ms(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 Fm(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 jm(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 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(
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 Hm(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 Bm(e){return e.prepare("SELECT MAX(seq) as maxSeq FROM mail_ledger").get().maxSeq}function Wm(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 Gm(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=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
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 m$(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 Ps(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>=m$(o.retry_count,r):!1})}function Vm(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 Jm(e,t){return e.prepare("UPDATE mail_ledger SET state = 'persisted' WHERE msg_id = ? AND state = 'failed'").run(t).changes>0}function Km(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 zm(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 Ym(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 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(
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 Qm(e,t){return e.prepare("SELECT * FROM mail_outbound_ledger WHERE msg_id = ?").get(t)??null}function Xm(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 Zm(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 Us(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 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
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 f$}from"node:fs";var p$=/^MemTotal:\s+(\d+)\s*kB/m,h$=/^MemAvailable:\s+(\d+)\s*kB/m;function Fs(e){return e===null?null:`memory headroom: ${e.percentAvailable.toFixed(1)}% available (context only, not a wake trigger)`}function yo(e="/proc/meminfo"){let t;try{t=f$(e,"utf8")}catch{return null}let r=p$.exec(t),n=h$.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 ef(e=mc,t=yo){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 js(){return process.env.LMBEE_QUEUE_DIR?process.env.LMBEE_QUEUE_DIR:sf(w$(),".lmbee","queue")}function E$(e,t,r){nf(r)||g$(r,{recursive:!0});let n=sf(r,`${e}.md`);return of(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 ge(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 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)
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=E$(m,n,o.queueDir??js());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 af(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 Hs(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 cf(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=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 (
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 T$(e){let{escalation_claim_token:t,prompt_file:r,admission_fingerprint:n,...o}=e;return o}var b$=50,Eo=200;function hc(e,t={}){let r=t.limit??b$;if(!Number.isSafeInteger(r)||r<1||r>Eo)throw new I("INVALID_ARGUMENT",`limit must be a positive integer <= ${Eo}`);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(T$),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 S$(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 v$(e){return`'${e.replaceAll("'","'\\''")}'`}function A$(e,t,r){return`${e}
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}
161
161
 
162
- [Delivery receipt: after reading this prompt, run \`lmbee queue retrieve ${v$(t)} --id ${r}\` to record that you received queue#${r}.]`}function $$(e,t,r,n,o){let i=(t.now??(()=>new Date().toISOString()))(),a={v:1,msgId:rf(),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(wo(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 k$(e,t,r,n,o,s=n.leadAlias){let i=t.now??(()=>new Date().toISOString()),a={v:1,msgId:rf(),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(wo(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),Gm(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 x$(e,t,r,n){if(!t.remoteMail)return!1;try{qs(n.prompt_file,"utf8")}catch{return!1}if(!S$(e,n.id))return!1;let o;try{o=qs(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 $$(e,t.remoteMail,r,n,o),!0}function R$(e){let t=new Map,r=[];for(let n of e){if(!B(n))continue;let o;try{o=Q(n)}catch{continue}t.set(n.name,n),r.push({name:n.name,teamfilePath:o,leadAlias:n.leadAlias})}return{refs:r,byName:t}}function gc(e){let t=e.expects_response?" (expects a response)":"";return`--- addendum from ${e.from_id}, ${e.created_ts}${t} ---`}function N$(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=qs(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 ${$$(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(`
166
166
 
167
167
  ${gc(d)}
168
- ${qs(d.prompt_file,"utf8")}`)}catch{l=!1;break}if(!l||c.length===0)continue;of(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??km,n=t.sendAwaited??Ht,o=t.memoryCheck??ef,{refs:s,byName:i}=R$(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));N$(e,a);let c=sc(e,s,{teamName:t.teamName,isTeamBusy:d=>Fe(i.get(d.name),t.report)||xm(e,d.name)||Dm(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,_=A$(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"?k$(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"&&zm(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)}
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)}
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}B(f)||x$(e,t,f,d)&&c++}return c}function Bs(e,t,r){return r!==void 0?L$(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 L$(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)||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 (
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 lf(e,t={}){let r=tf(t.queueDir??js()),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 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
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=tf(c.prompt_file);if(!(l!==r&&!l.startsWith(r+y$))&&nf(l))try{_$(l,{force:!0}),a++}catch{}}return a}import{spawn as U$}from"node:child_process";import{lstatSync as I$,readlinkSync as C$,realpathSync as O$}from"node:fs";import{homedir as D$}from"node:os";import{basename as M$,dirname as uf,isAbsolute as mf,join as P$,resolve as _c}from"node:path";var Tr="_lmauto_status_transition";function de(){return`${new Date().toISOString().replace("Z","000Z")}`}function we(e,t){if(!e.trim())throw new I("INVALID_ARGUMENT",`${t} must not be blank`);return e}function wc(e){let t;try{t=I$(e)}catch{let r=uf(e);return r===e?e:P$(wc(r),M$(e))}if(t.isSymbolicLink()){let r=C$(e),n=mf(r)?r:_c(uf(e),r);return wc(n)}return O$(e)}function At(e){let t=e==="~"||e.startsWith("~/")?e.replace(/^~/,D$()):e,r=mf(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 yt(e){try{return e()}catch(t){if(t instanceof I)throw t;return bn(t)}}function at(e,t){return yt(()=>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 ff(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 Ws(e,t){e.prepare("UPDATE entities SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}var Ne=1e4;function pf(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 yt(()=>{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 yt(()=>{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 hf(e,t){let r=e.transaction(()=>{let n=t.parentId!==void 0?Le(e,t.parentId):null,o=we(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{ff(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(we(t.owner.team,"owner team")),i=we(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:we(t.title,"title"),description:t.description??"",requirements:t.requirements??"",acceptance_criteria:t.acceptanceCriteria??"",status:we((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 yt(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(we(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"),pf(e,`SELECT * FROM entities WHERE ${r.join(" AND ")}`,n,t.limit??100)}function Sr(e,t){let r=Le(e,t),n=yt(()=>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 gf(e,t){return Le(e,t),yt(()=>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=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 (
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=gf(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 df(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 df(gf(e,t.id));let r=yt(()=>t.project!==void 0?e.prepare("SELECT * FROM entities WHERE project = ?").all(t.project):e.prepare("SELECT * FROM entities").all());return df(r)}function Gs(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=we(r.title,"title")),r.status!==void 0&&(s.status=we(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{ff(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(we(r.owner.team,"owner team")),s.owner_alias=we(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=we(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=we(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=we(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()),Ws(e,t),Le(e,t)});return yt(n)}function _f(e,t,r){e.prepare("UPDATE entities SET delivered_ts = ? WHERE id = ? AND delivered_ts IS NULL").run(r,t)}function wf(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(we(r.author.team,"author team")):null,s=r.author!==void 0?we(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,we(r.body,"body"),o,s,de());return Ws(e,t),{note:e.prepare("SELECT * FROM notes WHERE id = ?").get(i.lastInsertRowid),revision:Le(e,t).revision}});return yt(n)}function yc(e,t,r={}){return Le(e,t),pf(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 Vs(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 yt(()=>e.prepare("SELECT * FROM notes WHERE entity_id = ? ORDER BY id DESC").all(t).find(n=>Wt(n.body)===null)??null)}function yf(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 Ef(e,t,r){if(Le(e,t),Le(e,r),t===r)throw new I("SELF_DEPENDENCY","An entity cannot depend on itself")}function Tf(e,t,r){let n=e.transaction(()=>{Ef(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&&Ws(e,t),{entity_id:t,depends_on_id:r,changed:o,revision:Le(e,t).revision}});return yt(n)}function bf(e,t,r){let n=e.transaction(()=>{Ef(e,t,r);let s=e.prepare("DELETE FROM dependencies WHERE entity_id = ? AND depends_on_id = ?").run(t,r).changes>0;return s&&Ws(e,t),{entity_id:t,depends_on_id:r,changed:s,revision:Le(e,t).revision}});return yt(n)}var F$=new Set(["todo","in-progress"]),vn=new Set(["task","subtask"]),Gt="on-hold";function le(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}var zs="blocked",An=new Set(["done","closed"]);function ht(e){return An.has(le(e))}function Xs(e){return e.kind==="epic"&&!ht(e.status)&&le(e.status)!==Gt}var Ys=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 Qs(e,t){return(ct(e,t.id,"outgoing").outgoing??[]).some(n=>le(n.status)!=="done")}var q$=45*6e4;function Sf(e,t={}){let r=t.nowMs??Date.now(),n=t.staleInProgressThresholdMs??q$,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===zs){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&&!Qs(e,i)&&s.push({...i,attentionReason:"dependency_ready"})}return s}function bc(e){let t=le(e);return t==="done"||t===Gt}function Ks(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 To(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=>Ys.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||!Ys.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 ht(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)===zs&&!Vt(e,n,r))}var Sc=24*60*6e4,H$="DESIGN-FIRST:";function vf(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(H$)&&n-Date.parse(s.updated_at)>=r&&!Vt(e,s,o)&&!Qs(e,s)).map(s=>({id:s.id,title:s.title,updatedAt:s.updated_at}))}function Af(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 B$(e,t){return e.prepare("SELECT 1 FROM entities WHERE parent_id = ? LIMIT 1").get(t)!==void 0}function W$(e,t){return t.entities.filter(n=>n.kind==="epic"&&!ht(n.status)&&le(n.status)!==Gt).filter(n=>B$(e,n.id)&&!Ks(e,n.id))}function Js(e){return`'${e.replace(/'/g,"'\\''")}'`}var G$=3e4;function Ec(e,t={}){let r=t.timeoutMs??G$,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=U$(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 V$="ollama/qwen2.5:14b",J$=5e3,K$="deepseek/deepseek-flash";async function Zs(e,t={}){if(t.model!==void 0)return Ec(e,t);let r=await Ec(e,{...t,model:V$,timeoutMs:t.timeoutMs??J$});return r!==null?r:Ec(e,{...t,model:K$})}var z$=15*6e4;function Y$(e){let t=e.filter(r=>r.kind==="epic"&&!ht(r.status)&&le(r.status)!==Gt);return t.length===1?t[0]:null}async function $f(e,t,r={}){let n=r.backoffMs??z$,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=>Ys.has(le(k.status))),c=null,l=!1;for(let k of a){let H=Tc(e,k.id);if(H===null||!Ys.has(le(H.status)))continue;l=!0;let C=Date.now(),w=typeof H.attrs?.expected_reset_ts=="string"?Date.parse(H.attrs.expected_reset_ts):NaN;if(!Number.isNaN(w)&&w>C)continue;let T=typeof H.attrs?.last_renudge_ts=="string"?Date.parse(H.attrs.last_renudge_ts):NaN;if(!(!Number.isNaN(T)&&C-T<n)){c=H;break}}if(l){if(c===null)return null;let k=c.id,H=c.epochId;return{message:`Task #${c.id} ("${c.title}") is marked ${c.status} -- not nudging further; report status if this persists.`,onSent:()=>{e.transaction(()=>{let N=Tc(e,k);N===null||N.epochId!==H||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=_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?`
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=W$(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 ${Js(f.owner_team_path)} --owner-alias ${Js(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=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?`
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 H=[];return Qs(e,k)&&H.push("still has an unmet dependency"),Ks(e,k.id)&&H.push("still has an incomplete subtask"),{entity:k,reasons:H}}).filter(k=>k.reasons.length>0);if(g.length>0){let{entity:k,reasons:H}=g[0];return{message:`${k.kind==="subtask"?"Subtask":"Task"} #${k.id} ("${k.title}") is marked done but ${H.join(" and ")} -- please double-check and resolve the contradiction (confirm it's genuinely finished, or reopen it if something was missed).`}}let y=i.filter(k=>le(k.status)==="done"&&!j$(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=>F$.has(le(k.status))&&le(k.status)!==Gt&&!Ks(e,k.id));if(E.length===0){let k=i.filter(A=>{let q=le(A.status);return q!==zs&&q!==Gt&&Ks(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 H=i.filter(A=>le(A.status)===Gt),C=i.filter(A=>le(A.status)!==Gt&&le(A.status)!==zs),w=t.entities.some(A=>A.kind==="epic"&&!ht(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=Y$(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 ${Js(U)} --owner-alias ${Js(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=H.length>0&&u.length>0?"All your non-blocked/non-held tracked tasks are done.":H.length>0?"All your non-held tracked tasks are done.":u.length>0?"All your non-blocked tracked tasks are done.":"All your tracked tasks are done.",$=[];H.length>0&&$.push(`${H.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=>!Qs(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?()=>_f(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("; ")}.)`:"",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?`
188
188
 
189
189
  ${k}`:""}${d}${_}`,onSent:x}}let L=R.description.trim();return{message:`Continue task #${R.id}: "${R.title}" (status: ${R.status}).${L?`
190
190
 
191
191
  ${L}`:""}
192
192
 
193
- (${v.length-1} other ready task(s) also available: \`lmauto tasks list --owner-team <path> --owner-alias <alias> --status todo\`.)`+d+_,onSent:x}}var Te={idleThresholdMs:45*6e4,cooldownMs:30*6e4};function Q$(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||cf(e,t.name))return!1;let r;try{r=Q(t)}catch{return!0}return xe(e,r,t.leadAlias)===null}function X$(e){return vc({...e,config:{...e.config,idleThresholdMs:0}})}function kf(e){return`last_nudged:${e}`}function xc(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(kf(t))?.v??null}function bo(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(kf(t),r)}function xf(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:Q$(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 Rf(e,t,r,n,o,s,i){let a=xf(e,t,r,o,s,i,n);return a!==null&&vc(a)}async function Rc(e,t,r,n,o=Te,s=Date.now()){let i=await Ja(e,t,t.name,s);return Rf(e,t,r,n,o,s,i)}function Z$(e,t,r,n,o=Te,s=Date.now()){return Rf(e,t,r,n,o,s,ie(e,t.name))}async function kn(e,t,r,n,o=Te,s=Date.now(),i={}){let a=[];for(let c of t){if(!c.autoNudge||ie(e,c.name)?.confirmed_done_ts)continue;(i.readOnly?Z$(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 Nf(e,t,r,n,o=Te,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=xf(e,c,r,o,s,l,n);u!==null&&(vc(u)&&i.push(c.name),X$(u)&&a.push(c.name))}return{stalled:i,continueEligible:a}}import{existsSync as Lf,readFileSync as If}from"node:fs";import{dirname as Lc,join as Cf}from"node:path";import{fileURLToPath as Of}from"node:url";var Nc={sha:"unknown",dirty:!0,builtAt:"unknown"};function ek(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 Df(){let e=Lc(Of(import.meta.url));for(let t=0;t<5;t+=1){let r=Cf(e,"package.json");if(Lf(r))try{let n=JSON.parse(If(r,"utf8"));if(n&&typeof n=="object"&&typeof n.version=="string")return n.version}catch{}e=Lc(e)}return"unknown"}function Ic(){let e=Cf(Lc(Of(import.meta.url)),"..","build-info.json");if(!Lf(e))return Nc;try{let t=JSON.parse(If(e,"utf8"));return ek(t)?t:Nc}catch{return Nc}}var tk="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()||tk).replace(/\/+$/,"")}import{createServer as rk}from"http";import{Http2ServerRequest as Uf,constants as nk}from"http2";import{Http2ServerRequest as Cc}from"http2";import{Readable as Mf}from"stream";import pk from"crypto";var Zr=class extends Error{constructor(e,t){super(e,t),this.name="RequestError"}},ok=e=>e instanceof Zr?e:new Zr(e.message,{cause:e}),sk=global.Request,So=class extends sk{constructor(e,t){typeof e=="object"&&Nn in e&&(e=e[Nn]()),typeof t?.body?.getReader<"u"&&(t.duplex??="half"),super(e,t)}},ik=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)},Ff=Symbol("wrapBodyStream"),ak=(e,t,r,n,o)=>{let s={method:e,headers:r,signal:o.signal};if(e==="TRACE"){s.method="GET";let i=new So(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[Ff]){let i;s.body=new ReadableStream({async pull(a){try{i||=Mf.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=Mf.toWeb(n);return new So(t,s)},Nn=Symbol("getRequestCache"),qf=Symbol("requestCache"),ei=Symbol("incomingKey"),ti=Symbol("urlKey"),ck=Symbol("headersKey"),Rn=Symbol("abortControllerKey"),lk=Symbol("getAbortController"),vo={get method(){return this[ei].method||"GET"},get url(){return this[ti]},get headers(){return this[ck]||=ik(this[ei])},[lk](){return this[Nn](),this[Rn]},[Nn](){return this[Rn]||=new AbortController,this[qf]||=ak(this.method,this[ti],this.headers,this[ei],this[Rn])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(e=>{Object.defineProperty(vo,e,{get(){return this[Nn]()[e]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(e=>{Object.defineProperty(vo,e,{value:function(){return this[Nn]()[e]()}})});Object.defineProperty(vo,Symbol.for("nodejs.util.inspect.custom"),{value:function(e,t,r){let n={method:this.method,url:this.url,headers:this.headers,nativeRequest:this[qf]};return`Request (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(vo,So.prototype);var uk=(e,t)=>{let r=Object.create(vo);r[ei]=e;let n=e.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(e instanceof Cc)throw new Zr("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[ti]=a.href}catch(a){throw new Zr("Invalid absolute URL",{cause:a})}return r}let o=(e instanceof Cc?e.authority:e.headers.host)||t;if(!o)throw new Zr("Missing host header");let s;if(e instanceof Cc){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[ti]=i.href,r},Dc=Symbol("responseCache"),xn=Symbol("getResponseCache"),en=Symbol("cache"),Uc=global.Response,Ln=class jf{#t;#e;[xn](){return delete this[en],this[Dc]||=new Uc(this.#t,this.#e)}constructor(t,r){let n;if(this.#t=t,r instanceof jf){let o=r[Dc];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[Dc]};return`Response (lightweight) ${r(n,{...t,depth:e==null?null:e-1})}`}});Object.setPrototypeOf(Ln,Uc);Object.setPrototypeOf(Ln.prototype,Uc.prototype);async function dk(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function Hf(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 mk(e,t){if(e.locked)throw new TypeError("ReadableStream is locked.");return t.destroyed?void 0:Hf(e.getReader(),t)}var Mc=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},fk="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=pk);var Fc=Symbol("outgoingEnded"),Pf=Symbol("incomingDraining"),hk=500,gk=64*1024*1024,Oc=e=>{let t=e;if(e.destroyed||t[Pf])return;if(t[Pf]=!0,e instanceof Uf){try{e.stream?.close?.(nk.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,hk);s.unref?.();let i=a=>{r+=a.length,r>gk&&o()};e.on("data",i),e.on("end",n),e.on("error",n),e.resume()},_k=()=>new Response(null,{status:400}),Bf=e=>new Response(null,{status:e instanceof Error&&(e.name==="TimeoutError"||e.constructor.name==="TimeoutError")?504:500}),Pc=(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))},Wf=e=>{"flushHeaders"in e&&e.writable&&e.flushHeaders()},Gf=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=Mc(o);else if(Array.isArray(o)){let i=new Headers(o);s=i.has("content-length"),o=Mc(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())):(Wf(t),await mk(n,t)?.catch(i=>Pc(i,t))),t[Fc]?.()},wk=e=>typeof e.then=="function",yk=async(e,t,r={})=>{if(wk(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(Bf);if(en in e)return Gf(e,t);let n=Mc(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 dk(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&&Wf(t),await Hf(o,t,a))}else n[fk]||(t.writeHead(e.status,n),t.end());t[Fc]?.()},Ek=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==So&&(Object.defineProperty(global,"Request",{value:So}),Object.defineProperty(global,"Response",{value:Ln})),async(n,o)=>{let s,i;try{i=uk(n,t.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[Ff]=!0,n.on("end",()=>{a=!0}),n instanceof Uf&&(o[Fc]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{Oc(n)})})}),o.on("finish",()=>{a||Oc(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(()=>{Oc(n)})})}),s=e(i,{incoming:n,outgoing:o}),en in s)return Gf(s,o)}catch(a){if(s)return Pc(a,o);if(t.errorHandler){if(s=await t.errorHandler(i?a:ok(a)),!s)return}else i?s=Bf(a):s=_k()}try{return await yk(s,o,t)}catch(a){return Pc(a,o)}}},Tk=e=>{let t=e.fetch,r=Ek(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||rk)(e.serverOptions||{},r)},Vf=(e,t)=>{let r=Tk(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var qc=(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 Jf=Symbol();var Kf=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var zf=32,bk=1e4,ri=e=>"headers"in e,Xf=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(ri(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?Sk(e,{all:r,dot:n}):{}};async function Sk(e,t){if(!ri(e)&&e.bodyCache.formData)return Yf(await e.bodyCache.formData,t);let r=ri(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=Kf(n,r.get("Content-Type")||"");ri(e)||(e.bodyCache.formData=o);let s=await o;return s?Yf(s,t):{}}function Yf(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,s)=>{t.all||s.endsWith("[]")?vk(r,s,o):r[s]=o}),t.dot&&Object.entries(r).forEach(([o,s])=>{o.includes(".")&&(Ak(r,o,s,n),delete r[o])}),r}var vk=(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},Ak=(e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,s=t.split(".",zf+2);s.length>zf+1&&Qf(),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++>=bk&&Qf(),o[i]=Object.create(null)),o=o[i])})},Qf=()=>{throw new Error("Nesting limit exceeded")};var Hc=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Zf=e=>{let{groups:t,path:r}=$k(e),n=Hc(r);return kk(n,t)},$k=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},kk=(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},ni={},ep=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return ni[n]||(r[2]?ni[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:ni[n]=[e,r[1],!0]),ni[n]}return null},tp=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},xk=e=>tp(e,decodeURI),Bc=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 xk(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var rp=e=>{let t=Bc(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}`}`),oi=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)},si=e=>e.indexOf("%")!==-1?tp(e,Rk):e,jc=e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),si(e)),np=(e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let l=a+t.length+2,u=e.indexOf("&",l);return jc(e.slice(l,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let s=Object.create(null);o??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let l=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(o&&(l=jc(l)),i=a,l==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=jc(u))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(u)):s[l]??=u}return t?s[t]:s},op=np,sp=(e,t)=>np(e,t,!0),Rk=decodeURIComponent;var ip=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&&si(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]=si(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return op(this.url,e)}queries(e){return sp(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 Xf(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[Jf](){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 ap={Stringify:1,BeforeStream:2,Stream:3},Nk=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var Wc=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=>Wc(c,t,!1,n,o))).then(()=>o[0]));return r?Nk(await i,s):i};var Lk="text/plain; charset=UTF-8",Gc=(e,t)=>({"Content-Type":e,...t}),Ao=(e,t)=>new Response(e,t),Vc=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 ip(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||=Ao(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=Ao(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=Ao(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 Ao(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,Gc(Lk,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,Gc("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,Gc("text/html; charset=UTF-8",r));return typeof e=="object"?Wc(e,ap.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??=()=>Ao(),this.#l(this))};var Ke="ALL",cp="all",lp=["get","post","put","delete","options","patch","query"],ii="Can not add a route since the matcher is already built.",ai=class extends Error{};var up="__COMPOSED_HANDLER";var Ik=e=>e.text("404 Not Found",404),dp=(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)},mp=class fp{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...lp,cp].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??Bc:rp}#e(){let t=new fp({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Ik;errorHandler=dp;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===dp?s=o.handler:(s=async(i,a)=>(await qc([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[up]=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 Vc(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=qc(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 ci=[];function Jc(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[[],ci];let l=c.indexOf("",1);return[i[1][l],c]};return this.match=n,n(e,t)}var In="[^/]+",xr=".*",cr="(?:|/.*)",kr=Symbol(),pp=new Set(".\\+*[^]$()");function Ck(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 hp=class Kc{#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&&pp.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 Kc}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 Kc}i=d}if(i.#t!==void 0)throw kr;i.#t=s?-1:r}buildRegExpStr(){let r=Object.keys(this.#r).sort(Ck).map(n=>{let o=this.#r[n],s=o.buildRegExpStr();return s===""?"":(typeof o.#e=="number"?`(${n})@${o.#e}`:pp.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 zc=class{#t={varIndex:0};#e=new hp;#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 gp=He();function _p(e){return gp[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?cr:t==="*"?xr:`/:${In}`)}$`)}function li(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(_p(r).test(t))return[...e[r]]}var ui=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={[Ke]:He()},this.#e={[Ke]:He()},this.#r={[Ke]:new zc}}#s(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===kr?new ai(t):r}}add(e,t,r){let n=this.#t,o=this.#e;if(!n)throw new Error(ii);if(!n[e]){this.#r[e]=new zc;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=_p(t);for(let c of s)n[c][t]||(this.#s(c,t),n[c][t]=li(n[c],t)||li(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=oi(t)||[t];for(let a of i)for(let c of s)o[c][a]||(this.#s(c,a),o[c][a]=li(n[c],a)||li(n[Ke],a)||[]),o[c][a].push([r,a])}match=Jc;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,gp=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()]),ci];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 Yc=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(ii);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 ai)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 Qc=He(),Ok=0,wp=class yp{#t=[];#e=He();#r=[];#s;#n=Qc;insert(t,r,n){let o=this,s=Zf(r),i=new Set,a=0;for(let c of s){let l=s[++a],u=ep(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 yp;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:++Ok}})}#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=Qc;let s=[this],i=Hc(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===Qc?{}:{...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 H=r[0]==="/"?1:0;for(let C=0;C<c;C++)l[C]=H,H+=i[C].length+1}let L=r.slice(l[u]),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 H 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 Xc=class{name="TrieRouter";#t=new wp;add(e,t,r){for(let n of oi(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};var tn=class extends mp{constructor(e={}){super(e),this.router=e.router??new Yc({routers:[new ui,new Xc]})}};import{join as Dk}from"node:path";function Mk(e){return e||(process.env.LMBEE_TEAMS_CONF?process.env.LMBEE_TEAMS_CONF:Dk(process.cwd(),"teams.conf"))}function Pk(e,t){let r=process.env.LMBEE_TEAM_NAME;if(r===void 0)return;let n=t.find(o=>o.name===r);if(!(n===void 0||!B(n)))try{Yd(e.db,r,new Date().toISOString())}catch{}}function di(e={}){let t=Ts(e.dbPath,{readOnly:e.readOnly??!1}),r=Mk(e.teamsConfPath),n=Jr(t.db,r);return e.readOnly||Pk(t,n),{db:t,teamsConfPath:r,teams:n}}import{existsSync as cL,readFileSync as lL,statSync as uL}from"node:fs";import{execFile as Uk}from"node:child_process";import{promisify as Fk}from"node:util";var mi=Fk(Uk),ko=3,$o="auto_nudge_redirect:",Zc=3,el=5*60*6e4;function Et(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get($o+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:Zc,hoursThresholdMs:typeof n.hoursThresholdMs=="number"&&n.hoursThresholdMs>0?n.hoursThresholdMs:el,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 tl(e){return e.prepare("SELECT k FROM kv WHERE k LIKE ?").all($o+"%").map(r=>r.k.slice($o.length))}function fi(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run($o+t,JSON.stringify(r))}function Ep(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run($o+t)}async function Tp(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 qk(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 bp(e,t,r,n,o,s=mi){let i=r.shiftStartedTs!==null,a=i?r.shiftStartedSha:await Tp(n,s);fi(e,t,{...r,turnsDispatched:r.turnsDispatched+1,shiftStartedTs:i?r.shiftStartedTs:o,shiftStartedSha:a})}async function Sp(e,t,r=Date.now(),n=mi){let o=[];for(let s of tl(e)){let i=Et(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 qk(a,i.shiftStartedSha,n):null,u=i.turnsDispatched<=ko&&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 vp(e,t,r,n,o=mi){let s=Et(e,t);if(s===null)return;let i=await Tp(r,o);fi(e,t,{...s,shiftStartedTs:n,shiftStartedSha:i,lastReviewedTurn:s.turnsDispatched})}async function Ap(e,t,r=mi){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+_,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?`
194
194
 
195
195
  Commits this shift:
196
- ${s}`:"";return e.isRampUp?`[auto-nudge-redirect] RAMP-UP turn ${e.turnNumber}/${ko} 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 Wk}from"node:child_process";import{existsSync as Gk,readdirSync as Rp,readFileSync as Np,statSync as Vk}from"node:fs";import{hostname as Jk}from"node:os";import{promisify as Kk}from"node:util";import{existsSync as jk,statSync as Hk}from"node:fs";var MB=15*6e4;function Bk(e,t,r={}){let n=r.existsSyncImpl??jk,o=r.statSyncImpl??Hk,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 rl(e,t,r){if(e===null)return!1;let n=Date.parse(e);return Number.isNaN(n)?!1:r-n<=t}function $p(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&&Bk(e,t,o))return!0;if(n===void 0)return!1;let s=o.nowMs??Date.now();return rl(r,n,s)}var zk=Kk(Wk),Yk=45*6e4,Lp=100,kp=Lp,Qk=3;async function Xk(e,t=3e4){try{let{stdout:r}=await zk("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 pi(e,t){try{let r=Np(`${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 Ip(e,t="/proc"){let r=pi(e,t);return r===null?null:r.utime+r.stime}function xp(e,t){try{let r=Np(`${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 nl(e,t="/proc"){let r=pi(e,t);if(r===null)return null;let n;try{n=Rp(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=pi(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 Cp(e,t="/proc"){let r=xp(e,t);if(r===null)return null;let n;try{n=Rp(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=pi(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=xp(c,t);l!==null&&(s+=l),i.push(...o.get(c)??[])}return s}function Zk(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 ex(e,t,r,n){let o=n.fetchHealthImpl??Xk,s=n.readProcStatImpl??nl,i=n.hostnameImpl??Jk,a=n.wallClockThresholdMs??Yk,c=n.requiredLowCpuStreak??Qk,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=Zk(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<kp,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 ${kp/Lp}s of CPU time across ${v} consecutive checks -- possibly hung, not just slow.`,m)}async function Op(e,t,r={}){let n=r.existsSyncImpl??Gk,o=r.statSyncImpl??Vk,s=r.nowMs??Date.now();for(let i of t){if(!B(i))continue;if(r.sessionAliveExemptTeamName!==void 0&&i.name===r.sessionAliveExemptTeamName&&Cn(r.sessionAliveExemptPath,r.sessionAliveFreshnessMs,r.activityFreshnessMs!==void 0?ie(e,i.name)?.last_cli_activity_ts??null:null,r.activityFreshnessMs,{existsSyncImpl:n,statSyncImpl:o,nowMs:s})){Ba(e,i.name);continue}let a;try{a=Q(i)}catch{continue}try{await ex(e,i,a,r)}catch{continue}}}var xo="provider_disabled:";function Dp(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 hi(e,t){let r=e.prepare("SELECT v FROM kv WHERE k = ?").get(xo+t);return r===void 0?null:Dp(t,r.v)}function gi(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(xo+t,JSON.stringify(n))}function Mp(e,t){e.prepare("DELETE FROM kv WHERE k = ?").run(xo+t)}function Ro(e){let t=e.prepare("SELECT k, v FROM kv WHERE k LIKE ?").all(`${xo}%`),r=[];for(let n of t){let o=n.k.slice(xo.length),s=Dp(o,n.v);s!==null&&r.push(s)}return r}function rt(e,t,r=Date.now()){let n;try{n=hi(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 tx,readFileSync as rx,readdirSync as nx,statSync as Pp}from"node:fs";import{basename as _i}from"node:path";var sl="orphan_would_reap",ox=5e3,sx=6e4,ix=100,ax=3,cx=45*6e4;function Up(e,t){try{let n=rx(`${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 Fp(e,t){try{return Pp(`${e}/${t}`).mtime.getTime()}catch{return null}}function il(e){let t;try{t=nx(e)}catch{return[]}let r=[];for(let n of t){if(!/^\d+$/.test(n))continue;let o=Number(n),s=Up(e,o);if(s===null)continue;let i=Fp(e,o);i!==null&&r.push({pid:o,target:s,startedAtMs:i})}return r.sort((n,o)=>n.pid-o.pid),r}function ol(e){let t=e.lastIndexOf(":");return t===-1?null:{teamfilePath:e.slice(0,t),alias:e.slice(t+1)}}function lx(e,t){if(t===null)return!1;let r=ol(e),n=ol(t);return r===null||n===null?!1:r.alias===n.alias&&_i(r.teamfilePath)===_i(n.teamfilePath)}function ux(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"&&lx(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 dx(e,t,r,n,o,s,i,a){let c=s(t.pid,a);if(c===null)return!1;let l=Qd(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<ix?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 mx(e,t){let r=e.find(n=>n.name===t);if(r===void 0||!B(r))return null;try{return Q(r)}catch{return null}}function fx(e,t){let r=ol(t);if(r===null)return t;for(let n of e)if(B(n))try{let o=Q(n);if(_i(o)===_i(r.teamfilePath))return n.name}catch{continue}return t}async function px(e,t,r,n,o){if(Up(e,t.pid)!==t.target||Fp(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 qp(e,t,r,n={}){let o=n.procPath??"/proc",s=n.safetyMarginMs??sx,i=n.sigkillGraceMs??ox,a=n.requiredLowCpuStreak??ax,c=n.minCorroborationWallClockMs??cx,l=n.existsSyncImpl??tx,u=n.statSyncImpl??Pp,d=n.killImpl??process.kill.bind(process),m=n.sleepImpl??(R=>new Promise(x=>setTimeout(x,R))),f=n.readProcCpuTicksImpl??Ip,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?mx(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=il(o)}catch{return}Xd(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=ux(R,S,r);if(x.action!=="reap"){Ga(e,R.target,R.startedAtMs,R.pid);continue}if(!(x.requiresCpuCorroboration&&!dx(e,R,a,c,_,f,g,o))){if(h){try{try{p(e,fx(t,R.target),sl,_,{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 px(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 hx}from"node:fs";import{homedir as gx}from"node:os";import{join as _x}from"node:path";function wx(e){return e||(process.env.LCTL_STATE_DB?process.env.LCTL_STATE_DB:_x(gx(),".lmctl","state.db"))}function On(e){let t=wx(e);if(!hx(t))throw new Error(`lctl-src state db not found at ${t} -- set LCTL_STATE_DB or check the path`);return new pt(t,{readonly:!0,fileMustExist:!0})}function yx(e){return e==="done"?"done":e==="error"||e==="aborted"?"failed":e==="busy"||e==="running"||e==="cancelled"?"contention":null}function jp(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=yx(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 Ex=30*24*60*6e4;function Tx(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 Hp(e,t={}){let r=t.procPath??"/proc",n=t.nowMs??Date.now(),o=new Date(n).toISOString(),s=t.retentionMs??Ex,i=t.openLctlDbImpl??On,a;try{a=il(r)}catch{return}for(let u of a)try{let d=nl(u.pid,r),m=Cp(u.pid,r);Zd(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=Tx(i,t.lctlStateDbPath,u.pid);tm(e,u.target,u.started_at_ms,u.pid,d,o)}catch{}try{em(e,new Date(n-s).toISOString())}catch{}}import{createHash as bx}from"node:crypto";var Sx=24*60*6e4,vx=200,Ax=new Set(["all_good","needs_review"]),$x=24*60*6e4;function kx(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 xx(e,t){return kx(e,t).map(r=>{let n=Sn(e,r.id),o=Vs(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 Rx(e,t){let r=JSON.stringify([e.status,e.title,e.description,t.map(n=>[n.id,n.status,n.latestNoteId])]);return bx("sha256").update(r,"utf8").digest("hex")}function Nx(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}/${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(`
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 Lx(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"||!Ax.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,vx)}}async function Ix(e,t,r,n){let o=n.decompositionGraceMs??$x;if(r.length===0&&Date.now()-Date.parse(t.created_at)<o)return;let s=Rx(t,r),i=n.cooldownMs??Sx,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 Zs(Nx(t,r),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),u=Lx(l);if(u===null)return;let d=new Date().toISOString();wf(e,t.id,d,s,u.label==="needs_review"?{needsReview:!0,reason:u.reason}:{needsReview:!1})}async function Bp(e,t,r={}){for(let n of t){if(!B(n))continue;let o;try{o=Q(n)}catch{continue}let s=xe(e,o,n.leadAlias);if(s!==null)for(let i of s.entities.filter(Xs)){let a=xx(e,i.id);try{await Ix(e,i,a,r)}catch{continue}}}}import{createHash as Ux}from"node:crypto";import{execFile as Cx}from"node:child_process";import{promisify as Ox}from"node:util";var Wp=Ox(Cx),Dx=/^(?:(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) )?([A-Za-z0-9_]+): (.*)$/,Mx="\u2026 [truncated older output \u2014 raise with --max-bytes]";function Px(e){let t=[],r=!1;for(let n of e.split(`
220
- `)){if(n.length===0)continue;if(n===Mx){r=!0;continue}if(/^\s/.test(n)){let s=t[t.length-1];s&&(s.text+=`
221
- ${n.replace(/^ {2}/,"")}`);continue}let o=Dx.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 wi(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 Wp(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 Px(i)}async function yi(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 Wp(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 Fx=200,qx=new Set(["genuinely_done","blocked","stalled_needs_nudge","produced_output_no_report"]),jx=2*60*6e4;function Hx(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 Bx(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 Gp(e,t,r=null,n=[]){let o=Ux("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 Wx(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 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(`
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 Gx(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"||!qx.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,Fx)}}function Vx(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 Jx(e,t,r,n){let o=n.fetchTailJsonImpl??yi,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=Hx(e,r,t.leadAlias),a=Bx(e,r,t.leadAlias,Date.now())}catch{return}let c=ie(e,t.name),l=Gp(s,i,c,a),u=Gp("",i,c,a),d=n.cooldownMs??jx,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 Zs(Wx(t.name,s,i,c,a),{...n.spawnPrefix!==void 0?{spawnPrefix:n.spawnPrefix}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{}}),_=Gx(h);if(_===null)return;let g=_.label==="stalled_needs_nudge"&&a.length>0&&i.length===0?{label:"blocked",reason:Vx(a)}:_;jd(e,t.name,g.label,g.reason,new Date().toISOString(),l,u)}async function Vp(e,t,r,n={}){for(let o of t){let s=r.find(a=>a.name===o);if(s===void 0||!B(s))continue;let i;try{i=Q(s)}catch{continue}try{await Jx(e,s,i,n)}catch{continue}}}import{execFileSync as GR}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 cl(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=No(r[0],0,59);t="hour";let o=No(r[1],0,23);t="dayOfMonth";let s=No(r[2],1,31);t="month";let i=No(r[3],1,12);t="dayOfWeek";let a=No(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 No(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:al(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:al(l[0],t,r,s),d=a==="*"?r:l[1]!==void 0?al(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 al(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 Kx(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 Jp(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(Kx(e,new Date(s)))return!0;return!1}import{spawn as zx}from"node:child_process";import{closeSync as Yx,existsSync as Qx,mkdirSync as Xx,openSync as Zx,readdirSync as eR,unlinkSync as tR}from"node:fs";import{homedir as rR}from"node:os";import{join as Ei}from"node:path";var Kp=["systemd-run","--user","--scope","--collect","--quiet"],nR=10,oR=50*6e4,sR=5e3;function Ti(){return process.env.LMBEE_CRON_LOG_DIR?process.env.LMBEE_CRON_LOG_DIR:Ei(rR(),".lmbee","cron-logs")}function iR(e,t){try{let r=eR(e).sort();for(let n of r.slice(0,Math.max(0,r.length-t)))try{tR(Ei(e,n))}catch{}}catch{}}function aR(e,t){return[...t.spawnPrefix??(t.systemdUnitName!==void 0?[...Kp,"--unit",t.systemdUnitName,"--"]:[...Kp,"--"]),"sh","-c",e]}function Lo(e,t={}){let r=Ei(t.logDir??Ti(),String(e.id));Qx(r)||Xx(r,{recursive:!0});let n=Ei(r,`${new Date().toISOString().replace(/[:.]/g,"-")}.log`),o=Zx(n,"a"),s=aR(e.action_payload,t),[i,...a]=s,c;try{c=zx(i,a,{detached:!0,stdio:["ignore",o,o],...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{}})}finally{Yx(o)}c.unref();let l=c.pid??null,u=!1,d=t.timeoutMs??oR,m=t.sigkillGraceMs??sR,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),iR(r,nR),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 cR,randomUUID as lR}from"node:crypto";var rn=16*1024,Co=16*1024,ll=512,bi=100,ul=4096,dl=1024*1024,Oo="('pending','running')",uR="execution_state != 'gone' OR (status = 'escalated' AND escalation_resolved_at IS NULL)";function Do(e){let{run_token_hash:t,...r}=e;return r}function zp(e){return cR("sha256").update(e,"utf8").digest("hex")}function Tt(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 Yp(e,t){return Tt(()=>e.prepare("SELECT * FROM cron_runs WHERE id = ?").get(t)??null)}function ze(e,t){let r=Yp(e,t);if(r===null)throw new P("NOT_FOUND",`Cron run ${t} does not exist`,3);return r}function dR(e,t){return e.prepare("SELECT * FROM cron_runs WHERE run_token_hash = ?").get(t)??null}function Rr(e,t){return Tt(()=>e.prepare(`SELECT * FROM cron_runs WHERE job_id = ? AND (${uR}) ORDER BY id DESC LIMIT 1`).get(t)??null)}function ml(e,t,r,n){return Tt(()=>{let o=Rr(e,t);if(o!==null)return o.status==="escalated"?{kind:"escalation",run:o}:{kind:"overlap",run:o};let s=lR(),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,zp(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 Si(e,t,r,n){Tt(()=>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 fl(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 mR(e,t){Tt(()=>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 Mo(e,t,r){Tt(()=>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 Io(e,t,r){let n=we(e,t);if(Buffer.byteLength(n,"utf8")>r)throw new P("INVALID_ARGUMENT",`${t} exceeds ${r} bytes`);return n}function fR(e){if(e===void 0)return[];if(!Array.isArray(e))throw new P("INVALID_ARGUMENT","artifacts must be an array");if(e.length>bi)throw new P("INVALID_ARGUMENT",`at most ${bi} artifacts are allowed`);return e.map(t=>{if(typeof t!="string")throw new P("INVALID_ARGUMENT","artifacts must be strings");return Io(t,"artifact",ul)})}function Qp(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=Io(e.summary,"summary",rn),n=fR(e.artifacts),o=null,s=null,i=null;if(e.status==="escalated"){o=Io(e.action??"","requested action",Co),i=e.reason!==void 0?Io(e.reason,"escalation reason",Co):r;let a=e.owner!==void 0?Io(e.owner,"owner",ll):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 Xp(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 Zp(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 pl(e,t,r){let n=Qp(r,Zp(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 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 = ?,
266
266
  escalation_owner = ?, reported_at = ?, finished_at = ?, updated_at = ?
267
- WHERE id = ? AND status IN ${Oo} 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(Xp(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 eh(e,t,r){return Tt(()=>{let n=dR(e,zp(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=Qp(r,Zp(n));if(Xp(n,o))return n;throw new P("CONFLICTING_REPORT",`Cron run ${n.id} already has a different terminal report`,4)}return pl(e,n,r)})}function th(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&&pl(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 ${Oo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return mR(e,t),ze(e,t)});return Tt(()=>n.immediate())}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&&pl(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 ${Oo} AND reported_at IS NULL`).run(i,r.fallback.summary.slice(0,rn),de(),de(),t)}return ze(e,t)});return Tt(()=>n.immediate())}function hl(e,t,r){return Tt(()=>{let n=Yp(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 ${Oo} AND reported_at IS NULL`).run(o,r.summary.slice(0,rn),de(),de(),n.id),ze(e,n.id)})}function nh(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 ${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,
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 ${Oo} 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 Tt(()=>n.immediate())}function vi(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 Tt(()=>{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 gl}from"node:child_process";import{createHash as pR}from"node:crypto";import{existsSync as hR,mkdirSync as gR,mkdtempSync as _R,readFileSync as wR,rmSync as oh,writeFileSync as ch}from"node:fs";import{homedir as yR,tmpdir as ER}from"node:os";import{isAbsolute as TR,join as Fo,resolve as Dn}from"node:path";var bR=["lmctl"],SR=["miniplayer"],vR=10*6e4,AR=50*6e4,$R=50*6e4,sh=24*60*6e4,lh=5e3,Ai=1024*1024;function Po(){return{text:"",overflow:!1}}function Uo(e,t){if(e.overflow)return;let r=e.text+t.toString("utf8");r.length>Ai?(e.text=r.slice(0,Ai),e.overflow=!0):e.text=r}function Ye(e){return e instanceof Error?e.message:String(e)}function kR(e,t,r){try{Mo(e,t,r)}catch{}}function Be(e,t,r){try{return th(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 gt(e,t,r,n){kR(e,t,r);try{rh(e,t,n)}catch(o){process.stderr.write(`[lmcron] run ${t} outcome could not be persisted (fence retained): ${Ye(o)}
272
- `)}}function _l(e,t,r){let n=e??t;if(!Number.isFinite(n)||n<=0||n>sh)throw new Error(`${r} must be a positive number of milliseconds <= ${sh}`);return n}var ih=new Set(["claude","codex","opencode","lmplayer","gemini","copilot","qwen","agy","kimi","dsh","hermes","ClaudeMock"]),xR=/^[A-Za-z0-9][A-Za-z0-9._:@/+~-]*$/;function yl(e){if(!ih.has(e))throw new P("INVALID_ARGUMENT",`provider "${e}" is not one of lmctl's supported providers (${[...ih].join(", ")})`);return e}function El(e){if(!xR.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 $i(e){if(!TR(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 RR(e){let t=["_MEMBER_",`alias=${e.alias}`,`provider=${yl(e.provider)}`];return e.model!==null&&e.model!==void 0&&t.push(`model=${El(e.model)}`),t.push(`sessiondir="${$i(e.sessiondir)}"`),t.join(" ")}function NR(e){let t=e.name,r=t!==void 0&&t.length>0?Dn(t):":memory:";return pR("sha256").update(r,"utf8").digest("hex").slice(0,16)}function LR(){return process.env.LMBEE_CRON_SESSION_DIR?process.env.LMBEE_CRON_SESSION_DIR:Fo(yR(),".lmbee","cron-sessions")}function IR(e){return`'${e.replace(/'/g,"'\\''")}'`}function CR(e){let t=e.name;return t!==void 0&&t.length>0&&t!==":memory:"?`LMBEE_DB=${IR(Dn(t))} `:""}function OR(e,t,r){let n=CR(r);return`${e}
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}
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 DR(e,t){return`${e}
282
+ required. Never report succeeded unless the work actually succeeded.`}function MR(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 MR=new Set(["run_token","status","summary","artifacts","escalation"]),PR=new Set(["owner","reason","requestedAction"]);function uh(e,t){if(e===null)return{ok:!1,reason:"no output"};if(Buffer.byteLength(e,"utf8")>dl)return{ok:!1,reason:`result exceeds ${dl} 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(!MR.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>bi)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")>ul)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(!PR.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")>Co)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")>Co)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>ll)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 UR(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=Fo(r??LR(),NR(e)),s=t.session_generation??0,i=t.session_teamfile??Fo(o,`job-${t.id}-g${s}.lmctl`);if(t.session_teamfile!==null)return{teamfile:t.session_teamfile,alias:n};if(hR(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};gR(o,{recursive:!0});let a=RR({alias:n,provider:t.provider,model:t.model,sessiondir:t.working_directory});return ch(i,`#teamfile: ${i}
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}
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 Tl(e){try{return process.kill(-e,0),!0}catch{return!1}}function wl(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 FR(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 qR(e,t){try{let r=wR(e,"utf8").trim();return r.length>t?r.slice(-t):r}catch{return""}}var jR=500,ah=75;function HR(e){let{db:t,job:r,run:n}=e;try{Si(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{Lo({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===ah,l=qR(a,jR),u=o===ah?`script no-op (exit ${o})${l?`: ${l}`:""}`:`script exited with code ${o}${l?`: ${l}`:""}`;i!==null&&Tl(i)?gt(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 BR(e){let{db:t,job:r,run:n}=e,o,s,i,a;try{o=_l(e.timeoutMs,vR,"timeoutMs"),s=e.sigkillGraceMs??lh,i=[...e.spawnPrefixes?.miniplayer??SR,"run",...r.model!==null?["-m",r.model]:[]],a=DR(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=gl(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=Po(),m=Po(),f=!1,p=!1,h=setTimeout(()=>{f||(f=!0,wl(u,s),gt(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",_=>Uo(d,_)),u.stderr?.on("data",_=>Uo(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?gt(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&&Tl(y),v=d.overflow?{ok:!1,reason:`output exceeded the ${Ai}-byte capture limit`}:uh(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?gt(t,n.id,"miniplayer process group still alive after wrapper exit",S):d.overflow?gt(t,n.id,"miniplayer output exceeded the capture limit; result not trusted",S):Be(t,n.id,S)});try{Si(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(_)}
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
297
  `)}try{u.stdin?.write(a),u.stdin?.end()}catch(_){process.stderr.write(`[lmcron] miniplayer run ${n.id} stdin write failed: ${Ye(_)}
298
- `)}}function WR(e){let{db:t,job:r,run:n}=e,o,s,i;try{o=_l(e.timeoutMs,AR,"timeoutMs"),s=_l(e.seedTimeoutMs,$R,"seedTimeoutMs"),i=e.sigkillGraceMs??lh}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}=UR(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=OR(r.action_payload,e.runToken,t);v=_R(Fo(ER(),"lmbee-cron-session-")),S=Fo(v,`${n.id}.md`),ch(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=gl(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{oh(v,{recursive:!0,force:!0})}catch{}Be(t,n.id,{fallback:{ok:!1,summary:`session dispatch spawn error: ${Ye(J)}`}});return}k.unref();let H=Po(),C=Po(),w=!1,T=!1,N=()=>{try{oh(v,{recursive:!0,force:!0})}catch{}},U=setTimeout(()=>{w||(w=!0,wl(k,i),gt(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=>Uo(H,J)),k.stderr?.on("data",J=>Uo(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?gt(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&&Tl(ee),V=H.overflow?{kind:"overflow"}:FR(H.text),se=V.kind==="completed"?uh(V.text,e.runToken):null,$=V.kind==="completed"&&!oe&&!H.overflow,O=se!==null&&se.ok?{report:se.result}:{fallback:{ok:!1,summary:(V.kind==="completed"?"session ended without a valid report":V.kind==="stalled"?"session stalled (native turn still running)":V.kind==="busy"?"session was busy; not started":V.kind==="error"?`session provider error: ${V.message}`:V.kind==="overflow"?`session output exceeded the ${Ai}-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})`;gt(t,n.id,A,O)});try{Si(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{fl(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??bR,"seed",a],m=d[0],f=d.slice(1),p;try{p=gl(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=Po(),_=!1,g=!1,y=setTimeout(()=>{_||(_=!0,wl(p,i),gt(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=>Uo(h,E)),p.on("error",E=>{if(_)return;_=!0,clearTimeout(y);let v={fallback:{ok:!1,summary:`session seed spawn error: ${E.message}`}};g?gt(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){gt(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){gt(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{fl(t,n.id,{kind:"session",phase:"seed",teamfile:a,alias:c},p.pid??null)}catch{}}function bl(e){try{switch(e.job.action_kind){case"script":HR(e);return;case"miniplayer":BR(e);return;case"session":WR(e);return;default:Be(e.db,e.run.id,{fallback:{ok:!1,summary:`unsupported run worker kind: ${e.job.action_kind}`}})}}catch(t){gt(e.db,e.run.id,`unexpected worker dispatch failure: ${Ye(t)}`,{fallback:{ok:!1,summary:`worker dispatch error: ${Ye(t)}`}})}}function VR(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}function JR(e){return e==="script"||e==="session"||e==="miniplayer"}function bt(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 ki(e,t){e.prepare("UPDATE cron_jobs SET revision = revision + 1, updated_at = ? WHERE id = ?").run(de(),t)}function xi(e,t){return lr(()=>e.prepare("SELECT * FROM cron_jobs WHERE id = ?").get(t)??null)}function Ie(e,t){let r=xi(e,t);if(r===null)throw new P("NOT_FOUND",`Cron job ${t} does not exist`,3);return r}function KR(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 fh(e,t){we(t,"action_payload"),e==="enqueue"&&KR(t)}function ph(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(yl(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)");$i(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&&El(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 hh(e){let t=we(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 gh(e){let t=cl(e);if(!t.ok){let r=t.error.field?` (field: ${t.error.field})`:"";throw new P("INVALID_SCHEDULE",`${t.error.message}${r}`)}}function Ri(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=we(t.title,"title");if(!VR(t.actionKind))throw new P("INVALID_ARGUMENT",'action_kind must be "enqueue", "command", "script", "session", or "miniplayer"');gh(t.scheduleExpr),fh(t.actionKind,t.actionPayload),ph({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?hh(t.timezone):null,s=de();try{let i=e.prepare(t.id!==void 0?`INSERT INTO cron_jobs(id, title, schedule_expr, action_kind, action_payload, provider, model,
298
+ `)}}function 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,
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 Ni(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 _h(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=we(r.title,"title")),r.scheduleExpr!==void 0&&(gh(r.scheduleExpr),s.schedule_expr=r.scheduleExpr),r.actionPayload!==void 0&&(fh(o.action_kind,r.actionPayload),s.action_payload=r.actionPayload),r.timezone!==void 0&&(s.timezone=r.timezone===null?null:hh(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)&&ph({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=we(r.workingDirectory,"working_directory");o.action_kind==="session"&&$i(i),s.working_directory=i}}if(r.escalationOwner!==void 0&&(s.escalation_owner=r.escalationOwner===null?null:we(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 ki(e,t),Ie(e,t)});return lr(n)}function wh(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 ki(e,t),Ie(e,t)});return lr(n)}function yh(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 Eh(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),ki(e,t),Ie(e,t)});return lr(r)}var zR=24*60*60*1e3;function Th(e,t=GR){try{return t("systemctl",["--user","is-active","--quiet",e]),"active"}catch(r){return r.status===3?"confirmed-gone":"unknown"}}async function bh(e,t,r,n={}){let o=n.enqueueImpl??ge,s=n.spawnCommandImpl??Lo,i=n.isUnitStillRunningImpl??Th,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{YR(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??bl})}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",bt(d),a],u)}catch{}}return c}function dh(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 YR(e,t,r,n,o,s,i,a,c,l,u,d){let m=cl(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 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 = ?,
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>zR){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?dh(h,t.timezone):h,y=t.timezone!==null?dh(_,t.timezone):_;if(!Jp(f,g,y)){Nr(e,"UPDATE cron_jobs SET last_checked_ts = ?, updated_at = ?",[o,o],t);return}let v=xi(e,t.id);if(!(v===null||v.enabled===0||v.revision!==t.revision)){if(JR(t.action_kind)){QR(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",bt(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,H)=>{let C=k===0?"ok":"error",w=C==="ok"?null:H?bt(H):`Command exited with code ${k} -- see ${c??Ti()}/${t.id}/ for output`;if(H)try{u?.(t.id,H)}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",bt(k),o,t.id,S)}catch{}}}}}async function mh(e,t){for(;!e();)await new Promise(r=>setTimeout(r,t))}async function Sl(e,t,r,n={}){let o=n.enqueueImpl??ge,s=n.spawnCommandImpl??Lo,i=n.isUnitStillRunningImpl??Th,a=n.executeRunImpl??bl,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 Sl(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?bt(E):`Command exited with code ${y} -- see ${c??Ti()}/${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",bt(y),d,u.id,p)}catch{}throw new P("SPAWN_FAILED",`manual trigger of job ${t} failed to spawn: ${bt(y)}`,1)}return await mh(()=>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=ml(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{Mo(e,f.run.id,`worker dispatch threw: ${bt(p)}`),hl(e,f.run.id,{ok:!1,summary:`worker dispatch error: ${bt(p)}`})}catch{}throw new P("SPAWN_FAILED",`manual trigger of job ${t} failed to dispatch: ${bt(p)}`,1)}return await mh(()=>{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 QR(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=ml(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{Mo(e,a.run.id,`worker dispatch threw: ${bt(c)}`),hl(e,a.run.id,{ok:!1,summary:`worker dispatch error: ${bt(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 Sh(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 ki(e,t),Ie(e,t)});return lr(r)}import{execFileSync as XR}from"node:child_process";import{existsSync as ZR,readFileSync as vh}from"node:fs";import{homedir as Ah}from"node:os";import{join as $h}from"node:path";function Un(){return process.env.LMBEE_HEAVY_STATUS??$h(Ah(),".lmbee","heavy.status")}function Fn(){return process.env.LMBEE_HEAVY_LOCK??$h(Ah(),".lmbee","heavy.lock")}var Pn=class extends Error{};function eN(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 tN(e){let t;try{t=vh(e,"utf8")}catch{return null}try{let r=JSON.parse(t);return eN(r)?r:null}catch{return null}}function rN(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 nN(e){try{let t=vh(`/proc/${e}/stat`,"utf8");return t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/)[0]==="Z"}catch{return!1}}function oN(e){try{process.kill(e,0)}catch(t){return t.code==="EPERM"}return!nN(e)}function sN(e,t=XR){if(!ZR(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 vl(e=Un(),t=Fn(),r=tN,n=sN,o=oN){for(let s=0;s<3;s++){let i=r(e),a=n(t),c=r(e);if(i!==null&&rN(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 St(e=Un(),t=Fn(),r=vl,n){try{return r(e,t)}catch(o){if(!(o instanceof Pn))throw o;return n?.(o),{held:!0,holder:null}}}var Li={observedAt:null,report:null,lastErrorAt:null,lastError:null};function kh(e,t){Li={observedAt:t,report:e,lastErrorAt:null,lastError:null}}function xh(e,t){Li={...Li,lastErrorAt:t,lastError:e}}function qo(){return Li}import{execFile as iN}from"node:child_process";import{promisify as aN}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 pe(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 cN=aN(iN);function lN(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 uN(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(lN))throw new Error(`unexpected \`lmctl running --json\` shape: a malformed element (bad/missing target or from_identity) in \`${n}\``);return r}async function $e(e=3e4){let{stdout:t}=await cN("lmctl",["running","--json"],{timeout:e});return uN(t)}function Al(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:pe(r.started_at,t)})),dead:e.dead.map(r=>({...r,stale_for_human:me(r.stale_for_ms),started_human:pe(r.started_at,t)})),idle:e.idle.map(r=>({...r,ran_human:me(r.ran_ms)}))}}import{readFileSync as dN}from"node:fs";import{randomUUID as mN}from"node:crypto";var $l={staleThresholdMs:2*60*6e4,escalationCooldownMs:60*6e4,digestTimeoutMs:9e4,leaseTimeoutMs:10*6e4,providerQuotaBackoffMs:24*60*6e4,operatorStaleThresholdMs:6e4,operatorEscalationCooldownMs:6e4};function fN(e){return/usage limit/i.test(e)&&/quota/i.test(e)}function pN(e){let t=[];for(let r of e)try{t.push({row:r,content:dN(r.prompt_file,"utf8")})}catch{continue}return t}function hN(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),_=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} ---
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 gN(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 _N(e,t){let r=new Set,n=new Date().toISOString(),o=mN();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 Ii(e,t,r,n,o){let s=new Date().toISOString(),i=!1;e.transaction(()=>{for(let c of t)(n?e.prepare(`UPDATE queue SET status = 'sent', sent_ts = ?, delivered_via_escalation = 1, escalation_claimed_ts = NULL, escalation_claim_token = NULL
314
+ `)}`}function _N(e,t,r){let n=new Date(r-t).toISOString();e.prepare(`UPDATE queue SET status = 'pending', escalation_claimed_ts = NULL, escalation_claim_token = NULL
315
+ WHERE status = 'escalating' AND (escalation_claimed_ts IS NULL OR escalation_claimed_ts < ?)`).run(n)}function 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
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 Rh(e,t,r=$l,n=Date.now(),o={}){let s=o.sendAwaited??Ht,i=[];gN(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(Os(e,u,m.leadAlias,n))continue;let S;try{S=Q(m)}catch{continue}let R=pN(d);if(R.length===0)continue;let{claimed:x,token:L}=_N(e,R.map(C=>C.row.id)),k=R.filter(C=>x.has(C.row.id));if(k.length===0)continue;let H=!1;try{let C=hN(k);om(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")Ii(e,x,L,!0,()=>nm(e,u)),H=!0,i.push(u);else if(w.kind==="error"&&fN(w.message)){let T=new Date().toISOString();Ii(e,x,L,!1,()=>rm(e,u,T,w.message)),H=!0}else Ii(e,x,L,!1),H=!0}catch{}finally{if(!H)try{Ii(e,x,L,!1)}catch{}}}return i}var kl={minStaleMs:12e5,maxTotalAgeMs:144e5};function Nh(e,t,r=kl,n=Date.now()){return[]}var xl={staleMs:72e5,maxAgeMs:864e5,cooldownMs:36e5};function Lh(e,t,r,n=xl,o=Date.now()){return[]}import{execFile as bN}from"node:child_process";import{promisify as SN}from"node:util";var wN=["ok","provider_unavailable","auth_expired","not_applicable","reader_throttled"];function yN(e){return typeof e=="string"&&wN.includes(e)}function Rl(e){return typeof e=="object"&&e!==null}function EN(e){if(!Rl(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 TN(e){if(!Rl(e))return null;let t=e.provider,r=e.status,n=e.read_at;if(typeof t!="string"||t.length===0||!yN(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(EN).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 Ih(e){let t;try{t=JSON.parse(e)}catch{return null}return!Rl(t)||!Array.isArray(t.readings)?null:t.readings.map(TN).filter(r=>r!==null)}var vN=SN(bN);function Ch(){return process.env.LMBEE_RATE_LIMIT_BIN??"lmctl"}async function AN(e=Ch(),t=vN){try{let{stdout:r}=await t(e,["ratelimit","--json"]);return Ih(r)}catch{return null}}function $N(e){return e==null?null:typeof e=="string"?e:JSON.stringify(e)}function kN(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 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)
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,$N(i.raw_value),i.raw_scale??null,i.is_exhausted===!0?1:i.is_exhausted===!1?0:null,t.read_at)}}var Oh="rate_limit_collect:last_run_ms",xN=5*6e4;function RN(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(Oh);if(n===void 0)return!0;let o=Number(n.v);return Number.isFinite(o)?t-o>=r:!0}function NN(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Oh,String(t))}async function Dh(e,t={}){let r=t.nowMs??Date.now(),n=t.cooldownMs??xN;if(!RN(e,r,n))return{outcome:"skipped-cooldown"};let s=await(t.fetchImpl??AN)(t.binPath??Ch());if(s===null)return{outcome:"fetch-failed"};let i=Math.floor(r/1e3);return e.transaction(c=>{for(let l of c)kN(e,l,i)})(s),NN(e,r),{outcome:"collected",readingsStored:s.length}}var Nl={five_hour:9e5,weekly:36e5},Ci={five_hour:"five_hour_15m",weekly:"weekly_1h"};function Oi(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 Mh(e,t,r){return e.kind!=="forecast"?!1:e.forecastAtMs-r<=Nl[t]}var LN=new Set(["claude:week-scoped-Fable","codex:codex_bengalfox-5h","codex:codex_bengalfox-weekly"]);function Ph(e,t){return LN.has(`${e}:${t}`)}var IN=Nl.weekly;function CN(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 ON(e){return new Date(e*1e3).toISOString()}function DN(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=${Ci[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 Di(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 MN(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 PN(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,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)
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 Uh(e,t={}){let r=t.nowMs??Date.now(),n=t.dryRun??!0,o=t.checkProviderDisabledImpl??rt,s=t.setProviderDisableImpl??gi,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(Ph(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)Di(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=Oi(_,r);if(g.kind==="insufficient_data"){a.push({provider:c,bucketId:l,windowType:u,outcome:"insufficient-data",detail:g.reason});continue}let y=MN(e,c,l,m);if(g.kind==="no_forecast"||!Mh(g,u,r)){y!==null&&(Di(e,c,l,m),qn(e,r,c,l,u,"disarmed",`forecast no longer crosses the ${Ci[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){PN(e,c,l,m,Ci[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=CN(_),R=DN(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){Di(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+IN).toISOString():h[h.length-1]?.resetsAtIso??ON(m);s(e,c,{reason:R,expiresAt:x}),Di(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 UN(e,r,a),a}var Fh="rate_limit_policy_heartbeat";function UN(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(Fh,JSON.stringify(o))}function Pi(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Fh);if(t===void 0)return null;try{return JSON.parse(t.v)}catch{return null}}var FN=15*6e4;function qh(e,t=Date.now(),r=FN){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=Pi(e);if(s===null)return{status:"never-run",reason:"rate-limit policy has never completed an evaluation while collection is active",ageMs:1/0};let i=t-s.lastRunAtMs;return i>r?{status:"stale",reason:`rate-limit policy last ran ${Math.round(i/6e4)}m ago while collection is active`,ageMs:i}:null}var qN=.85;function jh(e,t=qN){return e.prepare(`SELECT s.provider AS provider, s.bucket_id AS bucketId, s.window_type AS windowType, s.used_fraction AS usedFraction, s.resets_at_iso AS resetsAtIso
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
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=>!Ph(n.provider,n.bucketId)&&n.usedFraction>=t)}var Ll="auto_scan_paused";function Lr(e){let t=e.prepare("SELECT v FROM kv WHERE k = ?").get(Ll);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 jN=3*24*60*6e4;function Hh(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>=jN?{status:"stale",state:r,ageMs:o,resumeAfterPassed:!1}:null}function Bh(e,t){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(Ll,JSON.stringify(t))}function Wh(e){e.prepare("DELETE FROM kv WHERE k = ?").run(Ll)}var HN=/usage limit|rate limit|too many requests|quota exceeded|insufficient_quota/i;function Ui(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||!HN.test(o.error))return!1;let s=Date.parse(o.ended_at);return Number.isFinite(s)?n-s<r:!1}import{existsSync as Il,mkdirSync as BN,readFileSync as WN,writeFileSync as GN}from"node:fs";import{homedir as VN}from"node:os";import{join as Gh}from"node:path";var JN=`# Autopilot check-in -- advance your work, then report status
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
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 Fi(e){return e||(process.env.LMBEE_PROMPTS_DIR?process.env.LMBEE_PROMPTS_DIR:Gh(VN(),".lmbee","prompts"))}function Vh(e,t){return Gh(e,`${t}.md`)}function KN(e){Il(e)||BN(e,{recursive:!0});let t=Vh(e,"default");Il(t)||GN(t,JN)}function zN(e,t){let r=Vh(e,t);if(!Il(r))if(t==="default")KN(e);else throw new Error(`loadPromptTemplate: no prompt file for "${t}" at ${r} -- prepare it (S1) before this team can be auto-nudged`);return WN(r,"utf8")}function qi(e,t){return zN(e,t.promptName)}import{existsSync as YN,readFileSync as Kh,rmSync as QN}from"node:fs";import{resolve as Jh,sep as XN}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 zh(e,t){return e.prepare("SELECT * FROM answers WHERE prompt_queue_id = ? ORDER BY created_at ASC, id ASC").all(t)}var ZN=`q.status != 'merged'
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'
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 Yh(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 Qh(e,t){return e.prepare(`SELECT q.* FROM queue q
353
353
  WHERE q.to_id = ?
354
- AND ${ZN}
355
- ORDER BY q.id`).all(t)}function Qh(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 Xh(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 Cl(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 Ol(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=Kh(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function nn(e,t){return 1+Cl(e,t).length}function jo(e,t){return(t.retracted_ts!==null?1:0)+Cl(e,t).filter(n=>n.retracted_ts!==null).length}function Zh(e,t,r,n,o={}){let s=we(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=Cl(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=Jh(js()),p=Jh(a.prompt_file);if((p===f||p.startsWith(f+XN))&&YN(p))try{QN(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=ge(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 Ho(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 e0=5;function t0(e,t,r){let n=new Set([t.from_id,t.to_id]);if(r.length>0){let a="";try{a=Kh(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,e0)}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=t0(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 eg(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 tg(e,t,r){let n=we(r,"reason"),s=e.transaction(()=>{let i=e.prepare("SELECT * FROM queue WHERE id = ?").get(t);if(i===void 0)throw new I("NOT_FOUND",`Queue prompt ${t} does not exist`,3);if(i.status!=="sent")throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is not in a redeliverable state (status: ${i.status}) -- only a dispatched-but-unconfirmed ('sent') row can be redelivered`,2);if(i.escalation_only)throw new I("INVALID_ARGUMENT",`Queue prompt ${t} is an operator-escalation row -- redelivery does not apply to that lane`,2);if(Ce(e,t)!==null)throw new I("CONFLICT",`Queue prompt ${t} already has a recorded answer -- nothing to redeliver`,4);if(i.retracted_ts!==null)throw new I("CONFLICT",`Queue prompt ${t} was retracted: ${i.retracted_reason??"(no reason recorded)"} -- nothing to redeliver`,4);return e.prepare("UPDATE queue SET status = 'pending', sent_ts = NULL WHERE id = ?").run(t),e.prepare("SELECT * FROM queue WHERE id = ?").get(t)}).immediate();return tt(e,s.to_id,"redelivery-requeued",Date.parse(de()),{note:`queue#${t}: ${n}`}),s}function ji(e,t,r,n){let o=e.prepare("SELECT * FROM queue WHERE from_id = ?").all(t),s=[];for(let i of o){let a=Ce(e,i.id);if(a===null)continue;let c=n-Date.parse(a.answered_at);Number.isNaN(c)||c>r||s.push({row:i,answer:a,ageMs:c})}return s.sort((i,a)=>i.ageMs-a.ageMs),s}function rg(e,t,r){e.prepare("UPDATE queue SET status = 'retrieved', retrieved_ts = COALESCE(retrieved_ts, ?) WHERE id = ?").run(r,t)}function ng(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&&(Gs(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=we(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),rg(e,t,c),ng(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 og(e,t,r,n){let o=we(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),rg(e,t,c),ng(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=we(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 ag(e,t,o)}).immediate()}function ig(e,t,r,n){let o=we(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 ag(e,t,`[resolved by proxy ${r}]: ${o}`)}).immediate()}function ag(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 r0=/standing by|standby|\bready\b|on-call/i,n0=4*60*6e4,lg=5;function o0(e,t){if(e.length===0)return"";let r=e.slice(0,lg),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 ${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)`),`
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 cg=140,s0=4*60*6e4;function i0(e){let t=e.trim().split(`
362
- `)[0]??"";return t.length>cg?`${t.slice(0,cg)}\u2026`:t}function a0(e){if(e.length===0)return"";let t=e.slice(0,lg).map(({row:r,answer:n,ageMs:o})=>` #${r.id} to ${r.to_id} (${me(o)} ago) -- "${i0(n.answer_text)}"`);return e.length>t.length&&t.push(` ...and ${e.length-t.length} more`),`
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`),`
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 c0(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 l0(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 ug(e,t,r,n={}){let o=n.config??Te,s=n.nowMs??Date.now(),i=n.fetchTailImpl??wi,a=Fi(n.promptsDir),c=n.readHeavyLockStatusImpl??St;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(Ui(r,y,n.providerExhaustionBackoffMs))return!1}catch{}return!0}let f=n.clearAutoNudgeSuspendedImpl??Wd,p=n.recordAutoNudgeSuspendedImpl??Bd;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 c0(h,i);if(_!==null&&r0.test(_.text)&&!l0(_.ts,n.standbyStaleMs??n0,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??$f,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=qi(a,h)}catch{continue}let x=(n.findOwedResponsesImpl??on)(e,h.name,s);v+=o0(x,h.name);let k=(n.findRecentlyAnsweredForSenderImpl??ji)(e,h.name,s0,s);v+=a0(k);let C=(n.loadAutoNudgeRedirectImpl??Et)(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(ge(e,t,w,v,{from:"autopilot"}),C!==null){let oe=n.recordRedirectedDispatchImpl??bp;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 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)}
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
- `)}bo(e,h.name,new Date().toISOString()),d.push(h.name)}}return d}import{readFileSync as u0}from"node:fs";function dg(e){return`last_maintainer_wake:${e}`}function d0(e,t){return e.prepare("SELECT v FROM kv WHERE k = ?").get(dg(t))?.v??null}function m0(e,t,r){e.prepare("INSERT INTO kv(k, v) VALUES (?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v").run(dg(t),r)}function f0(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 mg(e,t,r,n,o=a=>u0(a,"utf8"),s=Date.now(),i){let a=t.find(m=>m.name===n.teamName);if(!a||!B(a)||!(i??f0(e,t.filter(B),r,n.teamName))||Fe(a,r)||qe(e,n.teamName,{fromAutopilot:!0}).length>0)return!1;let l=n.cooldownMs??Te.cooldownMs,u=d0(e,n.teamName);if(u!==null&&s-Date.parse(u)<=l)return!1;let d;try{d=o(n.promptFile)}catch{return!1}return ge(e,t,n.teamName,d,{from:"autopilot"}),m0(e,n.teamName,new Date(s).toISOString()),!0}function Hi(e){return`blocked:${e}`}function fg(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 pg(e,t,r,n,o=Te,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(Hi(a.name))||(ge(e,n,r,fg(e,a.name,f,"your decision"),{from:"autopilot",subject:Hi(a.name)}),h=!0));for(let[_,g]of p)new Set(qe(e,_).map(E=>E.subject_id).filter(E=>E!==null)).has(Hi(a.name))||(ge(e,n,_,fg(e,a.name,g,"your decision"),{from:"autopilot",subject:Hi(a.name)}),h=!0);h&&(Ud(e,a.name,new Date().toISOString()),i.push(a.name))}return i}var p0=30*6e4;function h0(e){return`unresolvable-teamfile:${e}`}async function hg(e,t,r,n,o=Te,s=Date.now(),i=p0,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),Jd(e,l.name);continue}catch{}Vd(e,l.name,a());let u=Kd(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=h0(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.`;ge(e,n,r,_,{from:"autopilot",subject:f}),zd(e,l.name,a()),c.push(l.name)}return c}var Dl="epic_closed_surfaced_ts";function Bi(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[Dl]=="string"&&(s=!0)}}return{entity:n,status:n.status,alreadySurfacedThisEpisode:s}})()}function gg(e){return`epic-closed:${e}`}async function _g(e,t,r,n,o=Te,s=Date.now(),i={}){let a=n.find(u=>u.name===r);if(!a)return[];if(!B(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(gg(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=Bi(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.`;ge(e,n,r,S,{from:"autopilot",subject:gg(u.name),escalationOnly:!0});let R=new Date().toISOString();for(let x of E)Bt(e,x.id,{body:JSON.stringify({[Dl]:R})});qd(e,u.name,R),g=!0}).immediate(),g&&l.push(u.name)}return l}function wg(e){return`done-check:${e}`}var Eg="consistency_alert_ts";function yg(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[Eg]=="string"&&(a=!0)}}return{entity:n,status:n.status,epochId:s,doneTransitionIso:i,alreadyAlertedThisEpisode:a}})()}async function g0(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 Tg(e,t,r,n,o=Te,s={}){let i=s.hasEvidenceAroundDoneImpl??g0,a=n.find(u=>u.name===r);if(!a)return[];if(!B(a))return[];let c=new Set(qe(e,r).map(u=>u.subject_id).filter(u=>u!==null)),l=[];for(let u of t){if(u.name===r||c.has(wg(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=yg(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 H=yg(e,L.id);if(H===null)continue;let C=H.entity;le(C.status)==="done"&&(C.owner_team_path!==g||C.owner_alias!==u.leadAlias||Vt(e,C,new Map)||H.epochId!==k||H.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).`;ge(e,n,r,x,{from:"autopilot",subject:wg(u.name),escalationOnly:!0});for(let L of S)Bt(e,L.id,{body:JSON.stringify({[Eg]:y})});E=!0}).immediate(),E&&l.push(u.name)}return l}function bg(e){return`fault:${e}`}async function Sg(e,t,r,n,o=Te,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(bg(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=To(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=To(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.`;ge(e,n,r,E,{from:"autopilot",subject:bg(l.name)}),Fd(e,l.name,new Date().toISOString()),h=!0}).immediate(),h&&c.push(l.name)}return c}function vg(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
+ `)}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(
372
372
  SELECT 1 FROM tracked_invocation
373
373
  WHERE target_teamfile = ? AND target_alias = ?
374
374
  AND (
@@ -376,28 +376,28 @@ ${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 Ag(e){return`unknown:${e}`}async function $g(e,t,r,n,o=Te,s=Date.now(),i=On){if(!n.some(l=>l.name===r))return[];let a;function c(){return a??=i(),a}try{return await _0(e,t,r,n,o,s,c)}finally{a!==void 0&&a.close()}}async function _0(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(Ag(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!==""&&vg(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.`;ge(e,n,r,E,{from:"autopilot",subject:Ag(u)}),Pd(e,u,new Date().toISOString()),l.push(u)}return l}import{execFile as w0}from"node:child_process";import{promisify as y0}from"node:util";function Bo(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 Wi(e,t,r,n,o={}){let s=o.resolveMemberProviderImpl??jt,i=o.checkProviderDisabledImpl??rt,a=o.isProviderExhaustedImpl??Ui,c=o.allLocalTeams??[t],l=Et(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 kg=y0(w0),E0=new Set(["ENV-ERROR","NO-OUTPUT"]),T0=24*60*6e4,b0=3;async function Wo(e,t,r=kg){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 xg(e,t,r,n,o,s={}){let i=s.execImpl??kg,a=s.whyNotObservedImpl??Wi,c=s.flappingWindowMs??T0,l=s.flappingOccurrenceThreshold??b0,u=s.listRecentEventsByStatusImpl??bs,d=[],m=[];for(let f of t){let p=Dd(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,H)=>Date.parse(H.ts)-Date.parse(k.ts)),R=S.length>=l,x=E0.has(_.status)&&!Number.isNaN(E)&&E>=o;if(!x&&!R)continue;if(R&&!x){let k=S[0],H={kind:"flapping",team:f.name,mostRecentStatus:k.status,mostRecentAt:k.ts,occurrenceCount:S.length,windowMs:c};h.kind==="no_continuous_observer"?d.push(H):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 Wo(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 S0}from"node:child_process";import{promisify as v0}from"node:util";var A0=v0(S0);async function Rg(e,t=A0){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 $0}from"node:child_process";import{promisify as k0}from"node:util";var x0=k0($0);async function Lg(e,t=x0){try{let{stderr:r}=await t("lmctl",["lint",e],{timeout:15e3});return Ng(r)}catch(r){let n=r&&typeof r=="object"&&"stderr"in r?String(r.stderr):"",o=Ng(n);return o.length>0?o:null}}function Ng(e){return e.split(`
381
- `).map(t=>t.trim()).filter(t=>t.startsWith("warning:")||t.startsWith("error:"))}import{existsSync as Ml}from"node:fs";function Pl(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=Pl(e,n,r);return o===null?null:{...o,explicit:!1}}function Gi(e,t){if(t===null)return null;for(let r of e)if(B(r))try{if(Q(r)===t)return r.name}catch{continue}return null}function Ig(e){return e.prepare("SELECT * FROM entities WHERE kind = 'epic' AND owner_team_path IS NULL").all().filter(r=>!ht(r.status))}function Cg(e,t,r=Ml){return Gi(e,t)!==null?"registered":r(t)?"on_demand":"dangling"}function Og(e,t,r={}){let n=r.existsSyncImpl??Ml,o=e.prepare("SELECT * FROM entities WHERE kind IN ('task', 'subtask')").all(),s=[];for(let i of o){if(ht(i.status))continue;let a=Pl(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}Cg(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 Dg(e){return e.prepare("SELECT * FROM entities WHERE status = 'blocked'").all().filter(r=>(ct(e,r.id,"outgoing").outgoing??[]).length===0)}function R0(e,t){return e.prepare("SELECT 1 FROM queue WHERE to_id = ? LIMIT 1").get(t)!==void 0}function Mg(e,t,r,n=Ml){let o=Pl(e,r);if(o===null)return{ownerKind:"dangling",everContacted:null};let s=Cg(t,o.ownerTeamPath,n);if(s==="dangling")return{ownerKind:s,everContacted:null};if(s==="on_demand")return{ownerKind:s,everContacted:!1};let i=Gi(t,o.ownerTeamPath);return{ownerKind:s,everContacted:R0(e,i)}}function Ug(e,t){let r=ct(e,t,"outgoing").outgoing??[];return new Set(r.filter(n=>!ht(n.status)).map(n=>n.id))}function Vi(e,t,r=new Set){if(r.has(t))return[];r.add(t);let o=(ct(e,t,"outgoing").outgoing??[]).filter(a=>!ht(a.status)),s=[];for(let a of o)(ct(e,a.id,"outgoing").outgoing??[]).filter(u=>!ht(u.status)).length===0?s.push(Le(e,a.id)):s.push(...Vi(e,a.id,r));let i=new Set;return s.filter(a=>i.has(a.id)?!1:(i.add(a.id),!0))}function N0(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);ht(i.status)||(o.push(i),n.push(...(ct(e,s,"incoming").incoming??[]).map(a=>a.id)))}return o}function Pg(e){let t=e.trim().toLowerCase();return t==="todo"?0:t==="in_progress"||t==="in-progress"?1:2}function Fg(e,t,r){let n=new Map;for(let s of t)for(let i of Vi(e,s.id))n.set(i.id,i);let o=[];for(let s of n.values()){let i=N0(e,s.id),a=new Set;for(let l of i){let u=Gi(r,l.owner_team_path);u!==null&&a.add(u)}let c=Mg(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=Pg(s.entity.status)-Pg(i.entity.status);return a!==0?a:s.entity.id-i.entity.id}),o}import{execFile as L0}from"node:child_process";import{readFileSync as I0}from"node:fs";import{basename as C0,resolve as O0}from"node:path";import{promisify as D0}from"node:util";var Ul=D0(L0),M0=[/\.env\.(example|sample|template)$/i],P0=[/\.pem$/,/\.key$/,/(^|\/)id_rsa$/,/(^|\/)id_ed25519$/,/(^|\/)id_ecdsa$/],U0=[/(^|\/)\.env(\..+)?$/,/(^|\/)\.mcp\.json$/,/(^|\/)\.netrc$/,/(^|\/)\.npmrc$/],jg=[/\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,}/],F0=[...jg,/\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],Ji=20*1024*1024;async function Hg(e,t){try{let{stdout:r}=await t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Ji});return r.split(`
382
- `).filter(n=>n.length>0)}catch{return null}}async function Fl(e,t,r){try{let{stdout:n}=await r("git",["-C",e,"show",`HEAD:${t}`],{timeout:1e4,maxBuffer:Ji});return n}catch{return null}}async function Bg(e,t=Ul){let r=await Hg(e,t);if(r===null)return null;let n=a=>!M0.some(c=>c.test(a)),o=r.filter(a=>P0.some(c=>c.test(a))&&n(a)),s=r.filter(a=>U0.some(c=>c.test(a))&&n(a)),i=[];for(let a of s){let c=await Fl(e,a,t);c!==null&&F0.some(l=>l.test(c))&&i.push(a)}return[...o,...i]}async function Wg(e,t=Ul){let r=await Hg(e,t);if(r===null)return null;let n=r.filter(s=>s.endsWith(".lmctl")),o=[];for(let s of n){let i=await Fl(e,s,t);if(i===null)continue;let a=jg.reduce((c,l)=>c+(l.test(i)?1:0),0);a>0&&o.push({path:s,matchCount:a})}return o}var q0=[/(^|\/)template\.lmctl$/i,/(^|\/)examples\/.*\.lmctl$/i],qg=/_MEMBER_\b|\bsessionid\s*=\s*\S/;async function Gg(e,t=Ul){try{let[r,n]=await Promise.all([t("git",["-C",e,"ls-files"],{timeout:1e4,maxBuffer:Ji}),t("git",["-C",e,"ls-files","--others","--exclude-standard"],{timeout:1e4,maxBuffer:Ji})]),o=u=>!q0.some(d=>d.test(u)),s=u=>C0(u).includes(".lmctl")&&o(u),i=r.stdout.split(`
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(`
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 Fl(e,u,t);d!==null&&qg.test(d)&&c.push(u)}let l=[];for(let u of a){let d;try{d=I0(O0(e,u),"utf8")}catch{continue}qg.test(d)&&l.push(u)}return{tracked:c,unprotected:l}}catch{return null}}import{execFile as j0}from"node:child_process";import{statSync as Vg}from"node:fs";import{homedir as H0}from"node:os";import{join as Jg}from"node:path";import{promisify as B0}from"node:util";var ql=B0(j0);var W0="mike.ma@lmctl.com",jl="mike-lmctl";async function Kg(e,t=ql){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===W0}}var G0=6e4,Ki;async function zi(e=ql,t=Date.now(),r=Vg){let n=e===ql&&r===Vg;if(n&&Ki!==void 0&&t-Ki.atMs<G0)return Ki.result;let o=await J0(e,r);return n&&(Ki={result:o,atMs:t}),o}function V0(){let e=process.env.GH_CONFIG_DIR;return e?Jg(e,"hosts.yml"):Jg(H0(),".config","gh","hosts.yml")}async function J0(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(V0()).mtime.toISOString()}catch{c=null}return{account:a,matchesPolicy:a===jl,hostsFileChangedAt:c}}var K0=7*24*60*6e4,z0=500,Y0=3*60*6e4,Q0=3*60*6e4,Go=4*60*6e4,X0=24*60*6e4,Z0=48*60*6e4,eL=24*60*6e4,tL=20,Bl=24*60*6e4;function rL(e,t){let r=me(t);return`${t>Bl?`possible ${e}`:e} as of ${r} ago (not re-observed)`}var nL=7*24*60*6e4,oL=24*60*6e4;function sL(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<=oL)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>nL?{kind:"self-report",status:t.status,changedTs:t.changed_ts}:null}function iL(e,t){let r=e.teams.filter(B);return t===void 0?r:r.filter(n=>n.name===t)}function aL(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 Yi(e,t={}){let r=e.db.db,n=t.config??Te,o=t.nowMs??Date.now(),s=iL(e,t.team),i=t.awaitingReviewThresholdMs??Sc,a=[],c=[],l=[],u=[],d=[],m=new Set(Ho(r,o).map(F=>F.row.subject_id).filter(F=>F!==null)),f=[],p=[],h=[],_=[],g=[],y=[],E=t.countDirtyGitFilesImpl??Rg,v=[],S=t.lintTeamfileWarningsImpl??Lg,R=[],x=[],L=[],k=[],H=[],C=t.findNeverTrackFilesImpl??Bg,w=t.findSecretBearingTeamfilesImpl??Wg,T=t.checkTeamfileTrackingImpl??Gg,N=t.checkRepoGitIdentityImpl??Kg,U=t.resolveMemberProviderImpl??jt,J=t.listTeamMembersImpl??Vr,ee=[],oe=!1;try{ee=Ro(r).filter(F=>rt(r,F.provider,o).disabled)}catch{oe=!0}let V=qh(r,o),se=jh(r),$=null;try{$=Hh(r,o)}catch{$=null}let O=new Set(ee.map(F=>F.provider)),A=[],q=e.teams.filter(B),M=e.teams.map(F=>F.name);for(let F of s){let he;try{he=Q(F)}catch{continue}let Pe=await S(he);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&&H.push({team:F.name,identity:{name:Br.name,email:Br.email}});let Dt=O.size>0?aL(F,O,J):null;if(O.size>0){let ce=Et(r,F.name),Mt=ce===null?F.name:ce.companionTeam,Na=ce===null?F.leadAlias:ce.workerAlias,fo=ce===null?F.repoPath:q.find(po=>po.name===Mt)?.repoPath??F.repoPath,Wr=U({repoPath:fo,name:Mt},Na);if(Wr!==null&&O.has(Wr)){let po=ee.find(vv=>vv.provider===Wr)?.expiresAt??null;A.push({team:F.name,provider:Wr,expiresAt:po,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 _d=xa.filter(ce=>ce.row.status==="sent"||ce.row.status==="retrieved");if(_d.length>0){let ce=r.prepare("SELECT MAX(created_ts) AS ts FROM queue WHERE from_id = ?").get(F.name),Mt=sL(ie(r,F.name),Ue(r,F.name),ce.ts,o,F);Mt!==null&&d.push({team:F.name,rows:_d,reason:Mt})}let wd=ji(r,F.name,Go,o);wd.length>0&&u.push({team:F.name,rows:wd});let wr=xe(r,he,F.leadAlias);if(wr===null)continue;for(let ce of $n(r,wr)){let Mt;try{let fo=Ug(r,ce.id),Wr=Vi(r,ce.id).filter(po=>!fo.has(po.id));Wr.length>0&&(Mt=Wr)}catch{Mt=void 0}let Na=Vs(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(fo=>fo.name===ce.blocked_on)&&c.push({team:F.name,entity:ce,blockedOn:ce.blocked_on,reason:"team-unresolvable"})}for(let ce of To(r,wr,n.cooldownMs,o))f.push({team:F.name,entity:ce});for(let ce of vf(r,wr,i,o))p.push({team:F.name,task:ce});for(let ce of Af(r,wr,o))h.push({team:F.name,task:ce});for(let ce of wr.entities)ce.kind==="epic"&&ce.needs_review===1&&Xs(ce)&&_.push({team:F.name,entity:ce});for(let ce of wr.entities)ce.kind!=="epic"||!An.has(le(ce.status))||Bi(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??$e)(),ae=t.heavyLockImpl?t.heavyLockImpl():St(void 0,void 0,void 0,()=>{}),ye=await kn(r,s,W,ae,n,o,{readOnly:!0}),ne=new Set(A.map(F=>F.team)),D=ye.filter(F=>!ne.has(F)),j=t.findPersistentDispatchFailuresImpl??xg,{unreachable:Y,notObserved:K}=await j(r,s,W,o,Go),re=[];for(let F of D){let he=ie(r,F);if(he?.miniplayer_verdict_label&&he.miniplayer_verdict_reason&&he.miniplayer_verdict_ts){let Pe=Ue(r,F),it=he.miniplayer_verdict_label!=="genuinely_done"&&Pe?.status==="DONE"?{changedTs:Pe.changed_ts}:void 0;re.push({team:F,label:he.miniplayer_verdict_label,reason:he.miniplayer_verdict_reason,ts:he.miniplayer_verdict_ts,...it!==void 0?{selfReportedDone:it}:{}})}}let te=[];for(let F of s){let he=ie(r,F.name);he?.hung_holder_flagged_ts&&he.hung_holder_reason&&te.push({team:F.name,reason:he.hung_holder_reason,flaggedTs:he.hung_holder_flagged_ts})}let ue=Gd(r).map(F=>({team:F.team,reason:F.reason,detail:F.detail,suspendedAt:F.suspended_at})),Ae=t.blockedSelfReportUrgentThresholdMs??X0,be=t.blockedSelfReportUnconfirmedThresholdMs??Z0,z=[];for(let F of s){let he=Ue(r,F.name);if(he?.status==="BLOCKED"){let Pe=o-Date.parse(he.changed_ts),it=Pe>=be;z.push({team:F.name,changedTs:he.changed_ts,ageMs:Pe,urgent:!it&&Pe>=Ae,unconfirmed:it})}}z.sort((F,he)=>he.ageMs-F.ageMs);let Ee=t.orphanReapCandidateWindowMs??K0,Ge=new Date(o-Ee).toISOString(),Ct=bs(r,sl,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),...Hs(r,t.maintainer)].sort((F,he)=>F.id-he.id).filter(F=>F.from_id!=="autopilot"),_e=t.maintainer===void 0?[]:Xh(r,t.maintainer,o).map(F=>({row:F.row,constituentCount:nn(r,F.row)})),st=t.maintainer===void 0?[]:Ho(r,o).map(F=>{let he=nn(r,F.row),Pe=jo(r,F.row),it=F.ageMs>=Go||he>=2&&F.row.sent_ts===null;return{row:F.row,constituentCount:he,retractedCount:Pe,urgent:it}}),Ze=t.maintainerStaleThresholdMs??Y0,mt=[];if(t.maintainer!==void 0&&G!==null){let he=ie(r,t.maintainer)?.last_cli_activity_ts??null,Pe=$p(he,o),it=!rl(he,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(he===null?"no CLI activity ever recorded":`no CLI activity in ${me(Pe)}`),Br&&Dt.push(`oldest queued item is ${me(Ot)} old`),mt.push({team:t.maintainer,reason:Dt.join("; "),ageMs:Pe===null?1/0:Math.max(Pe,Ot??0)})}}let Ve;if(t.team===void 0)Ve=a.map(F=>F.entity);else{Ve=[];for(let F of e.teams.filter(B)){let he;try{he=Q(F)}catch{continue}let Pe=xe(r,he,F.leadAlias);Pe!==null&&Ve.push(...$n(r,Pe))}}let mn=Fg(r,Ve,e.teams),gr=Ig(r),or=Og(r,e.teams),et=Dg(r),_r=[];for(let F of e.teams.filter(B)){try{Q(F)}catch{continue}rc(F)===0&&_r.push({team:F.name,repoPath:F.repoPath})}let mo=t.stuckProcessingThresholdMs??Q0,gs=t.stuckProcessingMaxAgeMs??eL,ka=t.maintainer!==void 0&&t.stuckProcessingFleetWide!==!0?t.maintainer:void 0,Sv=Qh(r,{minAgeMs:mo,maxAgeMs:gs,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:mt,blockingRoots:mn,epicsWithoutOwner:gr,unresolvableOwnerEntities:or,untrackedBlockers:et,unseededTeams:_r,stuckProcessing:Sv,inbox:G,memory:(t.readMemoryAvailabilityImpl??yo)(),operatorPrompts:_e,operatorEscalations:st,uncommittedWork:y,teamfileLintWarnings:v,expiredHolds:h,neverTrackFiles:R,secretBearingTeamfiles:x,trackedTeamfiles:L,unprotectedTeamfiles:k,gitIdentityMismatches:H,activeGhAccount:await(t.checkActiveGhAccountImpl??zi)(),disabledProviders:ee,providerDisableReadFailed:oe,quiescedByProviderDisable:A,staleAutoScanPause:$,persistentDispatchFailures:Y,notObserved:K,rateLimitPolicyHealth:V,rateLimitLevelWarnings:se}}function Hl(e){return` ${e.team}: #${e.entity.id} ("${e.entity.title}")`}function zg(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} (${pe(r.row.created_ts)}, via ${r.matchedTeam})`).join("; ")}`}function Vo(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 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}):
387
387
  ${l.join(`
388
388
  `)}`)}if(e.operatorEscalations.length>0){let c=Date.now(),l=f=>{let p=f.constituentCount>1?` (${f.constituentCount} merged into this one${f.retractedCount>0?`, ${f.retractedCount} retracted`:""})`:"";return` #${f.row.id} from ${f.row.from_id} -- sent ${me(c-Date.parse(f.row.created_ts))} ago, unanswered${p}`},u=f=>{let p=f.reduce((h,_)=>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:
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=rL(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=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}):
393
393
  ${c.join(`
394
- `)}`)}if(e.notObserved.length>0){let c=e.notObserved.map(l=>{let u=me(l.ageMs),d=l.ageMs>Bl?`possible ${l.status}`:l.status;return` ${l.team}: last checked ${u} ago, ${d} then -- ${Bo(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>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}):
395
395
  ${c.join(`
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 ${pe(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:
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(`
398
398
  `)}`)}if(e.expiredHolds.length>0){let c=e.expiredHolds.map(l=>` ${l.team}: #${l.task.id} ("${l.task.title}") -- observation window complete, evidence due (was held until ${l.task.holdUntil}: ${l.task.holdReason})`);r.push(`HOLD EXPIRED (${e.expiredHolds.length}):
399
399
  ${c.join(`
400
- `)}`)}if(e.staleAutoScanPause!==null){let c=e.staleAutoScanPause,l=c.state.actor!==null?`, by ${c.state.actor}`:"",u=c.state.note!==null?` -- ${c.state.note}`:"";if(c.status==="unevaluable"){let d=c.reason==="corrupt-paused-at"?c.state.paused_at:c.state.resume_after,m=c.reason==="corrupt-paused-at"?"paused_at":"resume_after";r.push(`AUTO-SCAN PAUSE UNEVALUABLE: its ${m} ("${d}") could not be parsed, so staleness cannot be computed (paused since ${pe(c.state.paused_at)}${l}${u}) -- check by hand. \`lmbee scan start\` resumes.`)}else{let d=c.resumeAfterPassed?`resume_after (${c.state.resume_after}) has passed`:`paused ${me(c.ageMs)} with no resume_after set`;r.push(`AUTO-SCAN PAUSE STALE: ${d} (since ${pe(c.state.paused_at)}${l}${u}) -- still intended? \`lmbee scan start\` resumes.`)}}if(e.rateLimitPolicyHealth!==null){let c=e.rateLimitPolicyHealth;r.push(`RATE-LIMIT POLICY ${c.status==="never-run"?"NEVER RUN":"STALE"}: ${c.reason} -- collection is active, evaluation is not.`)}if(e.rateLimitLevelWarnings.length>0){let c=e.rateLimitLevelWarnings.map(l=>` ${l.provider}/${l.bucketId}: ${Math.round(l.usedFraction*100)}% used${l.resetsAtIso?`, resets ${l.resetsAtIso}`:""}`);r.push(`RATE-LIMIT LEVEL WATCH (${e.rateLimitLevelWarnings.length}, informational only -- not disabled):
400
+ `)}`)}if(e.staleAutoScanPause!==null){let c=e.staleAutoScanPause,l=c.state.actor!==null?`, by ${c.state.actor}`:"",u=c.state.note!==null?` -- ${c.state.note}`:"";if(c.status==="unevaluable"){let d=c.reason==="corrupt-paused-at"?c.state.paused_at:c.state.resume_after,m=c.reason==="corrupt-paused-at"?"paused_at":"resume_after";r.push(`AUTO-SCAN PAUSE UNEVALUABLE: its ${m} ("${d}") could not be parsed, so staleness cannot be computed (paused since ${he(c.state.paused_at)}${l}${u}) -- check by hand. \`lmbee scan start\` resumes.`)}else{let d=c.resumeAfterPassed?`resume_after (${c.state.resume_after}) has passed`:`paused ${me(c.ageMs)} with no resume_after set`;r.push(`AUTO-SCAN PAUSE STALE: ${d} (since ${he(c.state.paused_at)}${l}${u}) -- still intended? \`lmbee scan start\` resumes.`)}}if(e.rateLimitPolicyHealth!==null){let c=e.rateLimitPolicyHealth;r.push(`RATE-LIMIT POLICY ${c.status==="never-run"?"NEVER RUN":"STALE"}: ${c.reason} -- collection is active, evaluation is not.`)}if(e.rateLimitLevelWarnings.length>0){let c=e.rateLimitLevelWarnings.map(l=>` ${l.provider}/${l.bucketId}: ${Math.round(l.usedFraction*100)}% used${l.resetsAtIso?`, resets ${l.resetsAtIso}`:""}`);r.push(`RATE-LIMIT LEVEL WATCH (${e.rateLimitLevelWarnings.length}, informational only -- not disabled):
401
401
  ${c.join(`
402
402
  `)}`)}if(e.neverTrackFiles.length>0){let c=e.neverTrackFiles.map(l=>` ${l.team}: ${l.files.join(", ")}`);r.push(`TRACKED FILES THAT SHOULD NEVER BE TRACKED (${e.neverTrackFiles.length} team(s)):
403
403
  ${c.join(`
@@ -409,42 +409,42 @@ ${c.join(`
409
409
  ${c.join(`
410
410
  `)}`)}if(e.gitIdentityMismatches.length>0){let c=e.gitIdentityMismatches.map(l=>` ${l.team}: ${l.identity.name??"(unset)"} <${l.identity.email??"unset"}>`);r.push(`GIT IDENTITY POLICY MISMATCH (${e.gitIdentityMismatches.length} team(s)):
411
411
  ${c.join(`
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 ${pe(l.disabledAt)}${u}${d}`});r.push(`PROVIDER DISABLED FOR AUTO-NUDGE (${e.disabledProviders.length}):
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
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:
415
415
  ${c.join(`
416
- `)}`)}if(e.blocked.length>0){let c=e.blocked.map(l=>{let u=Hl(l),d=l.blockedSinceTs===null?" (blocked-since unknown)":(()=>{let f=Date.now()-Date.parse(l.blockedSinceTs),p=me(f);return f>Bl?` -- 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=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}):
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}`+zg(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)`+zg(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(_=>!_.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:
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(Hl).join(`
427
- `)}`),e.awaitingReview.length>0){let c=e.awaitingReview.map(l=>` ${l.team}: #${l.task.id} ("${l.task.title}") -- untouched since ${pe(l.task.updatedAt)}`);r.push(`awaiting meta-lead review (${e.awaitingReview.length}):
426
+ ${e.awaitingDecision.map(Bl).join(`
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
- `)}`)}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 ${pe(d.selfReportedDone.changedTs)})`:m});r.push(`stalled (${e.stalled.length}):
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}):
430
430
  ${l.join(`
431
- `)}`)}if(e.blockedSelfReports.length>0){let c=e.blockedSelfReports.map(l=>{let u=l.unconfirmed?" -- unconfirmed, needs re-affirmation":l.urgent?" -- URGENT":"";return` ${l.team}: blocked ${me(l.ageMs)}${u} (since ${pe(l.changedTs)})`});r.push(`blocked self-reports (${e.blockedSelfReports.length}):
431
+ `)}`)}if(e.blockedSelfReports.length>0){let c=e.blockedSelfReports.map(l=>{let u=l.unconfirmed?" -- unconfirmed, needs re-affirmation":l.urgent?" -- URGENT":"";return` ${l.team}: blocked ${me(l.ageMs)}${u} (since ${he(l.changedTs)})`});r.push(`blocked self-reports (${e.blockedSelfReports.length}):
432
432
  ${c.join(`
433
433
  `)}`)}if(e.hungHolders.length>0){let c=e.hungHolders.map(l=>` ${l.team}: ${l.reason}`);r.push(`hung holders (${e.hungHolders.length}):
434
434
  ${c.join(`
435
- `)}`)}if(e.autoNudgeSuspended.length>0){let c=e.autoNudgeSuspended.map(l=>` ${l.team}: ${l.reason} -- ${l.detail} (since ${pe(l.suspendedAt)})`);r.push(`auto-nudge suspended (${e.autoNudgeSuspended.length}):
435
+ `)}`)}if(e.autoNudgeSuspended.length>0){let c=e.autoNudgeSuspended.map(l=>` ${l.team}: ${l.reason} -- ${l.detail} (since ${he(l.suspendedAt)})`);r.push(`auto-nudge suspended (${e.autoNudgeSuspended.length}):
436
436
  ${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(Hl).join(`
440
+ ${e.closedEpicsToReview.map(Bl).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}:
444
444
  ${l.warnings.map(u=>` ${u}`).join(`
445
445
  `)}`);r.push(`teamfile lint warnings (${e.teamfileLintWarnings.length}) -- lmctl lint is warning-only and its codex model catalog is doc-driven; absence here means lint had nothing to say, not that every member is confirmed to resolve:
446
446
  ${c.join(`
447
- `)}`)}if(e.orphanReapCandidates.length>0){let c=e.orphanReapCandidates.map(l=>` ${pe(l.ts)} ${l.team}: ${l.reason}`);r.push(`orphan reap candidates, dry-run [observation window] (${e.orphanReapCandidates.length}):
447
+ `)}`)}if(e.orphanReapCandidates.length>0){let c=e.orphanReapCandidates.map(l=>` ${he(l.ts)} ${l.team}: ${l.reason}`);r.push(`orphan reap candidates, dry-run [observation window] (${e.orphanReapCandidates.length}):
448
448
  ${c.join(`
449
449
  `)}`)}if(e.blockingRoots.length>0){let c=Date.now(),l=e.blockingRoots.map(u=>{let d=c-Date.parse(u.entity.created_at),m=u.downstreamTeams.length>1?`blocks ${u.downstreamCount} across ${u.downstreamTeams.length} teams (${u.downstreamTeams.join(", ")})`:`blocks ${u.downstreamCount}`,f=u.ownerKind==="dangling"?" [owner UNRESOLVED -- verify a real, engaged owner exists]":u.ownerKind==="on_demand"?" [owner is on-demand -- not queue-addressable, stuck until worked directly]":u.everContacted===!1?" [owner never contacted]":"";return` #${u.entity.id} ("${u.entity.title}") -- ${m} (${le(u.entity.status)}, open ${me(d)})${f}`});r.push(`blocking roots (${e.blockingRoots.length}):
450
450
  ${l.join(`
@@ -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,tL),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,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?`
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=Fs(e.memory),s=o===null?n:`${n}
468
+ `),o=qs(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 Yg(e,t,r,n={}){let o={db:{path:"",db:e,close:()=>{}},teamsConfPath:"",teams:[...t]},s=await Yi(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??yo)(),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=Fs(i),l=c===null?Vo(s):`${Vo(s)}
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)}
473
473
 
474
- ${c}`;return{attention:s,memory:i,isEmpty:a,rendered:l}}var dL=18e5,mL={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 Qg(e){let t=e.fetchReport??$e,r=e.readHeavyLockStatusImpl??St,n=e.heavyLockStatusPath??Un(),o=e.heavyLockPath??Fn(),s=e.maintainerWakeImpl??mg,i=e.autoContinueImpl??ug,a=e.surfaceUnknownImpl??$g,c=e.surfaceBlockedImpl??pg,l=e.surfaceDoneConsistencyImpl??Tg,u=e.surfaceUnresolvableTeamfilesImpl??hg,d=e.surfaceFaultImpl??Sg,m=e.surfaceClosedEpicsImpl??_g,f=e.escalateImpl??Rh,p=e.autoRedeliverImpl??Nh,h=e.wakeImpl??Lh,_=e.evaluateCronJobsImpl??bh,g=e.miniplayerVerifyImpl??Vp,y=e.hungHolderCheckImpl??Op,E=e.epicReviewImpl??Bp,v=e.orphanReconcilerImpl??qp,S=e.hangProbeCollectImpl??Hp,R=e.rateLimitCollectImpl??Dh,x=e.rateLimitPolicyImpl??Uh,L=e.assembleWakeReportImpl??Yg,k=e.existsSyncImpl??cL,H=e.statSyncImpl??uL,C=e.config??Te,w=e.escalation??$l,T=e.autoRedeliver??kl,N=e.wake??xl,U=e.intervalMs??dL,J=null,ee=!1;async function oe(){if(ee)return mL;ee=!0;try{let V=e.getTeams(),se=V.filter(B),$;try{$=await t(),kh($,new Date().toISOString())}catch(G){throw xh(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=Ls(e.db,se,$),{stalled:M,continueEligible:Z}=await Nf(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&&Hd(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??Sp,_e=new Map(se.map(et=>[et.name,et.repoPath])),st=new Map(se.map(et=>[et.name,et])),Ze=await G(e.db,_e,O),mt=e.buildReviewMessageImpl??Ap,Ve=e.resetShiftImpl??vp,mn=e.enqueueImpl??ge,gr=e.checkProviderDisabledImpl??rt,or=e.resolveMemberProviderImpl??jt;for(let et of Ze)try{let _r=_e.get(et.team);if(_r===void 0)continue;let mo=st.get(et.team),gs=mo===void 0?null:or(mo,mo.leadAlias);if(gs!==null&&gr(e.db,gs,O).disabled)continue;let ka=await mt(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 _e=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:H,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 mt=Ve=>`${lL(Ve,"utf8")}
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")}
475
475
 
476
476
  ---
477
- ${st}`;ae=s(e.db,se,$,G,mt,O,_e?void 0:!Ze)}else ae=s(e.db,se,$,G,void 0,O)}catch(G){e.onError?.(G)}let ye=[];if(e.autoContinue&&Lr(e.db)===null)try{ye=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,_e)=>e.onError?.(_e)})}catch(G){e.onError?.(G)}let ue=[];try{ue=await f(e.db,se,w,O)}catch(G){e.onError?.(G)}let Ae=[];try{Ae=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,Ee=[],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(_e){e.onError?.(_e)}try{Ee=x(e.db,{nowMs:G,...Ge,dryRun:Ge===void 0})}catch(_e){e.onError?.(_e)}}let Ct={watch:q,stalled:M,maintainerWoken:ae,autoContinued:ye,surfacedUnknown:ne,surfacedBlocked:D,surfacedDoneConsistency:j,surfacedUnresolvableTeamfiles:re,surfacedFault:Y,surfacedClosedEpics:K,escalated:ue,autoRedelivered:Ae,woken:be,firedCronJobs:te,rateLimitCollected:z,rateLimitPolicyEvaluations:Ee};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 fL,linkSync as pL,openSync as hL,readdirSync as gL,readFileSync as Xi,readlinkSync as _L,realpathSync as wL,renameSync as Xg,unlinkSync as Gl,writeSync as yL}from"node:fs";import{dirname as EL,join as TL}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 Jo(e){return e===":memory:"?null:`${e}.lock`}function r_(e){let t=Ko(e);return t.kind==="held"?t.identity:null}function Zg(e){let t;try{t=Xi(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 Wl(n)?{kind:"held",identity:n}:{kind:"free"}}function bL(e,t){let r;try{r=wL(t)}catch{return!1}let n;try{n=gL(`/proc/${e}/fd`)}catch{return!1}for(let o of n)try{if(_L(`/proc/${e}/fd/${o}`)===r)return!0}catch{}return!1}function Ko(e){let t=Jo(e);if(t===null)return{kind:"free"};let r=Zg(t);if(r.kind==="held")return r;let n=TL(EL(e),"site.lock");if(n===t)return r;let o=Zg(n);return o.kind==="held"&&bL(o.identity.pid,e)?o:r}function Qi(e){try{let t=Qa(Xi(e,"utf8"));return t?{...t,bootId:t.bootId??null}:null}catch{return null}}function n_(){try{let e=Xi("/proc/sys/kernel/random/boot_id","utf8").trim();return Xa(e)?e:null}catch{return null}}function o_(e){try{let t=Xi(`/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 Wl(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=n_();if(n!==null&&n!==e.bootId)return!1}if(e.pidStartTicks===null)return!0;let r=o_(e.pid);return r===null?!0:r===e.pidStartTicks}function e_(e,t){let r=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,n=hL(r,"wx");try{yL(n,JSON.stringify(t))}finally{fL(n)}try{return pL(r,e),!0}catch(o){if(o.code!=="EEXIST")throw o;return!1}finally{Gl(r)}}function Zi(e,t){let r={pid:process.pid,ownerLabel:t,startedAt:new Date().toISOString(),pidStartTicks:o_(process.pid),bootId:n_()};if(e_(e,r))return t_(e,r);let n=Qi(e);if(n!==null&&Wl(n))throw new jn(n,e);let o=`${e}.reclaim.${process.pid}.${Math.random().toString(36).slice(2)}`,s=!1;try{Xg(e,o);let a=Qi(o);n===null&&a===null||n!==null&&a!==null&&a.pid===n.pid&&a.startedAt===n.startedAt?(Gl(o),s=!0):Xg(o,e)}catch{}if(s&&e_(e,r))return t_(e,r);let i=Qi(e);throw i!==null&&Wl(i)?new jn(i,e):new Error(`failed to acquire site lock at ${e} (lost a reclaim race)`)}function t_(e,t){let r=!1;return{release(){if(!r){r=!0;try{let n=Qi(e);n!==null&&n.pid===t.pid&&n.startedAt===t.startedAt&&Gl(e)}catch{}}}}}import{closeSync as Vl,existsSync as SL,fstatSync as vL,mkdirSync as AL,openSync as s_,readFileSync as i_,renameSync as $L,unlinkSync as kL,writeSync as xL}from"node:fs";import{dirname as a_,join as RL}from"node:path";import{createHash as NL,randomBytes as LL}from"node:crypto";var IL=32;function Hn(e){return e===":memory:"?null:RL(a_(e),"localweb-passcode")}function CL(){return LL(IL).toString("base64url")}function Jl(e,t){let r=a_(e);SL(r)||AL(r,{recursive:!0});let n=`${e}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`,o;try{o=s_(n,"wx",384);let s=Buffer.from(t,"utf8"),i=0;for(;i<s.length;){let a=xL(o,s,i,s.length-i);if(a<=0)throw new Error("passcode file write made no progress");i+=a}Vl(o),o=void 0,$L(n,e)}catch(s){if(o!==void 0)try{Vl(o)}catch{}try{kL(n)}catch{}throw s}}function c_(e){let t;try{t=s_(e,"r")}catch(r){if(r.code==="ENOENT")return null;throw r}try{let r=vL(t,{bigint:!0}),n=i_(t,"utf8"),o=NL("sha256").update(`${r.dev}:${r.ino}:${r.ctimeNs}:${r.mtimeNs}:${r.size}:`).update(n,"utf8").digest("base64url");return{passcode:n,generation:o}}finally{Vl(t)}}function l_(e){try{return i_(e,"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}function ea(e){let t=CL();return Jl(e,t),t}import{randomUUID as OL}from"node:crypto";function Kl(e){return`remote:${e.from.team?`${e.from.site}:${e.from.team}:${e.from.alias}`:`${e.from.site}:${e.from.alias}`}`}function u_(e,t,r){let n=t.find(o=>o.name===r.to.team);if(!n)throw new Error(`no local team registered for remote envelope's to.team "${r.to.team}"`);if(!B(n))throw new Error(`remote envelope addressed to "${r.to.team}", which is itself a remote (channel=lmmail) team -- not locally dispatchable`);ge(e,t,n.name,r.payload,{from:Kl(r),dedupeKey:r.msgId})}var DL=new Set(["dispatched","queued","failed"]);function ML(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"&&DL.has(r)}var PL="reply-surfaced:";function UL(e,t,r,n){let o=r.inReplyTo;if(!o)throw new Error("recordReplyOrAck: envelope has no in_reply_to");let s=Qm(e,o);if(!s)return"orphan";if(ML(r.payload))return Xm(e,o,n),"acked";Zm(e,o,n);let i=t.find(a=>B(a)&&a.name===s.from_alias);if(i)try{ge(e,t,i.name,r.payload,{from:Kl(r),dedupeKey:`${PL}${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 FL(e,t,r,n,o){let s=e.now??(()=>new Date().toISOString()),i={v:1,msgId:OL(),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(wo(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 d_(e,t,r,n){if(r.inReplyTo){UL(e,t,r,(n.now??(()=>new Date().toISOString()))());return}let o;try{u_(e,t,r)}catch(i){o=i}let s=n.now??(()=>new Date().toISOString());if(Km(e,r.msgId,s())){let i=o?(o instanceof Error?o.message:String(o)).slice(0,500):void 0;FL(n,r.from,r.msgId,o?"failed":"dispatched",i)}if(o)throw o}var h_=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qL=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,jL="text/plain; charset=utf-8",zl="exec",g_="exec-result";var HL="exec-result";var BL=`
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=`
480
480
  ... [lmexec output truncated; middle elided, see attachment] ...
481
- `;function __(e){return Yl(T_(e))}function w_(e){return y_(T_(e))}function Yl(e){let t=b_(e),r=S_(t.type,"type",zl),n=v_(t.id,"id"),o=Xl(t.command,"command"),s=KL(t.timeout_s,"timeout_s"),i=JL(t.reply_to,"reply_to"),a=GL(t.from,"from");return{v:1,type:r,id:n,command:o,timeout_s:s,reply_to:i,...a===void 0?{}:{from:a}}}function y_(e){let t=b_(e),r=WL(t.v),n=S_(t.type,"type",g_),o=v_(t.id,"id"),s=YL(t.exit_code,"exit_code"),i=f_(t.stdout,"stdout"),a=f_(t.stderr,"stderr"),c=zL(t.duration_ms,"duration_ms"),l=p_(t.timed_out,"timed_out"),u=p_(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=VL(t.sender_trust),f=Xl(t.sender,"sender");return{v:r,...d,sender_trust:m,sender:f}}function Ql(e){if(!h_.test(e))throw new Error(`invalid exec id: ${e}`);return`${HL} ${e}`}function m_(e,t,r){let n=Buffer.isBuffer(t)?t:Buffer.from(t,"utf8"),o=r?.capBytes??49152,s=r?.marker??BL;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:`${QL(a,l)}${s}${XL(a,u)}`,truncated:!0,attachment:{name:e==="stdout"?"stdout.txt":"stderr.txt",content_type:jL,data:n}}}function E_(e,t){let r=m_("stdout",e.stdout,t),n=m_("stderr",e.stderr,t),o=y_({v:2,type:g_,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:Ql(e.id),envelope:o,attachments:[r.attachment,n.attachment].filter(s=>s!==void 0)}}function T_(e){try{return JSON.parse(e)}catch(t){throw new Error(`invalid JSON: ${ZL(t)}`)}}function b_(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("expected object");return e}function S_(e,t,r){if(e!==r)throw new Error(`invalid ${t}: expected ${r}`);return r}function WL(e){if(e===void 0||e===1)return 1;if(e===2)return 2;throw new Error("invalid v: expected 1 or 2")}function v_(e,t){if(typeof e!="string"||!h_.test(e))throw new Error(`invalid ${t}: expected UUID v4`);return e}function Xl(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`invalid ${t}: expected non-empty string`);return e}function GL(e,t){if(e!==void 0)return Xl(e,t)}function VL(e){if(e==="admin"||e==="registered"||e==="anonymous")return e;throw new Error("invalid sender_trust: expected admin, registered, or anonymous")}function JL(e,t){if(typeof e!="string"||e.includes("/")||e.includes("\\")||e.includes("..")||e.endsWith(".")||/[\u0000-\u001f\u007f]/.test(e)||!qL.test(e))throw new Error(`invalid ${t}: expected mailbox name`);return e}function f_(e,t){if(typeof e!="string")throw new Error(`invalid ${t}: expected string`);return e}function KL(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<1)throw new Error(`invalid ${t}: expected positive integer`);return e}function zL(e,t){if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new Error(`invalid ${t}: expected non-negative integer`);return e}function YL(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 p_(e,t){if(typeof e!="boolean")throw new Error(`invalid ${t}: expected boolean`);return e}function QL(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 XL(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 ZL(e){return e instanceof Error&&e.message?e.message:String(e)}var eI=/[;&|`$<>(){}\\]/,A_=/[\x00-\x1f\x7f]/;function k_(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(A_.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(A_.test(e[r])||eI.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 Zl(e){if(!e.includes("--json"))return"requires --json when run via exec (plain-text output has no machine-readable contract)"}function tI(e){return e.includes("--watch")?"tail --watch is a long-running stream, not a fit for a single bounded exec call":e.includes("--lines")?Zl(e):"tail requires --lines N when run via exec (unbounded --max-bytes/no-limit output is not allowed)"}var rI=[{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:Zl},{prefix:["lmctl","running"],validate:Zl},{prefix:["lmctl","tail"],validate:tI}],nI=[{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 oI(e,t){return e.length<t.prefix.length?!1:t.prefix.every((r,n)=>e[n]===r)}function $_(e,t){return t.find(r=>oI(e,r))}function x_(e,t){let r=$_(e,rI);if(r){let o=r.validate?.(e);return o?{allowed:!1,code:"command_not_allowed",message:o}:{allowed:!0}}let n=$_(e,nI);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 R_}from"node:child_process";var sI=5e3,iI="/bin/sh";function N_(e){if(!Number.isInteger(e.timeoutMs)||e.timeoutMs<1)throw new Error("timeoutMs must be a positive integer");let t=e.killGraceMs??sI;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 L_(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,eu(e.pid,"SIGTERM"),r>0?m=setTimeout(()=>{eu(e.pid,"SIGKILL")},r):eu(e.pid,"SIGKILL")},t)})}async function I_(e,t){if(e.trim().length===0)throw new Error("command must be non-empty");let{killGraceMs:r,now:n}=N_(t),o=t.shellPath??iI,s=R_(o,["-c",e],{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return L_(s,t.timeoutMs,r,n)}async function C_(e,t){if(e.length===0)throw new Error("argv must be non-empty");let{killGraceMs:r,now:n}=N_(t),o=R_(e[0],e.slice(1),{cwd:t.cwd,env:t.env,detached:!0,stdio:["ignore","pipe","pipe"]});return L_(o,t.timeoutMs,r,n)}function eu(e,t){if(e)try{process.kill(-e,t)}catch(r){if(!aI(r))throw r}}function aI(e){return!!e&&typeof e=="object"&&"code"in e&&e.code==="ESRCH"}var O_=1e3,lI=6e4,uI=20,dI=1e3;async function M_(e,t){let r=t.runCommand??I_,n=t.runCommandArgv??C_,o=t.sleep??fI,s=t.pollNow??Date.now,i=t.now??(()=>new Date),a=t.stderr??(d=>process.stderr.write(`${d}
482
- `)),c=t.shouldStop??(()=>!1),l=O_,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:uI}}),f=Math.max(0,s()-d);for(let p of m.messages){if(c())break;let h=mI(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=__(g)}catch(x){kt(a,i,"warn","message_rejected",{seq:p.seq,sender:p.sender,sender_trust:h,reason:"malformed_request",error:tu(x)});continue}let E=e.execAllowlist?k_(y.command):void 0,v=e.execAllowlist?E?x_(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 D_(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:tu(x)});continue}let R=await D_(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=O_,e.once||c())break;m.messages.length===0&&f<dI&&(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:tu(d),retry_ms:l}),c())break;await o(l),l=Math.min(l*2,lI)}kt(a,i,"info","daemon_stopped",{mailbox:e.mailbox})}function mI(e,t){return e.adminUsers.has(t)?"admin":e.allowUsers.has(t)?"registered":"anonymous"}async function D_(e,t,r){let n=E_(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 fI(e){return new Promise(t=>setTimeout(t,e))}function tu(e){return e instanceof Error?e.message:String(e)}var pI=5e3,hI=300;async function P_(e,t){await e.createMailbox(t,{tolerate409:!0})}function U_(e){let t=!1,r=!1,n=Promise.resolve(),o=e.stderr??(c=>process.stderr.write(`${c}
483
- `)),s=e.runDaemonLoopImpl??M_,i={mailbox:e.mailbox,allowUsers:e.allowUsers,adminUsers:e.adminUsers,allowAnonymous:e.allowAnonymous,apiUrl:"",pollIntervalMs:e.pollIntervalMs??pI,timeoutCapSeconds:e.timeoutCapSeconds??hI,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 gI=64*1024;function F_(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 ru(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),Wm(e,r.msgId,o()),s.dispatched++}catch(i){Tn(e,r.msgId,i instanceof Error?i.message:String(i),o()),s.failed++}}async function q_(e,t,r,n){let o=n.now??(()=>new Date().toISOString()),s=n.maxBodyBytes??gI,i={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};for(let d of Hm(e))i.recovered++,await ru(e,n,F_(d),d.sender_user_id,o,i);let a=n.retryPolicy??lc;for(let d of Ps(e,o(),a))Jm(e,d.msg_id)&&(i.retriedFailed++,await ru(e,n,F_(d),d.sender_user_id,o,i));let c=Bm(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=qm(Buffer.from(f).toString("utf8"))}catch{i.stoppedEarly=!0;break}let h=o(),_=jm(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 ru(e,n,p,m.sender,o,i)}}return i}async function j_(e,t){await e.createMailbox(t,{tolerate409:!0})}var _I=6e4,wI={recovered:0,retriedFailed:0,listed:0,recorded:0,dispatched:0,rejected:0,failed:0,stoppedEarly:!1};function H_(e){let t=e.intervalMs??_I,r=null,n=!1;async function o(){if(n)return wI;n=!0;try{let s=await q_(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 yI=5e3;function B_(e){let t=e.intervalMs??yI,r=e.fetchReport??$e,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 PO}from"node:fs";var EI=10*6e4,TI=60*6e4;function W_(e,t,r={},n=Date.now()){let o=r.ackDeadlineMs??EI,s=r.replyThresholdMs??TI,i=[];for(let a of t){let c=Us(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 bI=[/^\S+'s turn has finished and exited; resubmit/i,/^resubmit .*lmctl chat/i];function SI(e){let t=e.split(/\r?\n/).filter(n=>n.trim().length>0).filter(n=>!bI.some(o=>o.test(n.trim()))),r=(t[t.length-1]??"").trim();return r==="BLOCKED"?"BLOCKED":r==="DONE"?"DONE":null}function G_(e){if(e.trim()==="")return{status:"NO-OUTPUT",wake:"env"};let t=SI(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 G_(e.replyText);case"stalled":{let t=G_(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 Z_=1e4;function ou(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>Z_)return ke("invalid_limit",`invalid limit "${r}" -- must be an integer from 0 to ${Z_}`);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 ew(e,t,r,n={}){let o=ou(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),pe(s.ts),(0,Wn.escapeCell)(s.team),(0,Wn.escapeCell)(s.status),(0,Wn.escapeCell)(s.note??"")])])}var tw=Ut(xt(),1);function su(e){let t=e.db.db,r=Vm(t),n=uc(t),o=n.filter(c=>c.failure_reason?.startsWith(Yr)).length,s=n.length-o,i=Ps(t,new Date().toISOString()).length,a=Ym(t);return{counts:r,retryEligibleCount:s,permanentCount:o,dueNowCount:i,deliveryErrorCount:a}}function rw(e,t={}){let r=su(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,tw.formatTable)([["STATE","COUNT"],...n]),s=r.deliveryErrorCount>0?`
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?`
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 ZI,existsSync as eC,openSync as tC,readFileSync as hu,readSync as rC,realpathSync as nC,statSync as oC}from"node:fs";var FI="member_health:";function iu(e,t){return`${FI}${e}:${t}`}function nw(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(iu(t,r),JSON.stringify(o))}function zo(e,t,r){let n=e.prepare("SELECT v FROM kv WHERE k = ?").get(iu(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 ow(e,t,r){e.prepare("DELETE FROM kv WHERE k = ?").run(iu(t,r))}function sw(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 Yo(e,t){return e.prepare("SELECT * FROM prompt_tasks WHERE id = ?").get(t)??null}function iw(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 aw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE task_id = ? ORDER BY id ASC").all(t)}function cw(e,t){return e.prepare("SELECT * FROM task_prompts WHERE to_id = ? AND retrieved_ts IS NULL ORDER BY id ASC").all(t)}function lw(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 uw(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 dw(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(Yo(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 mw(e,t){return e.prepare("SELECT * FROM prompt_task_reassignments WHERE prompt_id = ? ORDER BY id ASC").all(t)}function fw(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 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
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=Yo(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 qI}from"node:fs";function jI(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 HI(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=qI(o.prompt_file,"utf8")}catch{continue}if(s.includes(n))return o}return null}function au(e,t){return jI(e,t).map(r=>({row:r,verifiedTarget:HI(e,r)}))}function pw(e,t){let r=au(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 hw(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 cu="operator";function BI(e){if(e===cu)throw new Error(`logical_names: "${cu}" is reserved for the real operator entity (epic #162's #164) -- never a re-routable logical name`)}function gw(e,t,r,n,o=new Date().toISOString()){BI(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 ra(e,t){return t===cu?null:e.prepare("SELECT teamfile_path AS teamfilePath, alias FROM logical_names WHERE name = ?").get(t)??null}function _w(e){return e.prepare("SELECT name, teamfile_path AS teamfilePath, alias, updated_at AS updatedAt FROM logical_names ORDER BY name").all()}function ww(e,t){e.prepare("DELETE FROM logical_names WHERE name = ?").run(t)}function Qo(e,t,r){let n=ra(e,r);if(n===null)return null;for(let o of t){if(!B(o))continue;let s;try{s=Q(o)}catch{continue}if(s===n.teamfilePath)return{team:o.name,alias:n.alias}}return null}import{existsSync as WI,mkdirSync as GI,readFileSync as VI,renameSync as JI,writeFileSync as KI}from"node:fs";import{homedir as zI}from"node:os";import{dirname as YI,join as yw}from"node:path";function lu(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 uu(e,t,r){let n=`
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=`
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 Ew(e){return e.filter(t=>t.answer===null&&t.row.retracted_ts===null&&t.row.merged_into_id===null)}function Tw(e,t){let r=t??process.env.LMBEE_SENDER_PULL_SEEN_DIR??yw(zI(),".lmbee","sender-pull-seen");return yw(r,`${e}.json`)}function du(e){try{let t=JSON.parse(VI(e,"utf8"));return new Map(Object.entries(t).map(([r,n])=>[Number(r),n]))}catch{return new Map}}function bw(e,t){let r=YI(e);WI(r)||GI(r,{recursive:!0});let n={};for(let[s,i]of t)n[String(s)]=i;let o=`${e}.tmp`;KI(o,JSON.stringify(n,null,1)),JI(o,e)}var QI=["team","escalation_attempt_count","last_escalation_attempt_ts","quota_exhausted_last_seen_ts","quota_exhausted_message"],mu=QI.join(", ");function XI(e,t){return e.prepare(`SELECT ${mu} FROM team_progress WHERE team = ?`).get(t)??null}function Sw(e,t){let r=e-Date.parse(t);return Number.isFinite(r)?r:null}function vw(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:Sw(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?Sw(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(XI(e,f))}}),m=t?e.prepare(`SELECT ${mu} FROM team_progress WHERE team = ? AND escalation_attempt_count > 0`).all(t):e.prepare(`SELECT ${mu} 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 sC=[".md",".txt",".json",".log",".yaml",".yml",".csv",".html",".htm",".xml"];function iC(e){if(/\s/.test(e)||!(e.startsWith("/")||e.startsWith("./")||sC.some(r=>e.toLowerCase().endsWith(r))))return!1;try{return eC(e)}catch{return!1}}function aC(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 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}"
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 hu(t.slice(1),"utf8");if(!r&&iC(t))throw aC(e,t);return t}async function xw(e,t,r,n){let{baseId:o,alias:s}=Qr(t);if(o!=="operator"&&!e.teams.some(E=>E.name===o)){let E=Qo(e.db.db,e.teams,o);E!==null&&(o=E.team,s=s??E.alias,t=s!==null?`${o}:${s}`:o)}let i=`pending; the cron will deliver it -- or run: queue deliver ${o}`,a=e.teams.find(E=>E.name===o);if(a&&B(a)){let E=s??a.leadAlias,v=Vr(a);if(v.length>0&&!v.some(S=>S.alias===E))throw new Error(`enqueue: "${E}" is not a configured member of team "${o}" -- actual members: ${v.map(S=>S.alias).join(", ")}`)}if(n.inReplyTo!==void 0&&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=ge(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??Ko)(e.db.path),p=f.kind==="free"?"warning: no lmbee daemon appears to be running against this database -- queue delivery, mail polling, and anti-churn nudging are all offline; this prompt will sit undelivered until `lmbee serve` is started (or deliver it manually with `queue deliver`).\n":f.kind==="unknown"?`warning: could not confirm whether an lmbee daemon is running against this database (the site lock could not be read) -- this is not evidence it is down.
499
- `:"",h=a&&B(a)?cC(e,a,s??a.leadAlias,t):"",g=(n.inReplyTo===void 0?yr(e.db.db,d):null)?.expects_response===1&&!lC(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&&B(a))try{let v=await(n.fetchReport??$e)();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 cC(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=zo(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:zo(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 lC(e){return e.includes("?")}function gu(e,t){return{queue:fc(e.db.db,t)}}function Rw(e,t,r={}){if(r.json)return JSON.stringify(gu(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),pe(o.created_ts),o.sent_ts!==null?pe(o.sent_ts):o.retrieved_ts!==null?pe(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 Nw(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 fu=64*1024;function Aw(e){if(e===null)return null;let t=Buffer.byteLength(e.answer_text,"utf8");if(t<=fu)return{...e,byteLength:t,totalBytes:t,truncated:!1};let r=Buffer.from(e.answer_text,"utf8").subarray(0,fu).toString("utf8");for(;Buffer.byteLength(r,"utf8")>fu;)r=r.slice(0,-1);return{...e,answer_text:r,byteLength:Buffer.byteLength(r,"utf8"),totalBytes:t,truncated:!0}}function Xo(e,t){let r=yr(e.db.db,t);if(r===null)return null;let n=Ce(e.db.db,t),o=zh(e.db.db,t).map(s=>Aw(s)).filter(s=>s!==null);return{id:r.id,createdAt:r.created_ts,answer:Aw(n),answerHistory:o,mergedInto:r.status==="merged"?Ol(e.db.db,r)?.id??null:null,...vt(r,n)}}function Lw(e,t,r={}){let n=Xo(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 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=`
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 Iw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=Qo(e.db.db,e.teams,r),a=i!==null?i.team:r;try{let c=o.amend?sg(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 Cw(e,t,r,n,o={}){let s=Cr("queue answer",n,o.literal),i=Qo(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 Ow(e,t,r,n,o={}){let s=Cr("queue resolve",n,o.literal);try{let i=o.amend?ig(e.db.db,t,r,s):og(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 Dw(e,t,r,n,o={}){try{let s=Zh(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 Mw(e,t,r={}){let n=Date.now(),o=eg(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 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):
507
507
  ${s.join(`
508
- `)}`,exitCode:0}}function Pw(e,t,r,n={}){try{let o=tg(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 Uw(e,t,r,n={}){let o=new Date().toISOString();return Im(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 Fw(e,t,r={}){let n=Cm(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 qw(e,t,r={}){if(t!==void 0){let s=Nm(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=Lm(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 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}):
509
509
  ${o.join(`
510
- `)}`,exitCode:0}}function na(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 _u(e,t={}){return hc(e.db.db,t)}var pu=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=nC(r.prompt_file)}catch(u){return o(s(u)?"missing":"unreadable")}let a,c;try{let u=oC(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=tC(i,"r")}catch{return o("unreadable")}try{let u=Buffer.alloc(pu),d=rC(l,u,0,pu,0);return{id:t,status:"available",text:u.subarray(0,d).toString("utf8"),byteLength:d,truncated:a>pu,sourceModifiedAt:c,fetchedAt:n}}catch{return o("unreadable")}finally{ZI(l)}}async function jw(e,t,r={}){let o=await(r.fetchReport??$e)();return`queue deliver: dispatched ${Er(e.db.db,{teams:e.teams,teamName:t,report:o})} pending prompt(s)`}function Hw(e,t,r={}){let n=Bs(e.db.db,t,r.id),o=r.id===void 0?lw(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=hu(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 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}):
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 uC(e,t){if(t==="operator"||e.teams.some(n=>n.name===t))return t;let r=Qo(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 wu(e,t){let r=uC(e,t),n=[...Yh(e.db.db,r),...Hs(e.db.db,r)];n.sort((s,i)=>s.id-i.id);let o=cw(e.db.db,r);return{pending:n,taskPrompts:o}}function Bw(e,t,r={}){let n=wu(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=Ol(e.db.db,a),m=d!==null?` -> #${d.id}`:"";return{ts:a.created_ts,text:`[queue] #${a.id} from ${a.from_id} (${pe(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} (${pe(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} (${pe(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 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)
517
517
  ${i.map(a=>a.text).join(`
518
- `)}`}function Ww(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 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):
519
519
  ${o.join(`
520
- `)}`}function Gw(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 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:
521
521
  ${o.join(`
522
522
  `)}
523
- close with: queue answer ${n.map(s=>s.row.id).join(",")} <text|@file> --from ${t}`}function $w(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 kw=600;function Vw(e,t,r={}){let n=r.seenPath??Tw(t);if(r.mark!==void 0){let c=du(n),l=Array.isArray(r.mark)?r.mark:uu(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 bw(n,c),`marked ${l.length} pulled`}let o=du(n),s=r.ids!==void 0&&r.ids.length>0,i=uu(e.db.db,t,r.ids);if(!s&&!r.all&&(i=r.open?Ew(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:lu(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} ${lu(c)}`;if(c.answer!==null?(l+=` answered ${$w(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 ${$w(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>kw&&(u=`${u.slice(0,kw)}
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)}
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 yu(e,t,r=Date.now()){return{stats:vw(e.db.db,t,r)}}function dC(e){let t=e/36e5;return t<24?`${Math.round(t)}h ago`:`${Math.round(t/24)}d ago`}function Jw(e,t,r={}){let n=yu(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?pe(s.lastEscalationAttemptTs):"-",s.quotaExhaustedLastSeenAgeMs!==null?dC(s.quotaExhaustedLastSeenAgeMs):"-"]);return(0,Kt.formatTable)([["TO","PENDING","OLDEST AGE","ESCALATING","ESCALATING AGE","ESCALATION ATTEMPTS","LAST ESCALATION","QUOTA EXHAUSTED"],...o])}function Kw(e,t){let r=(t??7)*24*60*6e4;return`queue gc: removed ${lf(e.db.db,{retentionMs:r})} prompt file(s) older than ${t??7} day(s)`}function mC(e,t,r){let n=hw(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=hu(s.prompt_file,"utf8").split(`
528
- `)[0]??""}catch{}o.push(` #${s.id} from ${s.from_id} to ${s.to_id}, ${pe(s.created_ts)} -- merged into #${i.id}: "${a}"`)}return o.join(`
529
- `)}function zw(e,t,r={}){if(r.swallowed===!0)return mC(e,t,r.json);if(r.repair===!0){let l=pw(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=au(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(`
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(`
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(`
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 fC,statSync as pC}from"node:fs";var Vn=Ut(xt(),1);function oa(e,t,r){let n;try{n=pC(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=fC(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):_o(i);if(a.length===0)return{output:`error: source parsed to zero teams, not registered: ${t}`,ok:!1};xs(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 Eu(e){return{defaultTeamsConfPath:e.teamsConfPath,sources:tc(e.db.db)}}function Yw(e,t={}){let r=Eu(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 Qw(e,t){return Rs(e.db.db,t),`source removed: ${t}`}import{execFile as hC}from"node:child_process";import{promisify as gC}from"node:util";var Jn=Ut(xt(),1);var _C=gC(hC);function Xw(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 Tu(e){let t=e.teams.map(n=>Xw(e,n.name)),r=Ns(e.db.db)??[];return{teams:t,active:r}}function bu(e,t){return{team:Xw(e,t)}}var wC=new Set(["DONE"]);function Zw(e,t={}){let r=Tu(e),n=t.nonDone?r.teams.filter(i=>!wC.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?pe(i.state.changed_ts):"-",i.state?.last_ts?pe(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 ey(e,t,r={}){let{team:n}=bu(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 ty(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 ry(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 ny(e,t,r,n=Date.now(),o=_C){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||!B(a))return i;try{let c=await Wo(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 Su(e){return{active:Ns(e.db.db)??[]}}function oy(e,t={}){let r=Su(e);return t.json?JSON.stringify(r):`active: ${r.active.length?r.active.join(","):"(none)"}`}var Kn=Ut(xt(),1);function yC(e,t){return B(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead(reclaimable)":"Idle":"remote -- delivery only"}async function vu(e,t={}){let r=null;t.live&&(r=await(t.fetchReport??$e)());let n=e.teams.map(u=>{let d=Ue(e.db.db,u.name),m=af(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=yC(u,r)),f}),s=await(t.checkActiveGhAccountImpl??zi)(),i=s!==null&&!s.matchesPolicy?s:null,c=(t.readSiteLockStateImpl??Ko)(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 sy(e,t={}){let r=await vu(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?"-":pe(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 "${jl}". DO NOT PUSH until this is switched back. !!!`),i.push(s),i.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(`
536
536
 
537
- `)}var Dr=Ut(xt(),1);function Au(e){return{teams:e.teams}}function iy(e,t={}){if(t.json)return JSON.stringify(Au(e));let r=e.teams.map(n=>B(n)?[(0,Dr.escapeCell)(n.name),(0,Dr.escapeCell)(n.leadAlias),(0,Dr.escapeCell)(n.promptName),(0,Dr.escapeCell)(n.description)]:[(0,Dr.escapeCell)(n.name),"(remote)","--","--"]);return(0,Dr.formatTable)([["TEAM","LEAD","PROMPT","WHAT-IT-DOES"],...r])}function EC(e){let t=e.LMCTL_AUTH_URL?.trim()||e.LMCTL_AUTH_BASE_URL?.trim();return t?t.replace(/\/+$/,""):void 0}async function $u(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.validateAppkeyImpl??bd,o=EC(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 ay(e={}){let{data:t,exitCode:r}=await $u(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 $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}
538
538
  label: ${t.label}
539
- appkey source: ${t.appkeySource}`,exitCode:r}}import{execFile as TC}from"node:child_process";import{promisify as bC}from"node:util";var SC=bC(TC);async function cy(e,t=3e4){let r=e.trim().split(/\s+/).filter(Boolean),{stdout:n}=await SC("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 vC}from"node:child_process";import{existsSync as AC}from"node:fs";import{promisify as $C}from"node:util";var kC=$C(vC),sa=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 ku(e){let t=e.cliPath??process.env.LMBI_SUBSCRIPTION_CLI;if(t===void 0||t==="")throw new sa;let r=e.execFileImpl??kC,{stdout:n}=await r("node",[t,e.configPath,"--json"],{timeout:e.timeoutMs??3e4});return JSON.parse(n)}async function ly(e={}){let t=e.configPath??process.env.LMBI_SUBSCRIPTION_CONFIG_PATH;if(t===void 0||t===""||!AC(t))return{status:200,body:{needs_configuration:!0}};try{return{status:200,body:await ku({configPath:t,cliPath:e.cliPath,execFileImpl:e.execFileImpl})}}catch(r){return r instanceof sa?{status:500,body:{error:r.message}}:{status:502,body:{error:r instanceof Error?r.message:String(r)}}}}import{createHash as py,randomBytes as NC,timingSafeEqual as LC}from"node:crypto";var uy=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 dy}from"node:crypto";import{basename as xC}from"node:path";function b(e){return String(e??"").replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}var my="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}}",RC=`default-src 'none'; style-src 'sha256-${dy("sha256").update(my).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(pe(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=RC+`; base-uri '${a?"self":"none"}'`+(o.length?`; script-src ${o.map(d=>`'sha256-${dy("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 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">
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>${my}</style></head><body><a href="#main">Skip to content</a><header><p>Local operations / lmauto</p><nav aria-label="Main">${u.map(([d,m])=>Re(d,m)).join(" | ")}</nav></header><main${l} id="main"><h1>${b(e)}</h1>${t}</main><footer><p>Times are relative to this page load. Refresh for current data.</p></footer></body></html>`}function Mr(e){let t=new Map;for(let r of e)if(B(r))try{t.set(Q(r),r.name)}catch{}return t}function fy(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=`${xC(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(pe(s.ended_at)),b(me(s.idle_ms)),b(s.ran_human)]))}var ia="localweb_session",IC=8*1024,CC=1024,OC=30*24*60*60,DC=10,MC=6e4,PC=6e4,UC=1024;function Ty(e,t){let r=FC(t.mountPath),n=`${r}/login`||"/login",o=`${r}/`||"/",s=r||"/",i=t.allowedOrigins,a=new Map,c=new Map,l=t.remoteKey??JC,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=qC(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 Zo(m,p,n,r,"unavailable");let g=m.req.header("authorization");if(g!==void 0){let E=l(m),v=Date.now();if(wy(c,E,v))return Zo(m,p,n,r,"locked_out");let S=g.startsWith("Bearer ")?g.slice(7):"";if(!_y(S,_.passcode))return yy(c,E,v),Zo(m,p,n,r);Ey(c,E),await f();return}let y=gy(m.req.header("cookie"));if(y===null||a.get(y)!==_.generation)return Zo(m,p,n,r,y===null?"missing":"expired");if(WC(m.req.method)&&!hy(m.req.url,m.req.header("host"),h,i))return Zo(m,p,n,r);await f()}),e.get("/healthz",m=>m.json({ok:!0})),e.get("/login",m=>m.html(jC(vy(m,n,r),r))),e.post("/login",async m=>{if(!hy(m.req.url,m.req.header("host"),m.req.header("origin"),i))return xu(m,n,r);let f=l(m),p=Date.now();if(wy(c,f,p))return HC(m,r);let h=d();if(h===null)return xu(m,n,r);let _=await BC(m.req.raw).catch(()=>null);if(_===null||!_y(_,h.passcode))return yy(c,f,p),xu(m,n,r);Ey(c,f),a.size>=CC&&a.delete(a.keys().next().value);let g=NC(32).toString("base64url");return a.set(g,h.generation),m.header("Set-Cookie",GC(g,s,new URL(m.req.url).protocol==="https:")),m.redirect(Sy(m,r)??o,303)}),e.post("/logout",m=>{let f=gy(m.req.header("cookie"));return f!==null&&a.delete(f),m.header("Set-Cookie",VC(s,new URL(m.req.url).protocol==="https:")),m.redirect(n,303)})}function FC(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 qC(e,t){return t&&(e===t||e.startsWith(`${t}/`))?e.slice(t.length)||"/":e}function Zo(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"?by(`${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 xu(e,t,r){return e.html(ve("Login failed",`<p>Invalid credentials.</p><a href="${b(vy(e,t,r))}">Try again</a>`,r),401)}function HC(e,t){return e.html(ve("Login failed","<p>Too many failed attempts from this source. Try again shortly.</p>",t),429)}function by(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 Sy(e,t){let r=new URL(e.req.url).searchParams.getAll("next");return r.length===1?by(r[0],t):null}function vy(e,t,r){let n=Sy(e,r);return n===null?t:`${t}?next=${encodeURIComponent(n)}`}async function BC(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>IC)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 hy(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 WC(e){return e!=="GET"&&e!=="HEAD"&&e!=="OPTIONS"}function gy(e){let t=(e??"").split(";").map(r=>r.trim()).filter(r=>r.startsWith(`${ia}=`)).map(r=>r.slice(ia.length+1));return t.length===1&&/^[A-Za-z0-9_-]{43}$/.test(t[0])?t[0]:null}function GC(e,t,r){return`${ia}=${e}; Path=${t}; HttpOnly; SameSite=Strict; Max-Age=${OC}${r?"; Secure":""}`}function VC(e,t){return`${ia}=; Path=${e}; HttpOnly; SameSite=Strict; Max-Age=0${t?"; Secure":""}`}function _y(e,t){let r=py("sha256").update(e,"utf8").digest(),n=py("sha256").update(t,"utf8").digest();return LC(r,n)}function JC(e){try{return uy(e).remote.address??"unknown"}catch{return"unknown"}}function wy(e,t,r){let n=e.get(t);return n!==void 0&&r<n.lockedUntilMs}function yy(e,t,r){let n=e.get(t);if(n===void 0||r-n.windowStartMs>MC){e.size>=UC&&e.delete(e.keys().next().value),e.set(t,{count:1,windowStartMs:r,lockedUntilMs:0});return}n.count+=1,n.count>=DC&&(n.lockedUntilMs=r+PC)}function Ey(e,t){e.delete(t)}import{createHash as KC}from"node:crypto";var Ay=64*1024,zC=new Set(["math"]);function YC(e,t){return KC("sha256").update(e,"utf8").update("\0","utf8").update(t,"utf8").digest("hex")}function aa(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")>Ay)throw new I("INVALID_ARGUMENT",`prompt exceeds the ${Ay}-byte comm-flow cap`,2);if(!zC.has(n))throw new I("INVALID_ARGUMENT",`"${n}" is not a comm-flow-enabled target`,2);let i=t.find(l=>l.name===n);if(i===void 0||!B(i))throw new I("INVALID_ARGUMENT",`"${n}" is not a registered local team`,2);let a=YC(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=ge(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 QC,readFileSync as XC}from"node:fs";import{dirname as ky,join as Ru}from"node:path";import{fileURLToPath as xy}from"node:url";var ZC=Ru(ky(xy(import.meta.url)),"public"),eO={"/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"}},tO=Ru(ky(xy(import.meta.url)),"vendor-webui"),rO={"/":{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 nO(e){return e.endsWith("/")?e.slice(0,-1):e}function oO(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 $y(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=Ru(t,i.file);if(!QC(a))return s.notFound();let c=XC(a);return n!==void 0&&i.contentType.startsWith("text/html")&&(c=oO(c.toString("utf8"),n)),s.body(c,200,{"content-type":i.contentType})})}function Ry(e,t={}){let r=nO(t.mountPath??""),n=t.webDistDir??tO;$y(e,n,rO,r!==""?`${r}/`:void 0),$y(e,ZC,eO,`${r}/legacy/`)}import{createHash as Iu,createHmac as uO,randomBytes as Nu,timingSafeEqual as dO}from"node:crypto";import{basename as mO}from"node:path";import{existsSync as sO}from"node:fs";import{homedir as iO}from"node:os";import{join as aO}from"node:path";function cO(e){return e||(process.env.LMTEAM_DB_PATH?process.env.LMTEAM_DB_PATH:aO(iO(),".lmteam","lmteam.db"))}function ca(e){let t=cO(e);if(!sO(t))throw new Error(`lmteam database not found at ${t} -- set LMTEAM_DB_PATH or check the path`);return new pt(t,{readonly:!0,fileMustExist:!0})}function Ny(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 Ly(e){return e.prepare("SELECT * FROM asks WHERE status = 'open' ORDER BY raised_at ASC").all()}function Iy(e,t){return e.prepare("SELECT * FROM asks WHERE id = ?").get(t)??null}function Cy(e){return e.prepare("SELECT * FROM blocked WHERE status = 'open' ORDER BY raised_at ASC").all()}function lO(){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,ye=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 Ae=new Error(ue??"Unexpected server response");throw Ae.status=j.status,Ae}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(),ye])}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 ye=new TextEncoder().encode(W.answer_text).length;if(!Number.isSafeInteger(W.byteLength)||W.byteLength!==ye||ye>65536||!Number.isSafeInteger(W.totalBytes)||Number(W.totalBytes)<ye||(W.truncated?Number(W.totalBytes)<=ye:W.totalBytes!==ye))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,ye=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",ye);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,H=!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(H||e||document.hidden){Z.preventDefault();return}for(let W of M)W.input.value=W.value;H=!0,C=!0,q&&(q.disabled=!0),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>${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,`
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,ye=new AbortController;L=ye,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 _e of N(x))_e.name&&!_e.disabled&&G.append(_e.name,_e.value.replace(/\r\n|\r|\n/g,`\r
547
- `));return G.toString()},Y;try{Y=await d(ne.href,"html",ye,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",ye);if(!n(ae))return;let Ze=new DOMParser().parseFromString(st,"text/html").getElementById("comm-draft-form"),mt="";try{Ze&&(mt=U(Ze,"csrf").value)}catch{}if(!mt)throw G;U(x,"csrf").value=mt,Y=await d(ne.href,"html",ye,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 Ae=i("div");Ae.id="comm-review-panel",Ae.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 Ee=document.createElement("textarea");Ee.name="prompt",Ee.hidden=!0,Ee.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,Ee,Ge),Ae.append(be,je,Ct),je.addEventListener("click",()=>{C||je.disabled||(q.value=W,R.replaceChildren(...A),w=null)}),J(be,je),R.replaceChildren(Ae)}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===ye&&(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&&H&&(H=!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 la=`(function () {
546
+ `)).length>65536){s("comm-composer-notice","Enter a nonblank prompt of at most 64 KiB UTF-8.");return}let ae=t,Ee=new AbortController;L=Ee,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 () {
548
548
  function __name(value) { return value; }
549
- return (${lO.toString()})();
550
- })();`;var Oy=ve("","","").match(/<style>([\s\S]*?)<\/style>/),fO=Iu("sha256").update(Oy?Oy[1]:"").digest("base64"),pO=Iu("sha256").update(la).digest("base64"),hO=`default-src 'none'; style-src 'sha256-${fO}'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; script-src 'sha256-${pO}'; connect-src 'self'`,Lu="lmbee_comm_browser",gO=64*1024,_O=256*1024,Yn=class extends Error{};function Dy(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=Nu(32),a=new Map,c=$=>Iu("sha256").update($).digest("hex"),l=$=>uO("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||!dO(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(`${Lu}=`));if(A.length===1)try{let M=d(A[0].slice(Lu.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=Nu(24).toString("hex");return $.header("Set-Cookie",`${Lu}=${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(!$||!B($)||$.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(H($))}">${b(L($))}</span>`}function H($){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(!B(M))return!1;try{return Q(M)===O.teamfilePath}catch{return!1}});return q?`<a href="${b(`${n}/sessions/${encodeURIComponent(q.name)}/${encodeURIComponent(O.alias)}`)}" title="${b($)}">${b(`${q.name}:${O.alias}`)}</a>`:`<span title="${b($)}">${b(`${mO(O.teamfilePath)}:${O.alias}`)}</span>`}let A=r.teams.find(q=>q.name===$);return A&&B(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(!$||!B($))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>${la}</script>`,n,{},[la]),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 (${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>
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=ca(),M;try{M=Iy(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>_O)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)>gO)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",hO),$.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=na(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(H(M))}</td><td>${fe(M.created_ts)}</td><td>${h(M)}</td></tr>`).join("")}</tbody></table><p>Task links for these prompts: not recorded.</p>${q.meta.next_cursor?`<a href="${o}?after=${q.meta.next_cursor}">Older prompts</a>`:""}</section>`)}),t.post("/comm/math/review",async $=>{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:${Nu(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=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">
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
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 ye=s()-6e4;for(let[j,Y]of a)Y.start<ye&&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=aa(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=Xo(r,A),Z=Or(r,A),W=M.answer,ae=M.lifecycle==="finished"&&p(M.lifecycleBasis),ye=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: ${ye}. 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: ${ye}.`:"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(H(M))}</p><p><a href="${o}/prompts/${A}">Refresh state</a> \xB7 <a href="${o}">Math inbox</a></p>${j}<section aria-label="Prompt and answer sequence"><h2>Prompt and answer sequence</h2><article data-queue-id="${A}" data-event="request"><h3>Prompt text</h3><p>${C(q.from_id)} \u2192 ${C(q.to_id)} \xB7 queued ${fe(M.createdAt)}</p><details><summary>Prompt times</summary><p id="comm-handling-observation">Delivery attempted ${q.sent_ts?fe(q.sent_ts):"not recorded"} \xB7 Picked up ${q.retrieved_ts?fe(q.retrieved_ts):"not recorded"} </p><p>Answer recorded <span id="comm-reply-time">${W?fe(W.answered_at):"not recorded"}</span></p></details>${Z?.status==="available"?`<pre>
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>
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 wO}from"node:path";var Cu=50,yO=e=>e.trim().toLowerCase().replace(/[\s_]+/g,"-"),Ou=e=>["blocked","error","on-hold","rate-limited"].includes(yO(e));function qy(e){if(!/^[1-9]\d*$/.test(e)||!Number.isSafeInteger(Number(e)))throw new I("INVALID_ARGUMENT","Invalid positive integer ID");return Number(e)}function EO(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&&qy(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 My(e,t){let r=new URLSearchParams(Object.entries(t).filter(([,n])=>n!==""));return e+(r.size?`?${r}`:"")}function TO(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||Ou(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)*Cu,s*Cu),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*Cu,byId:a}}function Qn(e,t){return Re(`${t}/tasks/${e.id}`,`#${e.id} ${e.title}`)}function jy(e,t,r){if(e.owner_team_path===null)return"Unassigned";let n=`${wO(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 Hy(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 Py(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),Hy(s),jy(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 Uy(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 Fy(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 By(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=EO(i.req.url),c;if(a.team){let p=t.teams.find(h=>h.name===a.team&&B(h));if(!p||!B(p))throw new I("INVALID_ARGUMENT","Unknown local owning team");c=Q(p)}let l=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>'+Uy(a,d,n),503);let m=TO(l.rows,a,p=>Sr(t.db.db,p),c),f=`<nav aria-label="Task pages">${m.pageNumber>1?Re(My(`${n}/tasks`,{...a,page:String(m.pageNumber-1)}),"Previous page"):""} ${m.more?Re(My(`${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>'+Fy({total:l.rows.length,by_kind:l.rows.reduce((p,h)=>(p[h.kind]=(p[h.kind]??0)+1,p),{})})+Uy(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+Py(m.rows,m.byId,n,u)+f)}catch(a){return s(i,a)}}),e.get("/tasks/:id",i=>{try{let a=qy(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: ${jy(c,f,n)}.</p><p>Blocked / hold: ${Hy(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("")+Fy(Ar(t.db.db,{id:a}))+"<h2>Children</h2>"+Py(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 bO}from"node:path";var Wy=50,Gy='<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>',SO={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),Vy=e=>e.last_fire_status===null?"Not recorded":`${b(SO[e.last_fire_status]??e.last_fire_status)} <small>(${b(e.last_fire_status)})</small>`;function Jy(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 Ky(e,t,r){if(e.session_teamfile===null||e.session_alias===null)return"Not configured";let n=`${e.session_teamfile}:${e.session_alias}`,o=`${bO(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 zy(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 Du(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function vO(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 AO(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>"+Du([["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>`+Du([["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>`+vO(e.artifacts)+s+"</article>"}function Yy(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=Jy(a),l=Ni(t.db.db,{limit:Wy,after:c}),u=Mr(t.teams),d=l.rows.map(f=>({job:f,flags:zy(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",Vy(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>`,Ky(h,u,n)]),p);return o(a,"Cron jobs",Gy+"<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=Jy(a),u=Ie(t.db.db,Number(c)),d=vi(t.db.db,{jobId:u.id,limit:Wy,after:l}),m=Rr(t.db.db,u.id),f=zy(u,m),p=Du([["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",Ky(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",Vy(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}`,Gy+`<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(AO).join(""):_)+i(`${n}/cron/${u.id}`,l,d.next_cursor))}catch(c){return s(a,c)}})}function $O(e,t){return t===null&&e.retracted_ts===null&&(e.status==="pending"||e.status==="escalating"||e.status==="sent"||e.status==="retrieved")}var Xy=64*1024;async function kO(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>Xy)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 Zy(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 eE(e,t){let r=[];t.retracted_ts!==null&&t.retracted_reason&&r.push(t.retracted_reason);let n=Zy(e,t);for(let o of n)o.retracted_ts!==null&&o.retracted_reason&&r.push(o.retracted_reason);return r}function Mu(e,t=Date.now()){return Ho(e,t).map(n=>{let o=n.row,s=nn(e,o),i=jo(e,o),a=n.ageMs>=Go||s>=2&&o.sent_ts===null,c=eE(e,o);return{row:o,constituentCount:s,retractedCount:i,urgent:a,retractedReasons:c}})}function tE(e){return e===1?"1 of 1":`${e} merged into this one`}function xO(e){return e==="merged"||e==="informational"||e==="retracted"}function RO(e){return e.lifecycle==="queued"?"queued":e.lifecycle==="processing"?"processing":xO(e.lifecycleBasis)?"muted":"replied"}function NO(e){return e.lifecycle==="queued"?"Queued":e.lifecycle==="processing"?"Processing":e.lifecycleBasis==="merged"?"Combined":e.lifecycleBasis==="informational"?"Informational":e.lifecycleBasis==="retracted"?"Retracted":"Replied"}function rE(e){return`<span class="status-chip status-${RO(e)}" title="${b(Pu(e))}">${b(NO(e))}</span>`}function Pu(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 LO(e){return`<dl>${e.map(([t,r])=>`<dt>${b(t)}</dt><dd>${r}</dd>`).join("")}</dl>`}function IO(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 CO(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 OO(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 Qy(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=tE(i.constituentCount),p=i.retractedCount>0?`${i.retractedCount} retracted${i.retractedReasons.length>0?`: ${i.retractedReasons.map(_=>`\u201C${b(_)}\u201D`).join("; ")}`:""}`:"\u2014",h=`${rE(l)} \xB7 ${b(Pu(l))}`;return[u,d,m,f,p,h]});return zn(o,s,t)}function nE(e,t,r=""){let n=r.replace(/\/$/,"");e.get("/operator",o=>{try{let s=Mu(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>${Qy(i,"Urgent escalations",n,t.db.db)}</section>`,u=`<section aria-label="Routine escalations"><h2>Routine escalations</h2>${Qy(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 _=ca(),g,y,E;try{g=Cy(_),y=Ly(_),E=Ny(_)}finally{_.close()}m=`<section class="warning" aria-label="Blocked"><h2>Blocked</h2>${CO(g)}</section>`,f=`<section aria-label="Asks"><h2>Asks</h2>${OO(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>${IO(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=jo(t.db.db,a),f=eE(t.db.db,a),p=[["From",b(a.from_id)],["To",b(a.to_id)],["Queued",fe(a.created_ts)],["Lifecycle",`${rE(u)} \xB7 ${b(Pu(u))}`],["Constituents",b(tE(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>`:$O(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="${Xy}" required></textarea><button>Send answer</button></form></section>`);let g=Zy(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">${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>
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>${LO(p)}</section>
562
+ <section aria-label="Escalation metadata"><h2>Metadata</h2>${IO(p)}</section>
563
563
  <article aria-label="Prompt content"><h2>Prompt content</h2>${h}</article>
564
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 kO(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 oE(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+(Ou(y)?E:0),0),c=Mu(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=qo(),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(B),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(Bo(Wi(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>
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>
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 DO(e,t,r){return`${r.replace(/\/$/,"")}/api/session/${encodeURIComponent(e)}/${encodeURIComponent(t)}?limit=20`}function sE(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(DO(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",_,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))}">
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,47 +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 (${MO.toString()})();
589
- })();</script>`}function MO(){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 H=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,Ae=0,be="";for(;;){let z=await te.read();if(z.done)break;if(Ae+=z.value.byteLength,Ae>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 Ae=await w(`${n}/api/queue/${D}/preview`);if(Y!==_||!v(K))return;if(Ae.id!==D)throw new Error("Preview identity mismatch");l("comm-preview",Ae.status==="available"?`${Ae.text??""}${Ae.truncated?`
591
- [Prompt preview truncated]`:""}`:`Prompt preview ${Ae.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 Ee=await w(`${n}/api/queue/prompts?${z}=${encodeURIComponent(t)}&limit=20`);if(!Array.isArray(Ee.rows))throw new Error("Invalid message list");return Ee}));if(!v(D))return;let te=new Map;for(let z of re)for(let Ee of z.rows.slice(0,20)){if(!Number.isSafeInteger(Ee.id)||Ee.id<1)throw new Error("Invalid queue identity");if(Ee.to_id!==t&&Ee.from_id!==t)throw new Error("Message outside current team");let Ge=te.get(Ee.id);(!Ge||Ee.lifecycle==="finished"&&Ge.lifecycle!=="finished")&&te.set(Ee.id,Ee)}let ue=z=>Number.isFinite(Date.parse(z))?Date.parse(z):Number.MAX_VALUE,be=[...te.values()].sort((z,Ee)=>ue(z.created_ts)-ue(Ee.created_ts)||z.id-Ee.id).map(z=>{let Ee=u("li","");Ee.dataset.queueId=String(z.id);let Ge=u("a",`Read exchange #${z.id}`);Ge.href=H(z.id),Ge.addEventListener("click",_e=>{_e.defaultPrevented||_e.button!==0||_e.metaKey||_e.ctrlKey||_e.shiftKey||_e.altKey||(_e.preventDefault(),O(z.id))}),Ee.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}`)),Ee.append(je),z.lifecycle==="finished"&&!T(z.lifecycleBasis)){let _e=u("div","");_e.dataset.queueId=String(z.id),_e.dataset.event="response",_e.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 mt=!1,Ve=!1;st.addEventListener("toggle",async()=>{if(!st.open||mt||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?`
592
- [Reply excerpt; open the full exchange for available text.]`:""),mt=!0}catch(gr){v(mn)&&(Ze.textContent=`Reply unavailable: ${C(gr)}. Close and reopen to retry.`)}finally{Ve=!1}}),_e.append(st),Ee.append(_e)}else Ee.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 Ee});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,Ae="Page paused during admission";S=()=>{m||document.hidden||!re||!ue||(Y.disabled=te,te||(l("comm-send-status",`Admission uncertain or failed: ${Ae}. 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){Ae=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 ye=()=>{m=!0,Z(!0),document.removeEventListener("visibilitychange",ae)};window.addEventListener("pagehide",ye),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),ye}function iE(e){let{context:t}=e,r=e.config??Te,n=e.remoteStalledConfig??{},o=e.fetchReport??$e,s=e.send??Ht,i=e.whoami??$u,a=e.fetchHealth??cy,c=e.heavyLockStatusPath??Un(),l=e.heavyLockPath??Fn(),u=e.tail??wi,d=e.tailJson??yi,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:c_(w));Ty(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("/",Dy({context:t,allowedOrigins:e.allowedOrigins,mountPath:e.mountPath,enabled:!0})),oE(m,t,e.mountPath),Ry(m,{webDistDir:e.webDistDir,mountPath:e.mountPath}),By(m,t,e.mountPath),Yy(m,t,e.mountPath),nE(m,t,e.mountPath),m.get("/api/teams",w=>w.json(Au(t))),m.get("/api/identities/:key",w=>w.json(ks(t.teams,w.req.param("key")))),m.get("/api/state",w=>{let T=w.req.query("team");return T!==void 0?w.json(bu(t,T)):w.req.query("active")!==void 0?w.json(Su(t)):w.json(Tu(t))}),m.get("/api/status",async w=>{let T=w.req.query("live")==="1"||w.req.query("live")==="true",N=await vu(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=B(U)?null:Us(t.db.db,{site:U.peerSite,team:U.name,alias:U.alias});return{team:U.name,running:B(U)?Fe(U,T):!1,deadReclaimable:B(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=St(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(B),T,N,r,void 0,{readOnly:!0}),J=W_(t.db.db,t.teams.filter(ee=>!B(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(!B(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=qo(),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?"":fy(Al(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=sE(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(!B(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(gu(t,T))}),m.get("/api/queue/stats",w=>{try{let T=x(w.req.query("to"),"to");return w.json(yu(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:H(T.since,"since"),until:H(T.until,"until"),after:E(T.after,"after"),limit:E(T.limit,"limit",200)};return w.json(na(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=Xo(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=ge(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=aa(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=Bs(t.db.db,T.to,T.id).map(J=>{let ee;try{ee=PO(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(wu(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 H(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(yf(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(!B(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=ou(t,T,N);return"error"in U?w.json(U,400):w.json(U)}),m.get("/api/sources",w=>w.json(Eu(t))),m.get("/api/mail/status",w=>w.json(su(t))),m.get("/api/subscriptions",async w=>{let{status:T,body:N}=await ly();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(Al(await o()))),m.get("/api/running/observed",w=>w.json(qo())),m.get("/api/heavy-lock",w=>{try{return w.json(vl(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=oa(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?(Rs(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 Uu(e){return e.teams=Jr(e.db.db,e.teamsConfPath),e.teams}var UO=4173,FO="127.0.0.1";function aE(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??UO,r=e.hostname??FO,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=Jo(e.context.db.path),i=null;if(s!==null)try{i=Zi(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&&ea(h),l=iE({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=Qg({db:e.context.db.db,getTeams:()=>Uu(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(", ")})`:""}
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?`
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
595
  `)},onError:g=>{process.stderr.write(`[cron] tick failed: ${g instanceof Error?g.stack??g.message:String(g)}
596
- `)}}),m=B_({db:e.context.db.db,getTeams:()=>Uu(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}
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
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=H_({db:e.context.db.db,client:g.client,mailbox:g.mailbox,worker:{localSiteId:g.localSiteId,allowlist:g.allowlist,dispatch:y=>d_(e.context.db.db,Uu(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??$e,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)}
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
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??U_)({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=Vf({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??j_)(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??P_)(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)}
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
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 _t(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 ua(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 qO,readFileSync as jO,writeFileSync as HO}from"node:fs";var Fu="lmbee-cron-export",cE=["schema_version","kind","exported_at","exported_from","jobs"],lE=["id","title","schedule_expr","action_kind","action_payload","provider","model","working_directory","escalation_owner","timezone","enabled"],BO=["provider","model","working_directory","escalation_owner","timezone"];function WO(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 GO(e){return e instanceof Error&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("SQLITE_BUSY")}function VO(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 GO(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:Fu,exported_at:new Date().toISOString(),exported_from:t,jobs:r.map(WO)}}function JO(e,t,r){let n=VO(e,r);try{HO(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 KO(e){let t=go(e);Fa(t);let r=new pt(t,{readonly:!0,fileMustExist:!0});return r.pragma("busy_timeout = 0"),{db:r,path:t,close:()=>r.close()}}var uE=`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 es(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 dE(e){let{positionals:t,flags:r}=_t(e,["json","help"]),n=r.json===!0;try{if(r.help===!0)return{output:uE,exitCode:0};es("export",t,r);let o=t[0];if(o===void 0)throw new P("INVALID_ARGUMENT",`an export PATH is required
606
- ${uE}`);let s=KO();try{let i=JO(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 wt(e,t){throw new P("INVALID_ARGUMENT",`jobs[${e}]: ${t}`)}function zO(e,t){(typeof e!="object"||e===null||Array.isArray(e))&&wt(t,"must be a JSON object");let r=e;for(let l of Object.keys(r))lE.includes(l)||wt(t,`unknown key "${l}"`);for(let l of lE)l in r||wt(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)&&wt(t,"id must be a positive safe integer"),(typeof o!="string"||o.trim().length===0)&&wt(t,"title must be a nonblank string"),typeof s!="string"&&wt(t,"schedule_expr must be a string"),typeof i!="string"&&wt(t,"action_kind must be a string"),i==="enqueue"&&wt(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")&&wt(t,`import does not carry ${i}-kind jobs (out of scope -- untested expansion; create it manually)`),i!=="command"&&i!=="script"&&wt(t,`action_kind "${i}" is not a known kind; only "command" and "script" are accepted`),typeof a!="string"&&wt(t,"action_payload must be a string"),typeof c!="boolean"&&wt(t,`enabled must be a JSON boolean (true/false), not ${JSON.stringify(c)}`);for(let l of BO){let u=r[l];u!==null&&typeof u!="string"&&wt(t,`${l} must be a string or null`)}return r}function mE(e){let t;try{t=jO(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(!cE.includes(i))throw new P("INVALID_ARGUMENT",`unknown top-level key "${i}"`);for(let i of cE)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!==Fu)throw new P("INVALID_ARGUMENT",`kind must be "${Fu}", 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)=>zO(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 fE(e){return{...e,title:e.title.trim(),timezone:e.timezone===null?null:e.timezone.trim()}}function YO(e,t){let r=fE(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 QO(e){let t=fE(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 pE(e){mE(e)}function hE(e,t){let r=mE(t),n=[],o=[];e.transaction(()=>{for(let a of r){let c=xi(e,a.id);if(c!==null){if(YO(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)}Ri(e,QO(a)),o.push(a)}}).immediate();let i=[];for(let a of o)a.working_directory!==null&&!qO(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 gE(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
- `)}var da=Ut(xt(),1);import{readFileSync as XO}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 ZO(e){return e==="enqueue"||e==="command"||e==="script"||e==="session"||e==="miniplayer"}var eD=["pending","running","succeeded","failed","escalated"];function tD(e){return eD.includes(e)}function _E(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 XO(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 ut(e,t,r={}){return e?JSON.stringify({schema_version:1,ok:!0,data:t,meta:r}):rD(t,r)}function wE(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 rD(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(`
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(`
608
609
  `)}else typeof e=="string"?r=e:r=JSON.stringify(e,null,2);let n=t.next_cursor;return n!=null?`${r}
609
- More records: --after ${String(n)}`:r}var yE=`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 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
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.
611
- 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 EE(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"||!ZO(l))throw new P("INVALID_ARGUMENT",'--kind must be "enqueue", "command", "script", "session", or "miniplayer"');let u=_E(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=Ri(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:ut(n,d),exitCode:0}}case"show":{let a=ur(i[0],"id");return{output:ut(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}=Ni(e,{enabled:c,limit:cn(r.limit,"--limit",{maximum:Ne})??100,after:cn(r.after,"--after",{minimum:0})??0});return{output:ut(n,l,u),exitCode:0}}case"update":{let a=ur(i[0],"id"),c=_E(r),l=_h(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:ut(n,l),exitCode:0}}case"enable":case"disable":{let a=ur(i[0],"id"),c=wh(e,a,s==="enable");return{output:ut(n,c),exitCode:0}}case"remove":{let a=ur(i[0],"id"),c=yh(e,a);return{output:ut(n,c),exitCode:0}}case"reset":{let a=ur(i[0],"id"),c=Sh(e,a);return{output:ut(n,c),exitCode:0}}case"reset-session":{let a=ur(i[0],"id"),c=Eh(e,a);return{output:ut(n,c),exitCode:0}}case"runs":{let a=r.status;if(a!==void 0&&(typeof a!="string"||!tD(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}=vi(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:ut(n,l.map(Do),{next_cursor:u}),exitCode:0}}case"run":{let a=ur(i[0],"id");return{output:ut(n,Do(ze(e,a))),exitCode:0}}case"trigger":{let a=ur(i[0],"id"),c=await Sl(e,a,o);return{output:ut(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=eh(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:ut(n,Do(f)),exitCode:0}}case"import":{es("import",i,r);let a=i[0];if(a===void 0)throw new P("INVALID_ARGUMENT","an import PATH is required");let c=hE(e,a);return{output:n?ut(!0,c):gE(c),exitCode:0}}case"resolve":{let a=ur(i[0],"id"),c=nh(e,a,{resolution:We(r.resolution),actor:We(r.actor),note:We(r.note),confirmStopped:r["confirm-stopped"]===!0});return{output:ut(n,Do(c)),exitCode:0}}default:return n?wE(n,new P("INVALID_ARGUMENT",yE)):{output:yE,exitCode:1}}}catch(s){if(s instanceof P)return wE(n,s);throw s}}var TE=["disabled","confirm-stopped"];async function bE(e){let t=e.send??Ht,r=e.config??Te,n=e.nowMs??Date.now(),o=e.maxParallel??4,s=e.readHeavyLockStatusImpl??St,i=e.teams.filter(l=>!ie(e.db,l.name)?.confirmed_done_ts),a=await nD(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),bo(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}
612
- `)});if(m.held&&(m.holder===null||m.holder.holder===l.name))return{team:l.name,dispatched:!1,status:null,wake:null};if(Os(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),bo(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 nD(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 ts(e,t,r={}){let o=await(r.fetchReport??$e)(),s=r.readHeavyLockStatusImpl??St,i=s(void 0,void 0,void 0,l=>{process.stderr.write(`[scan] heavy-lock probe failed, treating conservatively as held: ${l.message}
613
- `)}),a=Fi(r.promptsDir);return(r.scanOnceImpl??bE)({db:e,teams:t.filter(B),report:o,heavyLock:i,readHeavyLockStatusImpl:s,resolveNudgeMessage:l=>qi(a,l)})}function rs(e){let t=e.results.map(r=>`${r.team}: ${r.dispatched?r.status:"skipped (not stalled)"}`);return t.length?t.join(`
614
- `):"(no eligible teams)"}async function SE(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 ts(e.db.db,n,r);return rs(o)}function vE(e,t,r){let n=Et(e.db.db,t),o={companionTeam:r.companionTeam,workerAlias:r.workerAlias??"Worker",commitThreshold:r.commitThreshold??Zc,hoursThresholdMs:r.hoursThresholdMs??el,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 fi(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).
615
- Manual nudge/enqueue/lctl chat and queue delivery to ${t} are unaffected.`}function AE(e,t,r={}){let n=Et(e.db.db,t)!==null;return Ep(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 oD(e,t){let r=t!==void 0?[t]:tl(e.db.db),n=[];for(let o of r){let s=Et(e.db.db,o);s!==null&&n.push({team:o,config:s})}return n}function $E(e,t,r={}){let n=oD(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<ko?`, ramp-up turn ${o.config.turnsDispatched}/${ko} (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(`
616
- `)}var sD=new Set(["operator","lmauto"]),iD=new Set(["autopilot"]);function aD(e,t){return iD.has(e)?t:e}function kE(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&&sD.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=sw(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=Yo(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=aD(n.from,t);o=uw(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#${iw(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 xE(e,t,r={}){let n=fw(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 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}:
617
618
  ${o.join(`
618
- `)}`}function RE(e,t,r={}){let n=Yo(e.db.db,t);if(n===null)return`prompt log: task #${t} does not exist`;let o=aw(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 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
620
  ${i.prompt}`);return`prompt log #${t} ("${n.title}"):
620
621
 
621
622
  ${s.join(`
622
623
 
623
- `)}`}function NE(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=dw(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 LE(e,t,r={}){let n=mw(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 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
625
  ${o.join(`
625
- `)}`}function IE(e,t,r={}){if(gi(e.db.db,t,{reason:r.reason??null,expiresAt:r.expiresAt??null}),r.json)return JSON.stringify(hi(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}.
626
- Every team whose resolved auto-nudge target uses "${t}" goes quiet; manual nudge/enqueue/lctl chat is unaffected.`}function CE(e,t,r={}){let n=hi(e.db.db,t)!==null;return Mp(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 cD(e,t,r=Date.now()){return(t!==void 0?Ro(e.db.db).filter(o=>o.provider===t):Ro(e.db.db)).map(o=>({provider:o.provider,config:o,expired:!rt(e.db.db,o.provider,r).disabled}))}function OE(e,t,r={}){let n=cD(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(`
627
- `)}function uD(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 dD(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
628
- 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=Oi(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 DE(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 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
629
630
  FROM rate_limit_readings r1
630
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)
631
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,
@@ -637,47 +638,47 @@ Every team whose resolved auto-nudge target uses "${t}" goes quiet; manual nudge
637
638
  ORDER BY read_at DESC, id DESC LIMIT 1
638
639
  )
639
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)
640
- 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=Pi(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,...uD(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.
641
- ${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(` ${dD(r,f.provider,f.bucketId,f.resetsAt)}`)}}return u.join(`
642
- `)}function ME(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
643
- 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=Pi(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(`
644
- `)}var mD=[7,30],qu=3,fD=20,pD="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 hD(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 gD(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 _D(e){return(e.tokens_in_cached??0)+(e.tokens_in_uncached??0)+(e.tokens_cache_write??0)+(e.tokens_out??0)}function wD(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=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
645
646
  FROM lmbi_session_responses
646
- 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+_D(s),0)}function yD(e,t){return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t)!==void 0}function PE(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<fD}}function UE(e){let t=e.nowMs??Date.now(),r=[],n={},o=yD(e.lmautoDb,"lmbi_session_responses");for(let s of mD){let i=new Date(t-s*24*60*60*1e3).toISOString(),{rows:a,skippedUnattributable:c}=jp(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-qu*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=PE(d.invocations),{doneCount:p,failedCount:h,contentionCount:_}=f,g=d.invocations.filter(S=>Date.parse(S.startedAtIso)>=u),y=PE(g),E=0,v=0;for(let S of d.invocations){if(S.outcome!=="done")continue;let R=wD(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:hD(m),p90DurationMs:gD(m),completionRate:f.completionRate,doneCount:p,failedCount:h,contentionCount:_,totalTokens:E,tokenJoinMisses:v,costUnavailableReason:pD})}}return{rows:r.sort((s,i)=>s.windowDays-i.windowDays||s.provider.localeCompare(i.provider)||(s.model??"").localeCompare(i.model??"")),skippedUnattributableByWindow:n}}function FE(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(`
647
- -- ${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 ${qu}d unknown (n=${i.recentSampleSize})`:`last ${qu}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+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(`
648
649
  (${s.join("; ")} -- see tracked_invocation's own meta shape)`),n.join(`
649
- `).trimStart()}function qE(e,t={}){let r=On(t.lctlDbPath);try{let{rows:n,skippedUnattributableByWindow:o}=UE({lctlDb:r,lmautoDb:e.db.db});return t.json?JSON.stringify({rows:n,skippedUnattributableByWindow:o}):FE(n,o)}finally{r.close()}}async function jE(e,t={}){let r=await ku({configPath:e});return t.json?JSON.stringify(r):JSON.stringify(r,null,2)}import{execFile as ED}from"node:child_process";import{basename as TD}from"node:path";import{promisify as bD}from"node:util";var SD=bD(ED),vD=["lmplayer run","opencode run"];function AD(){return Kr[Kr.length-1]??"lmctl"}function $D(e){let t=e.lastIndexOf(":");if(t===-1)return[e];let r=e.slice(0,t),n=e.slice(t+1);return[e,`${TD(r)} ${n}`]}async function HE(e,t=$e,r=SD){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=AD(),c=[`${a} chat`,`${a} terminal`,...vD],l=n.flatMap($D),u=i.split(`
650
- `).filter(d=>c.some(m=>d.includes(m))).filter(d=>!l.some(m=>d.includes(m)));return{lctlRunning:o,otherTeamsRunning:s,externalWrapperProcessLines:u}}function BE(e){return(e.otherTeamsRunning?.length??0)>0||e.externalWrapperProcessLines.length>0}function kD(e){let t=process.env.LMBEE_TEAM_NAME;if(!t)return null;let r=e.teams.find(n=>n.name===t);if(r===void 0||!B(r))return null;try{return`${Q(r)}:${r.leadAlias}`}catch{return null}}async function WE(e,t={}){let r=t.exclude===void 0?[]:typeof t.exclude=="string"?t.exclude.split(","):t.exclude,n=kD(e),o=n===null?r:[n,...r],i=await(t.checkInFlightDispatchImpl??HE)(o),a=BE(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 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:
651
652
  ${c.join(`
652
- `)}${l}`}import{readFileSync as xD,statSync as GE}from"node:fs";function ma(e,t=xD){try{let r=t(`/proc/${e}/stat`,"utf8");return r.slice(r.lastIndexOf(")")+2).trim().split(/\s+/)[19]??null}catch{return null}}function RD(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 ND(e,t=GE){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 VE(e,t,r=process.kill,n=ma,o=GE){let s=RD(e,r,n),i=ND(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 JE(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 LD(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(`
653
- `)}function KE(e,t,r={}){let n=VE({pid:e,startTicks:r.startTicks??null},t);return r.json?JSON.stringify({pid:e,...n}):LD(e,n)}function zE(e,t,r,n,o={}){return gw(e.db.db,t,r,n),o.json?JSON.stringify({name:t,teamfilePath:r,alias:n}):`logical name "${t}" -> ${r}:${n}`}function YE(e,t,r={}){let n=ra(e.db.db,t);return r.json?JSON.stringify(n):n===null?`"${t}" is not registered`:`"${t}" -> ${n.teamfilePath}:${n.alias}`}function QE(e,t={}){let r=_w(e.db.db);return t.json?JSON.stringify(r):r.length===0?"no logical names registered":r.map(n=>`${n.name} -> ${n.teamfilePath}:${n.alias} (updated ${n.updatedAt})`).join(`
654
- `)}function XE(e,t,r={}){let n=ra(e.db.db,t)!==null;return ww(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 ID}from"node:child_process";import{promisify as CD}from"node:util";var dr=Ut(xt(),1),ZE=CD(ID);async function OD(e){try{let[{stdout:t},{stdout:r}]=await Promise.all([ZE("git",["-C",e,"log","--oneline","-1"],{timeout:1e4}),ZE("git",["-C",e,"status","--porcelain"],{timeout:1e4})]),n=r.split(`
655
- `).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 DD(e,t){return B(e)?Fe(e,t)?"Running":Xr(e,t)?"Dead":"Idle":"remote -- delivery only"}async function eT(e,t={}){let n=await(t.fetchReport??$e)(),o=t.only&&t.only.length>0?new Set(t.only):null,s=o?e.teams.filter(c=>o.has(c.name)):e.teams,i=["TEAM","LIVE","STATUS(self-report)","PROGRESS","GIT-HEAD","UNCOMMITTED"],a=await Promise.all(s.map(async c=>{let l=Ue(e.db.db,c.name),u=ie(e.db.db,c.name),d=B(c)?await OD(c.repoPath):{head:"(remote)",dirty:"-"},m=u?.confirmed_done_ts?"DONE(confirmed)":u?.progress_status??"?";return[(0,dr.escapeCell)(c.name),(0,dr.escapeCell)(DD(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 MD=8,PD=18e5;function ju(e){return e.teams.filter(B).filter(t=>t.autoNudge)}function UD(e){let t=ju(e);return t.length>0&&t.every(r=>ie(e.db.db,r.name)?.confirmed_done_ts)}async function tT(e,t={}){let r=await ts(e.db.db,ju(e),t);return rs(r)}async function rT(e,t={}){let r=t.maxScans??MD,n=t.scanIntervalMs??PD,o=t.sleep??(i=>new Promise(a=>setTimeout(a,i))),s="(no scans ran)";for(let i=1;i<=r;i++){let a=await ts(e.db.db,ju(e),t);if(s=rs(a),a.wake)return`AUTOPILOT WAKE [${a.wake}]:
656
- ${s}`;if(UD(e))return`AUTOPILOT WAKE [all-done]:
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]:
657
658
  ${s}`;i<r&&await o(n)}return`AUTOPILOT WAKE [heartbeat]: exhausted ${r} scans with no wake condition
658
- ${s}`}function FD(e){let t=Lr(e.db.db);return{paused:t!==null,state:t}}function nT(e,t={}){let r=FD(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})`:"")}
659
- (manual nudge and queue delivery are unaffected)`}function oT(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(Bh(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.
660
- (manual nudge and queue delivery are unaffected; \`lmbee scan start\` resumes)`}function sT(e,t={}){let r=Lr(e.db.db)!==null;return Wh(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 iT(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(!B(i))throw new Error(`send: team "${o}" is a remote team (channel=lmmail) -- not reachable via lctl`);let a=s??i.leadAlias,c=Q(i),l=Vr(i);if(l.length>0&&!l.some(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??Wo,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||nw(e.db.db,c,a,{kind:"evicted",remedy:`lctl refresh ${c} ${a}`})}catch{}else zo(e.db.db,c,a)!==null&&ow(e.db.db,c,a);let _=p.kind==="ok"?p.replyText.split(`
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(`
661
662
  `).slice(-6).join(`
662
663
  `):"";return`${a===i.leadAlias?i.name:`${i.name}:${a}`}: ${h.status}${_?`
663
- ${_}`:""}`}import{spawnSync as jD}from"node:child_process";var HD=2e3,BD=3e4;async function aT(e,t,r,n={}){let{baseId:o,alias:s}=Qr(t),i=o.endsWith(".lmctl")?o.slice(0,-6):null,a=i??o,c=r??s,l=e.teams.find(C=>C.name===a);if(l===void 0||!B(l)){if(i!==null)return{output:`terminal: "${o}" is not a known local team -- did you mean "${i}"?
664
- (lctl takes a teamfile path; lmbee takes a team name)`,exitCode:1};let C=e.teams.filter(B).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??HD,f=n.leaseMs??6e4,p=n.maxWaitMs??BD,h=n.fetchReport??$e,_=n.spawnSyncImpl??jD,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(Om(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(!gm(d,u,C))break;if(y()-S>=p){L=!0;break}await g(m)}}finally{Mm(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(`
665
- `),exitCode:1};x.push(`${a}:${u} is available -- launching terminal now (reservation released)`);let k=_("lmctl",["terminal",d,u],{stdio:"inherit"}),H=k.status??(k.error?1:0);return{output:x.join(`
666
- `),exitCode:H}}import{readFileSync as mT}from"node:fs";import{basename as KD}from"node:path";import{execFileSync as cT}from"node:child_process";import{dirname as WD}from"node:path";var GD=new Set(["done","closed","cancelled"]);function VD(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-")}function JD(e){return WD(e)}function lT(e,t,r=cT){let n=Le(e,t);return uT(n,r)}function uT(e,t){let r={id:e.id,title:e.title,status:e.status};if(GD.has(VD(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=JD(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(`
667
- `).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 dT(e,t,r=cT){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=>uT(i,r))}var hT=["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 mT(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 mT(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 fT(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&&KD(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 pT(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}):YD(t,r)}function zD(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 YD(e,t){let r;Array.isArray(e)?r=e.length===0?"(empty)":e.map(o=>o&&typeof o=="object"&&"title"in o?[..."attentionReason"in o?["attentionReason"]:[],"id","kind","status","project","title"].map(s=>String(o[s]??"")).join(" "):JSON.stringify(o)).join(`
664
+ ${_}`:""}`}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(`
668
669
  `):typeof e=="string"?r=e:r=JSON.stringify(e,null,2);let n=t.next_cursor;return n!=null?`${r}
669
- More records: --after ${String(n)}`:r}function QD(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(`
670
- `)}var XD="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 gT(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||!pT(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=fT(r,o,u?.team),m=typeof r.status=="string"?r.status:void 0,f=hf(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=Sf(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"||!pT(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?dT(e,c):[lT(e,zt(l,"id"))];return n?{output:JSON.stringify({schema_version:1,ok:!0,data:u}),exitCode:0}:{output:QD(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=fT(r,o,d),f=typeof r.status=="string"?r.status:void 0,p=Gs(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"?Tf(e,u,d):bf(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:XD,exitCode:n?2:1}}}catch(s){if(s instanceof I)return zD(n,s);throw s}}var dt=Ut(xt(),1);var ZD=20;function eM(e,t,r={}){let n=ks(e.teams,t),o=r.limit??ZD,s=_u(e,{toId:t,limit:o}).rows,i=_u(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 _T(e,t,r={}){let n=eM(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,dt.escapeCell)(u.from_id),(0,dt.escapeCell)(u.status),pe(u.created_ts)]),a=n.messagesFrom.map(u=>[String(u.id),(0,dt.escapeCell)(u.to_id),(0,dt.escapeCell)(u.status),pe(u.created_ts)]),c=(n.ownedTasks??[]).map(u=>[String(u.id),(0,dt.escapeCell)(u.kind),(0,dt.escapeCell)(u.status),(0,dt.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,dt.measureColumns)(s);return o.push(`
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(`
671
672
  Messages to this team (queue, newest first):
672
- ${i.length===0?"(none)":(0,dt.renderGrid)(i,{widths:l,headers:["ID","FROM","STATUS","CREATED"]})}`),o.push(`
673
+ ${i.length===0?"(none)":(0,mt.renderGrid)(i,{widths:l,headers:["ID","FROM","STATUS","CREATED"]})}`),o.push(`
673
674
  Messages from this team (queue, newest first):
674
- ${a.length===0?"(none)":(0,dt.renderGrid)(a,{widths:l,headers:["ID","TO","STATUS","CREATED"]})}`),o.push(`
675
+ ${a.length===0?"(none)":(0,mt.renderGrid)(a,{widths:l,headers:["ID","TO","STATUS","CREATED"]})}`),o.push(`
675
676
  Owned tasks (lmtasks):
676
- ${n.ownedTasks===null?"(unavailable -- not a local team with a resolvable teamfile)":c.length===0?"(none)":(0,dt.renderGrid)(c,{widths:l,headers:["ID","KIND","STATUS","TITLE"]})}`),o.push(`
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(`
677
678
  Provider/invocation/mail history: unavailable -- pending lctl-src's own increment-2 delivery (not silently omitted; this coverage state is explicit).`),o.join(`
678
- `)}import{mkdirSync as tM,readFileSync as rM,statSync as nM,writeFileSync as oM}from"node:fs";import{homedir as sM}from"node:os";import{basename as wT,dirname as yT,join as iM}from"node:path";function aM(){return iM(sM(),".lmbee","on-demand-teams.conf")}function ET(e,t,r,n={}){let o;try{o=nM(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(wT(r)!==`${t}.lmctl`)return{output:`error: teamfile must be named "${t}.lmctl" to match team name "${t}" (got "${wT(r)}") -- resolveTeamfilePath's own convention, not a new rule`,ok:!1};let s=n.alias??"Lead",i=yT(r),a=n.confPath??aM(),c="";try{c=rM(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 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
680
  `)+`
680
- `;return tM(yT(a),{recursive:!0}),oM(a,p),xs(e.db.db,a,"on-demand teams (lmbee team register)"),_o(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 TT(e,t={}){let n=await(t.fetchReport??$e)(),o=Ls(e.db.db,e.teams.filter(B),n),s=o.active.length?o.active.join(","):"(none)";if(o.wake)return{text:`WATCH CHANGE [${o.why}] | now-active: ${s}`,changed:!0};let i=o.newlyActive.length?` (newly-active: ${o.newlyActive.join(",")})`:"";return{text:`WATCH nochange | active: ${s}${i}`,changed:!1}}var Ur=`usage: lmbee <command> [args]
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
682
 
682
683
  Core loop:
683
684
  lmbee run | once | watch
@@ -770,6 +771,8 @@ Teams & history:
770
771
  lmbee history [team] [N]
771
772
  lmbee state <list [--non-done]|get|set|active>
772
773
  lmbee attention [--team T] [--maintainer M] [--stuck-processing-all]
774
+ lmbee stalled [team] [--json] [--idle-threshold-ms N] [--cooldown-ms N]
775
+ raw read-only stalled verdict per local team (no scan or dispatch)
773
776
  lmbee in-flight [--exclude teamfile:alias[,teamfile:alias...]] pre-restart check: any other team's session running?
774
777
  lmbee dispatch-status capture --pid N | check --pid N [--start-ticks T] --artifacts P1,P2,...
775
778
  check whether ONE specific dispatch finished, without a live watcher
@@ -826,7 +829,7 @@ Daemon:
826
829
  [--remote-mail --remote-allow user_id1,user_id2,...]
827
830
  [--exec-worker [--exec-mailbox name] [--exec-admin id1,id2,...] [--exec-allow id1,id2,...] [--exec-allow-anonymous]]
828
831
  lmbee shutdown --force (graceful stop of the systemd-managed daemon: systemctl --user stop lmbee.service --
829
- --force is required; the unconfirmed default refuses rather than acting)`;function vT(e){if(e.length===0)return!0;let[t,r]=e;return t==="-h"||t==="--help"||t==="help"?!0:r==="-h"||r==="--help"}var cM=new Set(["status","oversee","history","teams","attention","in-flight"]);function AT(e){let[t,r]=e;return cM.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 bT=`usage: lmbee queue <command> [args]
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]
830
833
 
831
834
  Read: inbox <to> [--prompts] prompts waiting for a team (authoritative)
832
835
  list [team] all rows, optionally filtered
@@ -852,81 +855,82 @@ Close: answer <id[,id,...]> <text|@file> --from <team>
852
855
  Control: pause <team> [--reason <text>] | resume <team> | pause-status [<team>]
853
856
  gc [days]
854
857
 
855
- Pass --help after any subcommand for its own usage line, e.g. "lmbee queue list --help".`,ST={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 $T(e,t){if(t.length===0)return{output:`${Ur}
856
- `,exitCode:0};let[r,...n]=t,{positionals:o,flags:s}=_t(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}
857
- `,exitCode:0};switch(r){case"run":return{output:await rT(e),exitCode:0};case"once":return{output:await tT(e),exitCode:0};case"watch":{let a=await TT(e);return{output:a.text,exitCode:a.changed?10:0}}case"status":return{output:await sy(e,{live:s.live===!0,json:i}),exitCode:0};case"oversee":return{output:await eT(e,{only:o}),exitCode:0};case"state":{let[a,...c]=o;return a==="list"?{output:Zw(e,{json:i,nonDone:s["non-done"]===!0}),exitCode:0}:a==="get"?c[0]===void 0?X("usage: lmbee state get <team>"):{output:ey(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:ty(e,c[0],c[1],c.slice(2).join(" ")),exitCode:0}:a==="active"?{output:oy(e,{json:i}),exitCode:0}:a==="confirm-done"?c[0]===void 0?X("usage: lmbee state confirm-done <team> [note]"):{output:ry(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 ny(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 xw(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:xE(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:RE(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:NE(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:LE(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:kE(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?ST[a]:void 0;if(l!==void 0){if(s.help===!0)return{output:`${l.usage}
858
+ Pass --help after any subcommand for its own usage line, e.g. "lmbee queue list --help".`,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}
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}
858
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}
859
- ${l.usage}`)}if(a==="list")return{output:Rw(e,c[0],{json:i}),exitCode:0};if(a==="get")return c[0]===void 0?X("usage: lmbee queue get <id>"):{output:Nw(e,Number(c[0]),{json:i}),exitCode:0};if(a==="deliver")return{output:await jw(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
860
- usage: lmbee queue retrieve <to> [--id <queueId>]`):{output:Hw(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:Bw(e,c[0],{json:i,promptsOnly:s.prompts===!0}),exitCode:0};if(a==="gc")return{output:Kw(e,c[0]!==void 0?Number(c[0]):void 0),exitCode:0};if(a==="stats")return{output:Jw(e,c[0],{json:i}),exitCode:0};if(a==="doctor")return{output:zw(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:Lw(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
861
- ${m}`);let _=u.split(",").map(Number);return Cw(e,_,f,d.join(" "),{json:i,literal:p})}return Iw(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):Dw(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):Ow(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 Uw(e,c[0],u,{json:i})}if(a==="resume")return c[0]===void 0?X("usage: lmbee queue resume <team>"):Fw(e,c[0],{json:i});if(a==="pause-status")return qw(e,c[0],{json:i});if(a==="owed")return c[0]===void 0?X("usage: lmbee queue owed <team> [--ids]"):{output:Ww(e,c[0],{json:i,idsOnly:s.ids===!0}),exitCode:0};if(a==="pull"){let u=ST.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: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
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
863
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
864
- ${u}`);f=p}return{output:Vw(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:Gw(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>"):Mw(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):Pw(e,Number(u),p,{json:i})}return s.help===!0?{output:`${bT}
865
- `,exitCode:0}:X(bT)}case"nudge":return o.length===0?X("usage: lmbee nudge <team> [team2 ...]"):{output:await SE(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 iT(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 aT(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:ew(e,c,l,{json:i}),exitCode:0}}case"teams":return{output:iy(e,{json:i}),exitCode:0};case"in-flight":{let a=typeof s.exclude=="string"?s.exclude:void 0;return{output:await WE(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:JE(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:KE(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:zE(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:YE(e,c,{json:i}),exitCode:0}:a==="list"?{output:QE(e,{json:i}),exitCode:0}:a==="clear"?c===void 0?X("usage: lmbee logical-name clear <name>"):{output:XE(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 Yi(e,{team:a,maintainer:c,stuckProcessingFleetWide:l});return{output:Vo(u,{json:i}),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=ET(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=ua(s.limit,"--limit");return c instanceof Error?{output:`error: ${c.message}`,exitCode:1}:c!==void 0&&(c<1||c>Eo)?{output:`error: --limit must be a positive integer <= ${Eo}`,exitCode:1}:{output:_T(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=oa(e,c[0],c.slice(1).join(" ")||void 0);return{output:l.output,exitCode:l.ok?0:1}}return a==="list"?{output:Yw(e,{json:i}),exitCode:0}:a==="remove"?c[0]===void 0?X("usage: lmbee source remove <path>"):{output:Qw(e,c[0]),exitCode:0}:X("usage: lmbee source add <path> [label...] | list | remove <path>")}case"mail":{let[a]=o;return a==="status"?{output:rw(e,{json:i}),exitCode:0}:X("usage: lmbee mail status")}case"scan":{let[a]=o;if(a==="status")return{output:nT(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:oT(e,{...c!==void 0?{actor:c}:{},...l!==void 0?{note:l}:{},...u!==void 0?{resumeAfter:u}:{},json:i}),exitCode:0}}return a==="start"?{output:sT(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:$E(e,c,{json:i}),exitCode:0};if(a==="clear")return c===void 0?X("usage: lmbee auto-nudge-redirect clear <team>"):{output:AE(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:vE(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:OE(e,c,{json:i}),exitCode:0};if(a==="enable")return c===void 0?X("usage: lmbee provider enable <name>"):{output:CE(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:IE(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:DE(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:ME(e,{...c!==void 0?{provider:c}:{},...u!==void 0?{limit:u}:{},json:i}),exitCode:0}}return X("usage: lmbee rate-limit status | log [--provider NAME] [--limit N]")}case"reliability-report":try{return{output:qE(e,{json:i}),exitCode:0}}catch(a){return{output:`reliability-report: ${a instanceof Error?a.message:String(a)}`,exitCode:1}}case"subscriptions":{let a=typeof s.config=="string"?s.config:void 0;if(a===void 0)return X("usage: lmbee subscriptions --config <path> [--json]");try{return{output:await jE(a,{json:i}),exitCode:0}}catch(c){return{output:`subscriptions: ${c instanceof Error?c.message:String(c)}`,exitCode:1}}}case"tasks":{let a=_t(n,["json",...hT]),c=gT(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=_t(n,["json",...TE]),c=await EE(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}
866
- ${Ur}`,exitCode:1}}}function X(e){return{output:e,exitCode:1}}import{mkdir as RU,readFile as NU,stat as LU,writeFile as IU}from"node:fs/promises";import{mkdir as TM,readFile as BT,stat as bM,writeFile as SM}from"node:fs/promises";import{readFileSync as vM}from"node:fs";import{homedir as AM}from"node:os";import{dirname as $M,extname as kM}from"node:path";var VT="https://lmctl.ai/tools/lmchat";async function JT(e,t={}){let r=qM(t),n=Gu(e);if(n.kind==="whoami"){r.stdout(FM(r.env,n.api));return}if(n.kind==="login"){let{runLogin:s}=await Promise.resolve().then(()=>(HT(),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=MM(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 WT(r,o,n),n.kind==="post"){let s=await xM(r,o,n);r.stdout(String(s));return}if(n.kind==="say"){let s=await RM(r,o,n);r.stdout(String(s));return}if(n.kind==="list"){await WT(r,o,{...n,kind:"read"});return}if(n.kind==="get"){await LM(r,o,n),r.stdout(`saved ${n.out}`);return}if(n.kind==="delete"){let s=await IM(r,o,n);r.stdout(`deleted ${s}`);return}if(n.kind==="delete-room"){let s=await CM(r,o,n);r.stdout(`deleted room ${s}`);return}}function Gu(e){let t=[...e],r=De(t,"--api"),n=t.shift();if(!n||n==="help"||n==="--help"||n==="-h")throw new Qt(GT());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=Bu(t,"--name"),a=Bu(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=Bu(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: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
871
 
868
- ${GT()}`)}async function xM(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??UM(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 RM(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 WT(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 NM(e,t,r.roomName,n,r.limit);r.follow?r.json?c.files.length>0&&e.stdout(JSON.stringify(c.files)):(i||(zT(e.stdout),i=!0),YT(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)):PM(e.stdout,a);return}await OM(s)}}}async function NM(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 LM(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 Wu(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 Wu(s,"presigned download failed");let i=new Uint8Array(await s.arrayBuffer());await e.mkdir($M(r.out),{recursive:!0}),await e.writeFile(r.out,i)}async function IM(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 CM(e,t,r){return(await Fr(e.fetch,`${t}/rooms/${encodeURIComponent(r.roomName)}`,{method:"DELETE",headers:mr(e.env)})).room_name}function OM(e){return new Promise(t=>setTimeout(t,e))}async function Fr(e,t,r){let n=await e(t,r);return await Wu(n,"API request failed"),await n.json()}async function Wu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function DM(e){return KT(e).appkey}function KT(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=Hu(t);if(s)return{appkey:s,source:"LMCTL_APPKEY_FILE"}}let r=e.XDG_CONFIG_HOME?.trim()||`${AM()}/.config`,n=Hu(`${r}/lmctl/appkey.json`);if(n)return{appkey:n,source:"~/.config/lmctl/appkey.json"};let o=Hu(`${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 Hu(e){let t;try{t=vM(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 ${DM(e)}`}}function MM(e,t){return(e??t.LMCHAT_API_URL??VT).replace(/\/+$/,"")}function PM(e,t){zT(e),YT(e,t)}function zT(e){e("seq name size content_type created_at")}function YT(e,t){for(let r of t)e(`${r.seq} ${r.name} ${r.size} ${r.content_type} ${r.created_at}`)}function UM(e){let t=kM(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 FM(e,t){let r="unset";try{r=KT(e).source}catch{r="unset"}return[`API: ${t??e.LMCHAT_API_URL??VT}`,`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(`
869
- `)}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 Bu(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 qM(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?BT(t,{encoding:r}):BT(t)),writeFile:e.writeFile??((t,r)=>SM(t,r)),mkdir:e.mkdir??((t,r)=>TM(t,r)),stat:e.stat??(t=>bM(t))}}function GT(){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(`
870
- `)}var Qt=class extends Error{};import{mkdir as ZM,readFile as eP,stat as tP,writeFile as rP}from"node:fs/promises";import{basename as nP,extname as oP,join as sP}from"node:path";async function hb(e,t={}){let r=pP(t),n=Vu(e);if(n.kind==="whoami"){r.stdout(uP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:a}=await Promise.resolve().then(()=>(mb(),db));if(await a({env:r.env})!==0)throw new Error("login failed");return}let o=lP(n.api,r.env),s=Se({env:r.env}).appkey,i=ft({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(()=>iP(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:aP(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=fb(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=sP(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,fb(n.seq))),r.stdout(`deleted ${n.seq}`))}function Vu(e){let t=[...e],r=Zn(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new fr(pb());if(n==="login"||n==="whoami"||n==="mailboxes")return Xn(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=un(t,"mailbox");return Xn(t),{kind:"create",mailbox:o,...r?{api:r}:{}}}if(n==="send"){let o=un(t,"mailbox"),s=fP(t,"--file"),i=Zn(t,"--subject"),a=mP(t,"--attach");return Xn(t),{kind:"send",mailbox:o,file:s,attachments:a,...i?{subject:i}:{},...r?{api:r}:{}}}if(n==="list"){let o=un(t,"mailbox"),s=Zn(t,"--status"),i=Zn(t,"--after");return Xn(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=Zn(t,"--out")??".";return Xn(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 Xn(t),{kind:"delete",mailbox:o,seq:s,...r?{api:r}:{}}}throw new fr(`unknown command: ${n}
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}
871
875
 
872
- ${pb()}`)}async function iP(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:nP(s),contentType:dP(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 gb(o,r.status,r.responseBody)}}function fb(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 aP(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 gb("API request failed",400,JSON.stringify({error:e}))}function gb(e,t,r){return new Error(`${e}: ${t}${r?` ${r}`:""}`)}function cP(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 lP(e,t){let r=e??t.LMMAIL_API_URL;if(!r)throw new Error("missing LMMAIL_API_URL or --api");return r.replace(/\/+$/,"")}function uP(e,t){return[`API: ${t??e.LMMAIL_API_URL??"unset (set --api or LMMAIL_API_URL)"}`,`appkey source: ${cP(e)}`,"identity: derived server-side from the shared appkey"].join(`
873
- `)}function dP(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"}[oP(e).toLowerCase()]??"application/octet-stream"}function Zn(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 mP(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 fP(e,t){let r=Zn(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 Xn(e){if(e.length)throw new fr(`unexpected argument: ${e[0]}`)}function pP(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>console.log(t)),readFile:e.readFile??(t=>eP(t)),writeFile:e.writeFile??((t,r)=>rP(t,r)),mkdir:e.mkdir??((t,r)=>ZM(t,r)),stat:e.stat??(t=>tP(t))}}function pb(){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(`
874
- `)}var fr=class extends Error{};import{mkdir as kP,readFile as xP,stat as RP,writeFile as NP}from"node:fs/promises";import{dirname as LP,extname as IP}from"node:path";async function Ob(e,t={}){let r=jP(t),n=Ku(e);if(n.kind==="whoami"){r.stdout(UP(r.env,n.api));return}if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(Ib(),Lb));if(await i({env:r.env})!==0)throw new Error("login failed");return}let o=MP(n.api,r.env),s=PP(r.env);if(n.kind==="push"||n.kind==="update"){await CP(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 cs(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 cs(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"GET",headers:s}),a=await r.fetch(i.download_url);await zu(a,"presigned download failed");let c=new Uint8Array(await a.arrayBuffer());n.out?(await r.mkdir(LP(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 cs(r.fetch,`${o}/notes/${encodeURIComponent(n.name)}`,{method:"DELETE",headers:s}),r.stdout(`deleted ${n.name}`))}function Ku(e){let t=[...e],r=as(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new qr(Cb());if(n==="login"||n==="whoami")return is(t),{kind:n,...r?{api:r}:{}};if(n==="push"||n==="update"){let o=Ju(t,"name"),s=qP(t,"--file");return is(t),{kind:n,name:o,file:s,...r?{api:r}:{}}}if(n==="list"){let o=as(t,"--after"),s=as(t,"--limit");return is(t),{kind:"list",...o?{after:o}:{},...s?{limit:s}:{},...r?{api:r}:{}}}if(n==="read"){let o=Ju(t,"name"),s=as(t,"--out");return is(t),{kind:"read",name:o,...s?{out:s}:{},...r?{api:r}:{}}}if(n==="delete"){let o=Ju(t,"name");return is(t),{kind:"delete",name:o,...r?{api:r}:{}}}throw new qr(`unknown command: ${n}
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}
875
879
 
876
- ${Cb()}`)}async function CP(e,t,r,n){let o=await e.stat(n.file);if(!o.isFile())throw new Error(`not a file: ${n.file}`);let s=FP(n.file),i=n.kind==="push"?`${t}/notes`:`${t}/notes/${encodeURIComponent(n.name)}`,a=await cs(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 zu(u,"S3 upload failed");let d=a.finalize_url.startsWith("http")?a.finalize_url:`${t}${a.finalize_url.startsWith("/")?"":"/"}${a.finalize_url}`;await cs(e.fetch,d,{method:"POST",headers:{...r,"content-type":"application/json"},body:JSON.stringify({operation_token:a.operation_token})})}function OP(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 DP(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 MP(e,t){let r=e??t.LMNOTE_API_URL;if(!r)throw new Error("missing LMNOTE_API_URL or --api");return r.replace(/\/+$/,"")}function PP(e){return{authorization:`Bearer ${OP(e)}`}}function UP(e,t){return[`API: ${t??e.LMNOTE_API_URL??"unset (set --api or LMNOTE_API_URL)"}`,`appkey source: ${DP(e)}`,"notebook identity: derived server-side from the shared appkey"].join(`
877
- `)}function FP(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"}[IP(e).toLowerCase()]??"application/octet-stream"}async function cs(e,t,r){let n=await e(t,r);return await zu(n,"API request failed"),n.json()}async function zu(e,t){if(e.ok)return;let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status}${r?` ${r}`:""}`)}function as(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 qP(e,t){let r=as(e,t);if(!r)throw new qr(`missing required ${t}`);return r}function Ju(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new qr(`missing ${t}`);return r}function is(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=>xP(t)),writeFile:e.writeFile??((t,r)=>NP(t,r)),mkdir:e.mkdir??((t,r)=>kP(t,r)),stat:e.stat??(t=>RP(t))}}function Cb(){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(`
878
- `)}var qr=class extends Error{};async function tS(e,t={}){let r=t.fetch??fetch,n=t.env??process.env,o=t.stdout??(l=>console.log(l)),s=Yu(e);if(s.kind==="whoami"){o(oU(n,s.api));return}if(s.kind==="login"){let{runLogin:l}=await Promise.resolve().then(()=>(Yb(),zb));if(await l({env:n})!==0)throw new Error("login failed");return}let i=rU(s.api,n),a=nU(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} ${Qb(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 ${Qb(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 Yu(e){let t=[...e],r=eo(t,"--api"),n=t.shift();if(!n||["help","--help","-h"].includes(n))throw new er(eS());if(n==="login"||n==="whoami"||n==="sheets")return Zt(t),{kind:n,...r?{api:r}:{}};if(n==="create"){let o=ot(t,"name"),s=sU(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=eo(t,"--after"),i=eo(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=eo(t,"--row"),i=Xb(Zb(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=Xb(Zb(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
+ ${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}
879
883
 
880
- ${eS()}`)}function eU(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 tU(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 rU(e,t){let r=e??t.LMSHEET_API_URL;if(!r)throw new Error("missing LMSHEET_API_URL or --api");return r.replace(/\/+$/,"")}function nU(e){return{authorization:`Bearer ${eU(e)}`}}function oU(e,t){return[`API: ${t??e.LMSHEET_API_URL??"unset (set --api or LMSHEET_API_URL)"}`,`appkey source: ${tU(e)}`,"sheet identity: derived server-side from the shared appkey"].join(`
881
- `)}function Qb(e){return e.map(t=>`${t.letter}:${t.label}`).join(",")}function Xb(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 eo(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 Zb(e,t){let r=[];for(;e.includes(t);){let n=eo(e,t);n!==void 0&&r.push(n)}return r}function sU(e,t){let r=eo(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 eS(){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(`
882
- `)}var er=class extends Error{};import{readFile as wU,stat as yU}from"node:fs/promises";import{basename as wS,extname as EU}from"node:path";async function yS(e,t={}){let r=xU(t);if(!e.length||["help","-h","--help"].includes(e[0]??"")){r.stdout(Xu());return}let n=Zu(e);if(n.kind==="login"){let{runLogin:i}=await Promise.resolve().then(()=>(_S(),gS));if(await i({env:r.env})!==0)throw new Error("login failed");return}if(n.kind==="whoami"){let i=TU(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=bU(n.api,r.env),s=SU(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=$U(n.file),c=await to(r.fetch,`${o}/transcriptions`,{method:"POST",headers:{...s,"content-type":"application/json"},body:JSON.stringify({file_name:wS(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}),wS(n.file));let d=await r.fetch(c.upload_url,{method:"POST",body:u});if(await AU(d,"S3 upload failed"),await to(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 to(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 to(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 to(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 to(r.fetch,`${o}/transcriptions/${encodeURIComponent(n.id)}`,{method:"DELETE",headers:s});r.stdout(JSON.stringify(i,null,2));return}}function Zu(e){let t=[...e],r=ds(t,"--api"),n=t.shift();if(!n||["help","-h","--help"].includes(n))throw new dn(Xu());if(n==="login"||n==="whoami")return ms(t),{kind:n,...r?{api:r}:{}};if(n==="transcribe"){let o=Qu(t,"file"),s=ds(t,"--language"),i=kU(t,"--wait");return ms(t),{kind:"transcribe",file:o,...s?{language:s}:{},wait:i,...r?{api:r}:{}}}if(n==="list"){let o=ds(t,"--status"),s=ds(t,"--after"),i=ds(t,"--limit");return ms(t),{kind:"list",...o?{status:o}:{},...s?{after:s}:{},...i?{limit:i}:{},...r?{api:r}:{}}}if(n==="get"){let o=Qu(t,"id");return ms(t),{kind:"get",id:o,...r?{api:r}:{}}}if(n==="delete"){let o=Qu(t,"id");return ms(t),{kind:"delete",id:o,...r?{api:r}:{}}}throw new dn(`unknown command: ${n}
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}
883
887
 
884
- ${Xu()}`)}function TU(e){try{return{source:Se({env:e}).source}}catch(t){return t instanceof Gr?{source:"unset"}:{source:"unset"}}}function bU(e,t){let r=e??t.LMTEXT_API_URL;if(!r)throw new Error("missing LMTEXT_API_URL or --api");return r.replace(/\/+$/,"")}function SU(e){return{authorization:`Bearer ${vU(e)}`}}function vU(e){return Se({env:e}).appkey}async function to(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 AU(e,t){if(!e.ok){let r=await e.text().catch(()=>"");throw new Error(`${t}: ${e.status} ${r}`)}}function $U(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"}[EU(e).toLowerCase()]??"application/octet-stream"}function ds(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 kU(e,t){let r=e.indexOf(t);return r<0?!1:(e.splice(r,1),!0)}function Qu(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new dn(`missing ${t}`);return r}function ms(e){if(e.length)throw new dn(`unexpected argument: ${e[0]}`)}function Xu(){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(`
885
- `)}function xU(e){return{fetch:e.fetch??fetch,env:e.env??process.env,stdout:e.stdout??(t=>process.stdout.write(`${t}
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}
886
890
  `)),stderr:e.stderr??(t=>process.stderr.write(`${t}
887
- `)),sleep:e.sleep??(t=>new Promise(r=>setTimeout(r,t))),readFile:e.readFile??(t=>wU(t)),stat:e.stat??(t=>yU(t))}}var dn=class extends Error{};var fs=class extends Error{status;responseBody;constructor(t,r){super(`HTTP ${t}${r?` ${r}`:""}`),this.status=t,this.responseBody=r,this.name="HttpResponseError"}},ro=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"}},no=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"}},oo=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 fs(e.status,await e.text().catch(()=>""))}var ES=Object.freeze({lmchat:so("https://lmctl.ai/tools/lmchat","LMCTL_LMCHAT_API_URL","LMCHAT_API_URL"),lmmail:so("https://ecezfoozb3.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMMAIL_API_URL","LMMAIL_API_URL"),lmnote:so("https://vijni9tfxh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMNOTE_API_URL","LMNOTE_API_URL"),lmsheet:so("https://9zdvg8wfjh.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMSHEET_API_URL","LMSHEET_API_URL"),lmtext:so("https://bxdbjn5k90.execute-api.us-east-1.amazonaws.com/prod","LMCTL_LMTEXT_API_URL","LMTEXT_API_URL"),lmsound:so("https://lmctl.ai/tools/lmsound","LMCTL_LMSOUND_API_URL")});function ed(e,t){let r=ES[e];return(t[r.overrideEnv]?.trim()||r.defaultUrl).replace(/\/+$/,"")}function TS(e,t){let r=ES[e];return{...t,[r.serviceEnv]:ed(e,t)}}function so(e,t,r){return{defaultUrl:e,overrideEnv:t,...r?{serviceEnv:r}:{}}}var CU={lmchat:(e,t)=>JT(e,t),lmmail:(e,t)=>hb(e,t),lmnote:(e,t)=>Ob(e,t),lmsheet:(e,t)=>tS(e,t),lmtext:(e,t)=>yS(e,t)},OU={lmchat:Gu,lmmail:Vu,lmnote:Ku,lmsheet:Yu,lmtext:Zu},DU=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 bS(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??CU,c=r.serviceParsers??OU,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&&DU[e].has(g)&&!d)return o(`lmbee ${e}: refusing to run "${g}" without --force -- this permanently deletes data. Re-run with --force to proceed.
888
- `),1}let p=m.length===0?["--help"]:m,h=process.exitCode,_;try{let g=TS(e,n);if(!f){try{c[e](p)}catch(S){throw S instanceof Error&&S.constructor.name==="UsageError"?new no(e,S):S}g.LMCTL_APPKEY=i({env:n}).appkey}let E=MU(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 oo(e,S)}return 0}catch(g){if(f)return o(`${UU(g)}
889
- `),0;throw _!==void 0&&!PU(g)?new ro(e,_,g):g}finally{process.exitCode=h}}function MU(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=>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}
890
894
  `),stderr:o=>r(`${o}
891
- `),sleep:o=>new Promise(s=>setTimeout(s,o)),readFile:(o,s)=>NU(o,s),writeFile:(o,s)=>IU(o,s),mkdir:(o,s)=>RU(o,s),stat:o=>LU(o)}}function PU(e){return!!(e&&typeof e=="object"&&"status"in e&&typeof e.status=="number")}function UU(e){return e instanceof Error?e.message:String(e)}import{writeFile as FU}from"node:fs/promises";function io(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 qU(){return["usage:",' lmbee lmsound speak "text" [--voice ID] [--engine ENGINE] [--format FORMAT] [--out FILE]'," lmbee lmsound voices"].join(`
892
- `)}function Sa(e,t){return io(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=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 SS(e,t={}){if(e.length===0||e.length===1&&(e[0]==="--help"||e[0]==="-h"))return qU();let r=t.env??process.env,n=t.resolveAppkeyImpl??Se,o=t.fetchImpl??fetch,s=t.writeFileImpl??FU,i=jU(e),a=n({env:r}).appkey,c=ed("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(`
893
- `)}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 HU=new Set(["lmchat","lmmail","lmnote","lmsheet","lmtext"]);function vS(e){return HU.has(e)}async function AS(e,t){try{return await bS(e,[...t])}catch(r){return process.stderr.write(`${r instanceof Error?r.message:String(r)}
894
- `),kS(r)}}async function $S(e){try{return{output:await SS(e),exitCode:0}}catch(t){return{output:t instanceof Error?t.message:String(t),exitCode:kS(t)}}}function kS(e){if(e instanceof no||e instanceof pr)return 2;if(e instanceof oo)return BU(e.exitCode);if(e instanceof Gr||e instanceof _s)return 3;if(e instanceof sr||e instanceof ws)return 4;let t=e instanceof fs||e instanceof ro?e.status:void 0;return t===401||t===403?3:WU(e)?4:1}function BU(e){return Number.isInteger(e)&&e>0&&e<=255?e:1}function WU(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 yF}from"node:crypto";import{randomUUID as VU}from"node:crypto";import{hostname as JU,userInfo as KU}from"node:os";var zU=120,xS=60,YU=20,QU=1e3,XU=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function td(e,t,r){try{await e.createMailbox(t,{tolerate409:!1});return}catch(o){if(!ZU(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 ZU(e){if(!e||typeof e!="object")return!1;let t=e;return t.status===409&&t.code==="mailbox_exists"}async function rd(e,t){let r=Yl({v:1,type:zl,id:t.id,command:t.command,timeout_s:t.timeoutSeconds??xS,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 nd(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 eF(e,t,l,d,c);for(let f of m.messages){let p=oF(f.subject,i);if(p)try{let h=await nF(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(QU,u))}return a}async function eF(e,t,r,n,o){let s=o.supported?Math.min(YU,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||!tF(a))throw a;return o.supported=!1,await e.listMessages(t,{status:"unread",after:r})}}function tF(e){let t=e;return t?.status===400&&t.code==="wait_s_invalid"}function RS(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 NS(e){return RS(e,"fleet")}function rF(e){return XU.test(e)?yn(e.toLowerCase()):e}async function nF(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=w_(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 oF(e,t){for(let r of t)if(e===Ql(r))return r}var It=class extends Error{};async function LS(e,t,r={}){let n=r.env??process.env,o=r.resolveAppkeyImpl??Se,s=r.createMailClientImpl??ft,i=r.now??Date.now,a=r.sleep??(S=>new Promise(R=>setTimeout(R,S))),c=r.username??(()=>KU().username),l=r.hostname??JU,u=r.waitSeconds??zU;if(!Number.isFinite(u)||u<=0)throw new It("--wait-s must be positive");let d=r.replyMailbox??(n.LMEXEC_REPLY_MAILBOX?.trim()||RS(c(),l())),{appkey:m}=o({env:n}),f=s({apiUrl:$t(n),appkey:m}),p=VU();await td(f,d,a),await rd(f,{id:p,daemonMailbox:rF(e),command:t,replyMailbox:d,timeoutSeconds:xS});let h=[],_=i()+Math.round(u*1e3),y=(await nd(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)}
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)}
895
899
  `)})).get(p);if(!y)return{stdout:"",stderr:`${h.join("")}[lmbee exec] timed out waiting for a reply
896
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}
897
- `;return{stdout:y.stdout,stderr:`${y.stderr}${v}`,exitCode:y.result.exit_code??124}}import{randomUUID as sF}from"node:crypto";import{mkdir as iF,readFile as aF,rename as cF,rm as lF,writeFile as uF}from"node:fs/promises";import{dirname as OS,join as dF}from"node:path";var DS=2,mF=/^[A-Za-z0-9_-]+$/,od=/^[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 MS(){return dF(OS(ar()),"lmt-peers.json")}function tr(e,t){if(!od.test(e))throw new Me(`${t} must be a UUID`);return e.toLowerCase()}function sd(e){return od.test(e)}function PS(e){return va(e,"peer alias")}function va(e,t){if(e.length>128||!mF.test(e))throw new Me(`${t} must match [A-Za-z0-9_-]+`);if(od.test(e))throw new Me(`${t} must not be a UUID`);return e}function ps(e,t){try{return dm(e,t)}catch(r){throw new Me(r instanceof Error?r.message:String(r))}}function IS(){return Object.create(null)}async function hs(){let e=MS(),t;try{t=await aF(e,"utf8")}catch(i){if(i.code==="ENOENT")return IS();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!==DS||!n.peers||typeof n.peers!="object"||Array.isArray(n.peers))throw new Error(`peer registry is invalid: ${e}`);let o=IS(),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=ps(l,CS(c.mailbox,`peer registry has invalid mailbox for ${i}`)),d=c.alias===void 0?void 0:PS(CS(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 US(e){let t=MS(),r={v:DS,peers:e},n=`${t}.${process.pid}.${sF()}.tmp`;await iF(OS(t),{recursive:!0});let o=!1;try{await uF(n,`${JSON.stringify(r,null,2)}
898
- `),await cF(n,t),o=!0}finally{if(!o)try{await lF(n)}catch(s){if(s.code!=="ENOENT")throw s}}}function fF(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 FS(e,t){for(let[r,n]of Object.entries(t))if(n.alias===e)return{siteUuid:tr(r,"wire site-uuid"),mailbox:ps(r,n.mailbox)}}function CS(e,t){if(typeof e!="string")throw new Error(t);return e}async function qS(){let e=await hs(),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(`
899
- `)}async function jS(e,t,r){let n=tr(e,"site-uuid"),o=ps(n,t),s=await hs(),i=s[n],a=r===void 0?i?.alias:PS(r);return fF(s,n,a),s[n]=a===void 0?{mailbox:o}:{mailbox:o,alias:a},await US(s),`peer ${n}${a?` (${a})`:""} -> ${o}`}async function HS(e){let t=tr(e,"site-uuid"),r=await hs();if(!Object.hasOwn(r,t))throw new Error(`unknown peer site-uuid: ${t}`);return delete r[t],await US(r),`removed peer ${t}`}function ao(e){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??ft,{appkey:o}=r({env:t});return n({apiUrl:$t(t),appkey:o})}function ad(e){try{return Ka(e)}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function pF(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 BS(e,t={}){let r=ad(e),n=t.siteUuid===void 0?await Ds(ar()):tr(t.siteUuid,"--site-uuid"),o=t.mailbox??hn(n),s=ao(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 WS(e,t={}){let r=ad(e),n=ao(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=GS(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 GS(e){return e.site_uuid?`uuid#${e.site_uuid.toLowerCase()}`:`mailbox#${e.mailbox}#${e.owner_user_id}`}function hF(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 gF(e,t){let r=new Set(e.flatMap(hF));return t.filter(n=>!r.has(GS(n))&&!r.has(`mailbox#${n.mailbox}#${n.owner_user_id}`))}function id(e){return e.display_name??e.registered_name??e.site_name}function _F(e,t){let r=["REGISTERED","display-name registered-name site-uuid content-mailbox exec-mailbox"];for(let n of e.sort((o,s)=>id(o).localeCompare(id(s))))r.push([id(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(`
900
- `)}async function VS(e={}){let t=ao(e),r=await Aa(t);return _F(r.sites,gF(r.sites,r.discovered))}async function wF(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 JS(e,t,r){return t!==void 0?{kind:"uuid",value:tr(t,"--uuid")}:await wF(e,pF(r))}async function KS(e,t){let r=e.trim();if(!r)throw new Me("site display name must be non-empty");let n=ao(t),o=await JS(n,t.uuid,t.mailbox),s=await n.setSiteName(o,r);return`named ${s.site_key} -> ${s.name}`}async function zS(e){let t=ao(e),r=await JS(t,e.uuid,e.mailbox);return`cleared ${(await t.deleteSiteName(r)).site_key}`}async function YS(e,t={}){let r=ad(e);return await ao(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 EF=15,TF=60,bF="lmbee status --live --json";async function QS(e={}){let t=e.env??process.env,r=e.resolveAppkeyImpl??Se,n=e.createMailClientImpl??ft,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??EF;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=NS(i());await td(l,d,s);try{let m=u.map(v=>({site:v,execMailbox:yn(v.site_uuid),id:yF(),sentAt:o()}));await Promise.all(m.map(async v=>{try{await rd(l,{id:v.id,daemonMailbox:v.execMailbox,command:bF,replyMailbox:d,timeoutSeconds:TF})}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 nd(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=>SF(v,h.get(v.id))),generated_at:new Date(o()).toISOString()}}finally{await l.deleteMailbox(d)}}function SF(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=vF(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 vF(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 XS(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??"-",AF(r.status)??"-",$F(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(`
901
- `)}function AF(e){return Array.isArray(e?.teams)?e.teams.length:void 0}function $F(e){return typeof e?.live=="boolean"?`live:${e.live}`:void 0}function ZS(){return"usage: lmbee exec <site-uuid-or-mailbox> [--wait-s N] <command...> | lmbee exec <site-uuid-or-mailbox> [--wait-s N] -- <literal command...>"}function cd(){return"usage: lmbee fleet status [--json] [--wait-s N]"}function ev(e,t){return io(e,t,r=>new It(r))}function kF(e){let t=e.indexOf("--"),r=t<0?[...e]:[...e.slice(0,t)],n=t<0?void 0:e.slice(t+1),o=ev(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(ZS());let a=n??r;if(n&&r.length>0)throw new It(`unexpected argument before --: ${r[0]}`);if(a.length===0)throw new It(ZS());return{target:i,command:a.join(" "),...s===void 0?{}:{waitSeconds:s}}}async function tv(e){try{let{target:t,command:r,waitSeconds:n}=kF(e),o=await LS(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 rv(e){let[t,...r]=e;if(t!=="status")return{output:cd(),exitCode:1};let n=r.includes("--json");try{let o=[...r],s=o.indexOf("--json");n&&o.splice(s,1);let i=ev(o,"--wait-s"),a=i===void 0?void 0:Number(i);if(a!==void 0&&(!Number.isFinite(a)||a<=0))return{output:cd(),exitCode:1};if(o.length>0)return{output:cd(),exitCode:1};let c=await QS({waitSeconds:a});return{output:n?JSON.stringify(c,null,2):XS(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 xF,readFileSync as ld,readdirSync as RF,rmSync as nv,statSync as ov}from"node:fs";import{homedir as av}from"node:os";import{join as Xe,sep as ud}from"node:path";var co=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"}},dd=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 cv(){return Xe(av(),".lmauto")}function lv(){return Xe(process.env.LMCTL_HOME??Xe(av(),".lmctl"),"lmauto")}function NF(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}async function LF(e){try{return(await fetch(`http://127.0.0.1:${e}/api/teams`,{signal:AbortSignal.timeout(1e3)})).body?.cancel(),!0}catch{return!1}}function IF(e,t){let r=Xe(e,"serve.pid");if(!Hr(r))return null;let n=ld(r,"utf8").trim(),o=Number(n);return!Number.isInteger(o)||o<=0?null:t(o)?o:null}var sv=["team_state","kv","events","queue","sources","team_progress","mail_ledger","mail_outbound_ledger"];function iv(e,t){return e.prepare(`SELECT COUNT(*) as n FROM ${t}`).get().n}function md(e){if(!Hr(e))return 0;let t=0;for(let r of RF(e,{withFileTypes:!0}))r.isDirectory()?t+=md(Xe(e,r.name)):t+=1;return t}function CF(e,t,r){let n=t.endsWith(ud)?t:t+ud,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 uv(e){let{sourceDir:t,targetDir:r,port:n=4173}=e,o=e.isDaemonAlive??NF,s=e.probeHttpAlive??LF,i=e.checkSiteLock??r_,a=Xe(t,"state.db"),c=Xe(r,"state.db"),l=i(a);if(l!==null)throw new co(`${l.ownerLabel} pid ${l.pid} (site lock for ${a})`);let u=IF(t,o);if(u!==null)throw new co(`pid ${u}, ${Xe(t,"serve.pid")}`);if(await s(n))throw new co(`something is listening on port ${n}`);if(t===r||r.startsWith(t+ud))throw new Error(`migrate-home: target (${r}) must not be, or be nested inside, source (${t})`);let d=e.acquireSiteLock??Zi,m=Jo(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 co(`${p.holder.ownerLabel} pid ${p.holder.pid}, ${p.lockPath}`):p}try{xF(r,{recursive:!0});let p=!1,h=!1;if(Hr(a)){let oe=Hr(c);if(oe&&e.replaceExistingTargetDb!==!0)throw new dd(c,ov(c).size);let V=new pt(a);try{if(V.prepare("SELECT COUNT(*) AS n FROM sqlite_master").get(),oe){process.stderr.write(`migrate-home: replacing existing target database ${c} (${ov(c).size} bytes) with a snapshot of ${a} (explicit replaceExistingTargetDb consent)
902
- `);for(let se of["","-wal","-shm"])nv(c+se,{force:!0});h=!0}else for(let se of["-wal","-shm"])nv(c+se,{force:!0});V.prepare("VACUUM INTO ?").run(c)}finally{V.close()}p=!0}let _=Xe(t,"queue"),g=Xe(r,"queue"),y=md(_);y>0&&$a(_,g,{recursive:!0});let E=Xe(t,"prompts"),v=Xe(r,"prompts"),S=md(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=ld(R,"utf8")!==ld(x,"utf8"));let H=Xe(t,"lmt-peers.json"),C=Xe(r,"lmt-peers.json"),w=!1;Hr(H)&&($a(H,C),w=!0);let T=0,N=0,U=[],J=[],ee={};if(p){let oe=new pt(a,{readonly:!0});try{for(let se of sv)ee[se]={source:iv(oe,se),target:0}}finally{oe.close()}let V=new pt(c);try{for(let A of sv)ee[A].target=iv(V,A);let{rewrittenCount:se,originalPathById:$}=CF(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 dv(e={}){let t=e.source??cv(),r=e.target??lv(),n=await uv({sourceDir:t,targetDir:r,replaceExistingTargetDb:e.replaceExistingTargetDb});return{output:PF(n),exitCode:OF(n)}}function OF(e){return e.missingPromptFiles.length>0||e.siteIdentityMismatch||DF(e)?1:0}function DF(e){return Object.values(e.rowCountParity).some(t=>t.source!==t.target)}function MF(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:
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:
903
907
  `+t.map(([r,n])=>` ${r}: source=${n.source}, target=${n.target}`).join(`
904
- `)}function PF(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 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:
905
909
  `+e.missingPromptFiles.map(r=>` ${r}`).join(`
906
- `):" 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"}`,MF(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(`
907
- `)}function fd(e){return{output:e,exitCode:0}}function lo(e){return{output:e,exitCode:1}}function pd(){return"usage: lmbee localweb passcode get | set | rotate"}var mv=32;async function UF(){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 fv(e,t={}){let[r,n,...o]=e;if(r!=="passcode")return lo(pd());if(o.length)return lo(`unexpected argument; ${pd()}`);let s=go(),i=Hn(s);if(i===null)return{output:`no passcode file for an in-memory DB (${s})`,exitCode:2};if(n==="get"){let a=l_(i);return a===null?{output:"no passcode set yet -- start the daemon or run `lmbee localweb passcode rotate`",exitCode:1}:fd(a)}if(n==="set"){let a=t.readStdin??UF,c;try{c=(await a()).trim()}catch{return lo("passcode input rejected")}let l=Buffer.byteLength(c,"utf8");return l===0||l>4096?lo("usage: lmbee localweb passcode set (reads a nonempty value of at most 4096 bytes from stdin)"):l<mv?lo(`passcode rejected: at least ${mv} 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`):(Jl(i,c),fd("passcode updated"))}return n==="rotate"?fd(ea(i)):lo(pd())}import{randomUUID as FF}from"node:crypto";import{readFile as qF}from"node:fs/promises";function jF(e){try{let t=sm(e);return HF(t.site),t}catch(t){throw new Me(t instanceof Error?t.message:String(t))}}function HF(e){return sd(e)?e.toLowerCase():va(e,"peer alias")}function pv(e,t,r,n,o=!1){let s=e??(t===void 0||t===""?r:t);return o&&s===""?s:va(s,n)}async function BF(e,t){return e==="-"?t():qF(e,"utf8")}async function WF(){let e=[];for await(let t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")}async function GF(e,t,r){if(sd(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:ps(s,i.mailbox)}}let n=FS(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 hv(){return"usage: lmbee tell <site-uuid-or-alias:team-id:alias> (<prompt...> | --prompt-file <path|->) [--from-team <team>] [--from-alias <alias>]"}async function gv(e,t,r={}){let n=r.env??process.env,o=r.promptFile;if(!e||o===void 0&&t.length===0)throw new Me(hv());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 BF(o,r.readStdin??WF);if(!i.trim())throw new Me("tell prompt must be non-empty");let a=pv(r.fromTeam,n.LMT_FROM_TEAM,"","from-team",!0),c=pv(r.fromAlias,n.LMT_FROM_ALIAS,"operator","from-alias"),l=r.resolveAppkeyImpl??Se,u=r.createMailClientImpl??ft,{appkey:d}=l({env:n}),m=u({apiUrl:$t(n),appkey:d}),f=await hs(),{siteUuid:p,mailbox:h}=await GF(s.site,f,m),_={...s,site:p},g=await Ds(ar()),y=FF(),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 hd(e){return{output:e instanceof Error?e.message:String(e),exitCode:e instanceof Me?1:2}}function VF(){return"usage: lmbee peers list | add <site-uuid> <mailbox> [--alias <name>] | remove <site-uuid>"}function nr(e,t){return io(e,t,r=>new Me(r))}async function _v(e){let[t,...r]=e;try{if(t==="list"){if(r.length)throw new Me(`unexpected argument: ${r[0]}`);return hr(await qS())}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 HS(r[0])):rr(VF())}catch(n){return hd(n)}}function JF(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 wv(e){try{let{rawAddress:t,messageParts:r,promptFile:n,fromTeam:o,fromAlias:s}=JF(e);return hr(await gv(t,r,{promptFile:n,fromTeam:o,fromAlias:s}))}catch(t){return hd(t)}}async function yv(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 BS(r[0],{siteUuid:n,mailbox:o}))}if(t==="resolve")return r.length!==1?rr(jr()):await WS(r[0]);if(t==="list")return r.length?rr(jr()):hr(await VS());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 KS(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 zS({uuid:n,mailbox:o}))}return t==="remove"?r.length!==1?rr(jr()):hr(await YS(r[0])):rr(jr())}catch(n){return hd(n)}}import{execFile as KF}from"node:child_process";import{promisify as zF}from"node:util";var YF=zF(KF),QF="lmbee.service";function XF(){return process.env.LMBEE_SYSTEMD_UNIT??QF}async function Ev(e={}){let t=XF();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.
908
- `,exitCode:1};let r=e.execFileImpl??YF;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"}`,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}
909
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}
910
914
  `,exitCode:1}}n=s}switch(n){case"inactive":return{output:`lmbee shutdown: ${t} stopped (state: ${n})
911
915
  `,exitCode:0};case"active":return{output:`lmbee shutdown: stop reported success, but ${t} is active again (state: ${n})
912
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})
913
917
  `,exitCode:1};default:return{output:`lmbee shutdown: ${t} stop not confirmed (state: ${n})
914
- `,exitCode:1}}}function ZF(e,t,r){let n="";for(let o=0;o<e.length;o++){let s=e[o];t.atLineStart&&s!==`
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!==`
915
919
  `&&(n+=`${r()} `,t.atLineStart=!1),n+=s,s===`
916
- `&&(t.atLineStart=!0)}return n}var Tv=!1;function bv(e=()=>new Date().toISOString()){if(!Tv){Tv=!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"?ZF(o,n,e):o,...s)}}}function uo(e){return`${e instanceof Error?e.message:String(e)}
917
- `}function sq(e){let t=gd(oq(),".lmbee");rq(t,{recursive:!0});let r=gd(t,"serve.log"),n=gd(t,"serve.pid"),o=tq(r,"a"),s=eq(process.execPath,[process.argv[1],...e],{detached:!0,stdio:["ignore",o,o]});s.unref(),s.pid!==void 0&&nq(n,`${s.pid}
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}
918
922
  `),process.stdout.write(`lmbee serve: started detached (pid ${s.pid??"?"}), log: ${r}, pidfile: ${n}
919
923
  Stop it with: kill ${s.pid??"<pid>"}
920
- `)}async function iq(){let e=process.argv.slice(2);if(vT(e))return process.stdout.write(`${Ur}
921
- `),0;if(e.length===1&&(e[0]==="--version"||e[0]==="-v"||e[0]==="-V")){let r=Ic();return process.stdout.write(`lmbee ${Df()} (${r.sha}${r.dirty?".dirty":""})
922
- `),0}if(e[0]==="serve"){let{flags:r}=_t(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}
923
- `),0;if(r.daemon===!0)return sq(e.filter(ne=>ne!=="--daemon")),0;bv();let n;try{if(process.env.LMBEE_SITE_UUID!==void 0){let ne=Ts(void 0,{readOnly:!0});try{En(ne.db,ar(),process.env.LMBEE_SITE_UUID)}finally{ne.close()}}n=di()}catch(ne){return process.stderr.write(uo(ne)),1}let o=r["remote-mail"]===!0,s=typeof r["remote-allow"]=="string"?r["remote-allow"]:void 0;if(o&&s===void 0)return process.stderr.write(`error: --remote-mail requires --remote-allow <user_id1,user_id2,...>
924
+ `)}async function 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":""})
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,...>
924
928
  `),n.db.close(),1;if(!o&&s!==void 0)return process.stderr.write(`error: --remote-allow requires --remote-mail
925
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
926
- `),n.db.close(),1;let D;try{D=En(n.db.db)}catch(j){return process.stderr.write(uo(j)),n.db.close(),1}try{let{appkey:j}=Se({env:process.env});i={client:ft({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(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)}
927
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
928
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
929
- `),n.db.close(),1;let Y;try{Y=En(n.db.db)}catch(K){return process.stderr.write(uo(K)),n.db.close(),1}try{let{appkey:K}=Se({env:process.env}),re=c??yn(Y);m={client:ft({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(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)}
930
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
931
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}
932
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
@@ -936,24 +940,24 @@ Stop it with: kill ${s.pid??"<pid>"}
936
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}
937
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}
938
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
939
- `),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,H=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}
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}
940
944
  `),1;if(O instanceof Error)return process.stderr.write(`error: ${O.message}
941
- `),1;let A=ua(r["min-memory-percent"],"--min-memory-percent");if(A instanceof Error)return process.stderr.write(`error: ${A.message}
942
- `),1;let q=A??mc,M=$!==void 0||O!==void 0?{idleThresholdMs:$??Te.idleThresholdMs,cooldownMs:O??Te.cooldownMs}:void 0,Z;try{Z=await aE({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}:{},...H!==void 0?{autoContinue:H}:{},...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=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)}
943
947
  `),n.db.close(),1}process.stdout.write(`lmbee serve: listening on http://${Z.hostname}:${Z.port}
944
- `);let W=Ic();process.stdout.write(`lmbee serve: build ${W.sha}${W.dirty?" (dirty)":""}, built ${W.builtAt}
945
- `);let ae=!1,ye=()=>{ae||(ae=!0,Z.shutdown().catch(ne=>{process.stderr.write(`lmbee serve: error during graceful shutdown: ${ne instanceof Error?ne.message:String(ne)}
946
- `)}).finally(()=>{n.db.close(),process.exit(0)}))};return process.on("SIGINT",ye),process.on("SIGTERM",ye),new Promise(()=>{})}if(e[0]==="whoami"){let{flags:r}=_t(e.slice(1),["json"]),{output:n,exitCode:o}=await ay({json:r.json===!0});return n&&process.stdout.write(`${n}
947
- `),o}if(e[0]==="peers"||e[0]==="tell"||e[0]==="sites"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="peers"?await _v(r):e[0]==="tell"?await wv(r):await yv(r);return n&&process.stdout.write(`${n}
948
- `),o}if(e[0]==="localweb"){let{output:r,exitCode:n}=await fv(e.slice(1));return r&&process.stdout.write(`${r}
949
- `),n}if(vS(e[0]??""))return await AS(e[0],e.slice(1));if(e[0]==="lmsound"){let{output:r,exitCode:n}=await $S(e.slice(1));return r&&process.stdout.write(`${r}
950
- `),n}if(e[0]==="exec"||e[0]==="fleet"){let r=e.slice(1),{output:n,exitCode:o}=e[0]==="exec"?await tv(r):await rv(r);return n&&process.stdout.write(`${n}
951
- `),o}if(e[0]==="migrate-home"){let{flags:r,positionals:n}=_t(e.slice(1),["help","replace-existing-target-db"]);if(r.help===!0)return process.stdout.write(`${Ur}
948
+ `);let W=Cc();process.stdout.write(`lmbee serve: build ${W.sha}${W.dirty?" (dirty)":""}, built ${W.builtAt}
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}
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}
952
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.
953
- `),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 dv({source:o,target:s,replaceExistingTargetDb:r["replace-existing-target-db"]===!0});return i&&process.stdout.write(`${i}
954
- `),a}catch(i){return process.stderr.write(uo(i)),1}}if(e[0]==="shutdown"){let{flags:r}=_t(e.slice(1),["help","force"]);if(r.help===!0)return process.stdout.write(`${Ur}
955
- `),0;let{output:n,exitCode:o}=await Ev({force:r.force===!0});return n&&process.stdout.write(n),o}if(e[0]==="cron"&&e[1]==="export")try{let{output:r,exitCode:n}=dE(e.slice(2));return r&&process.stdout.write(`${r}
956
- `),n}catch(r){return process.stderr.write(uo(r)),1}if(e[0]==="cron"&&e[1]==="import"){let{positionals:r,flags:n}=_t(e.slice(2),["json","help"]);if(n.help!==!0){let o=n.json===!0;try{es("import",r,n);let s=r[0];if(s===void 0)throw new P("INVALID_ARGUMENT","an import PATH is required");pE(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 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
961
  `:`${s.code}: ${s.message}
958
- `),s.exitCode;throw s}}}let t;try{t=di({readOnly:AT(e)});let{output:r,exitCode:n}=await $T(t,e);return r&&process.stdout.write(`${r}
959
- `),n}catch(r){return process.stderr.write(uo(r)),1}finally{t?.db.close()}}iq().then(e=>{process.exitCode=e});
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});