agentix-cli 0.184.0 → 0.185.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.
Files changed (32) hide show
  1. package/dist/{board-dashboard-MHPJY4JB.js → board-dashboard-TCZ3RAQR.js} +1867 -426
  2. package/dist/board-dashboard-TCZ3RAQR.js.map +1 -0
  3. package/dist/{chunk-4IKZSV5A.js → chunk-2HZXLYWQ.js} +3 -3
  4. package/dist/chunk-BLWVMGSJ.js +12 -0
  5. package/dist/chunk-BLWVMGSJ.js.map +1 -0
  6. package/dist/{chunk-WKHRKYCY.js → chunk-DSIPKP2D.js} +2 -2
  7. package/dist/{chunk-UMHN33JQ.js → chunk-JJ7FHH53.js} +2 -2
  8. package/dist/{chunk-I5TUF6U7.js → chunk-LZVQ4N2Z.js} +72 -72
  9. package/dist/chunk-LZVQ4N2Z.js.map +1 -0
  10. package/dist/{chunk-DPV4M4AQ.js → chunk-P7K5ZQVT.js} +2 -2
  11. package/dist/{chunk-CVPERUWT.js → chunk-Z5DHUJIL.js} +2 -2
  12. package/dist/cli.js +1 -1
  13. package/dist/doctor-DKW3EP3O.js +2 -0
  14. package/dist/grants-COGXFWO3.js +2 -0
  15. package/dist/index.d.ts +7 -7
  16. package/dist/index.js +1 -1
  17. package/dist/{program-736BTK4B.js → program-2DFU4DCC.js} +5 -5
  18. package/package.json +1 -1
  19. package/dist/board-dashboard-MHPJY4JB.js.map +0 -1
  20. package/dist/chunk-CTNZVRPA.js +0 -6
  21. package/dist/chunk-CTNZVRPA.js.map +0 -1
  22. package/dist/chunk-I5TUF6U7.js.map +0 -1
  23. package/dist/doctor-22PZVT6A.js +0 -2
  24. package/dist/grants-FY2TIT7I.js +0 -2
  25. /package/dist/{chunk-4IKZSV5A.js.map → chunk-2HZXLYWQ.js.map} +0 -0
  26. /package/dist/{chunk-WKHRKYCY.js.map → chunk-DSIPKP2D.js.map} +0 -0
  27. /package/dist/{chunk-UMHN33JQ.js.map → chunk-JJ7FHH53.js.map} +0 -0
  28. /package/dist/{chunk-DPV4M4AQ.js.map → chunk-P7K5ZQVT.js.map} +0 -0
  29. /package/dist/{chunk-CVPERUWT.js.map → chunk-Z5DHUJIL.js.map} +0 -0
  30. /package/dist/{doctor-22PZVT6A.js.map → doctor-DKW3EP3O.js.map} +0 -0
  31. /package/dist/{grants-FY2TIT7I.js.map → grants-COGXFWO3.js.map} +0 -0
  32. /package/dist/{program-736BTK4B.js.map → program-2DFU4DCC.js.map} +0 -0
