agentix-cli 0.195.0 → 0.196.0

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.
@@ -1,10 +1,10 @@
1
- import{a as tt}from"./chunk-GTJIKXDB.js";import{H as er,O as dr,k as q}from"./chunk-M2E3CNFS.js";import{f as ir,g as ar,h as cr,k as lr}from"./chunk-LQIF2OHS.js";import{b as tr}from"./chunk-2VDO2HEK.js";import{a as nr,i as rr,l as or,n as Qe,o as et,q as re,r as K,t as sr}from"./chunk-XPZSEDE3.js";import{t as Zn,u as Qn}from"./chunk-FO762MEC.js";import{d as Yn,e as Jn}from"./chunk-AQASR6KR.js";import{a as Pn,b as Mn,d as Un,e as Fn}from"./chunk-MNG2AMKZ.js";import{h as ne,j as Wn,l as jn,m as qn,n as Bn}from"./chunk-RX5O5637.js";import{a as Hn,c as Vn,e as Xn,f as Ge,h as zn,j as Kn,k as Gn,l as Ye,m as Je,n as Ze}from"./chunk-5ELIX7BQ.js";import{h as Dn,i as Cn,j as Nn,l as Ln,m as On}from"./chunk-HOZZUN47.js";import{a as Rn,c as In}from"./chunk-KP7KDLZ2.js";import{c as ye,d as Tn,e as An}from"./chunk-XVV7ZZ77.js";import{Aa as te,Ca as Ke,b as Ve,f as kn,s as Xe,u as ze,xa as be,ya as $n,za as L}from"./chunk-PO2SORKY.js";import{a as fe,b as me,d as vn}from"./chunk-3FZ6WHKX.js";import{r as _n}from"./chunk-MC3ZZA5G.js";import{a as Sn,b as he,e as En}from"./chunk-KXJRXRSD.js";import{b as z}from"./chunk-5ONH4ITT.js";import{a as xn,c as He}from"./chunk-ILEC3IAV.js";import{a as wn}from"./chunk-QUFIUXMQ.js";import{A as ln,B as Ks,Ib as yn,d as We,f as an,j as zs,ma as pn,na as gn,pa as fn,pb as Be,qa as mn,y as ge,yb as hn,z as cn,zb as bn}from"./chunk-P6WSD2UR.js";import{a as je,h as Gs}from"./chunk-VJ5HC63R.js";import{j as qe,q as dn,r as un}from"./chunk-UEEB3UTU.js";import{existsSync as Ys,readdirSync as Js,readFileSync as Zs,statSync as Qs}from"fs";import{resolve as ei}from"path";function ur(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],c=a.filter(f=>n-f.at<=o),l=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=c.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&d*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:d,paused:u}}).sort((i,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[i.state]-c[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var we=new Map;function Gd(t,e=1e3){if(!Ys(t))return[];let n=Js(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=ei(t,s);return{path:i,mtime:Qs(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of we.keys())r.has(s)||we.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=we.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let c=ti(s,i);we.set(s,{mtime:i,summary:c}),c&&o.push(c)}return o}function ti(t,e){try{let n=Zs(t,"utf-8").split(`
2
- `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var pr=7,ni={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},S={routines:200,summary:160,filters:6,filterValue:60,text:120},ri=(t,e,n)=>{try{return _n(t,e,n)}catch{return null}},gr=864e5;function Qd(t){let e=t.now??Date.now(),n={...ni,...t.thresholds},r=t.nextFire??ri,o=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",d=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:D(a.id,S.text),trigger:{schedule:D(a.schedule,S.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?nt(a.nextRun)??nt(r(a.schedule,new Date(e),l)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:li(u.status==="success"?void 0:u.errorSummary,S.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:fr(d),sampledRuns:c.length,flags:[],attention:null,recent:c.slice(0,pr).map(g=>({at:g.startedAt,status:g.status}))};p.flags=mr(p,d,a.schedule,l,null,e,n,r),o.push(hr(p))}let s=new Map(ur(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let c=i.get(a.workflowId);c?c.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(v=>v.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((v,Fe)=>Fe.at-v.at),g=p.map(v=>({at:v.at,status:ii(v.status)})),f=g[0],m=c.type==="trigger.cron",h=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:D(a.title||a.id,S.text),trigger:m?{schedule:D(h,S.text),timezone:x}:{event:D(typeof l.event=="string"?l.event:"",S.text),filters:ci(l.filter,a)},agent:ai(a),enabled:u,state:d,nextRunAt:m&&u&&h?nt(r(h,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let v=g.find(Fe=>Fe.status==="success");return v?new Date(v.at).toISOString():null})(),consecutiveFailures:fr(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,pr).map(v=>({at:new Date(v.at).toISOString(),status:v.status}))},pe=Date.parse(a.updated||a.created||"");N.flags=m?mr(N,g,h,x,Number.isFinite(pe)?pe:null,e,n,r):oi(N,s.get(a.id)?.state==="dormant",Number.isFinite(pe)?pe:null,e,n),o.push(hr(N))}return o.sort(si).slice(0,S.routines)}function fr(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function mr(t,e,n,r,o,s,i,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=yr(l,o,s,i);return p&&c.push(p),c}if(t.consecutiveFailures>=i.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let d=new Date(l),u=null;for(let p=0;p<i.missedFires&&(u=a(n,d,r),!!u);p++)d=u;return u&&s>u.getTime()+i.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),c}function oi(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=yr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function yr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*gr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/gr)} days`:"Disabled and never ran"}}function hr(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var br={critical:0,warning:1,info:2};function si(t,e){let n=t.attention?br[t.attention]:3,r=e.attention?br[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ii(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ai(t){if(t.ownerAgent)return D(t.ownerAgent,S.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?D(String(e.config.agentId),S.text):null}function ci(t,e){let n=[],r=e?.project;if(r&&n.push(D(`project=${r}`,S.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(D(`${o}=${i.join(",")}`,S.filterValue))}return n.slice(0,S.filters)}function nt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function D(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function li(t,e){return t===void 0?void 0:D(t,e)}import{mkdirSync as di,readFileSync as ui,renameSync as pi,writeFileSync as gi}from"fs";import{resolve as fi}from"path";function wr(t){return fi(et(t),"_state.json")}function $(t){try{let e=JSON.parse(ui(wr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function oe(t,e){di(et(t),{recursive:!0});let n=wr(t),r=`${n}.${process.pid}.tmp`;gi(r,JSON.stringify(e,null,2)+`
3
- `),pi(r,n)}function xr(t,e,n,r=Date.now()){let o=$(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),oe(t,{...o,snoozed:s})}function ou(t,e){oe(t,{...$(t),lastDigest:e})}function rt(t,e,n,r=Date.now()){let o=$(t),s=new Set(n),i={};for(let[c,l]of Object.entries(o.popped??{}))s.has(c)&&(i[c]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(c=>c!==e&&s.has(c));oe(t,{...o,popped:i,wanted:a})}function kr(t,e){let n=$(t);oe(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function su(t,e=Date.now()){oe(t,{...$(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as mi,readFileSync as hi}from"fs";yn();Gs();function vr(t){let e=Sn(t),n={};if(mi(e))try{n=hn(JSON.parse(hi(e,"utf-8")))}catch{n={}}let r=Be.safeParse(n?.requests);return r.success?r.data:Be.parse(void 0)}async function uu(t,e={}){let n=(t.channels??[]).filter(r=>!je.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...je].join(", ")}`}:he(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as U,readdirSync as Ui,readFileSync as ct,statSync as Fi}from"fs";import{dirname as qr,resolve as k}from"path";import{randomBytes as _r}from"crypto";import{existsSync as yi,mkdirSync as wi,readdirSync as xi,readFileSync as ki,renameSync as $r,unlinkSync as vi,writeFileSync as Si}from"fs";import{resolve as Tr}from"path";function Sr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var bi=t=>t.trim().split(`
1
+ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as er,O as dr,k as q}from"./chunk-M2E3CNFS.js";import{f as ir,g as ar,h as cr,k as lr}from"./chunk-LQIF2OHS.js";import{b as tr}from"./chunk-2VDO2HEK.js";import{a as nr,i as rr,l as or,n as Qe,o as et,q as oe,r as K,t as sr}from"./chunk-XPZSEDE3.js";import{t as Zn,u as Qn}from"./chunk-FO762MEC.js";import{d as Yn,e as Jn}from"./chunk-AQASR6KR.js";import{a as Pn,b as Mn,d as Un,e as Fn}from"./chunk-MNG2AMKZ.js";import{h as re,j as Wn,l as jn,m as qn,n as Bn}from"./chunk-RX5O5637.js";import{a as Hn,c as Vn,e as Xn,f as Ge,h as zn,j as Kn,k as Gn,l as Ye,m as Je,n as Ze}from"./chunk-5ELIX7BQ.js";import{h as Dn,i as Cn,j as Nn,l as Ln,m as On}from"./chunk-HOZZUN47.js";import{a as Rn,c as In}from"./chunk-KP7KDLZ2.js";import{c as ye,d as Tn,e as An}from"./chunk-XVV7ZZ77.js";import{Aa as ne,Ca as Ke,b as Ve,f as kn,s as Xe,u as ze,xa as be,ya as $n,za as L}from"./chunk-PO2SORKY.js";import{a as me,b as te,d as vn}from"./chunk-3FZ6WHKX.js";import{r as _n}from"./chunk-MC3ZZA5G.js";import{a as Sn,b as he,e as En}from"./chunk-KXJRXRSD.js";import{b as z}from"./chunk-5ONH4ITT.js";import{a as xn,c as He}from"./chunk-ILEC3IAV.js";import{a as wn}from"./chunk-QUFIUXMQ.js";import{A as ln,B as Ks,Ib as yn,d as We,f as an,j as zs,ma as pn,na as gn,pa as fn,pb as Be,qa as mn,y as fe,yb as hn,z as cn,zb as bn}from"./chunk-P6WSD2UR.js";import{a as je,h as Gs}from"./chunk-VJ5HC63R.js";import{j as qe,q as dn,r as un}from"./chunk-UEEB3UTU.js";import{existsSync as Ys,readdirSync as Js,readFileSync as Zs,statSync as Qs}from"fs";import{resolve as ei}from"path";function ur(t,e,n=Date.now(),r=7){let o=r*864e5,s=new Map;for(let i of e){let a=s.get(i.workflowId);a?a.push(i):s.set(i.workflowId,[i])}return t.map(i=>{let a=s.get(i.id)??[],c=a.filter(f=>n-f.at<=o),l=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=c.filter(f=>f.status==="failed").length,u=a.filter(f=>f.status==="paused").length,p=a.length?Math.max(...a.map(f=>f.at)):null,g=a.length?l.length>0&&c.length===0?"dormant":c.length>0&&d*2>=c.length?"failing":c.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:c.length,prior:l.length,failed:d,paused:u}}).sort((i,a)=>{let c={dormant:0,failing:1,active:2,quiet:3,never:4};return c[i.state]-c[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var we=new Map;function Gd(t,e=1e3){if(!Ys(t))return[];let n=Js(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=ei(t,s);return{path:i,mtime:Qs(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of we.keys())r.has(s)||we.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=we.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let c=ti(s,i);we.set(s,{mtime:i,summary:c}),c&&o.push(c)}return o}function ti(t,e){try{let n=Zs(t,"utf-8").split(`
2
+ `).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),c=a.status??a.run?.status;if(c){s=c;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var pr=7,ni={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},S={routines:200,summary:160,filters:6,filterValue:60,text:120},ri=(t,e,n)=>{try{return _n(t,e,n)}catch{return null}},gr=864e5;function Qd(t){let e=t.now??Date.now(),n={...ni,...t.thresholds},r=t.nextFire??ri,o=[];for(let a of t.crons){let c=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",d=c.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=c[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:D(a.id,S.text),trigger:{schedule:D(a.schedule,S.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?nt(a.nextRun)??nt(r(a.schedule,new Date(e),l)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:li(u.status==="success"?void 0:u.errorSummary,S.summary)}:null,lastSuccessAt:c.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:fr(d),sampledRuns:c.length,flags:[],attention:null,recent:c.slice(0,pr).map(g=>({at:g.startedAt,status:g.status}))};p.flags=mr(p,d,a.schedule,l,null,e,n,r),o.push(hr(p))}let s=new Map(ur(t.workflows.map(a=>({id:a.id,name:a.title})),t.workflowRuns,e).map(a=>[a.id,a])),i=new Map;for(let a of t.workflowRuns){let c=i.get(a.workflowId);c?c.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let c=a.nodes.find(v=>v.type.startsWith("trigger."));if(!c||c.type!=="trigger.cron"&&c.type!=="trigger.hook")continue;let l=c.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((v,Fe)=>Fe.at-v.at),g=p.map(v=>({at:v.at,status:ii(v.status)})),f=g[0],m=c.type==="trigger.cron",h=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",N={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:D(a.title||a.id,S.text),trigger:m?{schedule:D(h,S.text),timezone:x}:{event:D(typeof l.event=="string"?l.event:"",S.text),filters:ci(l.filter,a)},agent:ai(a),enabled:u,state:d,nextRunAt:m&&u&&h?nt(r(h,new Date(e),x)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let v=g.find(Fe=>Fe.status==="success");return v?new Date(v.at).toISOString():null})(),consecutiveFailures:fr(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,pr).map(v=>({at:new Date(v.at).toISOString(),status:v.status}))},ge=Date.parse(a.updated||a.created||"");N.flags=m?mr(N,g,h,x,Number.isFinite(ge)?ge:null,e,n,r):oi(N,s.get(a.id)?.state==="dormant",Number.isFinite(ge)?ge:null,e,n),o.push(hr(N))}return o.sort(si).slice(0,S.routines)}function fr(t){let e=0;for(let n of t)if(!(n.status==="running"||n.status==="paused"||n.status==="unknown"))if(n.status==="failed"||n.status==="timeout")e++;else break;return e}function mr(t,e,n,r,o,s,i,a){let c=[],l=e.length?e[0].at:null;if(!t.enabled){let p=yr(l,o,s,i);return p&&c.push(p),c}if(t.consecutiveFailures>=i.failStreak&&c.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return c.push({reason:"never-ran",detail:"No persisted attempt"}),c;let d=new Date(l),u=null;for(let p=0;p<i.missedFires&&(u=a(n,d,r),!!u);p++)d=u;return u&&s>u.getTime()+i.graceMs&&c.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),c}function oi(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=yr(i,n,r,o);return a&&s.push(a),s}return t.consecutiveFailures>=o.failStreak&&s.push({reason:"failing",detail:`${t.consecutiveFailures} failed runs in a row`}),i===null?s.push({reason:"never-ran",detail:"No run recorded for this trigger"}):e&&s.push({reason:"dormant",detail:"Fired in the prior week, silent in the last one"}),s}function yr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*gr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/gr)} days`:"Disabled and never ran"}}function hr(t){let e=new Set(t.flags.map(n=>n.reason));return t.attention=e.has("failing")?"critical":e.has("overdue")||e.has("dormant")||e.has("never-ran")?"warning":e.has("disabled-long")?"info":null,t}var br={critical:0,warning:1,info:2};function si(t,e){let n=t.attention?br[t.attention]:3,r=e.attention?br[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ii(t){switch(t){case"completed":case"ok":return"success";case"failed":return"failed";case"timeout":return"timeout";case"canceled":return"canceled";case"running":return"running";case"paused":return"paused";default:return"unknown"}}function ai(t){if(t.ownerAgent)return D(t.ownerAgent,S.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?D(String(e.config.agentId),S.text):null}function ci(t,e){let n=[],r=e?.project;if(r&&n.push(D(`project=${r}`,S.filterValue)),t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Object.entries(t)){let i=Array.isArray(s)?s.map(String):s==null?[]:[String(s)];i.length&&n.push(D(`${o}=${i.join(",")}`,S.filterValue))}return n.slice(0,S.filters)}function nt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function D(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function li(t,e){return t===void 0?void 0:D(t,e)}import{mkdirSync as di,readFileSync as ui,renameSync as pi,writeFileSync as gi}from"fs";import{resolve as fi}from"path";function wr(t){return fi(et(t),"_state.json")}function $(t){try{let e=JSON.parse(ui(wr(t),"utf-8"));return{snoozed:e&&typeof e.snoozed=="object"&&e.snoozed?e.snoozed:{},...typeof e?.lastDigest=="string"?{lastDigest:e.lastDigest}:{},...e?.popped&&typeof e.popped=="object"?{popped:e.popped}:{},...typeof e?.passAt=="string"?{passAt:e.passAt}:{},...Array.isArray(e?.wanted)?{wanted:e.wanted.filter(n=>typeof n=="string")}:{}}}catch{return{snoozed:{}}}}function se(t,e){di(et(t),{recursive:!0});let n=wr(t),r=`${n}.${process.pid}.tmp`;gi(r,JSON.stringify(e,null,2)+`
3
+ `),pi(r,n)}function xr(t,e,n,r=Date.now()){let o=$(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),se(t,{...o,snoozed:s})}function ou(t,e){se(t,{...$(t),lastDigest:e})}function rt(t,e,n,r=Date.now()){let o=$(t),s=new Set(n),i={};for(let[c,l]of Object.entries(o.popped??{}))s.has(c)&&(i[c]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(c=>c!==e&&s.has(c));se(t,{...o,popped:i,wanted:a})}function kr(t,e){let n=$(t);se(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function su(t,e=Date.now()){se(t,{...$(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as mi,readFileSync as hi}from"fs";yn();Gs();function vr(t){let e=Sn(t),n={};if(mi(e))try{n=hn(JSON.parse(hi(e,"utf-8")))}catch{n={}}let r=Be.safeParse(n?.requests);return r.success?r.data:Be.parse(void 0)}async function uu(t,e={}){let n=(t.channels??[]).filter(r=>!je.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...je].join(", ")}`}:he(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as U,readdirSync as Ui,readFileSync as ct,statSync as Fi}from"fs";import{dirname as qr,resolve as k}from"path";import{randomBytes as _r}from"crypto";import{existsSync as yi,mkdirSync as wi,readdirSync as xi,readFileSync as ki,renameSync as $r,unlinkSync as vi,writeFileSync as Si}from"fs";import{resolve as Tr}from"path";function Sr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var bi=t=>t.trim().split(`
4
4
  `).pop()?.slice(0,300)||"no output";async function Er(t,e,n,r=tt){let o=await r(t.bin,[...Sr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${bi(o.stderr||o.stdout)}`}}async function fu(t,e,n,r,o=tt){return(await o(t.bin,[...Sr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ei=2e3,_i=t=>Er(t.wacli,t.to,t.text);function ot(t){return Tr(t,".agentx","whatsapp-triage","drafts")}var $i=t=>/^[a-z0-9-]{8,64}$/.test(t),xe=(t,e)=>Tr(ot(t),`${e}.json`);function Ar(t,e){wi(ot(t),{recursive:!0});let n=xe(t,e.id),r=`${n}.${process.pid}.tmp`;Si(r,JSON.stringify(e,null,2)+`
5
5
  `,{mode:384}),$r(r,n)}function xu(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ei);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${_r(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Ar(t,o),o}function ke(t,e){if(!$i(e))return null;try{return JSON.parse(ki(xe(t,e),"utf-8"))}catch{return null}}function Rr(t,e){let n=ot(t);return yi(n)?xi(n).filter(r=>r.endsWith(".json")).map(r=>ke(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Ir(t,e,n,r={}){let o=ke(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${xe(t,e)}.${process.pid}.${_r(3).toString("hex")}.claim`;try{$r(xe(t,e),s)}catch{return{ok:!1,error:`reply draft "${e}" is already being decided`}}let i={...o,decided_by:r.by??"operator",decided_at:new Date(r.now??Date.now()).toISOString()};if(n==="no")i.status="rejected";else{let a=await(r.send??_i)(o).catch(c=>({ok:!1,error:String(c?.message??c)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Ar(t,i);try{vi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Ai,writeFileSync as Ri}from"fs";import{resolve as Cr}from"path";function st(t,e,n,r){let o=t.agents?.[e];if(!o)return null;let s=o.integrations;if(!Array.isArray(s))return null;let i=s.find(a=>a.enabled!==!1&&a.kind===n&&(!r||a.label===r));return i?{agentId:e,integration:i}:null}function Ti(t,e){let r=(t.credentials??{})[e];if(!r)return{status:"no-credential",reason:`integration "${t.label}" has no ${String(e)} configured`};if(e==="auth"&&r==="keyring")return{status:"ok"};if(typeof r=="string"&&/^[A-Z][A-Z0-9_]*$/.test(r)){let o=process.env[r];return o?{status:"ok",value:o,envVar:r}:{status:"env-unset",envVar:r,reason:`env var ${r} is unset (declared by integration "${t.label}")`}}return typeof r=="string"?{status:"ok",value:r}:{status:"no-credential",reason:`unrecognized credential ref shape for ${String(e)}`}}function vu(t,e,n,r,o){let s=st(t,e,n,o);return s?Ti(s.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${o?` with label "${o}"`:""}`}}var Nr="ready",Ii="202510";function Di(t){let e=t.date??t.created_at.slice(0,10);return Cr(t.workspace,Nr,`${e}-${t.platform}-${t.id}.txt`)}function Dr(t){let e=Di(t);return Ai(Cr(t.workspace,Nr),{recursive:!0}),Ri(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function Lr(t,e,n){let r=st(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Or(t,e,n){return Lr(t,e,n)!==null}async function Ci(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??Ii),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function Ni(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function Li(t,e){let n=Lr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Dr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await Ci(t.text,n,r):await Ni(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Dr(t);return{ok:!1,error:`not posted on ${ne[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function Pr(t){return e=>Li(e,t)}un();mn();mn();un();var Du=["done","skipped"],Oi=1e3;function Pi(t){t.exec(`
7
+ `),e}function Lr(t,e,n){let r=st(t.config,e,n);if(!r)return null;let o=t.env??process.env,s=r.integration.credentials?.tokenEnv,i=s?o[s]:void 0;return i?{token:i,metadata:r.integration.metadata??{}}:null}function Or(t,e,n){return Lr(t,e,n)!==null}async function Ci(t,e,n){let r=String(e.metadata.author??"");if(!/^urn:li:(person|organization):/.test(r))throw new Error("the linkedin connector needs metadata.author, like urn:li:person:<id>");let o=await n("https://api.linkedin.com/rest/posts",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json","LinkedIn-Version":String(e.metadata.apiVersion??Ii),"X-Restli-Protocol-Version":"2.0.0"},body:JSON.stringify({author:r,commentary:t,visibility:"PUBLIC",distribution:{feedDistribution:"MAIN_FEED",targetEntities:[],thirdPartyDistributionChannels:[]},lifecycleState:"PUBLISHED",isReshareDisabledByAuthor:!1}),signal:AbortSignal.timeout(2e4)});if(!o.ok)throw new Error(`LinkedIn said ${o.status}: ${(await o.text().catch(()=>"")).slice(0,200)}`);let s=o.headers.get("x-restli-id");return s?{url:`https://www.linkedin.com/feed/update/${s}/`}:{}}async function Ni(t,e,n){let r=await n("https://api.x.com/2/tweets",{method:"POST",headers:{Authorization:`Bearer ${e.token}`,"Content-Type":"application/json"},body:JSON.stringify({text:t}),signal:AbortSignal.timeout(2e4)});if(!r.ok)throw new Error(`X said ${r.status}: ${(await r.text().catch(()=>"")).slice(0,200)}`);let o=await r.json().catch(()=>({}));return o.data?.id?{url:`https://x.com/i/web/status/${o.data.id}`}:{}}async function Li(t,e){let n=Lr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Dr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await Ci(t.text,n,r):await Ni(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Dr(t);return{ok:!1,error:`not posted on ${re[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function Pr(t){return e=>Li(e,t)}un();mn();mn();un();var Du=["done","skipped"],Oi=1e3;function Pi(t){t.exec(`
8
8
  CREATE TABLE IF NOT EXISTS request_plans (
9
9
  request_id TEXT PRIMARY KEY,
10
10
  created_by TEXT NOT NULL,
@@ -64,7 +64,7 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as er,O as dr,k as q}from"./ch
64
64
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
65
65
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,c)=>{let l=c===0,d=l&&a.agentId===n&&a.kind!=="message";i.run(e,c+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,d?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?it(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(Mr)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?Mr(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(it)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let c=Mi[i];!c||a===void 0||(o.push(`${c} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(it)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,Oi))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
66
66
  ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
67
- told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},Cu=pn;var Br=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],Wi=280;function T(t,e=Wi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function G(t){if(t.configPath)return k(t.configPath);let e=[k(t.root,"agentx.json"),k(t.root,".agentx","config.json")];return e.find(n=>U(n))??e[0]}function F(t){return t.wikiDir?k(t.wikiDir):k(t.root,".agentx","wiki")}function ji(t){return K(t.root,"pending").map(qi)}function qi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:T([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Bi(t){let e=G(t);if(!U(e))return[];let n;try{n=JSON.parse(ct(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=i.timezone||"UTC",l=i.schedule?Dn(i.schedule):"",d=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",u=String(i.prompt??i.command??""),p=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:p?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:p?`Let ${i.agent??"the agent"} run this ${d}?`:`Remove the schedule "${s}" (${d})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:T(`${u}${p&&i.schedule?` \xB7 first run ${Nn(Cn(i.schedule,c,r),c)}`:""}`),more:"agentx schedule list"})}return o}function Hr(t){let e=k(t,".agentx","memory");return U(e)?Ui(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Hi(t){let e=Hr(t.root);if(e.length===0)return[];let n=new Ve(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:T(s.content),more:`agentx memory facts held --agent ${o}`});return r}function Vi(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Xi(t){return Jn(F(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:T(`${Vi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var Fr=new Map;function Vr(t,e){let n=Fi(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=Fr.get(t);if(o?.version===r)return o.value;let s=e();return Fr.set(t,{version:r,value:s}),s}function zi(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${T(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:T(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function Ki(t,e){let n=F(t);if(!U(k(n,"_facts.json")))return;let r=ye(new z(n),"pending").find(o=>o.id===e);return r?zi(r):void 0}function Gi(t){let e=k(F(t),"_facts.json");if(!U(e))return;let n=Vr(e,()=>ye(new z(qr(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Yi(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function Xr(t){let e=F(t),n=new He(e);if(!U(n.path))return[];let r=Vr(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new z(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Yi(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Ji(t){return Rr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:T(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Zi(t){return ar(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:T(`Last try not sent: ${e.error}`)}:{}}))}function Qi(t){let e=Object.entries(Xe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Se(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:T(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Se(t){try{return JSON.parse(ct(G(t),"utf-8"))}catch{return{}}}function at(t){let e={};try{e=Object.fromEntries(wn(ct(k(qr(G(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ea(t){let e=qn(t.root,"pending");if(e.length===0)return[];let n=Se(t),r=at(t);return e.map(o=>{let s=ne[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:Or({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:T(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:Wn(o.text)}})}function B(t){if(t.requests)return t.requests;if(k(t.root)!==process.cwd()||!U(k(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e)return null;let n=Wr.get(e);return!n&&!gn(e)?null:(n||Wr.set(e,n=new fn(e)),n)}var Wr=new WeakMap;function ip(t){if(t.plans)return t.plans;if(t.requests||k(t.root)!==process.cwd()||!U(k(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e||!Ur(e))return null;let n=jr.get(e);return n||jr.set(e,n=new ve(e)),n}var jr=new WeakMap;function ta(t){let e=B(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:q(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:T(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var zr={card:ji,schedule:Bi,agent:Qi,memory:Hi,wiki:Xi,fact:()=>[],question:Xr,whatsapp:Ji,email:Zi,content:ea,request:ta};function na(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Kr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=$(t.root),o=[],s=[],i=[],a=0;for(let c of e.kinds??Br){if(c==="fact"){try{let d=Gi(t);d&&i.push(d)}catch(d){s.push({kind:c,error:String(d?.message??d).slice(0,200)})}continue}let l;try{l=zr[c](t)}catch(d){s.push({kind:c,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let u=r[d.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){a++;continue}d.snoozed_until=u}o.push(d)}}return o.sort(na),{items:o,snoozed:a,errors:s,backlog:i}}function Gr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Br.includes(n)||!r?null:{kind:n,ref:r}}function ra(t,e,n){switch(e){case"card":return re(t.root,n)?.status==="pending";case"wiki":return Yn(F(t),n)?.status==="pending";case"whatsapp":return ke(t.root,n)?.status==="pending";case"email":return ir(t.root,n)?.status==="pending";case"content":return jn(t.root,n)?.status==="pending";default:return!!Yr(t,e,n)}}function Yr(t,e,n){return e==="fact"?Ki(t,n):zr[e](t).find(r=>r.key===`${e}:${n}`)}async function Jr(t,e,n,r={}){let o=n==="later"?null:Gr(e),s;if(o)try{s=Yr(t,o.kind,o.ref)}catch{s=void 0}let i=await oa(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;nr(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function oa(t,e,n,r){let o=Gr(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),c=r.by??"operator";if(n==="later"){if(!ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let d=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+d*36e5);return xr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let d=sr(t.root,i,l?"yes":"no",{by:c,note:r.note,now:a,choice:r.choice,text:r.text});return d.ok?{ok:!0,message:`${e}: ${d.card.raised_by} will be told ${l?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(l?Ln:On)(i,{configPath:G(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Xe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ze(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let d=[],u=await he(p=>{En(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:G(t),reload:t.reload});return u.success?(ze(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${d.length?`, with its schedules ${d.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:u.error||"could not remove it from agentx.json"}}case"memory":{let d=i.indexOf("/");if(d<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,d),p=i.slice(d+1);if(!Hr(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ve(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let d=F(t),u=l?Zn(d,i,{by:c,force:r.force,now:a}):Qn(d,i,{by:c,reason:r.note,now:a});return u.ok?{ok:!0,message:l?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"fact":return sa(t,e,i,l,c,r);case"question":return aa(t,e,i,l,c,r);case"whatsapp":{let d=await Ir(t.root,i,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:l?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??lr(Se(t),at(t)),u=await cr(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??Pr({config:Se(t),env:at(t)}),u=await Bn(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let p=ne[u.draft.platform];return{ok:!0,message:u.draft.status==="posted"?`${e}: posted on ${p}${u.draft.url?` (${u.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${u.draft.file}`}}case"request":{let d=B(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?vr(G(t)).enabled?(d.requestPickup(i,a),{ok:!0,message:`${e}: ${u.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(d.close(i,"dropped",r.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}function sa(t,e,n,r,o,s){let i=new z(F(t));try{let a=ye(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return An(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let c=Tn(i,a.id,o);return{ok:!0,message:`${e}: ${c.write.fact.subject} \xB7 ${c.write.fact.attribute} recorded as "${c.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function ia(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function aa(t,e,n,r,o,s){let i=F(t),a=new He(i),c=a.list("open").find(l=>l.id===n);if(!c)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(xn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(c.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=Xr(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${c.id} "<value>"`};let d=ia(l.choices,s.choice);if(!d)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let u=new z(i),p=c.factId?u.get(c.factId):void 0;return p&&u.write({subject:p.subject,attribute:p.attribute,value:d,source:"owner said",verifiedBy:o,volatility:p.volatility},{confirmedBy:o}),a.resolve(c.id,"answered",d),{ok:!0,message:`${e}: answered "${d}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var ca=3,la=7,da=50,dt=120,ua=280,lt=600,Qr=36e5,pa=24*Qr;function lp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function Y(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Ee=t=>new Date(t).toISOString();function ga(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:Y(e.title,dt),...e.ask?{ask:Y(e.ask,lt)}:{},...e.detail?{facts:Y(e.detail,ua)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var fa={done:"Done",declined:"Declined",dropped:"Dropped"};function eo(t,e,n){let{record:r,links:o}=e,s=q(r,dt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:Y(s.said,lt)}:{},agent:r.agentId,askedAt:Ee(r.createdAt),changedAt:Ee(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:Y(r.question,lt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),c=t.now-r.updatedAt<(t.quietHours??ca)*Qr;return{...i,column:a||c?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Ee(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:fa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ma(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function ha(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:Y(e.title,dt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ma(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var A=t=>t&&Date.parse(t)||0,Zr=(t,e)=>t.map(n=>n[e]).filter(n=>!!A(n)).sort((n,r)=>A(n)-A(r))[0];function ut(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(ga(o,s,o.node===t.node))}let r=to(t,e);for(let o of t.requests??[]){let s=eo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function to(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function dp(t){let e=ut(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=to(t,n),s=[],i=[],a=[];for(let p of t.requests??[]){let g=eo(t,p,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let c=t.now-(t.doneDays??la)*pa;for(let p of t.cards)p.status!=="pending"&&A(p.decided_at)>=c&&a.push(ha(t,p));s.sort((p,g)=>A(g.changedAt)-A(p.changedAt)),i.sort((p,g)=>A(p.changedAt)-A(g.changedAt)),a.sort((p,g)=>A(g.changedAt)-A(p.changedAt));let l=a.filter(p=>A(p.changedAt)>=c).slice(0,da),d=Zr(n,"askedAt"),u=Zr(i,"changedAt");return{ts:Ee(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...d?{oldest:d}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:l.length}},errors:r}}function ba(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function ya(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function fp(t,e){let n=t.now??Date.now(),r=[],o=Kr(t,{includeSnoozed:!0});for(let d of o.errors)r.push(`What waits (${d.kind}) could not be read: ${d.error}`);let s=o.items.filter(d=>!d.snoozed_until),i=new Set(o.items.filter(d=>d.snoozed_until).map(d=>d.key)),a=null;try{let d=B(t);d&&(a=d.listByState("waiting_owner").map(u=>({record:u,links:d.links(u.id)})))}catch(d){r.push(`Requests could not be read: ${d?.message??d}`)}let{cards:c,errors:l}=ut({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(ba)}],requests:a,deferred:i});return ya(c,i.size,[...r,...l])}import{readFileSync as wa}from"fs";var xa=1e4,no=/^[0-9a-f]{7,64}$/i;function bp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&no.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&no.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function yp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=wa(n.tokenFile,"utf-8").trim().split(`
67
+ told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},Cu=pn;var Br=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],Wi=280;function T(t,e=Wi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function G(t){if(t.configPath)return k(t.configPath);let e=[k(t.root,"agentx.json"),k(t.root,".agentx","config.json")];return e.find(n=>U(n))??e[0]}function F(t){return t.wikiDir?k(t.wikiDir):k(t.root,".agentx","wiki")}function ji(t){return K(t.root,"pending").map(qi)}function qi(t){return{key:`card:${t.id}`,kind:"card",title:t.title,ask:t.ask,yes:`tell ${t.raised_by} yes`,no:`tell ${t.raised_by} no`,recommend:t.recommend,if_silent:t.if_silent,expires:t.expires,...t.source?{source:t.source}:{},raised_by:t.raised_by,...t.node?{node:t.node}:{},created_at:t.created_at,...t.choices?{choices:t.choices,more:`agentx approvals popup card:${t.id}`}:{},...t.draft?{draft:t.draft}:{},...t.context||t.draft?{detail:T([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Bi(t){let e=G(t);if(!U(e))return[];let n;try{n=JSON.parse(ct(e,"utf-8"))}catch{return[]}let r=new Date(t.now??Date.now()),o=[];for(let[s,i]of Object.entries(n?.crons??{})){let a=i?.approval;if(!a||a.action!=="create"&&a.action!=="delete")continue;let c=i.timezone||"UTC",l=i.schedule?Dn(i.schedule):"",d=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",u=String(i.prompt??i.command??""),p=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:p?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:p?`Let ${i.agent??"the agent"} run this ${d}?`:`Remove the schedule "${s}" (${d})?`,yes:p?"enable it":"remove it",no:p?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:T(`${u}${p&&i.schedule?` \xB7 first run ${Nn(Cn(i.schedule,c,r),c)}`:""}`),more:"agentx schedule list"})}return o}function Hr(t){let e=k(t,".agentx","memory");return U(e)?Ui(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Hi(t){let e=Hr(t.root);if(e.length===0)return[];let n=new Ve(t.root),r=[];for(let o of e)for(let s of n.held(o))r.push({key:`memory:${o}/${s.id}`,kind:"memory",title:`Fact ${o} learned from ${s.source.channel}`,ask:`Let ${o} use this fact in its prompts?`,yes:"use it",no:"keep it out for good",raised_by:o,created_at:s.createdAt,detail:T(s.content),more:`agentx memory facts held --agent ${o}`});return r}function Vi(t){let e=t.sources.filter(n=>n.failure);return e.length?e.map(n=>`Recurring failure: ${n.agentId}'s ${n.failure.tool} fails with "${n.failure.errorClass}" in ${n.occurrences??1} sessions (${n.failure.runs} runs).`).join(" "):`${t.sources.length} source(s)${t.occurrences>1?`, seen in ${t.occurrences} sessions`:""}.`}function Xi(t){return Jn(F(t),"pending").map(e=>{let n=e.evidence;return{key:`wiki:${e.id}`,kind:"wiki",title:e.article.title,ask:e.replaces?`Update "${e.article.path}" in the shared wiki?`:`Add "${e.article.path}" to the shared wiki?`,yes:"write the article",no:"decline it",raised_by:n.agents.join(", ")||"wiki promote",created_at:e.createdAt,detail:T(`${Vi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var Fr=new Map;function Vr(t,e){let n=Fi(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=Fr.get(t);if(o?.version===r)return o.value;let s=e();return Fr.set(t,{version:r,value:s}),s}function zi(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${T(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:T(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function Ki(t,e){let n=F(t);if(!U(k(n,"_facts.json")))return;let r=ye(new z(n),"pending").find(o=>o.id===e);return r?zi(r):void 0}function Gi(t){let e=k(F(t),"_facts.json");if(!U(e))return;let n=Vr(e,()=>ye(new z(qr(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Yi(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function Xr(t){let e=F(t),n=new He(e);if(!U(n.path))return[];let r=Vr(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new z(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Yi(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Ji(t){return Rr(t.root,"pending").map(e=>({key:`whatsapp:${e.id}`,kind:"whatsapp",title:`WhatsApp reply to ${e.chat_name||e.to}`,ask:`Send this to ${e.chat_name||e.to}? "${e.text}"`,yes:"send it on WhatsApp",no:"drop the draft",raised_by:e.agent,created_at:e.created_at,detail:T(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Zi(t){return ar(t.root,"pending").map(e=>({key:`email:${e.id}`,kind:"email",title:`Email reply to ${e.to_name?`${e.to_name} <${e.to}>`:e.to}`,ask:`Send this reply to ${e.to}, subject "${e.subject}"?`,yes:"send the email",no:"drop the reply",raised_by:e.agent,created_at:e.created_at,draft:e.text,...e.error?{detail:T(`Last try not sent: ${e.error}`)}:{}}))}function Qi(t){let e=Object.entries(Xe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Se(t).agents??{};return e.map(([r,o])=>{let s=n[r]??{};return{key:`agent:${r}`,kind:"agent",title:`New agent "${s.name||r}", created by ${o.by}`,ask:`Let ${s.name||r} (${s.tier||"claude-code"}) start working?`,yes:"let it run",no:"remove it from agentx.json (its folder is kept)",raised_by:o.by,created_at:o.at,detail:T(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Se(t){try{return JSON.parse(ct(G(t),"utf-8"))}catch{return{}}}function at(t){let e={};try{e=Object.fromEntries(wn(ct(k(qr(G(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ea(t){let e=qn(t.root,"pending");if(e.length===0)return[];let n=Se(t),r=at(t);return e.map(o=>{let s=re[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:Or({config:n,env:r},o.agent,o.platform)?`post it on ${s}`:"save it ready to paste (no connector is set)",no:"drop the draft",raised_by:o.agent,created_at:o.created_at,detail:T(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:Wn(o.text)}})}function B(t){if(t.requests)return t.requests;if(k(t.root)!==process.cwd()||!U(k(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e)return null;let n=Wr.get(e);return!n&&!gn(e)?null:(n||Wr.set(e,n=new fn(e)),n)}var Wr=new WeakMap;function ip(t){if(t.plans)return t.plans;if(t.requests||k(t.root)!==process.cwd()||!U(k(t.root,".agentx","db.sqlite")))return null;let e=qe({quiet:!0});if(!e||!Ur(e))return null;let n=jr.get(e);return n||jr.set(e,n=new ve(e)),n}var jr=new WeakMap;function ta(t){let e=B(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:q(n,120).headline,ask:`Not finished. Ask ${n.agentId} to pick it up again?`,yes:`hand it back to ${n.agentId}`,no:"drop the request",raised_by:n.agentId,created_at:new Date(n.createdAt).toISOString(),detail:T(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var zr={card:ji,schedule:Bi,agent:Qi,memory:Hi,wiki:Xi,fact:()=>[],question:Xr,whatsapp:Ji,email:Zi,content:ea,request:ta};function na(t,e){let n=t.expires?Date.parse(t.expires):1/0,r=e.expires?Date.parse(e.expires):1/0;return n!==r?n-r:(Date.parse(t.created_at)||0)-(Date.parse(e.created_at)||0)}function Kr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=$(t.root),o=[],s=[],i=[],a=0;for(let c of e.kinds??Br){if(c==="fact"){try{let d=Gi(t);d&&i.push(d)}catch(d){s.push({kind:c,error:String(d?.message??d).slice(0,200)})}continue}let l;try{l=zr[c](t)}catch(d){s.push({kind:c,error:String(d?.message??d).slice(0,200)});continue}for(let d of l){let u=r[d.key];if(u&&Date.parse(u)>n){if(!e.includeSnoozed){a++;continue}d.snoozed_until=u}o.push(d)}}return o.sort(na),{items:o,snoozed:a,errors:s,backlog:i}}function Gr(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Br.includes(n)||!r?null:{kind:n,ref:r}}function ra(t,e,n){switch(e){case"card":return oe(t.root,n)?.status==="pending";case"wiki":return Yn(F(t),n)?.status==="pending";case"whatsapp":return ke(t.root,n)?.status==="pending";case"email":return ir(t.root,n)?.status==="pending";case"content":return jn(t.root,n)?.status==="pending";default:return!!Yr(t,e,n)}}function Yr(t,e,n){return e==="fact"?Ki(t,n):zr[e](t).find(r=>r.key===`${e}:${n}`)}async function Jr(t,e,n,r={}){let o=n==="later"?null:Gr(e),s;if(o)try{s=Yr(t,o.kind,o.ref)}catch{s=void 0}let i=await oa(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;nr(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function oa(t,e,n,r){let o=Gr(e);if(!o)return{ok:!1,error:`unknown item "${e}": use a key from \`agentx approvals list\``};let{kind:s,ref:i}=o,a=t.now??Date.now(),c=r.by??"operator";if(n==="later"){if(!ra(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let d=r.laterHours&&r.laterHours>0?r.laterHours:24,u=new Date(a+d*36e5);return xr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let d=sr(t.root,i,l?"yes":"no",{by:c,note:r.note,now:a,choice:r.choice,text:r.text});return d.ok?{ok:!0,message:`${e}: ${d.card.raised_by} will be told ${l?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(l?Ln:On)(i,{configPath:G(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Xe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ze(t.root,i,"approval"),{ok:!0,message:`${e}: approved. It runs once the daemon has loaded it; if it was added while the daemon was running, run: agentx daemon restart`};let d=[],u=await he(p=>{En(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:G(t),reload:t.reload});return u.success?(ze(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${d.length?`, with its schedules ${d.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:u.error||"could not remove it from agentx.json"}}case"memory":{let d=i.indexOf("/");if(d<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let u=i.slice(0,d),p=i.slice(d+1);if(!Hr(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Ve(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,l?"approved":"rejected",c),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${p}" isn't waiting for review`}}case"wiki":{let d=F(t),u=l?Zn(d,i,{by:c,force:r.force,now:a}):Qn(d,i,{by:c,reason:r.note,now:a});return u.ok?{ok:!0,message:l?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"fact":return sa(t,e,i,l,c,r);case"question":return aa(t,e,i,l,c,r);case"whatsapp":{let d=await Ir(t.root,i,l?"yes":"no",{by:c,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:l?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??lr(Se(t),at(t)),u=await cr(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:l?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??Pr({config:Se(t),env:at(t)}),u=await Bn(t.root,i,l?"yes":"no",{by:c,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let p=re[u.draft.platform];return{ok:!0,message:u.draft.status==="posted"?`${e}: posted on ${p}${u.draft.url?` (${u.draft.url})`:""}`:`${e}: no ${p} connector is set, so it is saved ready to paste: ${u.draft.file}`}}case"request":{let d=B(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?vr(G(t)).enabled?(d.requestPickup(i,a),{ok:!0,message:`${e}: ${u.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(d.close(i,"dropped",r.note?.trim()||`dropped by ${c}`,a),{ok:!0,message:`${e}: dropped`})}}}function sa(t,e,n,r,o,s){let i=new z(F(t));try{let a=ye(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return An(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let c=Tn(i,a.id,o);return{ok:!0,message:`${e}: ${c.write.fact.subject} \xB7 ${c.write.fact.attribute} recorded as "${c.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function ia(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function aa(t,e,n,r,o,s){let i=F(t),a=new He(i),c=a.list("open").find(l=>l.id===n);if(!c)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(xn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(c.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=Xr(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${c.id} "<value>"`};let d=ia(l.choices,s.choice);if(!d)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let u=new z(i),p=c.factId?u.get(c.factId):void 0;return p&&u.write({subject:p.subject,attribute:p.attribute,value:d,source:"owner said",verifiedBy:o,volatility:p.volatility},{confirmedBy:o}),a.resolve(c.id,"answered",d),{ok:!0,message:`${e}: answered "${d}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var ca=3,la=7,da=50,dt=120,ua=280,lt=600,Qr=36e5,pa=24*Qr;function lp(t){let e=new Set;for(let n of t)for(let r of n.runningTasks??[])r.traceId&&e.add(r.traceId);return e}function Y(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Ee=t=>new Date(t).toISOString();function ga(t,e,n){let r=e.key.slice(0,Math.max(0,e.key.indexOf(":")))||"card";return{key:e.key,kind:r,column:"yours",node:t.node,nodeName:t.nodeName,title:Y(e.title,dt),...e.ask?{ask:Y(e.ask,lt)}:{},...e.detail?{facts:Y(e.detail,ua)}:{},...e.recommend?{recommend:e.recommend}:{},...e.raisedBy?{agent:e.raisedBy}:{},...e.yes?{yes:e.yes}:{},...e.no?{no:e.no}:{},...e.choices?.length?{choices:e.choices}:{},...e.draft?{draft:e.draft}:{},...e.expires?{expires:e.expires}:{},...e.ifSilent?{ifSilent:e.ifSilent}:{},...e.createdAt?{askedAt:e.createdAt}:{},can:{answer:!0,later:!0,reply:n&&r==="request"}}}var fa={done:"Done",declined:"Declined",dropped:"Dropped"};function eo(t,e,n){let{record:r,links:o}=e,s=q(r,dt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:Y(s.said,lt)}:{},agent:r.agentId,askedAt:Ee(r.createdAt),changedAt:Ee(r.stateChangedAt??r.updatedAt)};switch(r.state){case"candidate":case"needs_attention":return null;case"waiting_owner":return o.some(a=>a.kind==="card"&&n.has(`card:${a.ref}`))?null:{...i,column:"yours",...r.question?{ask:Y(r.question,lt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),c=t.now-r.updatedAt<(t.quietHours??ca)*Qr;return{...i,column:a||c?"agent":"quiet",...a?{live:a}:{},can:{answer:!1,later:!1,reply:!a}}}default:{let a=r.state==="done"?r.evidence:r.closeReason;return{...i,need:void 0,column:"done",changedAt:Ee(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:fa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ma(t){return t.status==="decided"?t.verdict==="yes"?`Answered yes${t.choice?`: ${t.choice}`:""}`:"Answered no":t.status==="expired"?`No answer in time: ${t.outcome==="discard"?"discarded":t.outcome==="pause"?"paused":"kept"}`:"Closed by the agent"}function ha(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:Y(e.title,dt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ma(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var A=t=>t&&Date.parse(t)||0,Zr=(t,e)=>t.map(n=>n[e]).filter(n=>!!A(n)).sort((n,r)=>A(n)-A(r))[0];function ut(t){let e=[],n=[];for(let o of t.inbox){o.error&&n.push(`What waits on ${o.nodeName} could not be read: ${o.error}`);for(let s of o.items)e.push(ga(o,s,o.node===t.node))}let r=to(t,e);for(let o of t.requests??[]){let s=eo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function to(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function dp(t){let e=ut(t.owner?{...t,requests:null}:t),n=t.owner?[...t.owner.items,...e.cards]:e.cards,r=t.owner?[...t.owner.errors,...e.errors]:e.errors,o=to(t,n),s=[],i=[],a=[];for(let p of t.requests??[]){let g=eo(t,p,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let c=t.now-(t.doneDays??la)*pa;for(let p of t.cards)p.status!=="pending"&&A(p.decided_at)>=c&&a.push(ha(t,p));s.sort((p,g)=>A(g.changedAt)-A(p.changedAt)),i.sort((p,g)=>A(p.changedAt)-A(g.changedAt)),a.sort((p,g)=>A(g.changedAt)-A(p.changedAt));let l=a.filter(p=>A(p.changedAt)>=c).slice(0,da),d=Zr(n,"askedAt"),u=Zr(i,"changedAt");return{ts:Ee(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...d?{oldest:d}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...u?{oldest:u}:{}},done:{count:l.length}},errors:r}}function ba(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function ya(t,e,n){let r=t.map(o=>o.askedAt).filter(o=>!!o&&!!Date.parse(o)).sort((o,s)=>Date.parse(o)-Date.parse(s));return{count:t.length,later:e,...r[0]?{oldest:r[0]}:{},items:t,errors:n}}function fp(t,e){let n=t.now??Date.now(),r=[],o=Kr(t,{includeSnoozed:!0});for(let d of o.errors)r.push(`What waits (${d.kind}) could not be read: ${d.error}`);let s=o.items.filter(d=>!d.snoozed_until),i=new Set(o.items.filter(d=>d.snoozed_until).map(d=>d.key)),a=null;try{let d=B(t);d&&(a=d.listByState("waiting_owner").map(u=>({record:u,links:d.links(u.id)})))}catch(d){r.push(`Requests could not be read: ${d?.message??d}`)}let{cards:c,errors:l}=ut({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(ba)}],requests:a,deferred:i});return ya(c,i.size,[...r,...l])}import{readFileSync as wa}from"fs";var xa=1e4,no=/^[0-9a-f]{7,64}$/i;function bp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&no.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&no.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function yp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=wa(n.tokenFile,"utf-8").trim().split(`
68
68
  `)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var ro=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function xp(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/content"||t.startsWith("/content/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function kp(t){return t==="/reload"||t==="/api/processes/kill"||t==="/send"||t==="/send/agent"||t==="/send/contact"||t==="/mesh/announce"||t==="/events"||t==="/voice/settings"||t==="/voice/preview"||/^\/api\/tasks\/[^/]+\/(cancel|followup)$/.test(t)||/^\/mesh\/guests\/[^/]+\/(pause|resume|end|update)$/.test(t)||/^\/crons\/[^/]+\/enabled$/.test(t)||/^\/channels\/[^/]+\/switch$/.test(t)||/^\/workflow-runs\/[^/]+\/cancel$/.test(t)||t==="/api/signals/stop"||t==="/api/signals/resume"||t==="/api/signals/drop"||t==="/api/signals/stop-all"||t==="/api/signals/stop-all/report"||t==="/api/review-gate/replay"}function vp(t){return ro.has(t)}function Sp(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(ro.has(t.remoteAddress))return{allowed:!0,reason:"loopback"};if(t.acceptedTokens.size===0)return{allowed:!0,reason:"no-tokens-configured"};let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.acceptedTokens.has(n)?{allowed:!0,reason:"token"}:{allowed:!1,reason:"missing-or-invalid-token"}}function Ep(t,e=process.env){let n=new Set;e.MESH_TOKEN&&n.add(e.MESH_TOKEN);for(let r of t.mesh?.peers||[])r.token&&n.add(r.token);return n}function _p(t,e,n=process.env){let r=s=>s.replace(/\/+$/,"");return(e===r(t.daemonUrl)?t.token:t.daemons.find(s=>r(s.url)===e)?.token)||n.MESH_TOKEN||void 0}function _e(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function ka(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function va(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Tp(t,e=va()){let n=_e(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=ka(n),s=[_e(t.host),_e(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=_e(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Ap(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var pt="/api/admin/pictures",Sa=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ea=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function y(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function _a(t){let e={agent:{},person:{}};for(let n of Hn)for(let[r,o]of Object.entries(zn(t,n)))e[n][r]=Kn(n,r,o);return e}function Dp(t,e,n,r,o){let s=n.match(Sa);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return y(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=Gn(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":Vn,"Content-Length":String(a.length),"Cache-Control":"private, max-age=31536000, immutable","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'"}),e.end(a),!0):(y(e,404,{error:"no such picture"}),!0)}async function Cp(t,e,n,r){if(n!==pt&&!n.startsWith(`${pt}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===pt)return o!=="GET"?(y(e,405,{error:"GET only"}),!0):(y(e,200,{..._a(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ea);if(!s)return y(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return y(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return y(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],c=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!Xn.test(c)||!l.includes(c))return y(e,404,{error:a==="agent"?`no agent "${c}" in agentx.json`:`no person "${c}" in agentx.json`}),!0;if(o==="DELETE"){let d=Je(r.root,a,c);return y(e,200,{ok:!0,removed:d}),!0}try{let d=await Ze(t),u=await Ye(r.root,a,c,d);y(e,200,{ok:!0,url:u.url})}catch(d){if(d instanceof Ge)return y(e,d.status,{error:d.message}),!0;throw d}return!0}async function Np(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){y(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){y(e,403,{error:"Only an agent sets its own picture, from its own run: send X-AgentX-Task (or X-AgentX-Channel and X-AgentX-Chat) of a running turn. The owner sets pictures in Settings."});return}if(s&&s!==i){y(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){y(e,200,{ok:!0,agent:i,removed:Je(r.root,"agent",i)});return}try{let a=await Ye(r.root,"agent",i,await Ze(t));y(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof Ge){y(e,a.status,{error:a.message});return}throw a}}var oo={};function Pp(t){oo=t}function Mp(){return oo}var Up=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
69
69
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
70
70
  <link rel="preconnect" href="https://fonts.googleapis.com">
@@ -355,7 +355,7 @@ import{a as tt}from"./chunk-GTJIKXDB.js";import{H as er,O as dr,k as q}from"./ch
355
355
  <span class="name">${O(r.name)}</span>
356
356
  <span class="chev">\u25BE</span>
357
357
  <div class="ax-mesh-menu" role="menu">${o}</div>
358
- </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:fe,href:me},{id:"live",label:"Live",href:`${me}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:vn},{id:"people",label:"People",href:`${me}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:"/admin"}]}].map(l=>{let d=l.tabs.map(u=>{let p=u.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=u.external?' target="_blank" rel="noopener"':"",f=u.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${u.href}" class="${p}"${g}>${u.label}${f}</a>`}).join("");return`<div class="ax-topbar__group" title="${O(l.name)} tier"><span class="ax-topbar__group-label">${O(l.name)}</span>${d}</div>`}).join("");return`<header class="ax-topbar">
358
+ </div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:me,href:te},{id:"live",label:"Live",href:`${te}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:vn},{id:"people",label:"People",href:`${te}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${te}#page=settings`}]}].map(l=>{let d=l.tabs.map(u=>{let p=u.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=u.external?' target="_blank" rel="noopener"':"",f=u.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${u.href}" class="${p}"${g}>${u.label}${f}</a>`}).join("");return`<div class="ax-topbar__group" title="${O(l.name)} tier"><span class="ax-topbar__group-label">${O(l.name)}</span>${d}</div>`}).join("");return`<header class="ax-topbar">
359
359
  <div class="ax-topbar__left">
360
360
  <div class="ax-brand">
361
361
  <span class="ax-brand__mark">AX</span>
@@ -487,8 +487,8 @@ for (let i = 0; i < vs.count; i++) {
487
487
  out.join("\\n")`,Fa=new Set(["Fred","Kathy","Ralph","Junior"]),Wa={Flo:"female",Sandy:"female",Shelley:"female",Grandma:"female",Kathy:"female",Eddy:"male",Reed:"male",Rocko:"male",Grandpa:"male",Fred:"male",Ralph:"male",Junior:"male"};function ho(t){let e=[];for(let n of t.split(`
488
488
  `)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Fa.has(o)||e.push({id:r,name:o,locale:s,quality:i==="3"?"premium":i==="2"?"enhanced":"standard",gender:a==="1"?"male":a==="2"?"female":Wa[o]??null})}return e}var ja=10*60*1e3,Jp=60*1e3,J=null,bt=!1;function yt(t=Date.now(),e=ja){if(process.platform!=="darwin")return[];if(J)t-J.at>e&&!bt&&(bt=!0,Ma("osascript",["-l","JavaScript","-e",mo],{timeout:1e4},(n,r)=>{bt=!1,n||(J={at:Date.now(),voices:[...ho(String(r)),...Te()]})}));else try{J={at:t,voices:[...ho(Ua("osascript",["-l","JavaScript","-e",mo],{encoding:"utf8",timeout:1e4})),...Te()]}}catch(n){wt(`[voice] could not list system voices: ${String(n?.message??n).split(`
489
489
  `)[0]}`),J={at:t,voices:Te()}}return J.voices}var wt=t=>process.stderr.write(t+`
490
- `),Ae=new Set;function Zp(t){wt=t}function H(t,e){Ae.has(t)||(Ae.add(t),wt(e))}function wo(t){for(let e of Ae)t(e)&&Ae.delete(e)}var xo=()=>{};function Qp(t){xo=t}function ko(t){try{xo(t)}catch(e){H("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var qa={premium:3,enhanced:2,standard:1},Ba=new Set(["Grandma","Grandpa"]);function bo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Ba.has(t.name)?1:0;return qa[t.quality]*10+e}var Z=t=>t.toLowerCase().split(/[-_]/)[0],yo=t=>t.id.startsWith("com.apple.voice.");function xt(t,e,n,r=new Set){let o=se(t.filter(a=>!a.siri&&Z(a.locale)===Z(e)),e);if(o.some(yo)&&(o=o.filter(yo)),n==="female"||n==="male"){let a=o.filter(c=>c.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function se(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=Z(e),o=t.filter(s=>Z(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>bo(i)-bo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function ie(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(R)){let l=r.slice(R.length).trim().toLowerCase(),d=se(e.filter(p=>p.siri&&p.name.toLowerCase()===l),n)[0];if(d||!l)return d??null;let u=ie(l,e.filter(p=>Z(p.locale)===Z(n)),n);return u&&H(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=se(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function vo(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",c=a?i.gender:s,l=e.filter(u=>!o.has(u.name.toLowerCase())),d=l.find(u=>u.gender===c)??(a?e.find(u=>u.gender===c):void 0)??l[0]??e[r.size%e.length];r.set(i.id,d),o.add(d.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}cn();var kt="system",Ha=t=>t.trim().toLowerCase()===kt,Va="21m00Tcm4TlvDq8ikWAM";function vt(t,e,n={},r=yt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Et(e,n,r).get(t)??null,c=Ga(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?Ie(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Ja(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var Ie=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Xa(t,e,n,r){if(!e||!n.length)return null;let o=ie(e,n,r);return o||(H(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),ko(e)),o}function $o(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:ht(n.slice(R.length).trim())};let r=$e(n);return r?{locale:r.locale,gender:ht(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var To=t=>t.toLowerCase().split(/[-_]/)[0],So=(t,e)=>typeof t=="string"?t:t?.[To(e)];function Re(t,e,n,r){if(e!==void 0)return Ha(e)?null:Xa(t,e,n,r)??void 0}var St=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function za(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=Re("voice.system",So(e.system,o),n,o),c=()=>new Set([...r,...[...s.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=So(d.system,o),p=Re(d.id,u,n,o),g=p!==void 0?p:u!==void 0&&n.length?Ka(d,u,o,a,n,c()):a!==void 0&&St(a,d.gender)?a:void 0;g!==void 0?s.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let l=c();for(let[d,u]of vo(i,se(n.filter(p=>!p.siri),o),l))s.set(d,u);return s}function Ka(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let c=Re(`${t.id}.fallbacks`,a,o,n);if(c!==void 0)return c}if(r!==void 0&&St(r,t.gender))return r;let i=$o(e,n);return xt(o,i.locale,t.gender??i.gender,s)??void 0}function Ga(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[d,u]of Object.entries(c)){let p=Re(`${a}.${d}`,u,o,d);p===void 0&&o.length&&(p=xt(o,d,n??$o(u,d).gender)??void 0),p!==void 0&&l(p)&&(s[To(d)]=p)}};return i("voice.system",r.system,a=>St(a,n)),i(t,e,()=>!0),s}function og(t,e){let n=e?ge(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?Ie(r):null}}function Et(t,e={},n=yt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return za(r,e,n)}function _t(t,e){let n={provider:t.provider,elevenlabs:Ya(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Ya(t,e){return t||e||process.env.AGENTX_VOICE_ID||Va}function Ja(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var Za=8*60*60*1e3,Qa=500,Eo=class{constructor(e=Za){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(_o(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=_o(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>Qa&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},_o=(t,e)=>`${t}\0${e}`;function Ao(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function sg(t,e,n,r={}){let o=e[t],s=vt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:_t(s),persona:i||`You are ${s.name}.`,introLine:Ao(s,n)}}var ec="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function ig(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${ec}
491
- ${Ao(o,e.voice.introduce===!0&&!!r)}`}var cc="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Do=(t=sc())=>ac(t,".agentx","voice","health.json");function lc(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===kt)return!0;if(r.toLowerCase().startsWith(R)){let o=r.slice(R.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return ie(r,e,n)!==null}function dc(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function uc(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of dc(t)){if(lc(s,e,i))continue;r??=Et(t.agents,t.voice,e);let c=n.get(s)??{voice:s,agents:[],speaksWith:{}};c.agents.includes(o)||c.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(c.speaksWith[o]=l?Ie(l):"the OS default voice"),n.set(s,c)}return[...n.values()]}function $t(t){let e=$e(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(R)){let n=t.slice(R.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function pc(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${$t(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
490
+ `),Ae=new Set;function Zp(t){wt=t}function H(t,e){Ae.has(t)||(Ae.add(t),wt(e))}function wo(t){for(let e of Ae)t(e)&&Ae.delete(e)}var xo=()=>{};function Qp(t){xo=t}function ko(t){try{xo(t)}catch(e){H("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var qa={premium:3,enhanced:2,standard:1},Ba=new Set(["Grandma","Grandpa"]);function bo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Ba.has(t.name)?1:0;return qa[t.quality]*10+e}var Z=t=>t.toLowerCase().split(/[-_]/)[0],yo=t=>t.id.startsWith("com.apple.voice.");function xt(t,e,n,r=new Set){let o=ie(t.filter(a=>!a.siri&&Z(a.locale)===Z(e)),e);if(o.some(yo)&&(o=o.filter(yo)),n==="female"||n==="male"){let a=o.filter(c=>c.gender===n);a.length&&(o=a)}if(!o.length)return null;let s=o.filter(a=>a.quality===o[0].quality),i=new Set([...r].map(a=>a.toLowerCase()));return s.find(a=>!i.has(a.name.toLowerCase()))??s[0]}function ie(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=Z(e),o=t.filter(s=>Z(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>bo(i)-bo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function ae(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(R)){let l=r.slice(R.length).trim().toLowerCase(),d=ie(e.filter(p=>p.siri&&p.name.toLowerCase()===l),n)[0];if(d||!l)return d??null;let u=ae(l,e.filter(p=>Z(p.locale)===Z(n)),n);return u&&H(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ie(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function vo(t,e,n=new Set){let r=new Map;if(!e.length)return r;let o=new Set([...n].map(i=>i.toLowerCase())),s="female";for(let i of t){let a=i.gender==="female"||i.gender==="male",c=a?i.gender:s,l=e.filter(u=>!o.has(u.name.toLowerCase())),d=l.find(u=>u.gender===c)??(a?e.find(u=>u.gender===c):void 0)??l[0]??e[r.size%e.length];r.set(i.id,d),o.add(d.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}cn();var kt="system",Ha=t=>t.trim().toLowerCase()===kt,Va="21m00Tcm4TlvDq8ikWAM";function vt(t,e,n={},r=yt()){let o=e[t],s=o?.name||t,i=o?.voice,a=Et(e,n,r).get(t)??null,c=Ga(t,i?.system,i?.gender,n,r);return{agentId:t,name:s,provider:i?.provider??n.provider??"system",elevenlabsVoiceId:i?.elevenlabsVoiceId||null,systemVoice:a?.id??null,systemVoiceName:a?Ie(a):null,systemByLanguage:c,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Ja(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var Ie=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Xa(t,e,n,r){if(!e||!n.length)return null;let o=ae(e,n,r);return o||(H(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),ko(e)),o}function $o(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:ht(n.slice(R.length).trim())};let r=$e(n);return r?{locale:r.locale,gender:ht(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var To=t=>t.toLowerCase().split(/[-_]/)[0],So=(t,e)=>typeof t=="string"?t:t?.[To(e)];function Re(t,e,n,r){if(e!==void 0)return Ha(e)?null:Xa(t,e,n,r)??void 0}var St=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function za(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=Re("voice.system",So(e.system,o),n,o),c=()=>new Set([...r,...[...s.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=So(d.system,o),p=Re(d.id,u,n,o),g=p!==void 0?p:u!==void 0&&n.length?Ka(d,u,o,a,n,c()):a!==void 0&&St(a,d.gender)?a:void 0;g!==void 0?s.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let l=c();for(let[d,u]of vo(i,ie(n.filter(p=>!p.siri),o),l))s.set(d,u);return s}function Ka(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let c=Re(`${t.id}.fallbacks`,a,o,n);if(c!==void 0)return c}if(r!==void 0&&St(r,t.gender))return r;let i=$o(e,n);return xt(o,i.locale,t.gender??i.gender,s)??void 0}function Ga(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,c,l)=>{if(!(!c||typeof c=="string"))for(let[d,u]of Object.entries(c)){let p=Re(`${a}.${d}`,u,o,d);p===void 0&&o.length&&(p=xt(o,d,n??$o(u,d).gender)??void 0),p!==void 0&&l(p)&&(s[To(d)]=p)}};return i("voice.system",r.system,a=>St(a,n)),i(t,e,()=>!0),s}function og(t,e){let n=e?fe(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?Ie(r):null}}function Et(t,e={},n=yt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return za(r,e,n)}function _t(t,e){let n={provider:t.provider,elevenlabs:Ya(e,t.elevenlabsVoiceId),system:t.systemVoice,fallback:t.fallback},r=Object.entries(t.systemByLanguage??{});return r.length&&(n.languages=Object.fromEntries(r.map(([o,s])=>[o,s?.id??null]))),t.rate&&t.rate!==1&&(n.rate=t.rate),t.priority&&t.priority!=="normal"&&(n.priority=t.priority),n}function Ya(t,e){return t||e||process.env.AGENTX_VOICE_ID||Va}function Ja(t,e){let n=(e??"").split(/(?<=\.)\s/)[0]??"",r=/^You are (.+?)\.?$/i.exec(n.trim());if(!r)return`Hello, this is ${t}.`;let o=r[1].replace(/\s*\([^)]*\)/g,"").trim(),[s,...i]=o.split(/,\s*/),a=i.join(", ");return a&&s.toLowerCase()===t.toLowerCase()?`Hello, this is ${t}, ${a}.`:!/^an? /i.test(o)&&o.toLowerCase().includes(t.toLowerCase())?`Hello, this is ${o}.`:`Hello, this is ${t}, ${o}.`}var Za=8*60*60*1e3,Qa=500,Eo=class{constructor(e=Za){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(_o(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=_o(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>Qa&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},_o=(t,e)=>`${t}\0${e}`;function Ao(t,e){let n=t.style?` Your speaking manner: ${t.style}.`:"";return e?`[VOICE INTRO] This is your first spoken exchange with this person in a while. Open with one short sentence introducing yourself in your own manner, along the lines of "${t.intro}", then answer.${n}`:"[VOICE CASUAL] You have already introduced yourself in this voice conversation. Do not introduce yourself or greet again; talk casually, like a colleague in the same office."+n}function sg(t,e,n,r={}){let o=e[t],s=vt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:_t(s),persona:i||`You are ${s.name}.`,introLine:Ao(s,n)}}var ec="[VOICE MODE] This question arrived by voice and your reply will be spoken aloud by a TTS engine. Answer in two or three short sentences. Plain language, no markdown, no code blocks, no bullet points, no URLs. Speak conversationally.";function ig(t){let e=t;if(e?.channel!=="voice"||!e.voice||typeof e.voice!="object")return;let n=s=>typeof s=="string"?s.replace(/\s+/g," ").slice(0,200):"",r=n(e.voice.intro),o={agentId:"",name:"",provider:"system",elevenlabsVoiceId:null,systemVoice:null,systemVoiceName:null,systemByLanguage:{},fallback:!0,gender:null,style:n(e.voice.style)||null,intro:r||"Hello."};return`${ec}
491
+ ${Ao(o,e.voice.introduce===!0&&!!r)}`}var cc="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Do=(t=sc())=>ac(t,".agentx","voice","health.json");function lc(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===kt)return!0;if(r.toLowerCase().startsWith(R)){let o=r.slice(R.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return ae(r,e,n)!==null}function dc(t){let e=t.voice?.locale??"en",n=[],r=(o,s)=>{if(typeof s=="string")n.push({owner:o,name:s,locale:e,perLanguage:!1});else for(let[i,a]of Object.entries(s??{}))n.push({owner:o,name:a,locale:i,perLanguage:!0})};r("voice.system",t.voice?.system);for(let[o,s]of Object.entries(t.agents))(s.voice?.provider??t.voice?.provider??"system")!=="system"&&t.voice?.fallback==="none"||r(o,s.voice?.system);return n}function uc(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of dc(t)){if(lc(s,e,i))continue;r??=Et(t.agents,t.voice,e);let c=n.get(s)??{voice:s,agents:[],speaksWith:{}};c.agents.includes(o)||c.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(c.speaksWith[o]=l?Ie(l):"the OS default voice"),n.set(s,c)}return[...n.values()]}function $t(t){let e=$e(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(R)){let n=t.slice(R.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function pc(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${$t(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
492
492
  `)}
493
493
  Reinstall in ${cc}. Agents switch back on their own once it is installed.`}}function gc(t=Do()){if(!Io(t))return null;try{let e=JSON.parse(nc(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function fc(t,e){tc(ic(t),{recursive:!0}),oc(`${t}.tmp`,JSON.stringify(e,null,2)+`
494
494
  `),rc(`${t}.tmp`,t)}var Ro=class{constructor(e){this.deps=e}running=!1;missingNow=!1;hasMissing(){return this.missingNow}async check(e,n,r=new Date){if(this.running||!n.length)return null;this.running=!0;try{let o=this.deps.file??Do(),s=new Map((gc(o)?.missing??[]).map(u=>[u.voice,u])),i=uc(e,n),a=i.map(u=>({...u,since:s.get(u.voice)?.since??r.toISOString(),...s.get(u.voice)?.notifiedAt?{notifiedAt:s.get(u.voice).notifiedAt}:{}})),c=[...s.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of c)this.deps.log(`[voice] ${$t(u)} is installed again; its agents speak with it again`);c.length&&wo(u=>c.some(p=>u===p||u.endsWith(`:${p}`)));let l=a.filter(u=>!u.notifiedAt);if(l.length){let{title:u,message:p}=pc(l);try{await this.deps.notify(u,p);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>$t(g.voice)).join(", ")} not installed`)}catch(g){this.deps.log(`[voice] could not send the missing-voice notice: ${g?.message??g}`)}}this.missingNow=a.length>0;let d={checkedAt:r.toISOString(),missing:a};return(!Io(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&fc(o,d),d}finally{this.running=!1}}};import{randomBytes as Co}from"crypto";var V={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:L.perMessage},mc=/^[a-f0-9]{32}$/,hc=/^c[a-z0-9]{8,32}$/,bc=/^#[0-9a-fA-F]{6}$/;function Tt(t){return hc.test(t)}var No=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
@@ -516,7 +516,7 @@ Reinstall in ${cc}. Agents switch back on their own once it is installed.`}}func
516
516
  WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
517
517
  ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>V.content?r.content.slice(0,V.content)+`
518
518
 
519
- [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,V.toolsPerMessage),c=[];for(let p of o){if(c.length>=V.filesPerMessage)break;let g=p.filename.trim(),f=te(g);if(!f||!g||g.length>L.pathChars||g.includes("\0"))continue;let m=(g.split(/[\\/]/).pop()||g).slice(0,120);c.push({id:Co(16).toString("hex"),name:m,mime:f.mime,kind:f.kind,path:g})}let l=c.map(p=>({id:p.id,name:p.name,mime:p.mime,kind:p.kind})),d=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
519
+ [Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,V.toolsPerMessage),c=[];for(let p of o){if(c.length>=V.filesPerMessage)break;let g=p.filename.trim(),f=ne(g);if(!f||!g||g.length>L.pathChars||g.includes("\0"))continue;let m=(g.split(/[\\/]/).pop()||g).slice(0,120);c.push({id:Co(16).toString("hex"),name:m,mime:f.mime,kind:f.kind,path:g})}let l=c.map(p=>({id:p.id,name:p.name,mime:p.mime,kind:p.kind})),d=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
520
520
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),u=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
521
521
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let p of c)u.run(p.id,n,Number(d.lastInsertRowid),p.path,p.name,p.mime,p.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
522
522
  (SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,V.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
@@ -570,13 +570,13 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
570
570
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
571
571
  ORDER BY at DESC LIMIT 500`).all(this.now()-ol)}seenByRequest(e,n){return this.byRequest(e,r=>this.seen(r,n))}answeredByRequest(e,n,r=this.now()){return this.byRequest(e,o=>this.answered(o,n,r),r)}seenPush(e,n="phone"){let r=[],o=this.db.prepare("SELECT id, title FROM owner_told WHERE channel = 'push' AND outcome IN ('sent', 'held') AND at BETWEEN ? AND ? ORDER BY at DESC");for(let s of e){let i=s.title.endsWith("\u2026")?s.title.slice(0,-1):s.title,c=o.all(s.at-sl,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));c&&r.push(c.id)}return this.seen(r,n)}seen(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET seen_at = ?, seen_via = ?
572
572
  WHERE seen_at IS NULL AND (${Jo(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
573
- WHERE answered_at IS NULL AND (${Jo(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function Jo(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function ef(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=ae(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function ae(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function al(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function cl(t){return ae(t)==="push"?["phone","desk"]:[t]}function tf(t,e,n){let r=t.filter(s=>n(ae(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>cl(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function ll(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(ae(s)))??null}var dl=3;async function nf(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*Oe,i=e.prepare(`SELECT id FROM owner_told
573
+ WHERE answered_at IS NULL AND (${Jo(e)})`).run(r,n,r,n,...e,...e,...e).changes:0}byRequest(e,n,r=1/0){let o=new Set(e.filter(Boolean));if(!o.size)return 0;let s=this.openRequestRows().filter(i=>o.has(i.requestId)&&i.at<=r).map(i=>i.id);return n(s)}};function Jo(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function ef(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=ce(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function ce(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function al(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function cl(t){return ce(t)==="push"?["phone","desk"]:[t]}function tf(t,e,n){let r=t.filter(s=>n(ce(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>cl(s).includes(a.surface)).map(a=>a.at));Number.isFinite(i)&&(!o||i>o.at)&&(o={stop:s,at:i})}return o?.stop??r[0]}function ll(t,e,n){let r=t.indexOf(e);return(r<0?t:[...t.slice(r+1),...t.slice(0,r)]).find(s=>s!==e&&n(ce(s)))??null}var dl=3;async function nf(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*Oe,i=e.prepare(`SELECT id FROM owner_told
574
574
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
575
575
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
576
576
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
577
577
  ORDER BY at LIMIT 20`).all(Math.max(o-dl*s,o-rl),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),c=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let d=n.get(l);if(!d)continue;let u=`${d.channel}:${d.chatId}`,p=ll(t.stops,u,t.up);if(!p){t.log(`[reach] urgent "${d.title.slice(0,80)}" ${d.outcome==="failed"?"failed":"unseen"} on ${u}; no other address to try`);continue}let g=Math.round((o-d.at)/Oe),f=d.outcome==="failed"?`it could not be sent on ${d.channel}`:`not seen on ${d.channel} for ${g} min`,m=`${d.text?`${d.text}
578
578
 
579
- `:""}(Sent again here: ${f}.)`,h=n.add({at:o,key:d.key,requestId:d.requestId,kind:d.kind,channel:ae(p),chatId:al(p),from:d.from,title:d.title,text:m,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,m),c++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(x){n.setOutcome(h,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${x?.message??x}`)}}return c}var Zo=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var ul={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},es=class{constructor(e=ul,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},pl="That code didn't work. Check it, or run agentx app pair for a new one.",gl=400;async function sf(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await tr(t,1024)).code}catch{}let a=e.codes.redeem(i),c=a?e.verify(a.token):null;return await fl(n,e.minMs??gl),!a||!c?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:pl}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${c}) from ${o}`),{status:200,body:{device:c},token:a.token})}async function fl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Dl}from"child_process";import{mkdtempSync as El,rmSync as _l,writeFileSync as $l}from"fs";import{tmpdir as Tl}from"os";import{join as ss}from"path";import{randomBytes as ml}from"crypto";function E(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var P={top:8,side:32,bottom:60},Ft={height:56,keep:52},ts=`
579
+ `:""}(Sent again here: ${f}.)`,h=n.add({at:o,key:d.key,requestId:d.requestId,kind:d.kind,channel:ce(p),chatId:al(p),from:d.from,title:d.title,text:m,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,m),c++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch(x){n.setOutcome(h,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${x?.message??x}`)}}return c}var Zo=class{constructor(e){this.opts=e}state=new Map;tick(){let e=(this.opts.now??Date.now)(),n=this.opts.confirmChecks??2;for(let[r,o]of Object.entries(this.opts.read())){let s=this.state.get(r)??{downSince:null,checks:0,told:!1};if(o.up){s.downSince!==null&&this.opts.log(`[reach] channel ${r} is up again`),this.state.set(r,{downSince:null,checks:0,told:!1});continue}s.downSince??=e,s.checks++,s.reason=o.reason,!s.told&&s.checks>=n&&(s.told=!0,this.opts.log(`[reach] channel ${r} is down: ${o.reason??"no reason given"}`),this.opts.notice(r,o.reason??"no reason given")),this.state.set(r,s)}}downSince(e){return this.state.get(e)?.downSince??void 0}};var ul={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},es=class{constructor(e=ul,n=Date.now){this.opts=e;this.now=n}clients=new Map;all={failures:[],lockedUntil:0};retryAfter(e){let n=this.now(),r=Math.max(this.all.lockedUntil,this.clients.get(e)?.lockedUntil??0);return r>n?Math.ceil((r-n)/1e3):0}fail(e){let n=this.clients.get(e);n||this.clients.set(e,n={failures:[],lockedUntil:0}),this.bump(n,this.opts.perClient),this.bump(this.all,this.opts.global)}succeed(e){this.clients.delete(e)}bump(e,n){let r=this.now();e.failures=e.failures.filter(o=>r-o<this.opts.windowMs),e.failures.push(r),e.failures.length>=n&&(e.lockedUntil=r+this.opts.lockoutMs)}},pl="That code didn't work. Check it, or run agentx app pair for a new one.",gl=400;async function sf(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await tr(t,1024)).code}catch{}let a=e.codes.redeem(i),c=a?e.verify(a.token):null;return await fl(n,e.minMs??gl),!a||!c?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:pl}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${c}) from ${o}`),{status:200,body:{device:c},token:a.token})}async function fl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Dl}from"child_process";import{mkdtempSync as El,rmSync as _l,writeFileSync as $l}from"fs";import{tmpdir as Tl}from"os";import{join as ss}from"path";import{randomBytes as ml}from"crypto";function E(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var P={top:8,side:32,bottom:60},Ft={height:56,keep:52},ts=`
580
580
  :root {
581
581
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
582
582
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -723,7 +723,7 @@ ${l?`<div class="options" role="radiogroup">${l}</div>`:""}
723
723
  ${c.why?`<p class="why" dir="auto">${E(c.why)}</p>`:""}
724
724
  ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><span class="edited"><i class="dot"></i>Edited</span><button class="reset" id="reset">Reset</button></div>
725
725
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
726
- <div class="notes"><div>${xl}<span>${a?`It stays on the ${fe} until you close it.`:`If you don't answer by ${E(bl(t.expires,n))}: ${E(t.if_silent)}.`}</span></div>
726
+ <div class="notes"><div>${xl}<span>${a?`It stays on the ${me} until you close it.`:`If you don't answer by ${E(bl(t.expires,n))}: ${E(t.if_silent)}.`}</span></div>
727
727
  <div>${vl}<span>Nothing goes out until you click.</span></div></div>
728
728
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
729
729
  <button class="btn" id="no">${a?"Drop":"No"}</button>
@@ -905,9 +905,9 @@ function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
905
905
 
906
906
  Message (edit it if you like):`:`${qt(t)}
907
907
 
908
- Message (edit it if you like):`,u=await n("/usr/bin/osascript",ds(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,Un(t.draft,i)),o),p=u.ok?us(u.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",ds(s,qt(t),["Not now","No","Yes"],r),o),c=a.ok?us(a.stdout):null;return c?.button==="Yes"?{action:"yes"}:c?.button==="No"?{action:"no"}:{action:"dismiss"}}var Vt=24*36e5,Bt=!1,Pl=10*6e4,fs=-1/0;function ms(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=$(t.root),a=s?Date.parse(s):NaN,c=K(t.root,"pending").filter(d=>Date.parse(d.expires)>n),l=c.find(d=>i.includes(`card:${d.id}`));if(l)return l;for(let d of c){let u=`card:${d.id}`;if(r[u]||!e(d)||dr(t.root,d.id,n))continue;let p=o[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(d.created_at);if(!(n-g>Vt&&!(g<=a)))return d}return null}function Ht(t){try{return B(t)?.listByState("needs_attention")??[]}catch{return[]}}var hs=new Map;function Ml(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=$(t.root);return e({})?Ht(t).find(s=>{let i=`request:${s.id}`,a=o[i];return hs.get(s.id)===q(s,Qe.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=Vt})??null:null}function Ul(t,e){return{id:t.id,title:q(t,Qe.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+Vt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Uf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(Bt)return"busy";let o=ms(e,t.reaches)?null:Ml(e,t.reaches),s=o?Ul(o,e.now??Date.now()):ms(e,t.reaches);if(!s)return"none";let i=(t.focus??zo)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,c=($(e.root).wanted??[]).includes(a)?null:rr(s);if(c){if(o)hs.set(o.id,s.title);else{let l=[...K(e.root,"pending").map(d=>`card:${d.id}`),...Ht(e).map(d=>`request:${d.id}`)];rt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${c}`),t.returnToAuthor?.(s,or(s,c)),"returned"}Bt=!0;try{let l=[...K(e.root,"pending").map(h=>`card:${h.id}`),...Ht(e).map(h=>`request:${h.id}`)];rt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let d=e.now??Date.now(),u=!!o&&d-fs<Pl;o&&n.speak&&(fs=d);let p=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??gs)(s,u?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${In(i)} when shown)`),"shown";if(!(o?B(e)?.get(o.id)?.state==="needs_attention":re(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Jr(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{Bt=!1}}function Ff(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?re(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(kr(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as Fl,mkdirSync as Wl,readFileSync as jl,renameSync as ql,writeFileSync as Bl}from"fs";import{dirname as Hl,resolve as Vl}from"path";var Xl=["all","urgent","off"],zl=24*36e5,bs=24*36e5,Kl=30*24*36e5,ys=t=>Xl.includes(t);function Bf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:ys(e)?e:"off",computer:ys(n)?n:t.popupEnabled?"all":"off"}}function xs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=zl}function ws(t,e,n){return t==="all"||t==="urgent"&&xs(e,n)}function ks(t){return Vl(t,".agentx","desk-routed.json")}function Gl(t){let e=ks(t);if(!Fl(e))return null;try{let n=JSON.parse(jl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Xt(t,e){let n=ks(t);Wl(Hl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Bl(r,JSON.stringify(e,null,2)),ql(r,n)}async function Hf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),c=Gl(e);if(!c){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Xt(e,{items:u}),i.primed=!0,i}let l=[],d=[];for(let u of r.items){let p=c.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>bs&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}c.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=bs&&l.push(u)}for(let[u,p]of Object.entries(c.items))n-Date.parse(p.seen)>Kl&&delete c.items[u];Xt(e,c);for(let u of l)if(ws(o.phone,u,n))try{await t.phone(u,xs(u,n)),i.phone.push(u.key)}catch(p){s(`[desk] ${u.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let u=!1;for(let p of[...d,...l]){let g=c.items[p.key];if(!ws(o.computer,p,n)){g.computerHeld&&(delete g.computerHeld,u=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,u=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,u=!0)}catch(f){s(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,u=!0)}}u&&Xt(e,c)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Vf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
909
- Answer it on the Desk.`}}import{closeSync as ce,createReadStream as Yl,fstatSync as Jl,openSync as Zl,realpathSync as vs}from"fs";import{isAbsolute as Ql,resolve as Ss,sep as Es}from"path";var Jf="/app-files",ed=/^[A-Za-z0-9_.:-]{1,64}$/;function td(t,e,n=process.cwd()){if(!e||e.length>L.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${Ke}/ first`};if(!te(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=vs(Ss(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=vs(Ql(e)?e:Ss(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Es))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Ke}/ first`};let s=te(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function nd(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function rd(t,e,n){return{"Content-Type":t,"Content-Disposition":nd(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function od(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Zf(t,e,n,r){let o=(x,N)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(N))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!ed.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let c=td(a,i,r.cwd);if(!c.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${c.error}`),o(c.status,{error:c.error});let l;try{l=Zl(c.path,"r")}catch{return o(404,{error:"file not found"})}let d;try{let x=Jl(l);if(!x.isFile())return ce(l),o(404,{error:"not a file"});d=x.size}catch{return ce(l),o(404,{error:"file not found"})}if(d>L.bytes)return ce(l),o(413,{error:`the file is larger than ${L.bytes/1024/1024} MB`});let u=c.path.split(Es).pop()||"file",p=rd(c.mime,u,c.kind),g=od(t.headers.range,d);if(g==="unsatisfiable"){ce(l),e.writeHead(416,{...p,"Content-Range":`bytes */${d}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:d-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(d?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${d}`}:{}}),t.method==="HEAD"||d===0){ce(l),e.end();return}let h=Yl("",{fd:l,start:f,end:m,autoClose:!0});h.on("error",()=>e.destroy()),e.on("close",()=>h.destroy()),h.pipe(e)}import{spawn as le}from"child_process";import{readFileSync as sd,writeFileSync as id}from"fs";import{tmpdir as ad}from"os";import{join as cd}from"path";cn();var _s=t=>t&&t!==1?Math.round(175*t):null,Pe=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function ld(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=sd(t,"utf8").trim();if(e)return e}catch{}return null}function am(t=ld()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Pe(n.voice.rate)?{voice_settings:{speed:Pe(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=cd(ad(),`agentx-say-${process.pid}-${++e}.mp3`);return id(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return H(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function $s(t,e){let n=t.languages&&ge(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var dd=(t,e="")=>{let n=$s(t,e),r=_s(t.rate);return[...n&&!uo(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function ud(t,e,n){if(!n)return["say",dd(t,e)];let r=$s(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function cm(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function lm(t=zt()){if(t)try{le("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function dm(t=zt()){if(t)try{le("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function zt(t={},e){if(!mt(t))return null;try{return fo(e)}catch(n){return H("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
910
- `)[0]}); Siri voices will not switch`),null}}var um=(t,e)=>{if(!t){let[n,r]=ud(e.voice,e.text,zt()),o=_s(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=le(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?le("afplay",[t],{stdio:"ignore"}):le("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Ts}from"child_process";import{accessSync as pd,constants as gd,readFileSync as As}from"fs";import{homedir as fd}from"os";import{basename as Q,delimiter as Rs,dirname as md,extname as hd,join as Kt}from"path";var j={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Is(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>j.ms+2e3?{status:413,error:Yt()}:null}var Yt=()=>`The recording is longer than ${j.ms/6e4} minutes.`,bd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function Ds(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return bd[e]??null}function Cs(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Jt(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function Gt(t,e,n=process.env.PATH??""){let r=fd(),o=[Kt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Rs).filter(Boolean)];for(let s of[e,...o.map(i=>Kt(i,t))])if(s)try{return pd(s,gd.X_OK),s}catch{}return null}function bm(t){return{key:t,mlx:Gt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Gt("whisper",process.env.AGENTX_WHISPER),ffmpeg:yd()}}var yd=()=>Gt("ffmpeg",process.env.AGENTX_FFMPEG);async function Ns(t,e){return e?wd(t,e):null}async function wd(t,e){let n=String(j.ms/1e3+5);try{let o=[...(await xd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function Ls(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([As(t)],{type:e}),Q(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Os(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${md(r)}${Rs}${process.env.PATH??""}`};await kd(e,s,12e4,i);try{return As(Kt(o,Q(n,hd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function xd(t,e,n){return new Promise((r,o)=>{let s=Ts(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${Q(t)} took too long`))},n);s.stderr.on("data",c=>{i=(i+c).slice(-8192)}),s.on("error",c=>{clearTimeout(a),o(c)}),s.on("exit",c=>{clearTimeout(a),c===0?r(i):o(new Error(`${Q(t)} exited ${c}`))})})}function kd(t,e,n,r=process.env){return new Promise((o,s)=>{let i=Ts(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",c="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${Q(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{c.length<4096&&(c+=d)}),i.on("error",d=>{clearTimeout(l),s(d)}),i.on("exit",d=>{clearTimeout(l),d===0?o(a):s(new Error(`${Q(t)} exited ${d}: ${c.trim().split(`
908
+ Message (edit it if you like):`,u=await n("/usr/bin/osascript",ds(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,Un(t.draft,i)),o),p=u.ok?us(u.stdout):null;if(p?.button==="Send"){let g=p.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return p?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",ds(s,qt(t),["Not now","No","Yes"],r),o),c=a.ok?us(a.stdout):null;return c?.button==="Yes"?{action:"yes"}:c?.button==="No"?{action:"no"}:{action:"dismiss"}}var Vt=24*36e5,Bt=!1,Pl=10*6e4,fs=-1/0;function ms(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=$(t.root),a=s?Date.parse(s):NaN,c=K(t.root,"pending").filter(d=>Date.parse(d.expires)>n),l=c.find(d=>i.includes(`card:${d.id}`));if(l)return l;for(let d of c){let u=`card:${d.id}`;if(r[u]||!e(d)||dr(t.root,d.id,n))continue;let p=o[u];if(p&&Date.parse(p)>n)continue;let g=Date.parse(d.created_at);if(!(n-g>Vt&&!(g<=a)))return d}return null}function Ht(t){try{return B(t)?.listByState("needs_attention")??[]}catch{return[]}}var hs=new Map;function Ml(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=$(t.root);return e({})?Ht(t).find(s=>{let i=`request:${s.id}`,a=o[i];return hs.get(s.id)===q(s,Qe.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=Vt})??null:null}function Ul(t,e){return{id:t.id,title:q(t,Qe.title).headline,context:t.attentionReason??"It is not finished and nothing is retrying it.",ask:`Hand it back to ${t.agentId}, or drop it?`,say:"A request you made is not finished.",recommend:"",if_silent:"keep",expires:new Date(e+Vt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Uf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(Bt)return"busy";let o=ms(e,t.reaches)?null:Ml(e,t.reaches),s=o?Ul(o,e.now??Date.now()):ms(e,t.reaches);if(!s)return"none";let i=(t.focus??zo)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,c=($(e.root).wanted??[]).includes(a)?null:rr(s);if(c){if(o)hs.set(o.id,s.title);else{let l=[...K(e.root,"pending").map(d=>`card:${d.id}`),...Ht(e).map(d=>`request:${d.id}`)];rt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${c}`),t.returnToAuthor?.(s,or(s,c)),"returned"}Bt=!0;try{let l=[...K(e.root,"pending").map(h=>`card:${h.id}`),...Ht(e).map(h=>`request:${h.id}`)];rt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let d=e.now??Date.now(),u=!!o&&d-fs<Pl;o&&n.speak&&(fs=d);let p=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??gs)(s,u?{...n,speak:!1}:n,{from:p,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${In(i)} when shown)`),"shown";if(!(o?B(e)?.get(o.id)?.state==="needs_attention":oe(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Jr(e,a,g.action,{by:"operator (popup)",...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(m.ok?`[approvals] popup: ${m.message}`:`[approvals] popup: ${a} not recorded: ${m.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{Bt=!1}}function Ff(t,e,n){if(!n)return{ok:!1,error:"the Mac popup is off; turn it on with `agentx approvals settings --popup on`"};let r=e.startsWith("card:")?oe(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(kr(t.root,e),{ok:!0,message:`${e} will show on the Mac within a minute`}):{ok:!1,error:`no card "${e}"; the popup shows decision cards only`}}import{existsSync as Fl,mkdirSync as Wl,readFileSync as jl,renameSync as ql,writeFileSync as Bl}from"fs";import{dirname as Hl,resolve as Vl}from"path";var Xl=["all","urgent","off"],zl=24*36e5,bs=24*36e5,Kl=30*24*36e5,ys=t=>Xl.includes(t);function Bf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:ys(e)?e:"off",computer:ys(n)?n:t.popupEnabled?"all":"off"}}function xs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=zl}function ws(t,e,n){return t==="all"||t==="urgent"&&xs(e,n)}function ks(t){return Vl(t,".agentx","desk-routed.json")}function Gl(t){let e=ks(t);if(!Fl(e))return null;try{let n=JSON.parse(jl(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Xt(t,e){let n=ks(t);Wl(Hl(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Bl(r,JSON.stringify(e,null,2)),ql(r,n)}async function Hf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),c=Gl(e);if(!c){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Xt(e,{items:u}),i.primed=!0,i}let l=[],d=[];for(let u of r.items){let p=c.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>bs&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}c.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=bs&&l.push(u)}for(let[u,p]of Object.entries(c.items))n-Date.parse(p.seen)>Kl&&delete c.items[u];Xt(e,c);for(let u of l)if(ws(o.phone,u,n))try{await t.phone(u,xs(u,n)),i.phone.push(u.key)}catch(p){s(`[desk] ${u.key}: not sent to the phone: ${p?.message??p}`)}if(t.computer){let u=!1;for(let p of[...d,...l]){let g=c.items[p.key];if(!ws(o.computer,p,n)){g.computerHeld&&(delete g.computerHeld,u=!0);continue}try{let f=await t.computer(p);f&&i.computer.push(p.key),f&&g.computerHeld&&(delete g.computerHeld,u=!0),!f&&!g.computerHeld&&(g.computerHeld=!0,u=!0)}catch(f){s(`[desk] ${p.key}: not shown on this computer: ${f?.message??f}`),g.computerHeld&&(delete g.computerHeld,u=!0)}}u&&Xt(e,c)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Vf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
909
+ Answer it on the Desk.`}}import{closeSync as le,createReadStream as Yl,fstatSync as Jl,openSync as Zl,realpathSync as vs}from"fs";import{isAbsolute as Ql,resolve as Ss,sep as Es}from"path";var Jf="/app-files",ed=/^[A-Za-z0-9_.:-]{1,64}$/;function td(t,e,n=process.cwd()){if(!e||e.length>L.pathChars||e.includes("\0"))return{ok:!1,status:400,error:"bad file path"};if(e.split(/[\\/]/).includes(".."))return{ok:!1,status:403,error:`the path leaves the workspace: copy the file into ${Ke}/ first`};if(!ne(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=vs(Ss(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=vs(Ql(e)?e:Ss(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Es))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Ke}/ first`};let s=ne(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function nd(t,e){let n=t.replace(/[^\x20-\x7e]/g,"_").replace(/["\\;]/g,"_").slice(0,120)||"file";return`${e==="file"?"attachment":"inline"}; filename="${n}"; filename*=UTF-8''${encodeURIComponent(t.slice(0,120))}`}function rd(t,e,n){return{"Content-Type":t,"Content-Disposition":nd(e,n),"X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; img-src 'self'; media-src 'self'; sandbox","Cache-Control":"private, max-age=3600","Accept-Ranges":"bytes"}}function od(t,e){let n=/^bytes=(\d*)-(\d*)$/.exec(String(t||"").trim());if(!n||!n[1]&&!n[2])return null;let r,o;return n[1]?(r=Number(n[1]),o=n[2]?Math.min(Number(n[2]),e-1):e-1):(r=Math.max(0,e-Number(n[2])),o=e-1),r>o||r>=e?"unsatisfiable":{start:r,end:o}}function Zf(t,e,n,r){let o=(x,N)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(N))};if(t.method!=="GET"&&t.method!=="HEAD")return o(405,{error:"GET only"});let s=n.searchParams.get("agent")||"",i=n.searchParams.get("file")||"";if(!ed.test(s))return o(400,{error:"bad agent id"});let a=r.workspaceOf(s);if(!a)return o(404,{error:`no agent "${s}" on this computer`});let c=td(a,i,r.cwd);if(!c.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${c.error}`),o(c.status,{error:c.error});let l;try{l=Zl(c.path,"r")}catch{return o(404,{error:"file not found"})}let d;try{let x=Jl(l);if(!x.isFile())return le(l),o(404,{error:"not a file"});d=x.size}catch{return le(l),o(404,{error:"file not found"})}if(d>L.bytes)return le(l),o(413,{error:`the file is larger than ${L.bytes/1024/1024} MB`});let u=c.path.split(Es).pop()||"file",p=rd(c.mime,u,c.kind),g=od(t.headers.range,d);if(g==="unsatisfiable"){le(l),e.writeHead(416,{...p,"Content-Range":`bytes */${d}`}),e.end();return}let{start:f,end:m}=g??{start:0,end:d-1};if(e.writeHead(g?206:200,{...p,"Content-Length":String(d?m-f+1:0),...g?{"Content-Range":`bytes ${f}-${m}/${d}`}:{}}),t.method==="HEAD"||d===0){le(l),e.end();return}let h=Yl("",{fd:l,start:f,end:m,autoClose:!0});h.on("error",()=>e.destroy()),e.on("close",()=>h.destroy()),h.pipe(e)}import{spawn as de}from"child_process";import{readFileSync as sd,writeFileSync as id}from"fs";import{tmpdir as ad}from"os";import{join as cd}from"path";cn();var _s=t=>t&&t!==1?Math.round(175*t):null,Pe=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function ld(){if(process.env.ELEVENLABS_API_KEY)return process.env.ELEVENLABS_API_KEY;for(let t of[`${process.env.HOME}/.elevenlabs/key`,`${process.env.HOME}/.agentx/elevenlabs-key.txt`])try{let e=sd(t,"utf8").trim();if(e)return e}catch{}return null}function am(t=ld()){let e=0;return async(n,r)=>{if(n.voice.provider==="system")return null;if(!t){if(n.voice.fallback)return null;throw new Error("ElevenLabs is the voice provider but no key is set")}try{let o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${n.voice.elevenlabs}/stream?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n.text,model_id:"eleven_flash_v2_5",...Pe(n.voice.rate)?{voice_settings:{speed:Pe(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=cd(ad(),`agentx-say-${process.pid}-${++e}.mp3`);return id(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return H(`elevenlabs:${String(o?.message??o).slice(0,40)}`,`[voice] ElevenLabs failed (${String(o?.message??o).slice(0,160)}); speaking with the system voice`),null}}}function $s(t,e){let n=t.languages&&fe(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var dd=(t,e="")=>{let n=$s(t,e),r=_s(t.rate);return[...n&&!uo(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function ud(t,e,n){if(!n)return["say",dd(t,e)];let r=$s(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function cm(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function lm(t=zt()){if(t)try{de("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function dm(t=zt()){if(t)try{de("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function zt(t={},e){if(!mt(t))return null;try{return fo(e)}catch(n){return H("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
910
+ `)[0]}); Siri voices will not switch`),null}}var um=(t,e)=>{if(!t){let[n,r]=ud(e.voice,e.text,zt()),o=_s(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=de(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?de("afplay",[t],{stdio:"ignore"}):de("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as Ts}from"child_process";import{accessSync as pd,constants as gd,readFileSync as As}from"fs";import{homedir as fd}from"os";import{basename as Q,delimiter as Rs,dirname as md,extname as hd,join as Kt}from"path";var j={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Is(t){let e=Array.isArray(t)?t[0]:t;return!e||!/^\d{1,9}$/.test(e.trim())?{status:400,error:"Say how long the recording is (X-Audio-Duration-Ms)."}:Number(e)>j.ms+2e3?{status:413,error:Yt()}:null}var Yt=()=>`The recording is longer than ${j.ms/6e4} minutes.`,bd={"audio/webm":"webm","video/webm":"webm","audio/ogg":"ogg","audio/mp4":"m4a","video/mp4":"m4a","audio/x-m4a":"m4a","audio/aac":"aac","audio/mpeg":"mp3","audio/wav":"wav","audio/x-wav":"wav","audio/wave":"wav"};function Ds(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return bd[e]??null}function Cs(t,e){let n=[];return t!=="local"&&e.key&&n.push("elevenlabs"),e.ffmpeg&&(e.mlx?n.push("mlx-whisper"):e.whisper&&n.push("whisper")),n}function Jt(t,e){return t==="local"&&e.key&&!e.ffmpeg?"Speech to text is set to local, and this computer has no ffmpeg.":(e.mlx||e.whisper)&&!e.ffmpeg?"This computer has Whisper but no ffmpeg to read the recording.":"Add an ElevenLabs key on this computer, or install mlx-whisper and ffmpeg."}function Gt(t,e,n=process.env.PATH??""){let r=fd(),o=[Kt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(Rs).filter(Boolean)];for(let s of[e,...o.map(i=>Kt(i,t))])if(s)try{return pd(s,gd.X_OK),s}catch{}return null}function bm(t){return{key:t,mlx:Gt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Gt("whisper",process.env.AGENTX_WHISPER),ffmpeg:yd()}}var yd=()=>Gt("ffmpeg",process.env.AGENTX_FFMPEG);async function Ns(t,e){return e?wd(t,e):null}async function wd(t,e){let n=String(j.ms/1e3+5);try{let o=[...(await xd(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function Ls(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([As(t)],{type:e}),Q(t));let s=await fetch("https://api.elevenlabs.io/v1/speech-to-text",{method:"POST",headers:{"xi-api-key":n},body:o,signal:r??AbortSignal.timeout(6e4)});if(!s.ok)throw new Error(`ElevenLabs ${s.status}: ${(await s.text().catch(()=>"")).slice(0,160)}`);let i=await s.json();if(typeof i.text!="string")throw new Error("ElevenLabs returned no text");return i.text.trim()}async function Os(t,e,n,r,o){let s=t==="mlx-whisper"?["--model",process.env.AGENTX_MLX_MODEL||"mlx-community/whisper-large-v3-turbo","--output-format","txt","--output-dir",o,n]:[n,"--model",process.env.AGENTX_WHISPER_MODEL||"base","--output_format","txt","--output_dir",o,"--fp16","False"],i={...process.env,PATH:`${md(r)}${Rs}${process.env.PATH??""}`};await kd(e,s,12e4,i);try{return As(Kt(o,Q(n,hd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function xd(t,e,n){return new Promise((r,o)=>{let s=Ts(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${Q(t)} took too long`))},n);s.stderr.on("data",c=>{i=(i+c).slice(-8192)}),s.on("error",c=>{clearTimeout(a),o(c)}),s.on("exit",c=>{clearTimeout(a),c===0?r(i):o(new Error(`${Q(t)} exited ${c}`))})})}function kd(t,e,n,r=process.env){return new Promise((o,s)=>{let i=Ts(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",c="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${Q(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{c.length<4096&&(c+=d)}),i.on("error",d=>{clearTimeout(l),s(d)}),i.on("exit",d=>{clearTimeout(l),d===0?o(a):s(new Error(`${Q(t)} exited ${d}: ${c.trim().split(`
911
911
  `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as vd,rm as Sd,writeFile as Ed}from"fs/promises";import{tmpdir as _d}from"os";import{join as Ps}from"path";Ks();var $d=64*1024,Td=2,Zt=0;function Am(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Rm(t,e,n,r){return t.method!=="POST"?w(e,405,{error:"POST"}):n==="/voice/transcribe"?Ad(t,e,r):Dd(t,e,r)}async function Ad(t,e,n){let r=String(t.headers["content-type"]||""),o=Ds(r);if(!o)return w(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=Is(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),w(e,s.status,{error:s.error});let i=await Ms(t,j.bytes);if(!i)return w(e,413,{error:Ld()});if(!i.length)return w(e,400,{error:"The recording is empty."});if(Zt>=Td)return w(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),c=n.host(),l=Cs(a,c);if(!c.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=l.length?"":" "+Jt(a,c);return w(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${u} for voice input from the phone.${p}`,setup:!1})}if(!l.length)return w(e,503,{error:"Voice input isn't set up on this computer.",hint:Jt(a,c),setup:!1});Zt++;let d;try{let u=await vd(Ps(_d(),"agentx-phone-voice-"));try{d=await Rd(u,`speech.${o}`,i,r,c,l,n)}finally{await Sd(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Zt--}w(e,d[0],d[1])}async function Rd(t,e,n,r,o,s,i){let a=Ps(t,e);if(await Ed(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??Ns)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>j.ms+2e3)return[413,{error:Yt()}]}let c=[];for(let l of s)try{let d=await Id(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),d?[200,{text:d,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(d){let u=String(d?.message??d).split(`
912
912
  `)[0].slice(0,200);c.push(`${l}: ${u}`),i.log(`[voice] phone transcription with ${l} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:c.join("; ")}]}function Id(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return Ls(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Os(t,a,e,r.ffmpeg,o)}async function Dd(t,e,n){let r=await Ms(t,$d);if(!r)return w(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return w(e,400,{error:"expected JSON"})}let s=typeof o?.agent=="string"?o.agent:"",i=typeof o?.peer=="string"&&o.peer?o.peer:void 0;if(!s)return w(e,400,{error:"agent is required"});let a=Cd(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return w(e,422,{error:"Nothing in this answer can be said aloud."});let c=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return w(e,404,{error:`Unknown agent: ${s}`});let d=(p,g=200)=>w(e,g,{fallback:"browser",reason:p,text:c});if(l.provider!=="elevenlabs")return d("This agent speaks with a system voice, which only plays on the computer.");let u=n.elevenLabsKey();if(!u)return d("No ElevenLabs key is set on this computer.");try{let p=await(n.synth??Nd)(u,l,c);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(c.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
913
913
  `)[0].slice(0,160)}`),d("ElevenLabs could not speak this answer.",502)}}function Cd(t,e){let n=Le(be(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return ln(n,e)}async function Nd(t,e,n){let r=Pe(e.rate),o=await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(e.elevenlabs)}?output_format=mp3_44100_128`,{method:"POST",headers:{"xi-api-key":t,"Content-Type":"application/json"},body:JSON.stringify({text:n,model_id:"eleven_flash_v2_5",...r?{voice_settings:{speed:r}}:{}}),signal:AbortSignal.timeout(6e4)});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text().catch(()=>"")).slice(0,160)}`);return Buffer.from(await o.arrayBuffer())}var Ld=()=>`The recording is larger than ${j.bytes/1024/1024} MB, more than ${j.ms/6e4} minutes of speech.`;function Im(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?_t(vt(t,o,n.voice)):null}function Ms(t,e){return Number(t.headers["content-length"])>e?(t.resume(),Promise.resolve(null)):new Promise((n,r)=>{let o=[],s=0;t.on("data",i=>{if(!(s>e)){if(s+=i.length,s>e){o.length=0,n(null);return}o.push(i)}}),t.on("end",()=>{s<=e&&n(Buffer.concat(o))}),t.on("error",r)})}function w(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var Od="operator",Pd=50,Us=4,Fs=500;function Md(t){let e={channel:"app",chatId:t.chatId,sender:Od,...t.spoken?{via:"voice"}:{}};return t.node==="local"?{path:"/task",body:{agent:t.agent,message:t.message,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:t.message,stream:!0,context:e}}}async function Om(t,e,n,r){let{path:o,body:s}=Md(e),i="",a=!1,c=[],l=new Map,d=(u,p,g)=>{let f=u!=="done",m=a?{text:$n(p,f),artifacts:[]}:be(p,L.perMessage,f),{cleanText:h,ui:x}=u==="done"?Le(m.text):{cleanText:m.text,ui:void 0},N=a?void 0:Fd(x);return{status:u,text:h,tools:c,files:m.artifacts,...N?{ui:N}:{},...g?{error:g}:{}}};try{let u=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!u.ok||!u.body){let p=await u.json().then(g=>g?.error).catch(()=>"");return d("error",i,p||`AgentX answered HTTP ${u.status}.`)}for await(let p of Wd(u.body)){r(p.event,p.data);let g=p.data??{};if(p.event==="start")a=g.rich===!1;else if(p.event==="text"&&typeof g.text=="string")i+=g.text;else if(p.event==="tool"&&g.status==="start"&&c.length<Pd){let f={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};c.push(f),g.id&&l.set(String(g.id),f)}else if(p.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(p.event==="done")return d("done",typeof g.content=="string"&&g.content?g.content:i);if(p.event==="error")return d("error",i,Ud(g.error))}}return n.aborted?d("stopped",i):d("error",i,"The connection to the agent closed before it answered.")}catch(u){return n.aborted?d("stopped",i):d("error",i,`Could not reach AgentX: ${u?.message||u}`)}}function Ud(t){let e=String(t||"The agent could not answer.");return kn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function Fd(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,Us).map(i=>i.slice(0,Fs));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,Us).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,Fs)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*Wd(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
@@ -915,7 +915,7 @@ Answer it on the Desk.`}}import{closeSync as ce,createReadStream as Yl,fstatSync
915
915
 
916
916
  `))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let c="message",l=[];for(let d of a.split(`
917
917
  `))d.startsWith("event:")?c=d.slice(6).trim():d.startsWith("data:")&&l.push(d.slice(5).replace(/^ /,""));if(l.length)try{yield{event:c,data:JSON.parse(l.join(`
918
- `))}}catch{}}}}finally{e.releaseLock()}}import{existsSync as I,readFileSync as nn,writeFileSync as rn,mkdirSync as Me,readdirSync as tn,rmSync as jd,statSync as C}from"fs";import{resolve as Ws,relative as qd,dirname as on,join as X,extname as de,basename as sn}from"path";var _=200*1024,js=new Set([".md",".markdown",".txt"]),ee=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),Bd=6,Hd=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function M(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Ws(t);if(I(n)||Me(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Ws(n,e);if(qd(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function qs(t){let e=de(t).toLowerCase();if(!js.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Qt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Fm(t){let e=M(t,"."),n=[],r=new Set,o=[];try{o=tn(e)}catch{}for(let a of Hd){let c=X(e,a);if(I(c)&&C(c).isFile()){let l=C(c).size,d=l>0&&l<_?en(c):"";n.push({path:a,title:Qt(d,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let c=X(e,a);try{let l=C(c);if(!l.isFile()||!js.has(de(a).toLowerCase()))continue;let d=l.size>0&&l.size<_?en(c):"";n.push({path:a,title:Qt(d,a),size:l.size,exists:!0})}catch{}}let s=[],i=X(e,".claude","skills");if(I(i))try{for(let a of tn(i)){let c=X(i,a),l;try{l=C(c)}catch{continue}if(!l.isDirectory())continue;let d=X(c,"SKILL.md");if(!I(d))continue;let u=C(d),p=u.size<_?en(d):"";s.push({slug:a,title:Qt(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:s,workspace:e}}function en(t){try{return nn(t,"utf-8")}catch{return""}}function Wm(t,e){let n=M(t,e);if(qs(n),!I(n))return{path:e,content:""};if(C(n).size>_)throw new Error(`File is too large to edit in the admin panel (> ${_/1024} KB).`);return{path:e,content:nn(n,"utf-8")}}function jm(t,e,n){let r=M(t,e);qs(r);let o=Buffer.from(n,"utf-8");if(o.length>_)throw new Error(`File too large (${o.length} > ${_} bytes).`);return Me(on(r),{recursive:!0}),rn(r,o),{path:e,bytes:o.length}}function qm(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,o=M(t,r);if(I(o))throw new Error(`Skill "${e}" already exists.`);Me(on(o),{recursive:!0});let s=n.content?.trim()?n.content:Vd(e,n.title);return rn(o,s),{slug:e,path:r}}function Bm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);if(!C(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return jd(n,{recursive:!0,force:!0}),{slug:e}}function Hm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,c){if(a>Bd)return;let l=[];try{l=tn(s)}catch{return}for(let d of l){if(d==="node_modules"||d===".git")continue;let u=X(s,d),p=i?`${i}/${d}`:d,g;try{g=C(u)}catch{continue}if(g.isDirectory())c.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),o(u,p,a+1,c);else if(g.isFile()){let f=de(d).toLowerCase(),m=ee.has(f)||ee.has(d.toLowerCase());c.push({path:p,kind:"file",size:g.size,editable:m&&g.size<_})}}}}function Vm(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=M(t,`.claude/skills/${e}/${n}`);if(!I(r)||!C(r).isFile())throw new Error(`File not found: ${n}`);let o=de(r).toLowerCase(),s=sn(r).toLowerCase();if(!ee.has(o)&&!ee.has(s))throw new Error(`File type not editable: ${n}`);if(C(r).size>_)throw new Error(`File too large to edit (> ${_/1024} KB): ${n}`);return{path:n,content:nn(r,"utf-8")}}function Xm(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let o=M(t,`.claude/skills/${e}/${n}`),s=de(o).toLowerCase(),i=sn(o).toLowerCase();if(!ee.has(s)&&!ee.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>_)throw new Error(`File too large (${a.length} > ${_} bytes).`);return Me(on(o),{recursive:!0}),rn(o,a),{path:n,bytes:a.length}}function zm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=o=>I(X(n,o));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Vd(t,e){return`# ${e?.trim()||t}
918
+ `))}}catch{}}}}finally{e.releaseLock()}}import{existsSync as I,readFileSync as nn,writeFileSync as rn,mkdirSync as Me,readdirSync as tn,rmSync as jd,statSync as C}from"fs";import{resolve as Ws,relative as qd,dirname as on,join as X,extname as ue,basename as sn}from"path";var _=200*1024,js=new Set([".md",".markdown",".txt"]),ee=new Set([".md",".markdown",".txt",".json",".jsonc",".yaml",".yml",".toml",".sh",".bash",".zsh",".py",".js",".mjs",".ts",".tsx",".jsx",".css",".html",".lock",".cfg",".ini",".env",".gitignore"]),Bd=6,Hd=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function M(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Ws(t);if(I(n)||Me(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Ws(n,e);if(qd(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function qs(t){let e=ue(t).toLowerCase();if(!js.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Qt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Fm(t){let e=M(t,"."),n=[],r=new Set,o=[];try{o=tn(e)}catch{}for(let a of Hd){let c=X(e,a);if(I(c)&&C(c).isFile()){let l=C(c).size,d=l>0&&l<_?en(c):"";n.push({path:a,title:Qt(d,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let c=X(e,a);try{let l=C(c);if(!l.isFile()||!js.has(ue(a).toLowerCase()))continue;let d=l.size>0&&l.size<_?en(c):"";n.push({path:a,title:Qt(d,a),size:l.size,exists:!0})}catch{}}let s=[],i=X(e,".claude","skills");if(I(i))try{for(let a of tn(i)){let c=X(i,a),l;try{l=C(c)}catch{continue}if(!l.isDirectory())continue;let d=X(c,"SKILL.md");if(!I(d))continue;let u=C(d),p=u.size<_?en(d):"";s.push({slug:a,title:Qt(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,c)=>a.slug.localeCompare(c.slug)),{identity:n,skills:s,workspace:e}}function en(t){try{return nn(t,"utf-8")}catch{return""}}function Wm(t,e){let n=M(t,e);if(qs(n),!I(n))return{path:e,content:""};if(C(n).size>_)throw new Error(`File is too large to edit in the admin panel (> ${_/1024} KB).`);return{path:e,content:nn(n,"utf-8")}}function jm(t,e,n){let r=M(t,e);qs(r);let o=Buffer.from(n,"utf-8");if(o.length>_)throw new Error(`File too large (${o.length} > ${_} bytes).`);return Me(on(r),{recursive:!0}),rn(r,o),{path:e,bytes:o.length}}function qm(t,e,n={}){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error("Skill slug must be lowercase (letters, digits, -, _) and start with a letter or digit.");let r=`.claude/skills/${e}/SKILL.md`,o=M(t,r);if(I(o))throw new Error(`Skill "${e}" already exists.`);Me(on(o),{recursive:!0});let s=n.content?.trim()?n.content:Vd(e,n.title);return rn(o,s),{slug:e,path:r}}function Bm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);if(!C(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return jd(n,{recursive:!0,force:!0}),{slug:e}}function Hm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=[];return o(n,"",0,r),r.sort((s,i)=>s.kind!==i.kind?s.kind==="dir"?-1:1:s.path.localeCompare(i.path)),r;function o(s,i,a,c){if(a>Bd)return;let l=[];try{l=tn(s)}catch{return}for(let d of l){if(d==="node_modules"||d===".git")continue;let u=X(s,d),p=i?`${i}/${d}`:d,g;try{g=C(u)}catch{continue}if(g.isDirectory())c.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),o(u,p,a+1,c);else if(g.isFile()){let f=ue(d).toLowerCase(),m=ee.has(f)||ee.has(d.toLowerCase());c.push({path:p,kind:"file",size:g.size,editable:m&&g.size<_})}}}}function Vm(t,e,n){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let r=M(t,`.claude/skills/${e}/${n}`);if(!I(r)||!C(r).isFile())throw new Error(`File not found: ${n}`);let o=ue(r).toLowerCase(),s=sn(r).toLowerCase();if(!ee.has(o)&&!ee.has(s))throw new Error(`File type not editable: ${n}`);if(C(r).size>_)throw new Error(`File too large to edit (> ${_/1024} KB): ${n}`);return{path:n,content:nn(r,"utf-8")}}function Xm(t,e,n,r){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);if(!n||n.includes(".."))throw new Error(`Invalid file path: ${n}`);let o=M(t,`.claude/skills/${e}/${n}`),s=ue(o).toLowerCase(),i=sn(o).toLowerCase();if(!ee.has(s)&&!ee.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>_)throw new Error(`File too large (${a.length} > ${_} bytes).`);return Me(on(o),{recursive:!0}),rn(o,a),{path:n,bytes:a.length}}function zm(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=M(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=o=>I(X(n,o));return r("pnpm-lock.yaml")?{manager:"pnpm",file:"pnpm-lock.yaml",command:"pnpm install"}:r("yarn.lock")?{manager:"yarn",file:"yarn.lock",command:"yarn install"}:r("package.json")?{manager:"npm",file:"package.json",command:"npm install"}:r("requirements.txt")?{manager:"pip",file:"requirements.txt",command:"pip install -r requirements.txt"}:r("Gemfile")?{manager:"bundle",file:"Gemfile",command:"bundle install"}:{manager:null,file:null,command:null}}function Vd(t,e){return`# ${e?.trim()||t}
919
919
 
920
920
  Describe what this skill does and when the agent should use it. Keep it under ~5 lines \u2014 the agent reads this to decide whether to invoke the skill.
921
921
 
@@ -930,5 +930,5 @@ Document the arguments, commands, or files the skill expects. Example:
930
930
  # Example invocation
931
931
  claude-code ${sn(t)} --arg value
932
932
  \`\`\`
933
- `}yn();var Bs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Hs(t){return{...Bs,...t??{},regions:{...t?.regions??{}},buffer:{...Bs.buffer,...t?.buffer??{}}}}function Ym(t){try{return Hs(bn(t).screen)}catch{return Hs(void 0)}}var Xd=/^[a-z][\w-]*$/,Vs=["window","screen","menubar","notifications"];function ue(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Ue=(t,e)=>ue(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Xs(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Jm(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ue(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ue(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ue(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ue(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ue(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Xd.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=Xs(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=ue(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ue(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ue(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!Vs.includes(r)&&!n.regions?.[r])try{Xs(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Vs,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{ur as a,Gd as b,Mt as c,Nc as d,Lc as e,Dg as f,Cg as g,Ng as h,Pg as i,Mg as j,Ug as k,qo as l,Bo as m,Fg as n,Le as o,jg as p,Bg as q,W as r,Ho as s,S as t,Qd as u,zo as v,Gg as w,Zg as x,Go as y,Qg as z,Yo as A,ef as B,ae as C,al as D,tf as E,nf as F,Zo as G,fu as H,_i as I,xu as J,Ir as K,vu as L,$ as M,ou as N,su as O,Du as P,ve as Q,Cu as R,vr as S,uu as T,B as U,ip as V,Kr as W,Jr as X,la as Y,da as Z,lp as _,dp as $,ba as aa,fp as ba,es as ca,sf as da,bp as ea,yp as fa,Uo as ga,At as ha,$c as ia,E as ja,gs as ka,Uf as la,Ff as ma,Xl as na,Bf as oa,ws as pa,Hf as qa,Vf as ra,Jf as sa,rd as ta,Zf as ua,xp as va,kp as wa,vp as xa,Sp as ya,Ep as za,_p as Aa,Tp as Ba,Ap as Ca,Dp as Da,Cp as Ea,Np as Fa,Pp as Ga,Mp as Ha,Up as Ia,Fp as Ja,Wp as Ka,jp as La,qp as Ma,Jp as Na,yt as Oa,Zp as Pa,Qp as Qa,se as Ra,ie as Sa,ld as Ta,am as Ua,cm as Va,lm as Wa,dm as Xa,zt as Ya,um as Za,kt as _a,vt as $a,Ie as ab,za as bb,Ga as cb,og as db,Et as eb,_t as fb,Ya as gb,Ja as hb,Eo as ib,Ao as jb,sg as kb,ec as lb,ig as mb,cc as nb,uc as ob,$t as pb,gc as qb,Ro as rb,j as sb,Is as tb,Ds as ub,Cs as vb,Gt as wb,bm as xb,yd as yb,Ls as zb,Os as Ab,Am as Bb,Rm as Cb,Ld as Db,Im as Eb,Ms as Fb,No as Gb,Om as Hb,Fd as Ib,De as Jb,kg as Kb,Ot as Lb,Ag as Mb,Fm as Nb,Wm as Ob,jm as Pb,qm as Qb,Bm as Rb,Hm as Sb,Vm as Tb,Xm as Ub,zm as Vb,Bs as Wb,Hs as Xb,Ym as Yb,Vs as Zb,Jm as _b};
934
- //# sourceMappingURL=chunk-I45E5TLK.js.map
933
+ `}yn();var Bs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Hs(t){return{...Bs,...t??{},regions:{...t?.regions??{}},buffer:{...Bs.buffer,...t?.buffer??{}}}}function Ym(t){try{return Hs(bn(t).screen)}catch{return Hs(void 0)}}var Xd=/^[a-z][\w-]*$/,Vs=["window","screen","menubar","notifications"];function pe(t,e,n,r){let o=Number(t);if(t===""||t===null||!Number.isFinite(o)||!n(o))throw new Error(`${e} must be ${r}`);return o}var Ue=(t,e)=>pe(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Xs(t){let e=typeof t=="string"?t.split(",").map(Number):[t?.x,t?.y,t?.width,t?.height].map(Number);if(e.length!==4||!e.every(Number.isFinite)||e[2]<=0||e[3]<=0)throw new Error("a region is x,y,width,height in screen points, with width and height above 0");return{x:e[0],y:e[1],width:e[2],height:e[3]}}function Jm(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ue(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ue(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ue(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=pe(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=pe(e.changeThreshold,"changeThreshold",o=>o>=0&&o<=1,"between 0 and 1")),e.regions&&typeof e.regions=="object"){let o={...n.regions??{}};for(let[s,i]of Object.entries(e.regions)){if(!Xd.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=Xs(i)}n.regions=o}if(e.buffer&&typeof e.buffer=="object"){let o=e.buffer,s={...n.buffer??{}};"enabled"in o&&(s.enabled=!!o.enabled),"seconds"in o&&(s.seconds=pe(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=pe(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ue(o.maxPixels,"buffer.maxPixels")),"region"in o&&(s.region=String(o.region).trim()),n.buffer=s}let r=n.buffer?.region;if(r!==void 0&&!Vs.includes(r)&&!n.regions?.[r])try{Xs(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Vs,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{ur as a,Gd as b,Mt as c,Nc as d,Lc as e,Dg as f,Cg as g,Ng as h,Pg as i,Mg as j,Ug as k,qo as l,Bo as m,Fg as n,Le as o,jg as p,Bg as q,W as r,Ho as s,S as t,Qd as u,zo as v,Gg as w,Zg as x,Go as y,Qg as z,Yo as A,ef as B,ce as C,al as D,tf as E,nf as F,Zo as G,fu as H,_i as I,xu as J,Ir as K,vu as L,$ as M,ou as N,su as O,Du as P,ve as Q,Cu as R,vr as S,uu as T,B as U,ip as V,Kr as W,Jr as X,la as Y,da as Z,lp as _,dp as $,ba as aa,fp as ba,es as ca,sf as da,bp as ea,yp as fa,Uo as ga,At as ha,$c as ia,E as ja,gs as ka,Uf as la,Ff as ma,Xl as na,Bf as oa,ws as pa,Hf as qa,Vf as ra,Jf as sa,rd as ta,Zf as ua,xp as va,kp as wa,vp as xa,Sp as ya,Ep as za,_p as Aa,Tp as Ba,Ap as Ca,Dp as Da,Cp as Ea,Np as Fa,Pp as Ga,Mp as Ha,Up as Ia,Fp as Ja,Wp as Ka,jp as La,qp as Ma,Jp as Na,yt as Oa,Zp as Pa,Qp as Qa,ie as Ra,ae as Sa,ld as Ta,am as Ua,cm as Va,lm as Wa,dm as Xa,zt as Ya,um as Za,kt as _a,vt as $a,Ie as ab,za as bb,Ga as cb,og as db,Et as eb,_t as fb,Ya as gb,Ja as hb,Eo as ib,Ao as jb,sg as kb,ec as lb,ig as mb,cc as nb,uc as ob,$t as pb,gc as qb,Ro as rb,j as sb,Is as tb,Ds as ub,Cs as vb,Gt as wb,bm as xb,yd as yb,Ls as zb,Os as Ab,Am as Bb,Rm as Cb,Ld as Db,Im as Eb,Ms as Fb,No as Gb,Om as Hb,Fd as Ib,De as Jb,kg as Kb,Ot as Lb,Ag as Mb,Fm as Nb,Wm as Ob,jm as Pb,qm as Qb,Bm as Rb,Hm as Sb,Vm as Tb,Xm as Ub,zm as Vb,Bs as Wb,Hs as Xb,Ym as Yb,Vs as Zb,Jm as _b};
934
+ //# sourceMappingURL=chunk-YWAJNF2A.js.map