@@ -1,10 +1,10 @@
1
- import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Un,J as Xn,k as U}from"./chunk-WKHRKYCY.js";import{f as Bn,g as Vn,h as Hn,k as zn}from"./chunk-NHW4IY6N.js";import{b as Fn}from"./chunk-2VDO2HEK.js";import{f as Wn,i as jn,k as Ve,l as He,n as Y,o as B,q as qn}from"./chunk-CTNZVRPA.js";import{t as On,u as Mn}from"./chunk-2V6ZGE74.js";import{d as Ln,e as Pn}from"./chunk-AQASR6KR.js";import{a as xn,b as kn,d as vn,e as Sn}from"./chunk-MNG2AMKZ.js";import{h as J,j as $n,l as En,m as _n,n as An}from"./chunk-RX5O5637.js";import{a as Rn,c as In,e as Tn,f as We,h as Dn,j as Cn,k as Nn,l as je,m as qe,n as Be}from"./chunk-5ELIX7BQ.js";import{h as mn,i as hn,j as bn,l as yn,m as wn}from"./chunk-V4IOGISL.js";import{a as gn,c as fn}from"./chunk-KP7KDLZ2.js";import{Aa as Ue,Ca as Fe,b as Pe,s as Oe,u as Me,xa as pn,za as de}from"./chunk-2GIYVYIM.js";import{r as un}from"./chunk-RTIGD4NG.js";import{a as cn,b as ce,e as dn}from"./chunk-NS2HSAHF.js";import{a as ln}from"./chunk-QUFIUXMQ.js";import{A as ks,Gb as an,d as De,f as Yt,j as xs,la as en,ma as tn,nb as Le,oa as nn,pa as rn,wb as on,x as le,xb as sn,y as Zt,z as Qt}from"./chunk-BZJF7DJR.js";import{a as Ce,h as vs}from"./chunk-VJ5HC63R.js";import{j as Ne,r as Ss}from"./chunk-UEEB3UTU.js";import{existsSync as $s,readdirSync as Es,readFileSync as _s,statSync as As}from"fs";import{resolve as Rs}from"path";function Kn(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)??[],l=a.filter(f=>n-f.at<=o),c=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=l.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?c.length>0&&l.length===0?"dormant":l.length>0&&d*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:d,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ue=new Map;function sd(t,e=1e3){if(!$s(t))return[];let n=Es(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Rs(t,s);return{path:i,mtime:As(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ue.keys())r.has(s)||ue.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=ue.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let l=Is(s,i);ue.set(s,{mtime:i,summary:l}),l&&o.push(l)}return o}function Is(t,e){try{let n=_s(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]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Gn=7,Ts={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Ds=(t,e,n)=>{try{return un(t,e,n)}catch{return null}},Jn=864e5;function cd(t){let e=t.now??Date.now(),n={...Ts,...t.thresholds},r=t.nextFire??Ds,o=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",d=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:T(a.id,k.text),trigger:{schedule:T(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Xe(a.nextRun)??Xe(r(a.schedule,new Date(e),c)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Ms(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Yn(d),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Gn).map(g=>({at:g.startedAt,status:g.status}))};p.flags=Zn(p,d,a.schedule,c,null,e,n,r),o.push(Qn(p))}let s=new Map(Kn(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 l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(x=>x.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((x,Te)=>Te.at-x.at),g=p.map(x=>({at:x.at,status:Ls(x.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",$=typeof c.timezone=="string"?c.timezone:"UTC",q={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:T(a.title||a.id,k.text),trigger:m?{schedule:T(b,k.text),timezone:$}:{event:T(typeof c.event=="string"?c.event:"",k.text),filters:Os(c.filter,a)},agent:Ps(a),enabled:u,state:d,nextRunAt:m&&u&&b?Xe(r(b,new Date(e),$)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(Te=>Te.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:Yn(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Gn).map(x=>({at:new Date(x.at).toISOString(),status:x.status}))},ae=Date.parse(a.updated||a.created||"");q.flags=m?Zn(q,g,b,$,Number.isFinite(ae)?ae:null,e,n,r):Cs(q,s.get(a.id)?.state==="dormant",Number.isFinite(ae)?ae:null,e,n),o.push(Qn(q))}return o.sort(Ns).slice(0,k.routines)}function Yn(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 Zn(t,e,n,r,o,s,i,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=tr(c,o,s,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let d=new Date(c),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&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Cs(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=tr(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 tr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Jn?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Jn)} days`:"Disabled and never ran"}}function Qn(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 er={critical:0,warning:1,info:2};function Ns(t,e){let n=t.attention?er[t.attention]:3,r=e.attention?er[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Ls(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 Ps(t){if(t.ownerAgent)return T(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?T(String(e.config.agentId),k.text):null}function Os(t,e){let n=[],r=e?.project;if(r&&n.push(T(`project=${r}`,k.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(T(`${o}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Xe(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function T(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Ms(t,e){return t===void 0?void 0:T(t,e)}import{mkdirSync as Us,readFileSync as Fs,renameSync as Ws,writeFileSync as js}from"fs";import{resolve as qs}from"path";function nr(t){return qs(He(t),"_state.json")}function E(t){try{let e=JSON.parse(Fs(nr(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 Z(t,e){Us(He(t),{recursive:!0});let n=nr(t),r=`${n}.${process.pid}.tmp`;js(r,JSON.stringify(e,null,2)+`
3
- `),Ws(r,n)}function rr(t,e,n,r=Date.now()){let o=E(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),Z(t,{...o,snoozed:s})}function fd(t,e){Z(t,{...E(t),lastDigest:e})}function Ke(t,e,n,r=Date.now()){let o=E(t),s=new Set(n),i={};for(let[l,c]of Object.entries(o.popped??{}))s.has(l)&&(i[l]=c);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(l=>l!==e&&s.has(l));Z(t,{...o,popped:i,wanted:a})}function or(t,e){let n=E(t);Z(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function md(t,e=Date.now()){Z(t,{...E(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Bs,readFileSync as Vs}from"fs";an();vs();function sr(t){let e=cn(t),n={};if(Bs(e))try{n=on(JSON.parse(Vs(e,"utf-8")))}catch{n={}}let r=Le.safeParse(n?.requests);return r.success?r.data:Le.parse(void 0)}async function kd(t,e={}){let n=(t.channels??[]).filter(r=>!Ce.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Ce].join(", ")}`}:ce(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])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.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 Q,readdirSync as pi,readFileSync as Qe}from"fs";import{dirname as gi,resolve as _}from"path";import{randomBytes as lr}from"crypto";import{existsSync as zs,mkdirSync as Xs,readdirSync as Ks,readFileSync as Gs,renameSync as cr,unlinkSync as Js,writeFileSync as Ys}from"fs";import{resolve as dr}from"path";function ir(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Hs=t=>t.trim().split(`
4
- `).pop()?.slice(0,300)||"no output";async function ar(t,e,n,r=ze){let o=await r(t.bin,[...ir(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Hs(o.stderr||o.stdout)}`}}async function $d(t,e,n,r,o=ze){return(await o(t.bin,[...ir(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Zs=2e3,Qs=t=>ar(t.wacli,t.to,t.text);function Ge(t){return dr(t,".agentx","whatsapp-triage","drafts")}var ei=t=>/^[a-z0-9-]{8,64}$/.test(t),pe=(t,e)=>dr(Ge(t),`${e}.json`);function ur(t,e){Xs(Ge(t),{recursive:!0});let n=pe(t,e.id),r=`${n}.${process.pid}.tmp`;Ys(r,JSON.stringify(e,null,2)+`
5
- `,{mode:384}),cr(r,n)}function Td(t,e,n=Date.now()){let r=e.text.trim().slice(0,Zs);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${lr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return ur(t,o),o}function ge(t,e){if(!ei(e))return null;try{return JSON.parse(Gs(pe(t,e),"utf-8"))}catch{return null}}function pr(t,e){let n=Ge(t);return zs(n)?Ks(n).filter(r=>r.endsWith(".json")).map(r=>ge(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function gr(t,e,n,r={}){let o=ge(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${pe(t,e)}.${process.pid}.${lr(3).toString("hex")}.claim`;try{cr(pe(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??Qs)(o).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}ur(t,i);try{Js(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ni,writeFileSync as ri}from"fs";import{resolve as mr}from"path";function Je(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 Cd(t,e,n,r,o){let s=Je(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 hr="ready",oi="202510";function si(t){let e=t.date??t.created_at.slice(0,10);return mr(t.workspace,hr,`${e}-${t.platform}-${t.id}.txt`)}function fr(t){let e=si(t);return ni(mr(t.workspace,hr),{recursive:!0}),ri(e,t.text.endsWith(`
1
+ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Fn,J as Gn,k as U}from"./chunk-DSIPKP2D.js";import{f as Hn,g as zn,h as Xn,k as Kn}from"./chunk-NHW4IY6N.js";import{b as Wn}from"./chunk-2VDO2HEK.js";import{a as jn,i as qn,l as Bn,n as Ve,o as He,q as Y,r as B,t as Vn}from"./chunk-BLWVMGSJ.js";import{t as Mn,u as Un}from"./chunk-2V6ZGE74.js";import{d as Pn,e as On}from"./chunk-AQASR6KR.js";import{a as kn,b as vn,d as Sn,e as $n}from"./chunk-MNG2AMKZ.js";import{h as J,j as _n,l as En,m as An,n as Rn}from"./chunk-RX5O5637.js";import{a as In,c as Tn,e as Dn,f as We,h as Cn,j as Nn,k as Ln,l as je,m as qe,n as Be}from"./chunk-5ELIX7BQ.js";import{h as hn,i as bn,j as yn,l as wn,m as xn}from"./chunk-V4IOGISL.js";import{a as fn,c as mn}from"./chunk-KP7KDLZ2.js";import{Aa as Ue,Ca as Fe,b as Pe,s as Oe,u as Me,xa as gn,za as de}from"./chunk-2GIYVYIM.js";import{r as pn}from"./chunk-RTIGD4NG.js";import{a as dn,b as ce,e as un}from"./chunk-NS2HSAHF.js";import{a as cn}from"./chunk-QUFIUXMQ.js";import{A as Ss,Gb as ln,d as De,f as Zt,j as vs,la as tn,ma as nn,nb as Le,oa as rn,pa as on,wb as sn,x as le,xb as an,y as Qt,z as en}from"./chunk-BZJF7DJR.js";import{a as Ce,h as $s}from"./chunk-VJ5HC63R.js";import{j as Ne,r as _s}from"./chunk-UEEB3UTU.js";import{existsSync as Es,readdirSync as As,readFileSync as Rs,statSync as Is}from"fs";import{resolve as Ts}from"path";function Jn(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)??[],l=a.filter(f=>n-f.at<=o),c=a.filter(f=>n-f.at>o&&n-f.at<=o*2),d=l.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?c.length>0&&l.length===0?"dormant":l.length>0&&d*2>=l.length?"failing":l.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:p,recent:l.length,prior:c.length,failed:d,paused:u}}).sort((i,a)=>{let l={dormant:0,failing:1,active:2,quiet:3,never:4};return l[i.state]-l[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var ue=new Map;function ad(t,e=1e3){if(!Es(t))return[];let n=As(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ts(t,s);return{path:i,mtime:Is(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of ue.keys())r.has(s)||ue.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=ue.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let l=Ds(s,i);ue.set(s,{mtime:i,summary:l}),l&&o.push(l)}return o}function Ds(t,e){try{let n=Rs(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]),l=a.status??a.run?.status;if(l){s=l;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Yn=7,Cs={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},k={routines:200,summary:160,filters:6,filterValue:60,text:120},Ns=(t,e,n)=>{try{return pn(t,e,n)}catch{return null}},Zn=864e5;function ud(t){let e=t.now??Date.now(),n={...Cs,...t.thresholds},r=t.nextFire??Ns,o=[];for(let a of t.crons){let l=t.cronRuns.get(a.id)??[],c=a.timezone||"UTC",d=l.map(g=>({at:Date.parse(g.startedAt),status:g.status})),u=l[0],p={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:T(a.id,k.text),trigger:{schedule:T(a.schedule,k.text),timezone:c},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?Xe(a.nextRun)??Xe(r(a.schedule,new Date(e),c)):null,lastRun:u?{at:u.startedAt,status:u.status,summary:Fs(u.status==="success"?void 0:u.errorSummary,k.summary)}:null,lastSuccessAt:l.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Qn(d),sampledRuns:l.length,flags:[],attention:null,recent:l.slice(0,Yn).map(g=>({at:g.startedAt,status:g.status}))};p.flags=er(p,d,a.schedule,c,null,e,n,r),o.push(tr(p))}let s=new Map(Jn(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 l=i.get(a.workflowId);l?l.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let l=a.nodes.find(x=>x.type.startsWith("trigger."));if(!l||l.type!=="trigger.cron"&&l.type!=="trigger.hook")continue;let c=l.config??{},d=a.state||"active",u=d==="active",p=(i.get(a.id)??[]).slice().sort((x,Te)=>Te.at-x.at),g=p.map(x=>({at:x.at,status:Os(x.status)})),f=g[0],m=l.type==="trigger.cron",b=typeof c.spec=="string"?c.spec:"",$=typeof c.timezone=="string"?c.timezone:"UTC",q={id:`workflow:${a.id}`,source:"workflow",kind:m?"schedule":"event",name:T(a.title||a.id,k.text),trigger:m?{schedule:T(b,k.text),timezone:$}:{event:T(typeof c.event=="string"?c.event:"",k.text),filters:Us(c.filter,a)},agent:Ms(a),enabled:u,state:d,nextRunAt:m&&u&&b?Xe(r(b,new Date(e),$)):null,lastRun:f?{at:new Date(f.at).toISOString(),status:f.status}:null,lastSuccessAt:(()=>{let x=g.find(Te=>Te.status==="success");return x?new Date(x.at).toISOString():null})(),consecutiveFailures:Qn(g),sampledRuns:p.length,flags:[],attention:null,recent:g.slice(0,Yn).map(x=>({at:new Date(x.at).toISOString(),status:x.status}))},ae=Date.parse(a.updated||a.created||"");q.flags=m?er(q,g,b,$,Number.isFinite(ae)?ae:null,e,n,r):Ls(q,s.get(a.id)?.state==="dormant",Number.isFinite(ae)?ae:null,e,n),o.push(tr(q))}return o.sort(Ps).slice(0,k.routines)}function Qn(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 er(t,e,n,r,o,s,i,a){let l=[],c=e.length?e[0].at:null;if(!t.enabled){let p=rr(c,o,s,i);return p&&l.push(p),l}if(t.consecutiveFailures>=i.failStreak&&l.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),c===null)return l.push({reason:"never-ran",detail:"No persisted attempt"}),l;let d=new Date(c),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&&l.push({reason:"overdue",detail:`No attempt since ${new Date(c).toISOString()}; ${i.missedFires} scheduled fires missed`}),l}function Ls(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=rr(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 rr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Zn?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Zn)} days`:"Disabled and never ran"}}function tr(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 nr={critical:0,warning:1,info:2};function Ps(t,e){let n=t.attention?nr[t.attention]:3,r=e.attention?nr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Os(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 Ms(t){if(t.ownerAgent)return T(t.ownerAgent,k.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?T(String(e.config.agentId),k.text):null}function Us(t,e){let n=[],r=e?.project;if(r&&n.push(T(`project=${r}`,k.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(T(`${o}=${i.join(",")}`,k.filterValue))}return n.slice(0,k.filters)}function Xe(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function T(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function Fs(t,e){return t===void 0?void 0:T(t,e)}import{mkdirSync as Ws,readFileSync as js,renameSync as qs,writeFileSync as Bs}from"fs";import{resolve as Vs}from"path";function or(t){return Vs(He(t),"_state.json")}function _(t){try{let e=JSON.parse(js(or(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 Z(t,e){Ws(He(t),{recursive:!0});let n=or(t),r=`${n}.${process.pid}.tmp`;Bs(r,JSON.stringify(e,null,2)+`
3
+ `),qs(r,n)}function sr(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(),Z(t,{...o,snoozed:s})}function hd(t,e){Z(t,{..._(t),lastDigest:e})}function Ke(t,e,n,r=Date.now()){let o=_(t),s=new Set(n),i={};for(let[l,c]of Object.entries(o.popped??{}))s.has(l)&&(i[l]=c);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(l=>l!==e&&s.has(l));Z(t,{...o,popped:i,wanted:a})}function ir(t,e){let n=_(t);Z(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function bd(t,e=Date.now()){Z(t,{..._(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as Hs,readFileSync as zs}from"fs";ln();$s();function ar(t){let e=dn(t),n={};if(Hs(e))try{n=sn(JSON.parse(zs(e,"utf-8")))}catch{n={}}let r=Le.safeParse(n?.requests);return r.success?r.data:Le.parse(void 0)}async function Sd(t,e={}){let n=(t.channels??[]).filter(r=>!Ce.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...Ce].join(", ")}`}:ce(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack"])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.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 Q,readdirSync as fi,readFileSync as Qe}from"fs";import{dirname as mi,resolve as E}from"path";import{randomBytes as dr}from"crypto";import{existsSync as Ks,mkdirSync as Gs,readdirSync as Js,readFileSync as Ys,renameSync as ur,unlinkSync as Zs,writeFileSync as Qs}from"fs";import{resolve as pr}from"path";function lr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Xs=t=>t.trim().split(`
4
+ `).pop()?.slice(0,300)||"no output";async function cr(t,e,n,r=ze){let o=await r(t.bin,[...lr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Xs(o.stderr||o.stdout)}`}}async function Ed(t,e,n,r,o=ze){return(await o(t.bin,[...lr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var ei=2e3,ti=t=>cr(t.wacli,t.to,t.text);function Ge(t){return pr(t,".agentx","whatsapp-triage","drafts")}var ni=t=>/^[a-z0-9-]{8,64}$/.test(t),pe=(t,e)=>pr(Ge(t),`${e}.json`);function gr(t,e){Gs(Ge(t),{recursive:!0});let n=pe(t,e.id),r=`${n}.${process.pid}.tmp`;Qs(r,JSON.stringify(e,null,2)+`
5
+ `,{mode:384}),ur(r,n)}function Cd(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)}-${dr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return gr(t,o),o}function ge(t,e){if(!ni(e))return null;try{return JSON.parse(Ys(pe(t,e),"utf-8"))}catch{return null}}function fr(t,e){let n=Ge(t);return Ks(n)?Js(n).filter(r=>r.endsWith(".json")).map(r=>ge(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function mr(t,e,n,r={}){let o=ge(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${pe(t,e)}.${process.pid}.${dr(3).toString("hex")}.claim`;try{ur(pe(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??ti)(o).catch(l=>({ok:!1,error:String(l?.message??l)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}gr(t,i);try{Zs(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as oi,writeFileSync as si}from"fs";import{resolve as br}from"path";function Je(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 ri(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 Ld(t,e,n,r,o){let s=Je(t,e,n,o);return s?ri(s.integration,r):{status:"kind-not-found",reason:`agent "${e}" has no integration of kind "${n}"${o?` with label "${o}"`:""}`}}var yr="ready",ii="202510";function ai(t){let e=t.date??t.created_at.slice(0,10);return br(t.workspace,yr,`${e}-${t.platform}-${t.id}.txt`)}function hr(t){let e=ai(t);return oi(br(t.workspace,yr),{recursive:!0}),si(e,t.text.endsWith(`
6
6
  `)?t.text:`${t.text}
7
- `),e}function br(t,e,n){let r=Je(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 yr(t,e,n){return br(t,e,n)!==null}async function ii(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??oi),"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 ai(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=br(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:fr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await ii(t.text,n,r):await ai(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=fr(t);return{ok:!1,error:`not posted on ${J[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function wr(t){return e=>li(e,t)}Ss();rn();rn();var Wd=["done","skipped"],ci=1e3;function di(t){t.exec(`
7
+ `),e}function wr(t,e,n){let r=Je(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 xr(t,e,n){return wr(t,e,n)!==null}async function li(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 ci(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 di(t,e){let n=wr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:hr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await li(t.text,n,r):await ci(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=hr(t);return{ok:!1,error:`not posted on ${J[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function kr(t){return e=>di(e,t)}_s();on();on();var qd=["done","skipped"],ui=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,
@@ -52,15 +52,15 @@ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Un,J as Xn,k as U}from"./ch
52
52
  FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
53
53
  );
54
54
  CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
55
- `)}function kr(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Ye(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function xr(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ui={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at"},fe=class{constructor(e){this.db=e;di(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
55
+ `)}function Sr(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function Ye(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function vr(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var gi={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at"},fe=class{constructor(e){this.db=e;pi(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
56
56
  to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at)
57
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,l)=>{let c=l===0,d=c&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,c?"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)}),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?Ye(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(xr)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?xr(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Ye)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let l=ui[i];!l||a===void 0||(o.push(`${l} = ?`),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(Ye)}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,ci))}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, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},jd=en;var $r=["card","schedule","agent","memory","wiki","whatsapp","email","content","request"],fi=280;function C(t,e=fi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function V(t){if(t.configPath)return _(t.configPath);let e=[_(t.root,"agentx.json"),_(t.root,".agentx","config.json")];return e.find(n=>Q(n))??e[0]}function et(t){return t.wikiDir?_(t.wikiDir):_(t.root,".agentx","wiki")}function mi(t){return B(t.root,"pending").map(hi)}function hi(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:C([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function bi(t){let e=V(t);if(!Q(e))return[];let n;try{n=JSON.parse(Qe(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 l=i.timezone||"UTC",c=i.schedule?mn(i.schedule):"",d=i.schedule?`${c.charAt(0).toLowerCase()}${c.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:C(`${u}${p&&i.schedule?` \xB7 first run ${bn(hn(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return o}function Er(t){let e=_(t,".agentx","memory");return Q(e)?pi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function yi(t){let e=Er(t.root);if(e.length===0)return[];let n=new Pe(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:C(s.content),more:`agentx memory facts held --agent ${o}`});return r}function wi(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 Pn(et(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:C(`${wi(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function ki(t){return pr(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:C(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function vi(t){return Vn(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:C(`Last try not sent: ${e.error}`)}:{}}))}function Si(t){let e=Object.entries(Oe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=me(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:C(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function me(t){try{return JSON.parse(Qe(V(t),"utf-8"))}catch{return{}}}function Ze(t){let e={};try{e=Object.fromEntries(ln(Qe(_(gi(V(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $i(t){let e=_n(t.root,"pending");if(e.length===0)return[];let n=me(t),r=Ze(t);return e.map(o=>{let s=J[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:yr({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:C(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:$n(o.text)}})}function F(t){if(t.requests)return t.requests;if(_(t.root)!==process.cwd()||!Q(_(t.root,".agentx","db.sqlite")))return null;let e=Ne({quiet:!0});if(!e)return null;let n=vr.get(e);return!n&&!tn(e)?null:(n||vr.set(e,n=new nn(e)),n)}var vr=new WeakMap;function du(t){if(t.plans)return t.plans;if(t.requests||_(t.root)!==process.cwd()||!Q(_(t.root,".agentx","db.sqlite")))return null;let e=Ne({quiet:!0});if(!e||!kr(e))return null;let n=Sr.get(e);return n||Sr.set(e,n=new fe(e)),n}var Sr=new WeakMap;function Ei(t){let e=F(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:U(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:C(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var _r={card:mi,schedule:bi,agent:Si,memory:yi,wiki:xi,whatsapp:ki,email:vi,content:$i,request:Ei};function _i(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 Ar(t,e={}){let n=t.now??Date.now(),{snoozed:r}=E(t.root),o=[],s=[],i=0;for(let a of e.kinds??$r){let l;try{l=_r[a](t)}catch(c){s.push({kind:a,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let d=r[c.key];if(d&&Date.parse(d)>n){if(!e.includeSnoozed){i++;continue}c.snoozed_until=d}o.push(c)}}return o.sort(_i),{items:o,snoozed:i,errors:s}}function Ai(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!$r.includes(n)||!r?null:{kind:n,ref:r}}function Ri(t,e,n){switch(e){case"card":return Y(t.root,n)?.status==="pending";case"wiki":return Ln(et(t),n)?.status==="pending";case"whatsapp":return ge(t.root,n)?.status==="pending";case"email":return Bn(t.root,n)?.status==="pending";case"content":return En(t.root,n)?.status==="pending";default:return _r[e](t).some(r=>r.key===`${e}:${n}`)}}async function Rr(t,e,n,r={}){let o=Ai(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(),l=r.by??"operator";if(n==="later"){if(!Ri(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 rr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let c=n==="yes";switch(s){case"card":{let d=qn(t.root,i,c?"yes":"no",{by:l,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 ${c?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(c?yn:wn)(i,{configPath:V(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Oe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(c)return Me(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 ce(p=>{dn(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:V(t),reload:t.reload});return u.success?(Me(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(!Er(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Pe(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"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=et(t),u=c?On(d,i,{by:l,force:r.force,now:a}):Mn(d,i,{by:l,reason:r.note,now:a});return u.ok?{ok:!0,message:c?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"whatsapp":{let d=await gr(t.root,i,c?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:c?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??zn(me(t),Ze(t)),u=await Hn(t.root,i,c?"yes":"no",{by:l,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:c?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??wr({config:me(t),env:Ze(t)}),u=await An(t.root,i,c?"yes":"no",{by:l,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!c)return{ok:!0,message:`${e}: dropped, nothing published`};let p=J[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=F(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:c?sr(V(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 ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var Ii=3,Ti=7,Di=50,nt=120,Ci=280,tt=600,Tr=36e5,Ni=24*Tr;function gu(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 H(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var he=t=>new Date(t).toISOString();function Li(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:H(e.title,nt),...e.ask?{ask:H(e.ask,tt)}:{},...e.detail?{facts:H(e.detail,Ci)}:{},...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 Pi={done:"Done",declined:"Declined",dropped:"Dropped"};function Dr(t,e,n){let{record:r,links:o}=e,s=U(r,nt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:H(s.said,tt)}:{},agent:r.agentId,askedAt:he(r.createdAt),changedAt:he(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:H(r.question,tt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(c=>c.kind==="run"&&!!t.liveRuns?.has(c.ref)),l=t.now-r.updatedAt<(t.quietHours??Ii)*Tr;return{...i,column:a||l?"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:he(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Pi[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Oi(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 Mi(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:H(e.title,nt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Oi(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var A=t=>t&&Date.parse(t)||0,Ir=(t,e)=>t.map(n=>n[e]).filter(n=>!!A(n)).sort((n,r)=>A(n)-A(r))[0];function rt(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(Li(o,s,o.node===t.node))}let r=Cr(t,e);for(let o of t.requests??[]){let s=Dr(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function Cr(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function fu(t){let e=rt(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=Cr(t,n),s=[],i=[],a=[];for(let p of t.requests??[]){let g=Dr(t,p,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??Ti)*Ni;for(let p of t.cards)p.status!=="pending"&&A(p.decided_at)>=l&&a.push(Mi(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 c=a.filter(p=>A(p.changedAt)>=l).slice(0,Di),d=Ir(n,"askedAt"),u=Ir(i,"changedAt");return{ts:he(t.now),cards:[...n,...s,...i,...c],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:c.length}},errors:r}}function Ui(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 Fi(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 yu(t,e){let n=t.now??Date.now(),r=[],o=Ar(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=F(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:l,errors:c}=rt({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ui)}],requests:a,deferred:i});return Fi(l,i.size,[...r,...c])}import{readFileSync as Wi}from"fs";var ji=1e4,Nr=/^[0-9a-f]{7,64}$/i;function ku(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Nr.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(ji)})}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"&&Nr.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function vu(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Wi(n.tokenFile,"utf-8").trim().split(`
58
- `)[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 Lr=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function $u(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/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 Eu(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 _u(t){return Lr.has(t)}function Au(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Lr.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 Ru(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 Iu(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 be(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function qi(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Bi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Du(t,e=Bi()){let n=be(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=qi(n),s=[be(t.host),be(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=be(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Cu(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var ot="/api/admin/pictures",Vi=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Hi=/^\/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 zi(t){let e={agent:{},person:{}};for(let n of Rn)for(let[r,o]of Object.entries(Dn(t,n)))e[n][r]=Cn(n,r,o);return e}function Pu(t,e,n,r,o){let s=n.match(Vi);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return y(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=Nn(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":In,"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 Ou(t,e,n,r){if(n!==ot&&!n.startsWith(`${ot}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===ot)return o!=="GET"?(y(e,405,{error:"GET only"}),!0):(y(e,200,{...zi(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Hi);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],l=decodeURIComponent(s[2]),c=a==="agent"?r.agentIds():r.personIds();if(!Tn.test(l)||!c.includes(l))return y(e,404,{error:a==="agent"?`no agent "${l}" in agentx.json`:`no person "${l}" in agentx.json`}),!0;if(o==="DELETE"){let d=qe(r.root,a,l);return y(e,200,{ok:!0,removed:d}),!0}try{let d=await Be(t),u=await je(r.root,a,l,d);y(e,200,{ok:!0,url:u.url})}catch(d){if(d instanceof We)return y(e,d.status,{error:d.message}),!0;throw d}return!0}async function Mu(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:qe(r.root,"agent",i)});return}try{let a=await je(r.root,"agent",i,await Be(t));y(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof We){y(e,a.status,{error:a.message});return}throw a}}var Pr={};function Fu(t){Pr=t}function Wu(){return Pr}var ju=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
57
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,l)=>{let c=l===0,d=c&&a.agentId===n&&a.kind!=="message";i.run(e,l+1,a.name,a.kind,a.agentId,a.doneWhen,c?"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)}),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?Ye(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(vr)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?vr(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(Ye)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let l=gi[i];!l||a===void 0||(o.push(`${l} = ?`),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(Ye)}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,ui))}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, rowid LIMIT ?").all(e,n).map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}},Bd=tn;var Er=["card","schedule","agent","memory","wiki","whatsapp","email","content","request"],hi=280;function C(t,e=hi){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function V(t){if(t.configPath)return E(t.configPath);let e=[E(t.root,"agentx.json"),E(t.root,".agentx","config.json")];return e.find(n=>Q(n))??e[0]}function et(t){return t.wikiDir?E(t.wikiDir):E(t.root,".agentx","wiki")}function bi(t){return B(t.root,"pending").map(yi)}function yi(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:C([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function wi(t){let e=V(t);if(!Q(e))return[];let n;try{n=JSON.parse(Qe(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 l=i.timezone||"UTC",c=i.schedule?hn(i.schedule):"",d=i.schedule?`${c.charAt(0).toLowerCase()}${c.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:C(`${u}${p&&i.schedule?` \xB7 first run ${yn(bn(i.schedule,l,r),l)}`:""}`),more:"agentx schedule list"})}return o}function Ar(t){let e=E(t,".agentx","memory");return Q(e)?fi(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function xi(t){let e=Ar(t.root);if(e.length===0)return[];let n=new Pe(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:C(s.content),more:`agentx memory facts held --agent ${o}`});return r}function ki(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 vi(t){return On(et(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:C(`${ki(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}function Si(t){return fr(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:C(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function $i(t){return zn(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:C(`Last try not sent: ${e.error}`)}:{}}))}function _i(t){let e=Object.entries(Oe(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=me(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:C(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function me(t){try{return JSON.parse(Qe(V(t),"utf-8"))}catch{return{}}}function Ze(t){let e={};try{e=Object.fromEntries(cn(Qe(E(mi(V(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Ei(t){let e=An(t.root,"pending");if(e.length===0)return[];let n=me(t),r=Ze(t);return e.map(o=>{let s=J[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:xr({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:C(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:_n(o.text)}})}function F(t){if(t.requests)return t.requests;if(E(t.root)!==process.cwd()||!Q(E(t.root,".agentx","db.sqlite")))return null;let e=Ne({quiet:!0});if(!e)return null;let n=$r.get(e);return!n&&!nn(e)?null:(n||$r.set(e,n=new rn(e)),n)}var $r=new WeakMap;function gu(t){if(t.plans)return t.plans;if(t.requests||E(t.root)!==process.cwd()||!Q(E(t.root,".agentx","db.sqlite")))return null;let e=Ne({quiet:!0});if(!e||!Sr(e))return null;let n=_r.get(e);return n||_r.set(e,n=new fe(e)),n}var _r=new WeakMap;function Ai(t){let e=F(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:U(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:C(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var tt={card:bi,schedule:wi,agent:_i,memory:xi,wiki:vi,whatsapp:Si,email:$i,content:Ei,request:Ai};function Ri(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 Rr(t,e={}){let n=t.now??Date.now(),{snoozed:r}=_(t.root),o=[],s=[],i=0;for(let a of e.kinds??Er){let l;try{l=tt[a](t)}catch(c){s.push({kind:a,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let d=r[c.key];if(d&&Date.parse(d)>n){if(!e.includeSnoozed){i++;continue}c.snoozed_until=d}o.push(c)}}return o.sort(Ri),{items:o,snoozed:i,errors:s}}function Ir(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Er.includes(n)||!r?null:{kind:n,ref:r}}function Ii(t,e,n){switch(e){case"card":return Y(t.root,n)?.status==="pending";case"wiki":return Pn(et(t),n)?.status==="pending";case"whatsapp":return ge(t.root,n)?.status==="pending";case"email":return Hn(t.root,n)?.status==="pending";case"content":return En(t.root,n)?.status==="pending";default:return tt[e](t).some(r=>r.key===`${e}:${n}`)}}async function Tr(t,e,n,r={}){let o=n==="later"?null:Ir(e),s;if(o)try{s=tt[o.kind](t).find(a=>a.key===e)}catch{s=void 0}let i=await Ti(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;jn(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 Ti(t,e,n,r){let o=Ir(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(),l=r.by??"operator";if(n==="later"){if(!Ii(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 sr(t.root,e,u,a),{ok:!0,message:`${e} put off until ${u.toISOString()}`}}let c=n==="yes";switch(s){case"card":{let d=Vn(t.root,i,c?"yes":"no",{by:l,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 ${c?"yes":"no"}${d.card.choice?` (${d.card.choice}${d.card.choice_suggested?", the suggested option":""})`:""}`}:d}case"schedule":{let d=await(c?wn:xn)(i,{configPath:V(t),reload:t.reload});return d.success?{ok:!0,message:d.message}:{ok:!1,error:d.message}}case"agent":{if(Oe(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(c)return Me(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 ce(p=>{un(p,`agents.${i}`);for(let[g,f]of Object.entries(p.crons??{}))f?.agent===i&&(delete p.crons[g],d.push(g))},{configPath:V(t),reload:t.reload});return u.success?(Me(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(!Ar(t.root).includes(u))return{ok:!1,error:`no memory for agent "${u}"`};let g=new Pe(t.root);return g.held(u).some(f=>f.id===p)?(g.review(u,p,c?"approved":"rejected",l),{ok:!0,message:`${e} ${c?"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=et(t),u=c?Mn(d,i,{by:l,force:r.force,now:a}):Un(d,i,{by:l,reason:r.note,now:a});return u.ok?{ok:!0,message:c?`${u.proposal.article.path} written to the shared wiki`:`${e} rejected`}:u}case"whatsapp":{let d=await mr(t.root,i,c?"yes":"no",{by:l,now:a,send:t.sendWhatsApp});return d.ok?{ok:!0,message:c?`${e}: sent to ${d.draft.chat_name||d.draft.to}`:`${e}: dropped, nothing sent`}:d}case"email":{let d=t.sendEmail??Kn(me(t),Ze(t)),u=await Xn(t.root,i,c?"yes":"no",{by:l,now:a,text:r.text,send:d});return u.ok?{ok:!0,message:c?`${e}: sent to ${u.draft.to}${u.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:u}case"content":{let d=t.publishContent??kr({config:me(t),env:Ze(t)}),u=await Rn(t.root,i,c?"yes":"no",{by:l,now:a,text:r.text,seen:r.seen,publish:d});if(!u.ok)return u;if(!c)return{ok:!0,message:`${e}: dropped, nothing published`};let p=J[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=F(t),u=d?.get(i);return!d||!u||u.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:c?ar(V(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 ${l}`,a),{ok:!0,message:`${e}: dropped`})}}}var Di=3,Ci=7,Ni=50,rt=120,Li=280,nt=600,Cr=36e5,Pi=24*Cr;function hu(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 H(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var he=t=>new Date(t).toISOString();function Oi(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:H(e.title,rt),...e.ask?{ask:H(e.ask,nt)}:{},...e.detail?{facts:H(e.detail,Li)}:{},...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 Mi={done:"Done",declined:"Declined",dropped:"Dropped"};function Nr(t,e,n){let{record:r,links:o}=e,s=U(r,rt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:H(s.said,nt)}:{},agent:r.agentId,askedAt:he(r.createdAt),changedAt:he(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:H(r.question,nt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(c=>c.kind==="run"&&!!t.liveRuns?.has(c.ref)),l=t.now-r.updatedAt<(t.quietHours??Di)*Cr;return{...i,column:a||l?"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:he(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:Mi[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ui(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 Fi(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:H(e.title,rt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ui(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var A=t=>t&&Date.parse(t)||0,Dr=(t,e)=>t.map(n=>n[e]).filter(n=>!!A(n)).sort((n,r)=>A(n)-A(r))[0];function ot(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(Oi(o,s,o.node===t.node))}let r=Lr(t,e);for(let o of t.requests??[]){let s=Nr(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function Lr(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function bu(t){let e=ot(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=Lr(t,n),s=[],i=[],a=[];for(let p of t.requests??[]){let g=Nr(t,p,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let l=t.now-(t.doneDays??Ci)*Pi;for(let p of t.cards)p.status!=="pending"&&A(p.decided_at)>=l&&a.push(Fi(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 c=a.filter(p=>A(p.changedAt)>=l).slice(0,Ni),d=Dr(n,"askedAt"),u=Dr(i,"changedAt");return{ts:he(t.now),cards:[...n,...s,...i,...c],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:c.length}},errors:r}}function Wi(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 ji(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 ku(t,e){let n=t.now??Date.now(),r=[],o=Rr(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=F(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:l,errors:c}=ot({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Wi)}],requests:a,deferred:i});return ji(l,i.size,[...r,...c])}import{readFileSync as qi}from"fs";var Bi=1e4,Pr=/^[0-9a-f]{7,64}$/i;function $u(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Pr.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(Bi)})}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"&&Pr.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function _u(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=qi(n.tokenFile,"utf-8").trim().split(`
58
+ `)[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 Or=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function Au(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/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 Ru(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 Iu(t){return Or.has(t)}function Tu(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Or.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 Du(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 Cu(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 be(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Vi(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Hi(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Lu(t,e=Hi()){let n=be(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Vi(n),s=[be(t.host),be(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=be(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function Pu(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var st="/api/admin/pictures",zi=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Xi=/^\/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 Ki(t){let e={agent:{},person:{}};for(let n of In)for(let[r,o]of Object.entries(Cn(t,n)))e[n][r]=Nn(n,r,o);return e}function Uu(t,e,n,r,o){let s=n.match(zi);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return y(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=Ln(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":Tn,"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 Fu(t,e,n,r){if(n!==st&&!n.startsWith(`${st}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===st)return o!=="GET"?(y(e,405,{error:"GET only"}),!0):(y(e,200,{...Ki(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Xi);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],l=decodeURIComponent(s[2]),c=a==="agent"?r.agentIds():r.personIds();if(!Dn.test(l)||!c.includes(l))return y(e,404,{error:a==="agent"?`no agent "${l}" in agentx.json`:`no person "${l}" in agentx.json`}),!0;if(o==="DELETE"){let d=qe(r.root,a,l);return y(e,200,{ok:!0,removed:d}),!0}try{let d=await Be(t),u=await je(r.root,a,l,d);y(e,200,{ok:!0,url:u.url})}catch(d){if(d instanceof We)return y(e,d.status,{error:d.message}),!0;throw d}return!0}async function Wu(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:qe(r.root,"agent",i)});return}try{let a=await je(r.root,"agent",i,await Be(t));y(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof We){y(e,a.status,{error:a.message});return}throw a}}var Mr={};function qu(t){Mr=t}function Bu(){return Mr}var Vu=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
59
59
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
60
60
  <link rel="preconnect" href="https://fonts.googleapis.com">
61
61
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
62
62
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700;800&family=Roboto+Mono:wght@400;500;600&display=swap" rel="stylesheet">
63
- <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,qu=`
63
+ <script>(function(){try{var t=localStorage.getItem('ax-theme');if(t!=='light'&&t!=='dark'){t='dark';localStorage.setItem('ax-theme',t)}document.documentElement.setAttribute('data-theme',t)}catch(e){document.documentElement.setAttribute('data-theme','dark')}})();</script>`,Hu=`
64
64
  .ax-topbar{display:flex;align-items:center;justify-content:space-between;
65
65
  padding:8px 18px;border-bottom:1px solid var(--ax-border);
66
66
  background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
@@ -141,7 +141,7 @@ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Un,J as Xn,k as U}from"./ch
141
141
  background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
142
142
  flex-wrap:wrap}
143
143
  .ax-subheader > * {flex-shrink:0}
144
- .ax-subheader .spacer{flex:1}`,Bu=`<script>
144
+ .ax-subheader .spacer{flex:1}`,zu=`<script>
145
145
  (function(){
146
146
  function wireTheme(){
147
147
  var sw = document.querySelectorAll('[data-theme-opt]');
@@ -336,7 +336,7 @@ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Un,J as Xn,k as U}from"./ch
336
336
  document.addEventListener('DOMContentLoaded', wire);
337
337
  } else { wire(); }
338
338
  })();
339
- </script>`;function Vu(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Xi='<span class="ax-build" hidden></span>';function Hu(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(c=>c.primary)?.id||e[0].id,r=e.find(c=>c.id===n)||e[0],o=e.map(c=>{let d=c.id===n,u=c.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",p=!!c.tokenScope&&!c.primary,g=p?"#":c.dashboardUrl?`${c.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",f=p?` data-peer-id="${N(c.id)}" data-peer-action="proxy"`:c.primary?' data-peer-id="primary" data-peer-action="proxy"':"",m=p?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':c.tokenScope?`<div class="url">${N(c.tokenScope)}</div>`:c.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${N(g)}" class="${d?"is-current":""}"${f}>
339
+ </script>`;function Xu(t){let e=n=>typeof n=="string"&&n?n:null;return{node:e(t?.node?.id),version:e(t?.version),commit:e(t?.commit),startedAt:e(t?.startedAt),diskNewer:t?.build?.newer===!0}}var Gi='<span class="ax-build" hidden></span>';function Ku(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(c=>c.primary)?.id||e[0].id,r=e.find(c=>c.id===n)||e[0],o=e.map(c=>{let d=c.id===n,u=c.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",p=!!c.tokenScope&&!c.primary,g=p?"#":c.dashboardUrl?`${c.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",f=p?` data-peer-id="${N(c.id)}" data-peer-action="proxy"`:c.primary?' data-peer-id="primary" data-peer-action="proxy"':"",m=p?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':c.tokenScope?`<div class="url">${N(c.tokenScope)}</div>`:c.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${N(g)}" class="${d?"is-current":""}"${f}>
340
340
  <div class="row"><span class="dot"></span><span>${N(c.name)}${u}</span></div>
341
341
  ${c.dashboardUrl?`<div class="url">${N(c.dashboardUrl)}</div>`:""}
342
342
  ${m}
@@ -356,14 +356,14 @@ import{a as ze}from"./chunk-GTJIKXDB.js";import{C as Un,J as Xn,k as U}from"./ch
356
356
  </div>
357
357
  <div class="ax-topbar__right">
358
358
  ${t.rightExtras||""}
359
- ${Xi}
359
+ ${Gi}
360
360
  ${s}
361
361
  <div class="ax-theme-switch" role="tablist" aria-label="Theme">
362
362
  <button data-theme-opt="dark">Dark</button>
363
363
  <button data-theme-opt="light">Light</button>
364
364
  </div>
365
365
  </div>
366
- </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function N(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as io,mkdirSync as va,readFileSync as Sa,renameSync as $a,writeFileSync as Ea}from"fs";import{homedir as _a}from"os";import{dirname as Aa,join as Ra}from"path";import{execFile as oa,execFileSync as sa}from"child_process";import{execFileSync as Ki}from"child_process";import{existsSync as Mr,mkdirSync as Gi,readdirSync as Ji,readFileSync as Ur,renameSync as Yi,writeFileSync as Zi}from"fs";import{homedir as Fr}from"os";import{join as it}from"path";var R="siri:",Wr="com.apple.ttsbundle.gryphon-neural_",jr=t=>!!t&&t.startsWith(Wr),Qi=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],ea=()=>{try{return Ki("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},st;function at(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&st!==void 0)return st;let{platform:n=process.platform,exists:r=Mr,prefDomain:o=ea}=t,s=n==="darwin"&&Qi.every(i=>r(i))&&o();return e||(st=s),s}var qr=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Br={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},lt=t=>Br[t.toLowerCase()]??null;function ye(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var ta=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function na(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(ta)){let i=`${r}-${o}`,a=`${Wr}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Br[s]??null,siri:!0})}return[...e.values()]}function we(t=qr,e={}){if(!at(e))return[];let n=[];for(let r of t){let o;try{o=Ji(r)}catch{continue}for(let s of o)try{n.push(Ur(it(r,s,"Info.plist"),"latin1"))}catch{}}return na(n)}var Or=`#!/bin/sh
366
+ </header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function N(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{existsSync as lo,mkdirSync as $a,readFileSync as _a,renameSync as Ea,writeFileSync as Aa}from"fs";import{homedir as Ra}from"os";import{dirname as Ia,join as Ta}from"path";import{execFile as ia,execFileSync as aa}from"child_process";import{execFileSync as Ji}from"child_process";import{existsSync as Fr,mkdirSync as Yi,readdirSync as Zi,readFileSync as Wr,renameSync as Qi,writeFileSync as ea}from"fs";import{homedir as jr}from"os";import{join as at}from"path";var R="siri:",qr="com.apple.ttsbundle.gryphon-neural_",Br=t=>!!t&&t.startsWith(qr),ta=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],na=()=>{try{return Ji("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},it;function lt(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&it!==void 0)return it;let{platform:n=process.platform,exists:r=Fr,prefDomain:o=na}=t,s=n==="darwin"&&ta.every(i=>r(i))&&o();return e||(it=s),s}var Vr=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Hr={aaron:"male",damon:"male",daniel:"male",pierre:"male",samer:"male",arthur:"male",gordon:"male",martin:"male",nora:"female",simone:"female",marie:"female",soha:"female",martha:"female",catherine:"female",helena:"female",nicky:"female"},ct=t=>Hr[t.toLowerCase()]??null;function ye(t){let e=/^com\.apple\.ttsbundle\.gryphon-neural_([a-z]+)_([a-z]{2}-[A-Z]{2})_premium$/.exec(t);return e?{name:e[1],locale:e[2]}:null}var ra=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function oa(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(ra)){let i=`${r}-${o}`,a=`${qr}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Hr[s]??null,siri:!0})}return[...e.values()]}function we(t=Vr,e={}){if(!lt(e))return[];let n=[];for(let r of t){let o;try{o=Zi(r)}catch{continue}for(let s of o)try{n.push(Wr(at(r,s,"Info.plist"),"latin1"))}catch{}}return oa(n)}var Ur=`#!/bin/sh
367
367
  # Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
368
368
  # siri-say.sh [voice] < text speak one line. A Siri voice id switches
369
369
  # the OS default for it; any other id is
@@ -375,7 +375,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
375
375
  dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
376
376
  stops="$dir/stop"
377
377
  read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
378
- assets=\${AGENTX_SIRI_ASSET_DIRS:-"${qr.join(" ")}"}
378
+ assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Vr.join(" ")}"}
379
379
  if [ "$1" = --stop ]; then
380
380
  mkdir -p "$dir" || exit 1
381
381
  # Queued lines see this change and drop. The owner's trap stops say,
@@ -468,29 +468,29 @@ wait "$say_pid"
468
468
  status=$?
469
469
  say_pid=
470
470
  finish $status
471
- `,ra=(t=Fr())=>it(t,".agentx","voice","siri-say.sh");function Vr(t=Fr()){let e=ra(t);return Mr(e)&&Ur(e,"utf8")===Or||(Gi(it(t,".agentx","voice"),{recursive:!0}),Zi(`${e}.tmp`,Or,{mode:493}),Yi(`${e}.tmp`,e)),e}var Hr=`ObjC.import("AVFoundation")
471
+ `,sa=(t=jr())=>at(t,".agentx","voice","siri-say.sh");function zr(t=jr()){let e=sa(t);return Fr(e)&&Wr(e,"utf8")===Ur||(Yi(at(t,".agentx","voice"),{recursive:!0}),ea(`${e}.tmp`,Ur,{mode:493}),Qi(`${e}.tmp`,e)),e}var Xr=`ObjC.import("AVFoundation")
472
472
  const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
473
473
  for (let i = 0; i < vs.count; i++) {
474
474
  const v = vs.objectAtIndex(i)
475
475
  out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
476
476
  }
477
- out.join("\\n")`,ia=new Set(["Fred","Kathy","Ralph","Junior"]),aa={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 zr(t){let e=[];for(let n of t.split(`
478
- `)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!ia.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":aa[o]??null})}return e}var la=10*60*1e3,ep=60*1e3,z=null,ct=!1;function dt(t=Date.now(),e=la){if(process.platform!=="darwin")return[];if(z)t-z.at>e&&!ct&&(ct=!0,oa("osascript",["-l","JavaScript","-e",Hr],{timeout:1e4},(n,r)=>{ct=!1,n||(z={at:Date.now(),voices:[...zr(String(r)),...we()]})}));else try{z={at:t,voices:[...zr(sa("osascript",["-l","JavaScript","-e",Hr],{encoding:"utf8",timeout:1e4})),...we()]}}catch(n){ut(`[voice] could not list system voices: ${String(n?.message??n).split(`
479
- `)[0]}`),z={at:t,voices:we()}}return z.voices}var ut=t=>process.stderr.write(t+`
480
- `),xe=new Set;function tp(t){ut=t}function W(t,e){xe.has(t)||(xe.add(t),ut(e))}function Gr(t){for(let e of xe)t(e)&&xe.delete(e)}var Jr=()=>{};function np(t){Jr=t}function Yr(t){try{Jr(t)}catch(e){W("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var ca={premium:3,enhanced:2,standard:1},da=new Set(["Grandma","Grandpa"]);function Xr(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!da.has(t.name)?1:0;return ca[t.quality]*10+e}var X=t=>t.toLowerCase().split(/[-_]/)[0],Kr=t=>t.id.startsWith("com.apple.voice.");function pt(t,e,n,r=new Set){let o=ee(t.filter(a=>!a.siri&&X(a.locale)===X(e)),e);if(o.some(Kr)&&(o=o.filter(Kr)),n==="female"||n==="male"){let a=o.filter(l=>l.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 ee(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=X(e),o=t.filter(s=>X(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Xr(i)-Xr(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function te(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(c=>c.id===r);if(o)return o;if(r.toLowerCase().startsWith(R)){let c=r.slice(R.length).trim().toLowerCase(),d=ee(e.filter(p=>p.siri&&p.name.toLowerCase()===c),n)[0];if(d||!c)return d??null;let u=te(c,e.filter(p=>X(p.locale)===X(n)),n);return u&&W(`siri:${c}`,`[voice] Siri voice "${c}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(c=>!c.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ee(e.filter(c=>c.name.toLowerCase()===i),n);return(s?a.find(c=>c.quality===s[2].toLowerCase()):void 0)??a[0]??null}function Zr(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",l=a?i.gender:s,c=e.filter(u=>!o.has(u.name.toLowerCase())),d=c.find(u=>u.gender===l)??(a?e.find(u=>u.gender===l):void 0)??c[0]??e[r.size%e.length];r.set(i.id,d),o.add(d.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}Zt();var gt="system",ua=t=>t.trim().toLowerCase()===gt,pa="21m00Tcm4TlvDq8ikWAM";function ft(t,e,n={},r=dt()){let o=e[t],s=o?.name||t,i=o?.voice,a=ht(e,n,r).get(t)??null,l=ha(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?ve(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||ya(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ve=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function ga(t,e,n,r){if(!e||!n.length)return null;let o=te(e,n,r);return o||(W(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Yr(e)),o}function no(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:lt(n.slice(R.length).trim())};let r=ye(n);return r?{locale:r.locale,gender:lt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var ro=t=>t.toLowerCase().split(/[-_]/)[0],Qr=(t,e)=>typeof t=="string"?t:t?.[ro(e)];function ke(t,e,n,r){if(e!==void 0)return ua(e)?null:ga(t,e,n,r)??void 0}var mt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function fa(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=ke("voice.system",Qr(e.system,o),n,o),l=()=>new Set([...r,...[...s.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=Qr(d.system,o),p=ke(d.id,u,n,o),g=p!==void 0?p:u!==void 0&&n.length?ma(d,u,o,a,n,l()):a!==void 0&&mt(a,d.gender)?a:void 0;g!==void 0?s.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let c=l();for(let[d,u]of Zr(i,ee(n.filter(p=>!p.siri),o),c))s.set(d,u);return s}function ma(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let l=ke(`${t.id}.fallbacks`,a,o,n);if(l!==void 0)return l}if(r!==void 0&&mt(r,t.gender))return r;let i=no(e,n);return pt(o,i.locale,t.gender??i.gender,s)??void 0}function ha(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,l,c)=>{if(!(!l||typeof l=="string"))for(let[d,u]of Object.entries(l)){let p=ke(`${a}.${d}`,u,o,d);p===void 0&&o.length&&(p=pt(o,d,n??no(u,d).gender)??void 0),p!==void 0&&c(p)&&(s[ro(d)]=p)}};return i("voice.system",r.system,a=>mt(a,n)),i(t,e,()=>!0),s}function ap(t,e){let n=e?le(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ve(r):null}}function ht(t,e={},n=dt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return fa(r,e,n)}function bt(t,e){let n={provider:t.provider,elevenlabs:ba(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 ba(t,e){return t||e||process.env.AGENTX_VOICE_ID||pa}function ya(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 wa=8*60*60*1e3,xa=500,eo=class{constructor(e=wa){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(to(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=to(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>xa&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},to=(t,e)=>`${t}\0${e}`;function oo(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 lp(t,e,n,r={}){let o=e[t],s=ft(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:bt(s),persona:i||`You are ${s.name}.`,introLine:oo(s,n)}}var ka="[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 cp(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`${ka}
481
- ${oo(o,e.voice.introduce===!0&&!!r)}`}var Ia="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",ao=(t=_a())=>Ra(t,".agentx","voice","health.json");function Ta(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===gt)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 te(r,e,n)!==null}function Da(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 Ca(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Da(t)){if(Ta(s,e,i))continue;r??=ht(t.agents,t.voice,e);let l=n.get(s)??{voice:s,agents:[],speaksWith:{}};l.agents.includes(o)||l.agents.push(o);let c=r.get(o);o!=="voice.system"&&!a&&(l.speaksWith[o]=c?ve(c):"the OS default voice"),n.set(s,l)}return[...n.values()]}function yt(t){let e=ye(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 Na(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${yt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
477
+ out.join("\\n")`,la=new Set(["Fred","Kathy","Ralph","Junior"]),ca={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 Kr(t){let e=[];for(let n of t.split(`
478
+ `)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!la.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":ca[o]??null})}return e}var da=10*60*1e3,rp=60*1e3,z=null,dt=!1;function ut(t=Date.now(),e=da){if(process.platform!=="darwin")return[];if(z)t-z.at>e&&!dt&&(dt=!0,ia("osascript",["-l","JavaScript","-e",Xr],{timeout:1e4},(n,r)=>{dt=!1,n||(z={at:Date.now(),voices:[...Kr(String(r)),...we()]})}));else try{z={at:t,voices:[...Kr(aa("osascript",["-l","JavaScript","-e",Xr],{encoding:"utf8",timeout:1e4})),...we()]}}catch(n){pt(`[voice] could not list system voices: ${String(n?.message??n).split(`
479
+ `)[0]}`),z={at:t,voices:we()}}return z.voices}var pt=t=>process.stderr.write(t+`
480
+ `),xe=new Set;function op(t){pt=t}function W(t,e){xe.has(t)||(xe.add(t),pt(e))}function Yr(t){for(let e of xe)t(e)&&xe.delete(e)}var Zr=()=>{};function sp(t){Zr=t}function Qr(t){try{Zr(t)}catch(e){W("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var ua={premium:3,enhanced:2,standard:1},pa=new Set(["Grandma","Grandpa"]);function Gr(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!pa.has(t.name)?1:0;return ua[t.quality]*10+e}var X=t=>t.toLowerCase().split(/[-_]/)[0],Jr=t=>t.id.startsWith("com.apple.voice.");function gt(t,e,n,r=new Set){let o=ee(t.filter(a=>!a.siri&&X(a.locale)===X(e)),e);if(o.some(Jr)&&(o=o.filter(Jr)),n==="female"||n==="male"){let a=o.filter(l=>l.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 ee(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=X(e),o=t.filter(s=>X(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Gr(i)-Gr(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function te(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(c=>c.id===r);if(o)return o;if(r.toLowerCase().startsWith(R)){let c=r.slice(R.length).trim().toLowerCase(),d=ee(e.filter(p=>p.siri&&p.name.toLowerCase()===c),n)[0];if(d||!c)return d??null;let u=te(c,e.filter(p=>X(p.locale)===X(n)),n);return u&&W(`siri:${c}`,`[voice] Siri voice "${c}" is not installed; speaking with ${u.name} (${u.locale}) instead.`),u}e=e.filter(c=>!c.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ee(e.filter(c=>c.name.toLowerCase()===i),n);return(s?a.find(c=>c.quality===s[2].toLowerCase()):void 0)??a[0]??null}function eo(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",l=a?i.gender:s,c=e.filter(u=>!o.has(u.name.toLowerCase())),d=c.find(u=>u.gender===l)??(a?e.find(u=>u.gender===l):void 0)??c[0]??e[r.size%e.length];r.set(i.id,d),o.add(d.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}Qt();var ft="system",ga=t=>t.trim().toLowerCase()===ft,fa="21m00Tcm4TlvDq8ikWAM";function mt(t,e,n={},r=ut()){let o=e[t],s=o?.name||t,i=o?.voice,a=bt(e,n,r).get(t)??null,l=ya(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?ve(a):null,systemByLanguage:l,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||xa(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ve=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function ma(t,e,n,r){if(!e||!n.length)return null;let o=te(e,n,r);return o||(W(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Qr(e)),o}function oo(t,e){let n=t.trim();if(n.toLowerCase().startsWith(R))return{locale:e,gender:ct(n.slice(R.length).trim())};let r=ye(n);return r?{locale:r.locale,gender:ct(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var so=t=>t.toLowerCase().split(/[-_]/)[0],to=(t,e)=>typeof t=="string"?t:t?.[so(e)];function ke(t,e,n,r){if(e!==void 0)return ga(e)?null:ma(t,e,n,r)??void 0}var ht=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function ha(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=ke("voice.system",to(e.system,o),n,o),l=()=>new Set([...r,...[...s.values()].flatMap(d=>d?[d.name]:[])]);for(let d of t){let u=to(d.system,o),p=ke(d.id,u,n,o),g=p!==void 0?p:u!==void 0&&n.length?ba(d,u,o,a,n,l()):a!==void 0&&ht(a,d.gender)?a:void 0;g!==void 0?s.set(d.id,g):i.push({id:d.id,gender:d.gender??null})}let c=l();for(let[d,u]of eo(i,ee(n.filter(p=>!p.siri),o),c))s.set(d,u);return s}function ba(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let l=ke(`${t.id}.fallbacks`,a,o,n);if(l!==void 0)return l}if(r!==void 0&&ht(r,t.gender))return r;let i=oo(e,n);return gt(o,i.locale,t.gender??i.gender,s)??void 0}function ya(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,l,c)=>{if(!(!l||typeof l=="string"))for(let[d,u]of Object.entries(l)){let p=ke(`${a}.${d}`,u,o,d);p===void 0&&o.length&&(p=gt(o,d,n??oo(u,d).gender)??void 0),p!==void 0&&c(p)&&(s[so(d)]=p)}};return i("voice.system",r.system,a=>ht(a,n)),i(t,e,()=>!0),s}function dp(t,e){let n=e?le(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ve(r):null}}function bt(t,e={},n=ut()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return ha(r,e,n)}function yt(t,e){let n={provider:t.provider,elevenlabs:wa(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 wa(t,e){return t||e||process.env.AGENTX_VOICE_ID||fa}function xa(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 ka=8*60*60*1e3,va=500,no=class{constructor(e=ka){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(ro(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=ro(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>va&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},ro=(t,e)=>`${t}\0${e}`;function io(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 up(t,e,n,r={}){let o=e[t],s=mt(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:yt(s),persona:i||`You are ${s.name}.`,introLine:io(s,n)}}var Sa="[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 pp(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`${Sa}
481
+ ${io(o,e.voice.introduce===!0&&!!r)}`}var Da="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",co=(t=Ra())=>Ta(t,".agentx","voice","health.json");function Ca(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===ft)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 te(r,e,n)!==null}function Na(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 La(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Na(t)){if(Ca(s,e,i))continue;r??=bt(t.agents,t.voice,e);let l=n.get(s)??{voice:s,agents:[],speaksWith:{}};l.agents.includes(o)||l.agents.push(o);let c=r.get(o);o!=="voice.system"&&!a&&(l.speaksWith[o]=c?ve(c):"the OS default voice"),n.set(s,l)}return[...n.values()]}function wt(t){let e=ye(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 Pa(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${wt(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
482
482
  `)}
483
- Reinstall in ${Ia}. Agents switch back on their own once it is installed.`}}function La(t=ao()){if(!io(t))return null;try{let e=JSON.parse(Sa(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Pa(t,e){va(Aa(t),{recursive:!0}),Ea(`${t}.tmp`,JSON.stringify(e,null,2)+`
484
- `),$a(`${t}.tmp`,t)}var so=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??ao(),s=new Map((La(o)?.missing??[]).map(u=>[u.voice,u])),i=Ca(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}:{}})),l=[...s.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of l)this.deps.log(`[voice] ${yt(u)} is installed again; its agents speak with it again`);l.length&&Gr(u=>l.some(p=>u===p||u.endsWith(`:${p}`)));let c=a.filter(u=>!u.notifiedAt);if(c.length){let{title:u,message:p}=Na(c);try{await this.deps.notify(u,p);for(let g of c)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${c.map(g=>yt(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()]))&&Pa(o,d),d}finally{this.running=!1}}};import{readFileSync as xt,writeFileSync as fo,existsSync as kt,readdirSync as Ha,statSync as za}from"fs";import{resolve as vt,join as Xa}from"path";import{existsSync as lo,mkdirSync as Oa,readFileSync as Ma,writeFileSync as co}from"fs";import{dirname as Ua,resolve as uo}from"path";import{z as h}from"zod";var Fa=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),Wa=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:Fa.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),ja=h.object({version:h.literal(1),items:h.array(Wa).default([])}),Se=class{constructor(e){this.path=e}jsonPath(){return uo(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return uo(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return lo(this.jsonPath())}load(){let e=this.jsonPath();if(!lo(e))return{version:1,items:[]};let n=Ma(e,"utf-8");try{return ja.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Oa(Ua(n),{recursive:!0}),co(n,JSON.stringify(e,null,2)+`
485
- `),co(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let l=s==="done"?"x":" ",c=a.assignee?`@${a.assignee} `:"",d=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",u=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${c}${a.title}${d}${u}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
486
- `)}};function kp(t){return`${t.type}:${t.project}:${t.iid}`}function po(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function wt(t,e,n,r=()=>{}){return t.source?qa(t.source,e,n,r):{ok:!0,attempts:[]}}async function qa(t,e,n,r=()=>{}){return t.type==="gitlab"?Ba(t,e,n,r):t.type==="github"?Va(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ba(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...f.headers||{}}}),c=encodeURIComponent(t.project),d;e.assigneeUsernames!==void 0&&(d=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":s}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=0;else try{let g=await l(`/projects/${c}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(u=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),d!==void 0&&(p.assignee_ids=d),u!==void 0&&(p.milestone_id=u),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await l(`/projects/${c}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await l(`/projects/${c}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function Va(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),l=t.project,c;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")c=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(c=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let d;if(e.labels!==void 0)d=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);d=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(d===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.body=e.description),d!==void 0&&(u.labels=d),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),c!==void 0&&(u.milestone=c),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${l}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(u)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${l}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var St=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,$e=/@([a-z0-9_-]+)/i,go=/\[time:\s*([0-9hm\s]+)\]/i;function Ka(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var $t=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Se(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=vt(process.cwd(),this.path);return kt(e)?xt(e,"utf-8").split(`
487
- `):[]}writeMd(e){let n=vt(process.cwd(),this.path);fo(n,e.join(`
488
- `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match(St);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],l=a.match($e);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let c=a.match(go),d=a.replace($e,"").replace(go,"").trim();r.push({id:`backlog:${o}`,title:d||`Task at line ${o+1}`,assignee:l?l[1]:void 0,estimatedSeconds:c?Ka(c[1]):void 0,priority:o})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=po([o.assignee||e],o.source,this.daemon);wt(o,{assigneeUsernames:s,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let l=this.store.update(e,a);if(l.source&&this.daemon){let c={};n.status==="done"?(c.addLabels=["Done"],c.removeLabels=["Doing"]):n.status==="blocked"&&(c.addLabels=["Blocked"]),n.note&&(c.note=n.note),Object.keys(c).length&&wt(l,c,this.daemon,this.log).catch(d=>this.log(`[backlog-sync] report failed for ${e}: ${d?.message??d}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match(St))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},Et=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(kt(e))for(let r of Ha(e)){let o=Xa(e,r);za(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(vt(process.cwd(),this.root),n);let r=[];for(let o of n){let s=xt(o,"utf-8").split(`
489
- `);for(let i=0;i<s.length;i++){let a=s[i].match(St);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match($e);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace($e,"").trim(),assignee:l[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!kt(s))return;let i=xt(s,"utf-8").split(`
490
- `);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),fo(s,i.join(`
491
- `)))}},_t=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(c=>({name:c.name,color:c.color,text_color:c.text_color})),o=s.map(c=>c.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(c=>({username:c.username,name:c.name,avatarUrl:c.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,c=await this.api(l);for(let d of c){let u=this.mapIssue(d,i);u.assignee=e,r.push(u)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),l=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(c){this.log(`[business] add_spent_time failed: ${c.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let c of i)try{let d=c==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(c)}/issues?${o.toString()}`,u=await this.api(d);for(let p of u)a.push(this.mapIssue(p,c))}catch(d){this.log(`[business] GitLab listAll failed on ${c}: ${d.message}`)}let l=a;if(e.notLabels?.length){let c=new Set(e.notLabels);l=l.filter(d=>!(d.labels||[]).some(u=>c.has(u)))}if(e.withoutScopedPrefix){let c=e.withoutScopedPrefix+"::";l=l.filter(d=>!(d.labels||[]).some(u=>u.startsWith(c)))}return l}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async d=>{try{let u=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(d=>typeof d=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let c=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(i=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${c.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async c=>{try{let d=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch(d){return this.log(`[board] user lookup failed for ${c}: ${d.message}`),null}}))).filter(c=>typeof c=="number"));let s;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(s=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${l.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function Rp(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new $t(r.path,e,n);case"wiki":return new Et(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new _t(o.host,o.token,i,s,n)}}}xs();var At="unmapped";function Rt(t,e=[]){if(!t)return At;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Ga(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of Yt(t)){let a=De(i.from),l=De(i.to);i.type==="reports-to"&&a.kind==="agent"&&l.kind==="agent"&&o.set(a.id,l.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Rt(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let l=o.get(i);if(!l)return;let c=s(l,a);return c&&e.set(i,c),c};for(let i of Object.keys(r))s(i);return e}function Ja(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function Dp(t,e){let n=Ja(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Rt(t.project,e.projects);if(t.agentId){let r=Ga(e).get(t.agentId);if(r)return r}return At}function Cp(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var Ya=t=>t===At?"internal":"client";function Za(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Ya(t),respondWithinMinutes:Qa(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Np(t){let e=new Set;for(let n of t.projects??[])e.add(Rt(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>Za(n,t))}function Qa(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as el}from"crypto";var Op={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},tl=40,nl=20,Mp=90,rl=2e3,mo=36e5;function ol(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
492
- ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<tl?null:`text:${el("sha256").update(r).digest("hex").slice(0,24)}`}function Up(t){let e=t.indexOf(`
493
- `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function It(t){t.exec(`
483
+ Reinstall in ${Da}. Agents switch back on their own once it is installed.`}}function Oa(t=co()){if(!lo(t))return null;try{let e=JSON.parse(_a(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Ma(t,e){$a(Ia(t),{recursive:!0}),Aa(`${t}.tmp`,JSON.stringify(e,null,2)+`
484
+ `),Ea(`${t}.tmp`,t)}var ao=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??co(),s=new Map((Oa(o)?.missing??[]).map(u=>[u.voice,u])),i=La(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}:{}})),l=[...s.keys()].filter(u=>!i.some(p=>p.voice===u));for(let u of l)this.deps.log(`[voice] ${wt(u)} is installed again; its agents speak with it again`);l.length&&Yr(u=>l.some(p=>u===p||u.endsWith(`:${p}`)));let c=a.filter(u=>!u.notifiedAt);if(c.length){let{title:u,message:p}=Pa(c);try{await this.deps.notify(u,p);for(let g of c)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${c.map(g=>wt(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(!lo(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&Ma(o,d),d}finally{this.running=!1}}};import{readFileSync as kt,writeFileSync as ho,existsSync as vt,readdirSync as Xa,statSync as Ka}from"fs";import{resolve as St,join as Ga}from"path";import{existsSync as uo,mkdirSync as Ua,readFileSync as Fa,writeFileSync as po}from"fs";import{dirname as Wa,resolve as go}from"path";import{z as h}from"zod";var ja=h.object({type:h.enum(["gitlab","github"]),host:h.string().optional(),project:h.string(),iid:h.number().int().positive(),url:h.string()}),qa=h.object({id:h.string(),title:h.string(),description:h.string().optional(),assignee:h.string().optional(),labels:h.array(h.string()).default([]),milestone:h.string().optional(),status:h.enum(["todo","doing","blocked","done"]).default("todo"),priority:h.number().int().optional(),estimatedSeconds:h.number().int().optional(),source:ja.optional(),importedAt:h.string().optional(),createdAt:h.string(),updatedAt:h.string(),blocker:h.string().optional(),doneNote:h.string().optional()}),Ba=h.object({version:h.literal(1),items:h.array(qa).default([])}),Se=class{constructor(e){this.path=e}jsonPath(){return go(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return go(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return uo(this.jsonPath())}load(){let e=this.jsonPath();if(!uo(e))return{version:1,items:[]};let n=Fa(e,"utf-8");try{return Ba.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Ua(Wa(n),{recursive:!0}),po(n,JSON.stringify(e,null,2)+`
485
+ `),po(this.mdPath(),this.toMarkdown(e))}list(){return this.load().items}findById(e){return this.list().find(n=>n.id===e)}add(e){let n=this.load();if(n.items.some(s=>s.id===e.id))throw new Error(`backlog item ${e.id} already exists`);let r=new Date().toISOString(),o={...e,labels:e.labels??[],status:e.status??"todo",createdAt:e.createdAt??r,updatedAt:r};return n.items.push(o),this.save(n),o}addMany(e){let n=this.load(),r=new Set(n.items.map(i=>i.id)),o=new Date().toISOString(),s=[];for(let i of e){if(r.has(i.id))continue;let a={...i,labels:i.labels??[],status:i.status??"todo",createdAt:i.createdAt??o,updatedAt:o};n.items.push(a),s.push(a),r.add(a.id)}return s.length&&this.save(n),s}update(e,n){let r=this.load(),o=r.items.findIndex(i=>i.id===e);if(o<0)throw new Error(`backlog item ${e} not found`);let s={...r.items[o],...n,id:r.items[o].id,createdAt:r.items[o].createdAt,updatedAt:new Date().toISOString()};return r.items[o]=s,this.save(r),s}remove(e){let n=this.load(),r=n.items.length;return n.items=n.items.filter(o=>o.id!==e),n.items.length===r?!1:(this.save(n),!0)}toMarkdown(e){let n=["# Backlog","","_Generated from `backlog.json`. Do not edit by hand \u2014 use `agentx backlog` commands._",""],r={doing:[],blocked:[],todo:[],done:[]};for(let s of e.items)r[s.status].push(s);let o=[["doing","Doing"],["blocked","Blocked"],["todo","To Do"],["done","Done"]];for(let[s,i]of o)if(r[s].length){n.push(`## ${i}`,"");for(let a of r[s]){let l=s==="done"?"x":" ",c=a.assignee?`@${a.assignee} `:"",d=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",u=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${l}] ${c}${a.title}${d}${u}`),a.source?.url&&n.push(` - <${a.source.url}>`),a.labels.length&&n.push(` - labels: ${a.labels.join(", ")}`),a.milestone&&n.push(` - milestone: ${a.milestone}`),a.blocker&&n.push(` - BLOCKED: ${a.blocker}`)}n.push("")}return n.join(`
486
+ `)}};function $p(t){return`${t.type}:${t.project}:${t.iid}`}function fo(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function xt(t,e,n,r=()=>{}){return t.source?Va(t.source,e,n,r):{ok:!0,attempts:[]}}async function Va(t,e,n,r=()=>{}){return t.type==="gitlab"?Ha(t,e,n,r):t.type==="github"?za(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ha(t,e,n,r){let o=n.channels.gitlab,s=o?.token,i=o?.host||(t.host?`https://${t.host}`:void 0);if(!s||!i)return{ok:!1,error:"gitlab token/host not configured",attempts:[]};let a=[],l=async(g,f={})=>fetch(`${i}/api/v4${g}`,{...f,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...f.headers||{}}}),c=encodeURIComponent(t.project),d;e.assigneeUsernames!==void 0&&(d=(await Promise.all(e.assigneeUsernames.map(async f=>{try{let m=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(f)}`,{headers:{"PRIVATE-TOKEN":s}});if(!m.ok)return null;let b=await m.json();return Array.isArray(b)&&b[0]?.id?b[0].id:null}catch{return null}}))).filter(f=>typeof f=="number"));let u;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")u=0;else try{let g=await l(`/projects/${c}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let f=await g.json();Array.isArray(f)&&f[0]?.id&&(u=f[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.description=e.description),e.labels!==void 0&&(p.labels=e.labels.join(",")),e.addLabels?.length&&(p.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(p.remove_labels=e.removeLabels.join(",")),d!==void 0&&(p.assignee_ids=d),u!==void 0&&(p.milestone_id=u),e.state&&(p.state_event=e.state==="closed"?"close":"reopen"),Object.keys(p).length)try{let g=await l(`/projects/${c}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(p)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let f=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${f.slice(0,200)}`,url:t.url}}}catch(g){return a.push({kind:"PUT issue",ok:!1,error:g.message}),{ok:!1,attempts:a,error:g.message,url:t.url}}if(e.note)try{let g=await l(`/projects/${c}/issues/${t.iid}/notes`,{method:"POST",body:JSON.stringify({body:e.note})});a.push({kind:"POST note",ok:g.ok,status:g.status})}catch(g){a.push({kind:"POST note",ok:!1,error:g.message})}return{ok:a.every(g=>g.ok),attempts:a,url:t.url}}async function za(t,e,n,r){let s=n.channels.github?.token;if(!s)return{ok:!1,error:"github token not configured",attempts:[]};let i=[],a=async(p,g={})=>fetch(`https://api.github.com${p}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),l=t.project,c;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")c=null;else try{let p=await a(`/repos/${l}/milestones?state=all&per_page=100`);if(p.ok){let g=await p.json(),f=Array.isArray(g)?g.find(m=>m.title===e.milestoneTitle):null;f?.number&&(c=f.number)}}catch(p){r(`[backlog-sync] github milestone lookup failed: ${p.message}`)}let d;if(e.labels!==void 0)d=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let p=await a(`/repos/${l}/issues/${t.iid}`);if(p.ok){let g=await p.json(),f=Array.isArray(g.labels)?g.labels.map(b=>typeof b=="string"?b:b.name):[],m=new Set([...f,...e.addLabels??[]]);for(let b of e.removeLabels??[])m.delete(b);d=[...m]}}catch(p){r(`[backlog-sync] github label fetch failed: ${p.message}`)}if(d===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.body=e.description),d!==void 0&&(u.labels=d),e.assigneeUsernames!==void 0&&(u.assignees=e.assigneeUsernames),c!==void 0&&(u.milestone=c),e.state&&(u.state=e.state),Object.keys(u).length)try{let p=await a(`/repos/${l}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(u)});if(i.push({kind:"PATCH issue",ok:p.ok,status:p.status}),!p.ok){let g=await p.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${p.status}: ${g.slice(0,200)}`,url:t.url}}}catch(p){return i.push({kind:"PATCH issue",ok:!1,error:p.message}),{ok:!1,attempts:i,error:p.message,url:t.url}}if(e.note)try{let p=await a(`/repos/${l}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:p.ok,status:p.status})}catch(p){i.push({kind:"POST comment",ok:!1,error:p.message})}return{ok:i.every(p=>p.ok),attempts:i,url:t.url}}var $t=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,$e=/@([a-z0-9_-]+)/i,mo=/\[time:\s*([0-9hm\s]+)\]/i;function Ja(t){let e=t.match(/(\d+)\s*h/i),n=t.match(/(\d+)\s*m/i);return(e?parseInt(e[1],10)*3600:0)+(n?parseInt(n[1],10)*60:0)}var _t=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Se(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=St(process.cwd(),this.path);return vt(e)?kt(e,"utf-8").split(`
487
+ `):[]}writeMd(e){let n=St(process.cwd(),this.path);ho(n,e.join(`
488
+ `))}async listOpen(e){if(this.store.exists())return this.store.list().filter(s=>s.status!=="done"&&(!s.assignee||s.assignee.toLowerCase()===e.toLowerCase())).map(s=>this.toWorkItem(s));let n=this.readMd(),r=[];for(let o=0;o<n.length;o++){let s=n[o].match($t);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],l=a.match($e);if(l&&l[1].toLowerCase()!==e.toLowerCase())continue;let c=a.match(mo),d=a.replace($e,"").replace(mo,"").trim();r.push({id:`backlog:${o}`,title:d||`Task at line ${o+1}`,assignee:l?l[1]:void 0,estimatedSeconds:c?Ja(c[1]):void 0,priority:o})}return r}async listAll(e={}){return this.store.exists()?this.store.list().map(n=>this.toWorkItem(n)):[]}async claim(e,n){if(!this.store.exists())return;let r=this.store.findById(n);if(!r)return;let o=this.store.update(n,{assignee:r.assignee||e,status:"doing"});if(o.source&&this.daemon){let s=fo([o.assignee||e],o.source,this.daemon);xt(o,{assigneeUsernames:s,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let l=this.store.update(e,a);if(l.source&&this.daemon){let c={};n.status==="done"?(c.addLabels=["Done"],c.removeLabels=["Doing"]):n.status==="blocked"&&(c.addLabels=["Blocked"]),n.note&&(c.note=n.note),Object.keys(c).length&&xt(l,c,this.daemon,this.log).catch(d=>this.log(`[backlog-sync] report failed for ${e}: ${d?.message??d}`))}return}if(!e.startsWith("backlog:"))throw new Error(`not a backlog id: ${e}`);let r=parseInt(e.slice(8),10),o=this.readMd(),s=o[r];if(!s)throw new Error(`backlog line ${r} missing`);if(!s.match($t))throw new Error(`backlog line ${r} not a checkbox`);if(n.status==="done"){o[r]=s.replace(/- \[ \]/,"- [x]");let a=n.timeSeconds?` <!-- done by agent, ${Math.round(n.timeSeconds/60)}m -->`:" <!-- done by agent -->";o.splice(r+1,0,a)}else n.status==="blocked"?o.splice(r+1,0,` <!-- BLOCKED: ${n.blocker||n.note||"?"} -->`):n.note&&o.splice(r+1,0,` <!-- ${n.note.replace(/-->/g,"\u2014 >")} -->`);this.writeMd(o)}toWorkItem(e){let n={todo:"todo",doing:"doing",blocked:"onhold",done:"done"}[e.status];return{id:e.id,title:e.title,description:e.description,assignee:e.assignee,estimatedSeconds:e.estimatedSeconds,priority:e.priority,labels:e.labels,stage:n,milestone:e.milestone,url:e.source?.url,updatedAt:e.updatedAt,state:e.status==="done"?"closed":"opened"}}},Et=class{constructor(e,n){this.root=e;this.glob=n}type="wiki";capabilities={listAll:!1,create:!1,transition:!1,labels:!1,search:!1};walk(e,n){if(vt(e))for(let r of Xa(e)){let o=Ga(e,r);Ka(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(St(process.cwd(),this.root),n);let r=[];for(let o of n){let s=kt(o,"utf-8").split(`
489
+ `);for(let i=0;i<s.length;i++){let a=s[i].match($t);if(!a||a[2].toLowerCase()==="x")continue;let l=a[3].match($e);!l||l[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace($e,"").trim(),assignee:l[1],priority:i})}}return r}async claim(){}async report(e,n){let r=e.split(":"),o=parseInt(r[r.length-1],10),s=r.slice(1,-1).join(":");if(!vt(s))return;let i=kt(s,"utf-8").split(`
490
+ `);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),ho(s,i.join(`
491
+ `)))}},At=class{constructor(e,n,r,o,s){this.host=e;this.token=n;this.projects=r;this.agentUsernames=o;this.log=s}type="gitlab";capabilities={listAll:!0,create:!0,transition:!0,labels:!0,search:!0};usernameToAgent(e){for(let[n,r]of Object.entries(this.agentUsernames))if(r.some(o=>o.toLowerCase()===e.toLowerCase()))return n}mapIssue(e,n){let r=e.references?.full?.split("#")[0]||n,o=[],s;Array.isArray(e.labels)&&(e.labels.length&&typeof e.labels[0]=="object"?(s=e.labels.map(c=>({name:c.name,color:c.color,text_color:c.text_color})),o=s.map(c=>c.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(c=>({username:c.username,name:c.name,avatarUrl:c.avatar_url})),l=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:l?this.usernameToAgent(l)||l:void 0,assignees:a,url:e.web_url,priority:e.weight??99,estimatedSeconds:e.time_stats?.time_estimate||void 0,labels:o,labelDetails:s,updatedAt:e.updated_at,state:e.state==="closed"?"closed":"opened",milestone:e.milestone?.title||void 0}}async api(e,n={}){let r=await fetch(`${this.host}/api/v4${e}`,{...n,headers:{"PRIVATE-TOKEN":this.token,"Content-Type":"application/json",...n.headers||{}}});if(!r.ok)throw new Error(`GitLab ${r.status}: ${await r.text().catch(()=>"")}`);return r.json()}async listOpen(e){let n=this.agentUsernames[e]||[];if(!n.length)return[];let r=[],o=this.projects.length?this.projects:["__ALL__"];for(let s of n)for(let i of o)try{let a=`assignee_username=${encodeURIComponent(s)}&state=opened&scope=all&per_page=20`,l=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,c=await this.api(l);for(let d of c){let u=this.mapIssue(d,i);u.assignee=e,r.push(u)}}catch(a){this.log(`[business] GitLab listOpen failed for ${s} on ${i}: ${a.message}`)}return r}async claim(e,n){let{project:r,iid:o,type:s}=this.parseId(n),i=`/projects/${encodeURIComponent(r)}/${s==="issue"?"issues":"merge_requests"}/${o}?add_labels=Doing&remove_labels=To Do`;try{await this.api(i,{method:"PUT"})}catch(a){this.log(`[business] claim label update failed: ${a.message}`)}}async report(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";if(n.timeSeconds&&n.timeSeconds>0){let a=Math.max(1,Math.round(n.timeSeconds/60)),l=a>=60?`${Math.floor(a/60)}h${a%60?` ${a%60}m`:""}`:`${a}m`;try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/add_spent_time?duration=${encodeURIComponent(l)}`,{method:"POST"})}catch(c){this.log(`[business] add_spent_time failed: ${c.message}`)}}if(n.status==="done")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Done&remove_labels=Doing`,{method:"PUT"})}catch(a){this.log(`[business] done label update failed: ${a.message}`)}else if(n.status==="blocked")try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?add_labels=Blocked`,{method:"PUT"})}catch(a){this.log(`[business] blocked label update failed: ${a.message}`)}if(n.note)try{await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}/notes`,{method:"POST",body:JSON.stringify({body:n.note})})}catch(a){this.log(`[business] report note failed: ${a.message}`)}}async listAll(e={}){let n=e.sinceDays??30,r=new Date(Date.now()-n*24*36e5).toISOString(),o=new URLSearchParams,s=e.state??"opened";o.set("state",s),o.set("updated_after",r),o.set("scope","all"),o.set("per_page","100"),o.set("with_labels_details","true"),o.set("order_by","updated_at"),o.set("sort","desc"),e.labels?.length&&o.set("labels",e.labels.join(",")),e.milestone&&o.set("milestone",e.milestone),e.search&&o.set("search",e.search);let i=this.projects.length?this.projects:["__ALL__"],a=[];for(let c of i)try{let d=c==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(c)}/issues?${o.toString()}`,u=await this.api(d);for(let p of u)a.push(this.mapIssue(p,c))}catch(d){this.log(`[business] GitLab listAll failed on ${c}: ${d.message}`)}let l=a;if(e.notLabels?.length){let c=new Set(e.notLabels);l=l.filter(d=>!(d.labels||[]).some(u=>c.has(u)))}if(e.withoutScopedPrefix){let c=e.withoutScopedPrefix+"::";l=l.filter(d=>!(d.labels||[]).some(u=>u.startsWith(c)))}return l}async setState(e,n){let{project:r,iid:o,type:s}=this.parseId(e),i=s==="issue"?"issues":"merge_requests";await this.api(`/projects/${encodeURIComponent(r)}/${i}/${o}?state_event=${n}`,{method:"PUT"})}async getItem(e){let{project:n,iid:r}=this.parseId(e);try{let o=await this.api(`/projects/${encodeURIComponent(n)}/issues/${r}?with_labels_details=true`);return{...this.mapIssue(o,n),descriptionHtml:o.description_html||void 0,createdAt:o.created_at,author:o.author?{username:o.author.username,name:o.author.name,avatarUrl:o.author.avatar_url}:void 0,allLabels:Array.isArray(o.labels)?typeof o.labels[0]=="object"?o.labels.map(i=>i.name):o.labels:[]}}catch(o){return this.log(`[board] GitLab getItem failed for ${e}: ${o.message}`),null}}async updateItem(e,n){let{project:r,iid:o}=this.parseId(e),s;n.assigneeUsernames&&(s=(await Promise.all(n.assigneeUsernames.map(async d=>{try{let u=await this.api(`/users?username=${encodeURIComponent(d)}`);return Array.isArray(u)&&u[0]?.id?u[0].id:null}catch{return null}}))).filter(d=>typeof d=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let c=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(c)&&c[0]?.id&&(i=c[0].id)}catch(c){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${c.message}`)}let a={};n.title!==void 0&&(a.title=n.title),n.description!==void 0&&(a.description=n.description),n.labels!==void 0&&(a.labels=n.labels.join(",")),n.addLabels?.length&&(a.add_labels=n.addLabels.join(",")),n.removeLabels?.length&&(a.remove_labels=n.removeLabels.join(",")),s!==void 0&&(a.assignee_ids=s),i!==void 0&&(a.milestone_id=i);let l=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(l,r)}async listMembers(){let e=new Map;for(let n of this.projects)try{let r=await this.api(`/projects/${encodeURIComponent(n)}/members/all?per_page=100`);for(let o of r)o.username&&!e.has(o.username)&&e.set(o.username,{username:o.username,name:o.name,avatarUrl:o.avatar_url})}catch(r){this.log(`[board] listMembers failed for ${n}: ${r.message}`)}return[...e.values()].sort((n,r)=>n.username.localeCompare(r.username))}async listMilestones(){let e=new Map;for(let r of this.projects)try{let o=await this.api(`/projects/${encodeURIComponent(r)}/milestones?per_page=100`);for(let s of o)s.title&&!e.has(s.title)&&e.set(s.title,{id:s.id,title:s.title,state:s.state,dueDate:s.due_date})}catch(o){this.log(`[board] listMilestones failed for ${r}: ${o.message}`)}let n=[...e.values()];return n.sort((r,o)=>r.state!==o.state?r.state==="active"?-1:1:r.title.localeCompare(o.title)),n}async create(e){let n=e.projectHint||this.projects[0];if(!n)throw new Error("GitLabWorkSource.create requires projectHint or configured projects");let r,o=e.assigneeUsernames?.length?e.assigneeUsernames:e.assignee?(this.agentUsernames[e.assignee]||[]).slice(0,1):[];o.length&&(r=(await Promise.all(o.map(async c=>{try{let d=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(d)&&d[0]?.id?d[0].id:null}catch(d){return this.log(`[board] user lookup failed for ${c}: ${d.message}`),null}}))).filter(c=>typeof c=="number"));let s;if(e.milestoneTitle)try{let l=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(s=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${l.message}`)}let i={title:e.title,description:e.description,labels:(e.labels||[]).join(",")};r?.length&&(i.assignee_ids=r),s!==void 0&&(i.milestone_id=s);let a=await this.api(`/projects/${encodeURIComponent(n)}/issues`,{method:"POST",body:JSON.stringify(i)});return this.mapIssue(a,n)}async transition(e,n,r){await this.transitionMany(e,n?[n]:[],r?[r]:[])}async transitionMany(e,n,r){let{project:o,iid:s,type:i}=this.parseId(e),a=i==="issue"?"issues":"merge_requests",l=new URLSearchParams;n.length&&l.set("add_labels",n.join(",")),r.length&&l.set("remove_labels",r.join(",")),l.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${l.toString()}`,{method:"PUT"})}parseId(e){let r=e.replace(/^gitlab:/,"").split(":"),o=r.pop(),s=r.pop()==="mr"?"mr":"issue";return{project:r.join(":"),type:s,iid:o}}};function Dp(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new _t(r.path,e,n);case"wiki":return new Et(r.path,r.glob);case"gitlab":{let o=e.channels.gitlab;if(!o?.token)throw new Error("business.workSource.type=gitlab requires channels.gitlab.token");let s={};for(let a of o.agentMappings)a.gitlabUsernames.length&&(s[a.agentId]=a.gitlabUsernames);let i=r.projects.length?r.projects:o.routes.map(a=>a.project);return new At(o.host,o.token,i,s,n)}}}vs();var Rt="unmapped";function It(t,e=[]){if(!t)return Rt;let n=e.find(o=>o.id===t);if(n?.client)return n.client;let r=t.indexOf("/");return r>0?t.slice(0,r):t}function Ya(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of Zt(t)){let a=De(i.from),l=De(i.to);i.type==="reports-to"&&a.kind==="agent"&&l.kind==="agent"&&o.set(a.id,l.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,It(i.id,n)));let s=(i,a=new Set)=>{if(e.has(i))return e.get(i);if(a.has(i))return;a.add(i);let l=o.get(i);if(!l)return;let c=s(l,a);return c&&e.set(i,c),c};for(let i of Object.keys(r))s(i);return e}function Za(t,e,n=[]){if(!n.length)return;let r=n.filter(o=>!o.channel||o.channel===t);return r.find(o=>o.chatId&&e.chatId&&o.chatId===e.chatId)??r.find(o=>o.username&&e.username&&o.username===e.username)??r.find(o=>o.senderId&&e.senderId&&o.senderId===e.senderId)??r.find(o=>o.channel&&!o.chatId&&!o.username&&!o.senderId)}function Lp(t,e){let n=Za(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return It(t.project,e.projects);if(t.agentId){let r=Ya(e).get(t.agentId);if(r)return r}return Rt}function Pp(t,e){let n=String(t||"").split(":");if(n.length<3)return{agentId:e};let[r,o,...s]=n,i=s.join(":"),a={agentId:e||r,channel:o};return o==="gitlab"||o==="github"?a.project=i.split(":")[0]:o==="cron"||o==="api"||(a.chatId=i.split("@")[0]),a}var Qa=t=>t===Rt?"internal":"client";function el(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Qa(t),respondWithinMinutes:tl(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Op(t){let e=new Set;for(let n of t.projects??[])e.add(It(n.id,t.projects));for(let n of t.contactMap??[])e.add(n.client);for(let n of Object.keys(t.clients??{}))e.add(n);return[...e].sort().map(n=>el(n,t))}function tl(t){let e=/^(\d+)\s*([mhd])$/.exec(String(t??"").trim());if(!e)return;let n=Number(e[1]);return e[2]==="m"?n:e[2]==="h"?n*60:n*1440}import{createHash as nl}from"crypto";var Fp={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},rl=40,ol=20,Wp=90,sl=2e3,bo=36e5;function il(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
492
+ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<rl?null:`text:${nl("sha256").update(r).digest("hex").slice(0,24)}`}function jp(t){let e=t.indexOf(`
493
+ `);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Tt(t){t.exec(`
494
494
  CREATE TABLE IF NOT EXISTS owner_told (
495
495
  id INTEGER PRIMARY KEY AUTOINCREMENT,
496
496
  at INTEGER NOT NULL,
@@ -508,34 +508,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<tl?null:`text:${e
508
508
  CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
509
509
  CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
510
510
  CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
511
- `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of sl)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var sl=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function Ee(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var ho=class{constructor(e){this.db=e;It(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
512
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,rl),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?Ee(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return o?Ee(o):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(Ee)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let o of e)r.run(n,o)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(Ee)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
511
+ `);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of al)if(!e.has(n))try{t.exec(`ALTER TABLE owner_told ADD COLUMN ${n} ${r}`)}catch(o){if(!/duplicate column/i.test(String(o?.message)))throw o}}var al=[["urgent","INTEGER NOT NULL DEFAULT 0"],["seen_at","INTEGER"],["seen_via","TEXT"],["answered_at","INTEGER"],["answered_via","TEXT"],["escalated_at","INTEGER"],["escalation_of","INTEGER"]];function _e(t){return{id:t.id,at:t.at,key:t.item_key,requestId:t.request_id??null,kind:t.kind,channel:t.channel,chatId:t.chat_id,from:t.sender??null,title:t.title,text:t.text,outcome:t.outcome,digestedAt:t.digested_at??null,urgent:t.urgent===1,seenAt:t.seen_at??null,seenVia:t.seen_via??null,answeredAt:t.answered_at??null,answeredVia:t.answered_via??null,escalatedAt:t.escalated_at??null,escalationOf:t.escalation_of??null,state:t.answered_at!=null?"answered":t.seen_at!=null?"seen":"sent"}}var yo=class{constructor(e){this.db=e;Tt(e)}add(e){return Number(this.db.prepare(`INSERT INTO owner_told (at, item_key, request_id, kind, channel, chat_id, sender, title, text, outcome, urgent, escalation_of)
512
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.at,e.key,e.requestId,e.kind,e.channel,e.chatId,e.from,e.title.slice(0,300),e.text.slice(0,sl),e.outcome,e.urgent?1:0,e.escalationOf??null).lastInsertRowid)}get(e){let n=this.db.prepare("SELECT * FROM owner_told WHERE id = ?").get(e);return n?_e(n):null}setOutcome(e,n){this.db.prepare("UPDATE owner_told SET outcome = ? WHERE id = ?").run(n,e)}lastTold(e,n,r=!0){let o=this.db.prepare(`SELECT * FROM owner_told WHERE item_key = ? AND at >= ? AND outcome IN ('sent', 'held'${r?", 'digest'":""}) ORDER BY at DESC LIMIT 1`).get(e,n);return o?_e(o):null}waitingForDigest(e=500){return this.db.prepare("SELECT * FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL ORDER BY at LIMIT ?").all(e).map(_e)}waitingCount(){return this.db.prepare("SELECT COUNT(*) AS n FROM owner_told WHERE outcome = 'digest' AND digested_at IS NULL").get().n}markDigested(e,n){let r=this.db.prepare("UPDATE owner_told SET digested_at = ? WHERE id = ?");this.db.transaction(()=>{for(let o of e)r.run(n,o)})()}since(e,n=200){return this.db.prepare("SELECT * FROM owner_told WHERE at >= ? ORDER BY at DESC, id DESC LIMIT ?").all(e,n).map(_e)}counts(e){let n={sent:0,held:0,digest:0,repeat:0,failed:0};for(let r of this.db.prepare("SELECT outcome, COUNT(*) AS n FROM owner_told WHERE at >= ? GROUP BY outcome").all(e))n[r.outcome]=r.n;return n}states(e){let n=this.db.prepare(`SELECT SUM(CASE WHEN answered_at IS NULL AND seen_at IS NULL THEN 1 ELSE 0 END) AS sent,
513
513
  SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
514
514
  SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
515
- FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},bo=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=ol(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,nl):r.repeatWindowHours)*mo,l=r.digestNags&&r.digestAvailable!==!1,c="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,l)?c="repeat":!n.urgent&&i==="nag"&&l&&(c="digest");let d=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:c==="send"?"sent":c,urgent:n.urgent===!0});return{verdict:c,key:s,rowId:d}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:il(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*mo)}};function Fp(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function il(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...c]=a.title.split(": "),d=c.join(": ").trim(),u=r.get(l.trim())??{count:0,names:[]};u.count++,d&&!u.names.includes(d)&&u.names.push(d),r.set(l.trim(),u)}let o=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:l,names:c}])=>{let d=c.length?` (${c.slice(0,n).join(", ")}${c.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${d}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}var al=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,ll=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function yo(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(ll)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=cl(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function jp(t){if(!t||!t.includes("agentx:ui"))return t;let e=al.exec(t);return e?t.slice(0,e.index).trimEnd():t}function cl(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],o=[],s=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function Bp(t,e){let n=`${e}/call?to=${encodeURIComponent(t.from)}&callId=${encodeURIComponent(t.callId)}`;return t.reason==="camera"?`\u{1F4F7} ${t.from} is sharing a phone camera \u2014 tap to watch: ${n}&watch=1`:`\u{1F4DE} ${t.from} is calling \u2014 tap to join: ${n}`}var dl=5*6e4;function O(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var wo=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(O)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${O(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let l=Date.now(),c=a.filter(d=>d.expiresAt>l);for(let{signal:d}of c)this.deliverTo(o,d);this.pending.delete(i),c.length&&this.log(`flushed ${c.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
515
+ FROM owner_told WHERE at >= ? AND outcome IN ('sent', 'held')`).get(e);return{sent:n.sent??0,seen:n.seen??0,answered:n.answered??0}}prune(e){return this.db.prepare("DELETE FROM owner_told WHERE at < ?").run(e).changes}},wo=class{constructor(e,n,r=Date.now){this.ledger=e;this.settings=n;this.now=r}isOwnerAddress(e,n){let r=this.settings();return r.enabled?r.channels.includes(e)||r.addresses.includes(`${e}:${n}`):!1}decide(e,n={}){let r=this.settings(),o=this.now(),s=il(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,ol):r.repeatWindowHours)*bo,l=r.digestNags&&r.digestAvailable!==!1,c="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,l)?c="repeat":!n.urgent&&i==="nag"&&l&&(c="digest");let d=this.ledger.add({at:o,key:s??`once:${o}`,requestId:n.requestId??null,kind:i,channel:e.channel,chatId:e.chatId,from:n.from??null,title:e.title,text:e.text,outcome:c==="send"?"sent":c,urgent:n.urgent===!0});return{verdict:c,key:s,rowId:d}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:ll(e),ids:e.map(n=>n.id)}:null}markDigested(e){this.ledger.markDigested(e,this.now())}report(e,n=50){return{counts:this.ledger.counts(e),landed:this.ledger.states(e),waitingForDigest:this.ledger.waitingCount(),items:this.ledger.since(e,n)}}prune(e){return this.ledger.prune(this.now()-e*24*bo)}};function qp(t,e){let n=t&&typeof t=="object"?t:{},r=(i,a)=>typeof i=="string"&&i.trim()?i.trim().slice(0,a):void 0,o=n.kind==="nag"||n.kind==="notice"?n.kind:void 0,s=r(n.from,100)??r(e,100);return{...r(n.key,190)?{key:`send:${r(n.key,190)}`}:{},...r(n.requestId,100)?{requestId:r(n.requestId,100)}:{},...o?{kind:o}:{},...n.urgent===!0?{urgent:!0}:{},...n.textKey===!0?{textKey:!0}:{},...s?{from:s}:{}}}function ll(t,e=5,n=3){let r=new Map;for(let a of t){let[l,...c]=a.title.split(": "),d=c.join(": ").trim(),u=r.get(l.trim())??{count:0,names:[]};u.count++,d&&!u.names.includes(d)&&u.names.push(d),r.set(l.trim(),u)}let o=[...r.entries()].sort((a,l)=>l[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:l,names:c}])=>{let d=c.length?` (${c.slice(0,n).join(", ")}${c.length>n?", \u2026":""})`:"";return`${a}${l>1?` \xD7${l}`:""}${d}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}var cl=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,dl=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function xo(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(dl)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=ul(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function Vp(t){if(!t||!t.includes("agentx:ui"))return t;let e=cl.exec(t);return e?t.slice(0,e.index).trimEnd():t}function ul(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],o=[],s=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function zp(t,e){let n=`${e}/call?to=${encodeURIComponent(t.from)}&callId=${encodeURIComponent(t.callId)}`;return t.reason==="camera"?`\u{1F4F7} ${t.from} is sharing a phone camera \u2014 tap to watch: ${n}&watch=1`:`\u{1F4DE} ${t.from} is calling \u2014 tap to join: ${n}`}var pl=5*6e4;function O(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ko=class{subs=new Set;log;forwarder;localName;allowedCallers;pending=new Map;cleanupTimer;ringHandler;recentRings=new Map;constructor(e,n=[],r=console.error.bind(console,"[webrtc]")){this.localName=e,this.allowedCallers=new Set(n.map(O)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${O(n)}`}cleanupExpired(){let e=Date.now();for(let[n,r]of this.pending){let o=r.filter(s=>s.expiresAt>e);o.length===0?this.pending.delete(n):o.length!==r.length&&this.pending.set(n,o)}for(let[n,r]of this.recentRings)r<=e&&this.recentRings.delete(n)}setForwarder(e){this.forwarder=e}setRingHandler(e){this.ringHandler=e}subscribe(e,n,r){return this.addSubscriber(e,n,{kind:"sse",res:r})}subscribeInternal(e,n,r){return this.addSubscriber(e,n,{kind:"callback",deliver:r})}addSubscriber(e,n,r){let o={callId:e,recipient:n,sink:r};this.subs.add(o);let s=r.kind==="sse"?"sse":"internal";this.log(`subscribe[${s}] call=${e} as=${n} (${this.subs.size} total)`);let i=this.pendingKey(e,n),a=this.pending.get(i);if(a&&a.length){let l=Date.now(),c=a.filter(d=>d.expiresAt>l);for(let{signal:d}of c)this.deliverTo(o,d);this.pending.delete(i),c.length&&this.log(`flushed ${c.length} buffered signal(s) to new subscriber call=${e} as=${n}`)}return()=>{this.subs.delete(o),this.log(`unsubscribe[${s}] call=${e} as=${n} (${this.subs.size} remaining)`)}}deliverTo(e,n){try{return e.sink.kind==="sse"?e.sink.res.write(`event: signal
516
516
  data: ${JSON.stringify(n)}
517
517
 
518
- `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=O(e.to);if(n===O(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&O(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(O(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+dl),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=O(e.to);for(let o of this.subs)o.callId===e.callId&&O(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as ul,readFileSync as xo,renameSync as pl,rmSync as gl,writeFileSync as fl}from"fs";import{homedir as ml}from"os";import{dirname as hl,join as bl}from"path";var ko=bl(ml(),".agentx","call.json");function yl(t=ko,e=Date.now()){try{let n=JSON.parse(xo(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function vo(t=gn,e=yl){let n=t();return n.active?n:e()}function Gp(t,e,n=ko,r=Date.now()){let o=null;try{o=JSON.parse(xo(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&gl(n,{force:!0});return}ul(hl(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;fl(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
519
- `),pl(s,n)}var So="owner",_e=6e4,Ro=60*_e,wl=24*Ro,xl=7*24*Ro,kl=2*_e,Zp={enabled:!1,escalateAfterMinutes:10,ladder:[]};function vl(t){t.exec(`
518
+ `):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=O(e.to);if(n===O(this.localName)||this.hasSubscriberFor(e.callId,n))return this.fanOut(e),{ok:!0};if(!this.forwarder)return{ok:!1,error:"mesh forwarder not wired"};let o=await this.forwarder(e.to,e);return o?{ok:o}:{ok:!1,error:`forward to "${e.to}" failed`}}hasSubscriberFor(e,n){for(let r of this.subs)if(r.callId===e&&O(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(O(e.from)))return this.log(`reject inbound ${e.kind} from "${e.from}": not in allowedCallers`),{ok:!1,error:"caller not allowed"};if(e.kind==="ring"){let r=Date.now(),o=this.recentRings.get(e.callId);if(o&&o>r)return this.log(`dedup ring for call=${e.callId} (already notified)`),{ok:!0};if(this.recentRings.set(e.callId,r+pl),this.ringHandler)try{this.ringHandler(e)}catch(s){this.log(`ringHandler threw: ${s.message}`)}else this.log(`ring received for call=${e.callId} but no handler wired`);return{ok:!0}}if(this.fanOut(e)===0){let r=this.pendingKey(e.callId,e.to),o=this.pending.get(r)||[];o.push({signal:e,expiresAt:Date.now()+3e4}),this.pending.set(r,o),this.log(`buffered ${e.kind} for call=${e.callId} to=${e.to} (no subscriber yet, ${o.length} pending)`)}return{ok:!0}}fanOut(e){let n=0,r=O(e.to);for(let o of this.subs)o.callId===e.callId&&O(o.recipient)===r&&(this.deliverTo(o,e)?n++:this.subs.delete(o));return n}get subscriberCount(){return this.subs.size}shutdown(){this.cleanupTimer&&clearInterval(this.cleanupTimer);for(let e of this.subs)if(e.sink.kind==="sse")try{e.sink.res.end()}catch{}this.subs.clear(),this.pending.clear()}};import{mkdirSync as gl,readFileSync as vo,renameSync as fl,rmSync as ml,writeFileSync as hl}from"fs";import{homedir as bl}from"os";import{dirname as yl,join as wl}from"path";var So=wl(bl(),".agentx","call.json");function xl(t=So,e=Date.now()){try{let n=JSON.parse(vo(t,"utf-8"));if(n?.active===!0&&!(n.until&&Date.parse(n.until)<=e))return{active:!0,mode:"call",reason:`in a call${n.reason?`: ${n.reason}`:""}`}}catch{}return{active:!1,mode:null,reason:"not in a call"}}function $o(t=fn,e=xl){let n=t();return n.active?n:e()}function Zp(t,e,n=So,r=Date.now()){let o=null;try{o=JSON.parse(vo(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&ml(n,{force:!0});return}gl(yl(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;hl(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
519
+ `),fl(s,n)}var _o="owner",Ee=6e4,To=60*Ee,kl=24*To,vl=7*24*To,Sl=2*Ee,tg={enabled:!1,escalateAfterMinutes:10,ladder:[]};function $l(t){t.exec(`
520
520
  CREATE TABLE IF NOT EXISTS owner_presence (
521
521
  person TEXT NOT NULL,
522
522
  surface TEXT NOT NULL,
523
523
  at INTEGER NOT NULL,
524
524
  PRIMARY KEY (person, surface)
525
525
  );
526
- `)}var $o=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;vl(e)}written=new Map;touch(e,n=So){let r=this.now(),o=`${n}
526
+ `)}var Eo=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;$l(e)}written=new Map;touch(e,n=_o){let r=this.now(),o=`${n}
527
527
  ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this.db.prepare(`INSERT INTO owner_presence (person, surface, at) VALUES (?, ?, ?)
528
- ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=So){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Qp(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Eo=class{constructor(e,n=Date.now){this.db=e;this.now=n;It(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
528
+ ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=_o){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function ng(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Ao=class{constructor(e,n=Date.now){this.db=e;this.now=n;Tt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
529
529
  WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
530
- ORDER BY at DESC LIMIT 500`).all(this.now()-xl)}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,l=o.all(s.at-kl,s.at).find(c=>c.title===s.title||i!==s.title&&c.title.startsWith(i));l&&r.push(l.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 = ?
531
- WHERE seen_at IS NULL AND (${_o(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, ?)
532
- WHERE answered_at IS NULL AND (${_o(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 _o(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 eg(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=ne(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function ne(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Sl(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function $l(t){return ne(t)==="push"?["phone","desk"]:[t]}function tg(t,e,n){let r=t.filter(s=>n(ne(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>$l(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 El(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(ne(s)))??null}var _l=3;async function ng(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*_e,i=e.prepare(`SELECT id FROM owner_told
530
+ ORDER BY at DESC LIMIT 500`).all(this.now()-vl)}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,l=o.all(s.at-Sl,s.at).find(c=>c.title===s.title||i!==s.title&&c.title.startsWith(i));l&&r.push(l.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 = ?
531
+ WHERE seen_at IS NULL AND (${Ro(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, ?)
532
+ WHERE answered_at IS NULL AND (${Ro(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 Ro(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 rg(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=ne(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function ne(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function _l(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function El(t){return ne(t)==="push"?["phone","desk"]:[t]}function og(t,e,n){let r=t.filter(s=>n(ne(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>El(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 Al(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(ne(s)))??null}var Rl=3;async function sg(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*Ee,i=e.prepare(`SELECT id FROM owner_told
533
533
  WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
534
534
  AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
535
535
  AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
536
- ORDER BY at LIMIT 20`).all(Math.max(o-_l*s,o-wl),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:c}of i){if(a.run(o,c).changes!==1)continue;let d=n.get(c);if(!d)continue;let u=`${d.channel}:${d.chatId}`,p=El(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)/_e),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}
536
+ ORDER BY at LIMIT 20`).all(Math.max(o-Rl*s,o-kl),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),l=0;for(let{id:c}of i){if(a.run(o,c).changes!==1)continue;let d=n.get(c);if(!d)continue;let u=`${d.channel}:${d.chatId}`,p=Al(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)/Ee),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}
537
537
 
538
- `:""}(Sent again here: ${f}.)`,b=n.add({at:o,key:d.key,requestId:d.requestId,kind:d.kind,channel:ne(p),chatId:Sl(p),from:d.from,title:d.title,text:m,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,m),l++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch($){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${$?.message??$}`)}}return l}var Ao=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 Al={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Io=class{constructor(e=Al,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)}},Rl="That code didn't work. Check it, or run agentx app pair for a new one.",Il=400;async function sg(t,e){let n=Date.now(),r=e.log??(c=>console.log(c)),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 Fn(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await Tl(n,e.minMs??Il),!a||!l?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Rl}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${o}`),{status:200,body:{device:l},token:a.token})}async function Tl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}function v(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{execFile as Xl}from"child_process";import{mkdtempSync as Wl,rmSync as jl,writeFileSync as ql}from"fs";import{tmpdir as Bl}from"os";import{join as Lo}from"path";import{randomBytes as Dl}from"crypto";var L={top:8,side:32,bottom:60},Tt={height:56,keep:52},To=`
538
+ `:""}(Sent again here: ${f}.)`,b=n.add({at:o,key:d.key,requestId:d.requestId,kind:d.kind,channel:ne(p),chatId:_l(p),from:d.from,title:d.title,text:m,outcome:"sent",urgent:!0,escalationOf:d.id});try{await t.send(p,d,m),l++,t.log(`[reach] urgent "${d.title.slice(0,80)}": ${f}; sent once to ${p}`)}catch($){n.setOutcome(b,"failed"),t.log(`[reach] urgent "${d.title.slice(0,80)}": escalation to ${p} failed: ${$?.message??$}`)}}return l}var Io=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 Il={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Do=class{constructor(e=Il,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)}},Tl="That code didn't work. Check it, or run agentx app pair for a new one.",Dl=400;async function lg(t,e){let n=Date.now(),r=e.log??(c=>console.log(c)),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 Wn(t,1024)).code}catch{}let a=e.codes.redeem(i),l=a?e.verify(a.token):null;return await Cl(n,e.minMs??Dl),!a||!l?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Tl}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${l}) from ${o}`),{status:200,body:{device:l},token:a.token})}async function Cl(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}function v(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}import{execFile as Gl}from"child_process";import{mkdtempSync as ql,rmSync as Bl,writeFileSync as Vl}from"fs";import{tmpdir as Hl}from"os";import{join as Oo}from"path";import{randomBytes as Nl}from"crypto";var L={top:8,side:32,bottom:60},Dt={height:56,keep:52},Co=`
539
539
  :root {
540
540
  --ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
541
541
  --ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
@@ -664,16 +664,16 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
664
664
  button.primary:disabled { opacity: .55; cursor: not-allowed; }
665
665
  kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
666
666
  button.primary kbd { color: inherit; opacity: .7; }
667
- `;var Do=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Co=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Cl(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Do(n):Co(n)}`}function Nl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Co(n)],Do(n)].join(" ")}function Ll(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Pl(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var Dt=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,Ol=Dt('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),Ml=Dt('<path d="m6 15 6-6 6 6"/>'),Ul=Dt('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function No(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Dl(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=Sn(t),c=s.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${v(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),d=t.recommend?`<span class="rec"><i class="dot"></i>${v(r)} recommends</span>`:"",u={choices:s,draft:t.draft??"",placeholder:kn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:l.index};return`<!doctype html>
667
+ `;var No=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Lo=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Ll(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?No(n):Lo(n)}`}function Pl(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Lo(n)],No(n)].join(" ")}function Ol(t){let e=t.trim().split(/[\s_-]+/).filter(Boolean);return(e.length>1?e[0][0]+e[1][0]:t.trim().slice(0,1)).toUpperCase()}function Ml(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var Ct=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,Ul=Ct('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),Fl=Ct('<path d="m6 15 6-6 6 6"/>'),Wl=Ct('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Po(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Nl(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",l=$n(t),c=s.map((p,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${v(p)}</span>${g===l.index?'<i class="dot"></i>':""}</button>`).join(""),d=t.recommend?`<span class="rec"><i class="dot"></i>${v(r)} recommends</span>`:"",u={choices:s,draft:t.draft??"",placeholder:vn,chime:e.sound==="chime",volume:Math.min(1,Math.max(0,e.volume??.4)),theme:e.theme??"system",pick:e.pick&&e.pick<=s.length?e.pick-1:l.index};return`<!doctype html>
668
668
  <html lang="en"><head><meta charset="utf-8">
669
669
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
670
670
  <title>AgentX</title>
671
- <style>${To}</style></head>
671
+ <style>${Co}</style></head>
672
672
  <body><div class="wrap"><main class="card${e.still?" still":""}">
673
- <div class="head" title="Drag to move"><span class="avatar">${v(Ll(r))}</span>
674
- <div class="who"><b>${v(r)}</b><span>${v(Cl(t.created_at,n))}</span></div>
673
+ <div class="head" title="Drag to move"><span class="avatar">${v(Ol(r))}</span>
674
+ <div class="who"><b>${v(r)}</b><span>${v(Ll(t.created_at,n))}</span></div>
675
675
  <span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
676
- <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${Ml}</button></div>
676
+ <button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${Fl}</button></div>
677
677
  <div class="body"><h1 dir="auto">${v(t.title)}</h1>
678
678
  ${t.context?`<p class="context" dir="auto">${v(t.context)}</p>`:""}
679
679
  <p class="ask" dir="auto">${v(t.ask)}</p>
@@ -682,15 +682,15 @@ ${c?`<div class="options" role="radiogroup">${c}</div>`:""}
682
682
  ${l.why?`<p class="why" dir="auto">${v(l.why)}</p>`:""}
683
683
  ${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>
684
684
  <textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
685
- <div class="notes"><div>${Ol}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${v(Nl(t.expires,n))}: ${v(t.if_silent)}.`}</span></div>
686
- <div>${Ul}<span>Nothing goes out until you click.</span></div></div>
685
+ <div class="notes"><div>${Ul}<span>${a?"It stays in Open requests on the Approvals page until you close it.":`If you don't answer by ${v(Pl(t.expires,n))}: ${v(t.if_silent)}.`}</span></div>
686
+ <div>${Wl}<span>Nothing goes out until you click.</span></div></div>
687
687
  </div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
688
688
  <button class="btn" id="no">${a?"Drop":"No"}</button>
689
- <button class="btn primary" id="yes">${Pl(t)}<kbd>\u2318\u21A9</kbd></button></div>
689
+ <button class="btn primary" id="yes">${Ml(t)}<kbd>\u2318\u21A9</kbd></button></div>
690
690
  </main></div>
691
691
  <script type="application/json" id="data">${JSON.stringify(u).replace(/</g,"\\u003c")}</script>
692
- <script nonce="${o}">${Fl}</script>
693
- </body></html>`}var Fl=`
692
+ <script nonce="${o}">${jl}</script>
693
+ </body></html>`}var jl=`
694
694
  (function () {
695
695
  var d = JSON.parse(document.getElementById("data").textContent);
696
696
  var root = document.documentElement;
@@ -779,10 +779,10 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
779
779
  });
780
780
  } catch (e) {}
781
781
  })();
782
- `;var Vl=440,Hl=`
782
+ `;var zl=440,Xl=`
783
783
  ObjC.import("Cocoa"); ObjC.import("WebKit")
784
784
  function run(argv) {
785
- var path = argv[0], side = ${L.side}, gripTop = ${L.top}, gripEnd = ${L.top+Tt.height}, keep = ${Tt.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
785
+ var path = argv[0], side = ${L.side}, gripTop = ${L.top}, gripEnd = ${L.top+Dt.height}, keep = ${Dt.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
786
786
  var app = $.NSApplication.sharedApplication
787
787
  app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
788
788
  ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
@@ -854,22 +854,22 @@ function run(argv) {
854
854
  }
855
855
  function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
856
856
  function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
857
- `;function zl(t,e){let n=t.trim().split(`
858
- `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Oo.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
859
- `).trim():"",!i||i.length>xn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Po(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=Wl(Lo(Bl(),"agentx-card-"));try{let s=Lo(o,"card.html");ql(s,No(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Hl,s,String(Vl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?zl(a.stdout,t):null}finally{jl(o,{recursive:!0,force:!0})}}var Oo=["not now","timed out","closed"],Kl=(t,e,n)=>new Promise(r=>{try{Xl(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Mo=160,Ct=15e3;function Uo(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Mo?e.slice(0,Mo):e}async function Gl(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?Un(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],Ct),!!e.speak)if(o){let a;await Promise.race([o(Uo(t)),new Promise(l=>{a=setTimeout(l,Ct)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Uo(t)],Ct)}}function jo(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Jl(t,e,n){return jo(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function Fo(t,e,n,r,o){return jo(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
860
- `),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Wo(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
861
- `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function Nt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
857
+ `;function Kl(t,e){let n=t.trim().split(`
858
+ `).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Uo.includes(r.why))return{action:"dismiss",why:r.why};if(r?.action!=="yes")return{action:"dismiss"};let o=e.choices??[],s;if(o.length){if(typeof r.choice!="string"||!o.includes(r.choice))return{action:"dismiss"};s=r.choice}let i;return e.draft&&(i=typeof r.text=="string"?r.text.replace(/\r\n?/g,`
859
+ `).trim():"",!i||i.length>kn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Mo(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=ql(Oo(Hl(),"agentx-card-"));try{let s=Oo(o,"card.html");Vl(s,Po(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Xl,s,String(zl),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Kl(a.stdout,t):null}finally{Bl(o,{recursive:!0,force:!0})}}var Uo=["not now","timed out","closed"],Jl=(t,e,n)=>new Promise(r=>{try{Gl(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Fo=160,Nt=15e3;function Wo(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Fo?e.slice(0,Fo):e}async function Yl(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?Fn(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],Nt),!!e.speak)if(o){let a;await Promise.race([o(Wo(t)),new Promise(l=>{a=setTimeout(l,Nt)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Wo(t)],Nt)}}function Bo(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Zl(t,e,n){return Bo(["on run argv","set opts to items 3 thru -1 of argv",'set pick to choose from list opts with title (item 1 of argv) with prompt (item 2 of argv) OK button name "Next" cancel button name "Not now"','if pick is false then return ""',"return item 1 of pick","end run"],[t,e,...n])}function jo(t,e,n,r,o){return Bo(["on run argv","set AppleScript's text item delimiters to linefeed","set btns to text items of (item 3 of argv)","set secs to (item 5 of argv) as integer","if (count of argv) > 5 then","set r to display dialog (item 2 of argv) with title (item 1 of argv) default answer (item 6 of argv) buttons btns default button (item 4 of argv) giving up after secs","else","set r to display dialog (item 2 of argv) with title (item 1 of argv) buttons btns default button (item 4 of argv) giving up after secs","end if",'if gave up of r then return ""',"if (count of argv) > 5 then return (button returned of r) & linefeed & (text returned of r)","return button returned of r","end run"],[t,e,n.join(`
860
+ `),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function qo(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
861
+ `);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function Lt(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
862
862
 
863
- `)}async function qo(t,e,n={}){let r=n.run??Kl,o=(e.style??"card")==="card",s=Gl(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Po(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await s,Yl(t,e,r)}async function Yl(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let c=await n("/usr/bin/osascript",Jl(s,Nt(t),t.choices),o);if(i=c.stdout.replace(/\n$/,""),!c.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let c=i?`${i}
863
+ `)}async function Vo(t,e,n={}){let r=n.run??Jl,o=(e.style??"card")==="card",s=Yl(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Mo(t,{timeoutSeconds:e.timeoutSeconds,sound:e.sound,volume:e.volume,theme:e.theme,from:n.from,capture:n.capture,pick:n.pick},r).catch(()=>null);if(i)return i}return await s,Ql(t,e,r)}async function Ql(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=(r+5)*1e3,s=`${t.raised_by}: ${t.title}`,i;if(t.choices?.length){let c=await n("/usr/bin/osascript",Zl(s,Lt(t),t.choices),o);if(i=c.stdout.replace(/\n$/,""),!c.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let c=i?`${i}
864
864
 
865
- Message (edit it if you like):`:`${Nt(t)}
865
+ Message (edit it if you like):`:`${Lt(t)}
866
866
 
867
- Message (edit it if you like):`,u=await n("/usr/bin/osascript",Fo(s,c,i?["Cancel","Send"]:["Not now","No","Send"],r,vn(t.draft,i)),o),p=u.ok?Wo(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",Fo(s,Nt(t),["Not now","No","Yes"],r),o),l=a.ok?Wo(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var Ot=24*36e5,Lt=!1,Zl=10*6e4,Bo=-1/0;function Vo(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=E(t.root),a=s?Date.parse(s):NaN,l=B(t.root,"pending").filter(d=>Date.parse(d.expires)>n),c=l.find(d=>i.includes(`card:${d.id}`));if(c)return c;for(let d of l){let u=`card:${d.id}`;if(r[u]||!e(d)||Xn(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>Ot&&!(g<=a)))return d}return null}function Pt(t){try{return F(t)?.listByState("needs_attention")??[]}catch{return[]}}var Ho=new Map;function Ql(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=E(t.root);return e({})?Pt(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Ho.get(s.id)===U(s,Ve.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=Ot})??null:null}function ec(t,e){return{id:t.id,title:U(t,Ve.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+Ot).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Og(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(Lt)return"busy";let o=Vo(e,t.reaches)?null:Ql(e,t.reaches),s=o?ec(o,e.now??Date.now()):Vo(e,t.reaches);if(!s)return"none";let i=(t.focus??vo)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,l=(E(e.root).wanted??[]).includes(a)?null:Wn(s);if(l){if(o)Ho.set(o.id,s.title);else{let c=[...B(e.root,"pending").map(d=>`card:${d.id}`),...Pt(e).map(d=>`request:${d.id}`)];Ke(e.root,a,c,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${l}`),t.returnToAuthor?.(s,jn(s,l)),"returned"}Lt=!0;try{let c=[...B(e.root,"pending").map(b=>`card:${b.id}`),...Pt(e).map(b=>`request:${b.id}`)];Ke(e.root,a,c,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let d=e.now??Date.now(),u=!!o&&d-Bo<Zl;o&&n.speak&&(Bo=d);let p=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??qo)(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"} (${fn(i)} when shown)`),"shown";if(!(o?F(e)?.get(o.id)?.state==="needs_attention":Y(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Rr(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(c){return r(`[approvals] popup failed for ${a}: ${c?.message??c}`),"shown"}finally{Lt=!1}}function Mg(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:")?Y(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(or(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 tc,mkdirSync as nc,readFileSync as rc,renameSync as oc,writeFileSync as sc}from"fs";import{dirname as ic,resolve as ac}from"path";var lc=["all","urgent","off"],cc=24*36e5,zo=24*36e5,dc=30*24*36e5,Xo=t=>lc.includes(t);function jg(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Xo(e)?e:"off",computer:Xo(n)?n:t.popupEnabled?"all":"off"}}function Go(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=cc}function Ko(t,e,n){return t==="all"||t==="urgent"&&Go(e,n)}function Jo(t){return ac(t,".agentx","desk-routed.json")}function uc(t){let e=Jo(t);if(!tc(e))return null;try{let n=JSON.parse(rc(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Mt(t,e){let n=Jo(t);nc(ic(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;sc(r,JSON.stringify(e,null,2)),oc(r,n)}async function qg(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=uc(e);if(!l){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Mt(e,{items:u}),i.primed=!0,i}let c=[],d=[];for(let u of r.items){let p=l.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>zo&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}l.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=zo&&c.push(u)}for(let[u,p]of Object.entries(l.items))n-Date.parse(p.seen)>dc&&delete l.items[u];Mt(e,l);for(let u of c)if(Ko(o.phone,u,n))try{await t.phone(u,Go(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,...c]){let g=l.items[p.key];if(!Ko(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&&Mt(e,l)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function Bg(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
868
- Answer it on the Desk.`}}import{closeSync as re,createReadStream as pc,fstatSync as gc,openSync as fc,realpathSync as Yo}from"fs";import{isAbsolute as mc,resolve as Zo,sep as Qo}from"path";var Gg="/app-files",hc=/^[A-Za-z0-9_.:-]{1,64}$/;function bc(t,e,n=process.cwd()){if(!e||e.length>de.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 ${Fe}/ first`};if(!Ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Yo(Zo(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Yo(mc(e)?e:Zo(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Qo))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Fe}/ first`};let s=Ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function yc(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 wc(t,e,n){return{"Content-Type":t,"Content-Disposition":yc(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 xc(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 Jg(t,e,n,r){let o=($,q)=>{e.writeHead($,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(q))};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(!hc.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 l=bc(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${l.error}`),o(l.status,{error:l.error});let c;try{c=fc(l.path,"r")}catch{return o(404,{error:"file not found"})}let d;try{let $=gc(c);if(!$.isFile())return re(c),o(404,{error:"not a file"});d=$.size}catch{return re(c),o(404,{error:"file not found"})}if(d>de.bytes)return re(c),o(413,{error:`the file is larger than ${de.bytes/1024/1024} MB`});let u=l.path.split(Qo).pop()||"file",p=wc(l.mime,u,l.kind),g=xc(t.headers.range,d);if(g==="unsatisfiable"){re(c),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){re(c),e.end();return}let b=pc("",{fd:c,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as oe}from"child_process";import{readFileSync as kc,writeFileSync as vc}from"fs";import{tmpdir as Sc}from"os";import{join as $c}from"path";Zt();var es=t=>t&&t!==1?Math.round(175*t):null,Ae=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Ec(){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=kc(t,"utf8").trim();if(e)return e}catch{}return null}function sf(t=Ec()){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",...Ae(n.voice.rate)?{voice_settings:{speed:Ae(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=$c(Sc(),`agentx-say-${process.pid}-${++e}.mp3`);return vc(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return W(`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 ts(t,e){let n=t.languages&&le(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var _c=(t,e="")=>{let n=ts(t,e),r=es(t.rate);return[...n&&!jr(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Ac(t,e,n){if(!n)return["say",_c(t,e)];let r=ts(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function af(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function lf(t=Ut()){if(t)try{oe("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function cf(t=Ut()){if(t)try{oe("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Ut(t={},e){if(!at(t))return null;try{return Vr(e)}catch(n){return W("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
869
- `)[0]}); Siri voices will not switch`),null}}var df=(t,e)=>{if(!t){let[n,r]=Ac(e.voice,e.text,Ut()),o=es(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=oe(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?oe("afplay",[t],{stdio:"ignore"}):oe("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ns}from"child_process";import{accessSync as Rc,constants as Ic,readFileSync as rs}from"fs";import{homedir as Tc}from"os";import{basename as K,delimiter as os,dirname as Dc,extname as Cc,join as Ft}from"path";var M={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function ss(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)>M.ms+2e3?{status:413,error:jt()}:null}var jt=()=>`The recording is longer than ${M.ms/6e4} minutes.`,Nc={"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 is(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Nc[e]??null}function as(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 qt(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 Wt(t,e,n=process.env.PATH??""){let r=Tc(),o=[Ft(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(os).filter(Boolean)];for(let s of[e,...o.map(i=>Ft(i,t))])if(s)try{return Rc(s,Ic.X_OK),s}catch{}return null}function hf(t){return{key:t,mlx:Wt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:Wt("whisper",process.env.AGENTX_WHISPER),ffmpeg:Lc()}}var Lc=()=>Wt("ffmpeg",process.env.AGENTX_FFMPEG);async function ls(t,e){return e?Pc(t,e):null}async function Pc(t,e){let n=String(M.ms/1e3+5);try{let o=[...(await Oc(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 cs(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([rs(t)],{type:e}),K(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 ds(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:`${Dc(r)}${os}${process.env.PATH??""}`};await Mc(e,s,12e4,i);try{return rs(Ft(o,K(n,Cc(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Oc(t,e,n){return new Promise((r,o)=>{let s=ns(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${K(t)} took too long`))},n);s.stderr.on("data",l=>{i=(i+l).slice(-8192)}),s.on("error",l=>{clearTimeout(a),o(l)}),s.on("exit",l=>{clearTimeout(a),l===0?r(i):o(new Error(`${K(t)} exited ${l}`))})})}function Mc(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ns(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",c=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${K(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{l.length<4096&&(l+=d)}),i.on("error",d=>{clearTimeout(c),s(d)}),i.on("exit",d=>{clearTimeout(c),d===0?o(a):s(new Error(`${K(t)} exited ${d}: ${l.trim().split(`
870
- `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as Uc,rm as Fc,writeFile as Wc}from"fs/promises";import{tmpdir as jc}from"os";import{join as us}from"path";ks();var qc=64*1024,Bc=2,Bt=0;function Af(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Rf(t,e,n,r){return t.method!=="POST"?w(e,405,{error:"POST"}):n==="/voice/transcribe"?Vc(t,e,r):Xc(t,e,r)}async function Vc(t,e,n){let r=String(t.headers["content-type"]||""),o=is(r);if(!o)return w(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=ss(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),w(e,s.status,{error:s.error});let i=await ps(t,M.bytes);if(!i)return w(e,413,{error:Jc()});if(!i.length)return w(e,400,{error:"The recording is empty."});if(Bt>=Bc)return w(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),c=as(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=c.length?"":" "+qt(a,l);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(!c.length)return w(e,503,{error:"Voice input isn't set up on this computer.",hint:qt(a,l),setup:!1});Bt++;let d;try{let u=await Uc(us(jc(),"agentx-phone-voice-"));try{d=await Hc(u,`speech.${o}`,i,r,l,c,n)}finally{await Fc(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Bt--}w(e,d[0],d[1])}async function Hc(t,e,n,r,o,s,i){let a=us(t,e);if(await Wc(a,n,{mode:384}),o.ffmpeg){let c=await(i.measure??ls)(a,o.ffmpeg);if(c==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(c*1e3>M.ms+2e3)return[413,{error:jt()}]}let l=[];for(let c of s)try{let d=await zc(c,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${c} (${Math.round(n.length/1024)} KB)`),d?[200,{text:d,engine:c}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:c}]}catch(d){let u=String(d?.message??d).split(`
871
- `)[0].slice(0,200);l.push(`${c}: ${u}`),i.log(`[voice] phone transcription with ${c} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function zc(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return cs(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return ds(t,a,e,r.ffmpeg,o)}async function Xc(t,e,n){let r=await ps(t,qc);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=Kc(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return w(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,c=n.voiceOf(s,i);if(!c)return w(e,404,{error:`Unknown agent: ${s}`});let d=(p,g=200)=>w(e,g,{fallback:"browser",reason:p,text:l});if(c.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??Gc)(u,c,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
872
- `)[0].slice(0,160)}`),d("ElevenLabs could not speak this answer.",502)}}function Kc(t,e){let n=yo(pn(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Qt(n,e)}async function Gc(t,e,n){let r=Ae(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 Jc=()=>`The recording is larger than ${M.bytes/1024/1024} MB, more than ${M.ms/6e4} minutes of speech.`;function If(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?bt(ft(t,o,n.voice)):null}function ps(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))}import{existsSync as I,readFileSync as Xt,writeFileSync as Kt,mkdirSync as Re,readdirSync as zt,rmSync as Yc,statSync as D}from"fs";import{resolve as gs,relative as Zc,dirname as Gt,join as j,extname as se,basename as Jt}from"path";var S=200*1024,fs=new Set([".md",".markdown",".txt"]),G=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"]),Qc=6,ed=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function P(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=gs(t);if(I(n)||Re(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=gs(n,e);if(Zc(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function ms(t){let e=se(t).toLowerCase();if(!fs.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Vt(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Nf(t){let e=P(t,"."),n=[],r=new Set,o=[];try{o=zt(e)}catch{}for(let a of ed){let l=j(e,a);if(I(l)&&D(l).isFile()){let c=D(l).size,d=c>0&&c<S?Ht(l):"";n.push({path:a,title:Vt(d,a),size:c,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 l=j(e,a);try{let c=D(l);if(!c.isFile()||!fs.has(se(a).toLowerCase()))continue;let d=c.size>0&&c.size<S?Ht(l):"";n.push({path:a,title:Vt(d,a),size:c.size,exists:!0})}catch{}}let s=[],i=j(e,".claude","skills");if(I(i))try{for(let a of zt(i)){let l=j(i,a),c;try{c=D(l)}catch{continue}if(!c.isDirectory())continue;let d=j(l,"SKILL.md");if(!I(d))continue;let u=D(d),p=u.size<S?Ht(d):"";s.push({slug:a,title:Vt(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:s,workspace:e}}function Ht(t){try{return Xt(t,"utf-8")}catch{return""}}function Lf(t,e){let n=P(t,e);if(ms(n),!I(n))return{path:e,content:""};if(D(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Xt(n,"utf-8")}}function Pf(t,e,n){let r=P(t,e);ms(r);let o=Buffer.from(n,"utf-8");if(o.length>S)throw new Error(`File too large (${o.length} > ${S} bytes).`);return Re(Gt(r),{recursive:!0}),Kt(r,o),{path:e,bytes:o.length}}function Of(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=P(t,r);if(I(o))throw new Error(`Skill "${e}" already exists.`);Re(Gt(o),{recursive:!0});let s=n.content?.trim()?n.content:td(e,n.title);return Kt(o,s),{slug:e,path:r}}function Mf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);if(!D(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Yc(n,{recursive:!0,force:!0}),{slug:e}}function Uf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(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,l){if(a>Qc)return;let c=[];try{c=zt(s)}catch{return}for(let d of c){if(d==="node_modules"||d===".git")continue;let u=j(s,d),p=i?`${i}/${d}`:d,g;try{g=D(u)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),o(u,p,a+1,l);else if(g.isFile()){let f=se(d).toLowerCase(),m=G.has(f)||G.has(d.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<S})}}}}function Ff(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=P(t,`.claude/skills/${e}/${n}`);if(!I(r)||!D(r).isFile())throw new Error(`File not found: ${n}`);let o=se(r).toLowerCase(),s=Jt(r).toLowerCase();if(!G.has(o)&&!G.has(s))throw new Error(`File type not editable: ${n}`);if(D(r).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Xt(r,"utf-8")}}function Wf(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=P(t,`.claude/skills/${e}/${n}`),s=se(o).toLowerCase(),i=Jt(o).toLowerCase();if(!G.has(s)&&!G.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return Re(Gt(o),{recursive:!0}),Kt(o,a),{path:n,bytes:a.length}}function jf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=o=>I(j(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 td(t,e){return`# ${e?.trim()||t}
867
+ Message (edit it if you like):`,u=await n("/usr/bin/osascript",jo(s,c,i?["Cancel","Send"]:["Not now","No","Send"],r,Sn(t.draft,i)),o),p=u.ok?qo(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",jo(s,Lt(t),["Not now","No","Yes"],r),o),l=a.ok?qo(a.stdout):null;return l?.button==="Yes"?{action:"yes"}:l?.button==="No"?{action:"no"}:{action:"dismiss"}}var Mt=24*36e5,Pt=!1,ec=10*6e4,Ho=-1/0;function zo(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,l=B(t.root,"pending").filter(d=>Date.parse(d.expires)>n),c=l.find(d=>i.includes(`card:${d.id}`));if(c)return c;for(let d of l){let u=`card:${d.id}`;if(r[u]||!e(d)||Gn(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>Mt&&!(g<=a)))return d}return null}function Ot(t){try{return F(t)?.listByState("needs_attention")??[]}catch{return[]}}var Xo=new Map;function tc(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=_(t.root);return e({})?Ot(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Xo.get(s.id)===U(s,Ve.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=Mt})??null:null}function nc(t,e){return{id:t.id,title:U(t,Ve.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+Mt).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Fg(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(Pt)return"busy";let o=zo(e,t.reaches)?null:tc(e,t.reaches),s=o?nc(o,e.now??Date.now()):zo(e,t.reaches);if(!s)return"none";let i=(t.focus??$o)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,l=(_(e.root).wanted??[]).includes(a)?null:qn(s);if(l){if(o)Xo.set(o.id,s.title);else{let c=[...B(e.root,"pending").map(d=>`card:${d.id}`),...Ot(e).map(d=>`request:${d.id}`)];Ke(e.root,a,c,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${l}`),t.returnToAuthor?.(s,Bn(s,l)),"returned"}Pt=!0;try{let c=[...B(e.root,"pending").map(b=>`card:${b.id}`),...Ot(e).map(b=>`request:${b.id}`)];Ke(e.root,a,c,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let d=e.now??Date.now(),u=!!o&&d-Ho<ec;o&&n.speak&&(Ho=d);let p=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Vo)(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"} (${mn(i)} when shown)`),"shown";if(!(o?F(e)?.get(o.id)?.state==="needs_attention":Y(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let m=await Tr(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(c){return r(`[approvals] popup failed for ${a}: ${c?.message??c}`),"shown"}finally{Pt=!1}}function Wg(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:")?Y(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(ir(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 rc,mkdirSync as oc,readFileSync as sc,renameSync as ic,writeFileSync as ac}from"fs";import{dirname as lc,resolve as cc}from"path";var dc=["all","urgent","off"],uc=24*36e5,Ko=24*36e5,pc=30*24*36e5,Go=t=>dc.includes(t);function Vg(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Go(e)?e:"off",computer:Go(n)?n:t.popupEnabled?"all":"off"}}function Yo(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=uc}function Jo(t,e,n){return t==="all"||t==="urgent"&&Yo(e,n)}function Zo(t){return cc(t,".agentx","desk-routed.json")}function gc(t){let e=Zo(t);if(!rc(e))return null;try{let n=JSON.parse(sc(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function Ut(t,e){let n=Zo(t);oc(lc(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;ac(r,JSON.stringify(e,null,2)),ic(r,n)}async function Hg(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),l=gc(e);if(!l){let u={};for(let p of r.items)u[p.key]={at:a,seen:a};return Ut(e,{items:u}),i.primed=!0,i}let c=[],d=[];for(let u of r.items){let p=l.items[u.key];if(p){p.seen=a,p.computerHeld&&n-Date.parse(p.at)>Ko&&delete p.computerHeld,p.computerHeld&&d.push(u);continue}l.items[u.key]={at:a,seen:a};let g=u.askedAt?Date.parse(u.askedAt):n;n-g<=Ko&&c.push(u)}for(let[u,p]of Object.entries(l.items))n-Date.parse(p.seen)>pc&&delete l.items[u];Ut(e,l);for(let u of c)if(Jo(o.phone,u,n))try{await t.phone(u,Yo(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,...c]){let g=l.items[p.key];if(!Jo(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&&Ut(e,l)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function zg(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
868
+ Answer it on the Desk.`}}import{closeSync as re,createReadStream as fc,fstatSync as mc,openSync as hc,realpathSync as Qo}from"fs";import{isAbsolute as bc,resolve as es,sep as ts}from"path";var Zg="/app-files",yc=/^[A-Za-z0-9_.:-]{1,64}$/;function wc(t,e,n=process.cwd()){if(!e||e.length>de.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 ${Fe}/ first`};if(!Ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Qo(es(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Qo(bc(e)?e:es(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+ts))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${Fe}/ first`};let s=Ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function xc(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 kc(t,e,n){return{"Content-Type":t,"Content-Disposition":xc(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 vc(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 Qg(t,e,n,r){let o=($,q)=>{e.writeHead($,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(q))};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(!yc.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 l=wc(a,i,r.cwd);if(!l.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${l.error}`),o(l.status,{error:l.error});let c;try{c=hc(l.path,"r")}catch{return o(404,{error:"file not found"})}let d;try{let $=mc(c);if(!$.isFile())return re(c),o(404,{error:"not a file"});d=$.size}catch{return re(c),o(404,{error:"file not found"})}if(d>de.bytes)return re(c),o(413,{error:`the file is larger than ${de.bytes/1024/1024} MB`});let u=l.path.split(ts).pop()||"file",p=kc(l.mime,u,l.kind),g=vc(t.headers.range,d);if(g==="unsatisfiable"){re(c),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){re(c),e.end();return}let b=fc("",{fd:c,start:f,end:m,autoClose:!0});b.on("error",()=>e.destroy()),e.on("close",()=>b.destroy()),b.pipe(e)}import{spawn as oe}from"child_process";import{readFileSync as Sc,writeFileSync as $c}from"fs";import{tmpdir as _c}from"os";import{join as Ec}from"path";Qt();var ns=t=>t&&t!==1?Math.round(175*t):null,Ae=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function Ac(){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=Sc(t,"utf8").trim();if(e)return e}catch{}return null}function cf(t=Ac()){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",...Ae(n.voice.rate)?{voice_settings:{speed:Ae(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=Ec(_c(),`agentx-say-${process.pid}-${++e}.mp3`);return $c(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return W(`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 rs(t,e){let n=t.languages&&le(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Rc=(t,e="")=>{let n=rs(t,e),r=ns(t.rate);return[...n&&!Br(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Ic(t,e,n){if(!n)return["say",Rc(t,e)];let r=rs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function df(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function uf(t=Ft()){if(t)try{oe("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function pf(t=Ft()){if(t)try{oe("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Ft(t={},e){if(!lt(t))return null;try{return zr(e)}catch(n){return W("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
869
+ `)[0]}); Siri voices will not switch`),null}}var gf=(t,e)=>{if(!t){let[n,r]=Ic(e.voice,e.text,Ft()),o=ns(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=oe(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?oe("afplay",[t],{stdio:"ignore"}):oe("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as os}from"child_process";import{accessSync as Tc,constants as Dc,readFileSync as ss}from"fs";import{homedir as Cc}from"os";import{basename as K,delimiter as is,dirname as Nc,extname as Lc,join as Wt}from"path";var M={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function as(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)>M.ms+2e3?{status:413,error:qt()}:null}var qt=()=>`The recording is longer than ${M.ms/6e4} minutes.`,Pc={"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 ls(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Pc[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 Bt(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 jt(t,e,n=process.env.PATH??""){let r=Cc(),o=[Wt(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(is).filter(Boolean)];for(let s of[e,...o.map(i=>Wt(i,t))])if(s)try{return Tc(s,Dc.X_OK),s}catch{}return null}function wf(t){return{key:t,mlx:jt("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:jt("whisper",process.env.AGENTX_WHISPER),ffmpeg:Oc()}}var Oc=()=>jt("ffmpeg",process.env.AGENTX_FFMPEG);async function ds(t,e){return e?Mc(t,e):null}async function Mc(t,e){let n=String(M.ms/1e3+5);try{let o=[...(await Uc(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 us(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ss(t)],{type:e}),K(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 ps(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:`${Nc(r)}${is}${process.env.PATH??""}`};await Fc(e,s,12e4,i);try{return ss(Wt(o,K(n,Lc(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Uc(t,e,n){return new Promise((r,o)=>{let s=os(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${K(t)} took too long`))},n);s.stderr.on("data",l=>{i=(i+l).slice(-8192)}),s.on("error",l=>{clearTimeout(a),o(l)}),s.on("exit",l=>{clearTimeout(a),l===0?r(i):o(new Error(`${K(t)} exited ${l}`))})})}function Fc(t,e,n,r=process.env){return new Promise((o,s)=>{let i=os(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",l="",c=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${K(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",d=>{a.length<4096&&(a+=d)}),i.stderr.on("data",d=>{l.length<4096&&(l+=d)}),i.on("error",d=>{clearTimeout(c),s(d)}),i.on("exit",d=>{clearTimeout(c),d===0?o(a):s(new Error(`${K(t)} exited ${d}: ${l.trim().split(`
870
+ `).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as Wc,rm as jc,writeFile as qc}from"fs/promises";import{tmpdir as Bc}from"os";import{join as gs}from"path";Ss();var Vc=64*1024,Hc=2,Vt=0;function Tf(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Df(t,e,n,r){return t.method!=="POST"?w(e,405,{error:"POST"}):n==="/voice/transcribe"?zc(t,e,r):Gc(t,e,r)}async function zc(t,e,n){let r=String(t.headers["content-type"]||""),o=ls(r);if(!o)return w(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=as(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),w(e,s.status,{error:s.error});let i=await fs(t,M.bytes);if(!i)return w(e,413,{error:Zc()});if(!i.length)return w(e,400,{error:"The recording is empty."});if(Vt>=Hc)return w(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),l=n.host(),c=cs(a,l);if(!l.ffmpeg&&!n.allowUnmeasured?.()){let u=n.nodeName?`on ${n.nodeName}`:"on this computer",p=c.length?"":" "+Bt(a,l);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(!c.length)return w(e,503,{error:"Voice input isn't set up on this computer.",hint:Bt(a,l),setup:!1});Vt++;let d;try{let u=await Wc(gs(Bc(),"agentx-phone-voice-"));try{d=await Xc(u,`speech.${o}`,i,r,l,c,n)}finally{await jc(u,{recursive:!0,force:!0}).catch(()=>{})}}finally{Vt--}w(e,d[0],d[1])}async function Xc(t,e,n,r,o,s,i){let a=gs(t,e);if(await qc(a,n,{mode:384}),o.ffmpeg){let c=await(i.measure??ds)(a,o.ffmpeg);if(c==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(c*1e3>M.ms+2e3)return[413,{error:qt()}]}let l=[];for(let c of s)try{let d=await Kc(c,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${c} (${Math.round(n.length/1024)} KB)`),d?[200,{text:d,engine:c}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:c}]}catch(d){let u=String(d?.message??d).split(`
871
+ `)[0].slice(0,200);l.push(`${c}: ${u}`),i.log(`[voice] phone transcription with ${c} failed: ${u}`)}return[502,{error:"Speech to text failed on this computer.",detail:l.join("; ")}]}function Kc(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return us(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return ps(t,a,e,r.ffmpeg,o)}async function Gc(t,e,n){let r=await fs(t,Vc);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=Jc(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return w(e,422,{error:"Nothing in this answer can be said aloud."});let l=n.pronounce?n.pronounce(a):a,c=n.voiceOf(s,i);if(!c)return w(e,404,{error:`Unknown agent: ${s}`});let d=(p,g=200)=>w(e,g,{fallback:"browser",reason:p,text:l});if(c.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??Yc)(u,c,l);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":p.length,"Cache-Control":"no-store","X-Spoken-Chars":String(l.length)}),e.end(p)}catch(p){return n.log(`[voice] phone answer synthesis failed: ${String(p?.message??p).split(`
872
+ `)[0].slice(0,160)}`),d("ElevenLabs could not speak this answer.",502)}}function Jc(t,e){let n=xo(gn(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return en(n,e)}async function Yc(t,e,n){let r=Ae(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 Zc=()=>`The recording is larger than ${M.bytes/1024/1024} MB, more than ${M.ms/6e4} minutes of speech.`;function Cf(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?yt(mt(t,o,n.voice)):null}function fs(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))}import{existsSync as I,readFileSync as Kt,writeFileSync as Gt,mkdirSync as Re,readdirSync as Xt,rmSync as Qc,statSync as D}from"fs";import{resolve as ms,relative as ed,dirname as Jt,join as j,extname as se,basename as Yt}from"path";var S=200*1024,hs=new Set([".md",".markdown",".txt"]),G=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"]),td=6,nd=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function P(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=ms(t);if(I(n)||Re(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=ms(n,e);if(ed(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function bs(t){let e=se(t).toLowerCase();if(!hs.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Ht(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Of(t){let e=P(t,"."),n=[],r=new Set,o=[];try{o=Xt(e)}catch{}for(let a of nd){let l=j(e,a);if(I(l)&&D(l).isFile()){let c=D(l).size,d=c>0&&c<S?zt(l):"";n.push({path:a,title:Ht(d,a),size:c,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 l=j(e,a);try{let c=D(l);if(!c.isFile()||!hs.has(se(a).toLowerCase()))continue;let d=c.size>0&&c.size<S?zt(l):"";n.push({path:a,title:Ht(d,a),size:c.size,exists:!0})}catch{}}let s=[],i=j(e,".claude","skills");if(I(i))try{for(let a of Xt(i)){let l=j(i,a),c;try{c=D(l)}catch{continue}if(!c.isDirectory())continue;let d=j(l,"SKILL.md");if(!I(d))continue;let u=D(d),p=u.size<S?zt(d):"";s.push({slug:a,title:Ht(p,a),size:u.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,l)=>a.slug.localeCompare(l.slug)),{identity:n,skills:s,workspace:e}}function zt(t){try{return Kt(t,"utf-8")}catch{return""}}function Mf(t,e){let n=P(t,e);if(bs(n),!I(n))return{path:e,content:""};if(D(n).size>S)throw new Error(`File is too large to edit in the admin panel (> ${S/1024} KB).`);return{path:e,content:Kt(n,"utf-8")}}function Uf(t,e,n){let r=P(t,e);bs(r);let o=Buffer.from(n,"utf-8");if(o.length>S)throw new Error(`File too large (${o.length} > ${S} bytes).`);return Re(Jt(r),{recursive:!0}),Gt(r,o),{path:e,bytes:o.length}}function Ff(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=P(t,r);if(I(o))throw new Error(`Skill "${e}" already exists.`);Re(Jt(o),{recursive:!0});let s=n.content?.trim()?n.content:rd(e,n.title);return Gt(o,s),{slug:e,path:r}}function Wf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);if(!D(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Qc(n,{recursive:!0,force:!0}),{slug:e}}function jf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(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,l){if(a>td)return;let c=[];try{c=Xt(s)}catch{return}for(let d of c){if(d==="node_modules"||d===".git")continue;let u=j(s,d),p=i?`${i}/${d}`:d,g;try{g=D(u)}catch{continue}if(g.isDirectory())l.push({path:`${p}/`,kind:"dir",size:0,editable:!1}),o(u,p,a+1,l);else if(g.isFile()){let f=se(d).toLowerCase(),m=G.has(f)||G.has(d.toLowerCase());l.push({path:p,kind:"file",size:g.size,editable:m&&g.size<S})}}}}function qf(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=P(t,`.claude/skills/${e}/${n}`);if(!I(r)||!D(r).isFile())throw new Error(`File not found: ${n}`);let o=se(r).toLowerCase(),s=Yt(r).toLowerCase();if(!G.has(o)&&!G.has(s))throw new Error(`File type not editable: ${n}`);if(D(r).size>S)throw new Error(`File too large to edit (> ${S/1024} KB): ${n}`);return{path:n,content:Kt(r,"utf-8")}}function Bf(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=P(t,`.claude/skills/${e}/${n}`),s=se(o).toLowerCase(),i=Yt(o).toLowerCase();if(!G.has(s)&&!G.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>S)throw new Error(`File too large (${a.length} > ${S} bytes).`);return Re(Jt(o),{recursive:!0}),Gt(o,a),{path:n,bytes:a.length}}function Vf(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=P(t,`.claude/skills/${e}`);if(!I(n))throw new Error(`Skill "${e}" not found.`);let r=o=>I(j(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 rd(t,e){return`# ${e?.trim()||t}
873
873
 
874
874
  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.
875
875
 
@@ -882,7 +882,7 @@ Document the arguments, commands, or files the skill expects. Example:
882
882
 
883
883
  \`\`\`bash
884
884
  # Example invocation
885
- claude-code ${Jt(t)} --arg value
885
+ claude-code ${Yt(t)} --arg value
886
886
  \`\`\`
887
- `}an();var hs={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function bs(t){return{...hs,...t??{},regions:{...t?.regions??{}},buffer:{...hs.buffer,...t?.buffer??{}}}}function Vf(t){try{return bs(sn(t).screen)}catch{return bs(void 0)}}var nd=/^[a-z][\w-]*$/,ys=["window","screen","menubar","notifications"];function ie(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 Ie=(t,e)=>ie(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ws(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 Hf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ie(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ie(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ie(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ie(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ie(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(!nd.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=ws(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=ie(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ie(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ie(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&&!ys.includes(r)&&!n.regions?.[r])try{ws(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...ys,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Kn as a,sd as b,Rt as c,Ga as d,Ja as e,Dp as f,Cp as g,Np as h,Op as i,Mp as j,Up as k,ho as l,bo as m,Fp as n,yo as o,jp as p,Bp as q,O as r,wo as s,k as t,cd as u,vo as v,Gp as w,Zp as x,$o as y,Qp as z,Eo as A,eg as B,ne as C,Sl as D,tg as E,ng as F,Ao as G,$d as H,Qs as I,Td as J,gr as K,Cd as L,E as M,fd as N,md as O,Wd as P,fe as Q,jd as R,sr as S,kd as T,F as U,du as V,Ar as W,Rr as X,Ti as Y,Di as Z,gu as _,fu as $,Ui as aa,yu as ba,Io as ca,sg as da,ku as ea,vu as fa,po as ga,wt as ha,qa as ia,v as ja,qo as ka,Og as la,Mg as ma,lc as na,jg as oa,Ko as pa,qg as qa,Bg as ra,Gg as sa,wc as ta,Jg as ua,$u as va,Eu as wa,_u as xa,Au as ya,Ru as za,Iu as Aa,Du as Ba,Cu as Ca,Pu as Da,Ou as Ea,Mu as Fa,Fu as Ga,Wu as Ha,ju as Ia,qu as Ja,Bu as Ka,Vu as La,Hu as Ma,ep as Na,dt as Oa,tp as Pa,np as Qa,ee as Ra,te as Sa,Ec as Ta,sf as Ua,af as Va,lf as Wa,cf as Xa,Ut as Ya,df as Za,gt as _a,ft as $a,ve as ab,fa as bb,ha as cb,ap as db,ht as eb,bt as fb,ba as gb,ya as hb,eo as ib,oo as jb,lp as kb,ka as lb,cp as mb,Ia as nb,Ca as ob,yt as pb,La as qb,so as rb,M as sb,ss as tb,is as ub,as as vb,Wt as wb,hf as xb,Lc as yb,cs as zb,ds as Ab,Af as Bb,Rf as Cb,Jc as Db,If as Eb,ps as Fb,Se as Gb,kp as Hb,_t as Ib,Rp as Jb,Nf as Kb,Lf as Lb,Pf as Mb,Of as Nb,Mf as Ob,Uf as Pb,Ff as Qb,Wf as Rb,jf as Sb,hs as Tb,bs as Ub,Vf as Vb,ys as Wb,Hf as Xb};
888
- //# sourceMappingURL=chunk-I5TUF6U7.js.map
887
+ `}ln();var ys={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function ws(t){return{...ys,...t??{},regions:{...t?.regions??{}},buffer:{...ys.buffer,...t?.buffer??{}}}}function Xf(t){try{return ws(an(t).screen)}catch{return ws(void 0)}}var od=/^[a-z][\w-]*$/,xs=["window","screen","menubar","notifications"];function ie(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 Ie=(t,e)=>ie(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ks(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 Kf(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ie(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ie(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ie(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ie(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ie(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(!od.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=ks(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=ie(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ie(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ie(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&&!xs.includes(r)&&!n.regions?.[r])try{ks(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...xs,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Jn as a,ad as b,It as c,Ya as d,Za as e,Lp as f,Pp as g,Op as h,Fp as i,Wp as j,jp as k,yo as l,wo as m,qp as n,xo as o,Vp as p,zp as q,O as r,ko as s,k as t,ud as u,$o as v,Zp as w,tg as x,Eo as y,ng as z,Ao as A,rg as B,ne as C,_l as D,og as E,sg as F,Io as G,Ed as H,ti as I,Cd as J,mr as K,Ld as L,_ as M,hd as N,bd as O,qd as P,fe as Q,Bd as R,ar as S,Sd as T,F as U,gu as V,Rr as W,Tr as X,Ci as Y,Ni as Z,hu as _,bu as $,Wi as aa,ku as ba,Do as ca,lg as da,$u as ea,_u as fa,fo as ga,xt as ha,Va as ia,v as ja,Vo as ka,Fg as la,Wg as ma,dc as na,Vg as oa,Jo as pa,Hg as qa,zg as ra,Zg as sa,kc as ta,Qg as ua,Au as va,Ru as wa,Iu as xa,Tu as ya,Du as za,Cu as Aa,Lu as Ba,Pu as Ca,Uu as Da,Fu as Ea,Wu as Fa,qu as Ga,Bu as Ha,Vu as Ia,Hu as Ja,zu as Ka,Xu as La,Ku as Ma,rp as Na,ut as Oa,op as Pa,sp as Qa,ee as Ra,te as Sa,Ac as Ta,cf as Ua,df as Va,uf as Wa,pf as Xa,Ft as Ya,gf as Za,ft as _a,mt as $a,ve as ab,ha as bb,ya as cb,dp as db,bt as eb,yt as fb,wa as gb,xa as hb,no as ib,io as jb,up as kb,Sa as lb,pp as mb,Da as nb,La as ob,wt as pb,Oa as qb,ao as rb,M as sb,as as tb,ls as ub,cs as vb,jt as wb,wf as xb,Oc as yb,us as zb,ps as Ab,Tf as Bb,Df as Cb,Zc as Db,Cf as Eb,fs as Fb,Se as Gb,$p as Hb,At as Ib,Dp as Jb,Of as Kb,Mf as Lb,Uf as Mb,Ff as Nb,Wf as Ob,jf as Pb,qf as Qb,Bf as Rb,Vf as Sb,ys as Tb,ws as Ub,Xf as Vb,xs as Wb,Kf as Xb};
888
+ //# sourceMappingURL=chunk-LZVQ4N2Z.js.map