agentix-cli 0.215.0 → 0.217.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.
- package/dist/{App-OUWMH6QG.js → App-IXJCCCGN.js} +2 -2
- package/dist/{ChatApp-EZ5A47FV.js → ChatApp-4YCCRL5M.js} +2 -2
- package/dist/{absorb-eval-WM6JQGYG.js → absorb-eval-YE57HA6N.js} +2 -2
- package/dist/{adapter-W26OC6ET.js → adapter-CRVWPQBN.js} +2 -2
- package/dist/{agent-KOKQSRAH.js → agent-CTZN3P2K.js} +2 -2
- package/dist/{board-dashboard-NVQUQSWI.js → board-dashboard-2WE2HBEW.js} +621 -394
- package/dist/board-dashboard-2WE2HBEW.js.map +1 -0
- package/dist/{chunk-OQNJIIR2.js → chunk-2F7KQ4DJ.js} +2 -2
- package/dist/{chunk-XHON5WB5.js → chunk-2MAKXLK2.js} +3 -3
- package/dist/{chunk-GGAEFVXL.js → chunk-3B7RH3IK.js} +2 -2
- package/dist/{chunk-ACPGDZOV.js → chunk-3C6UDZDX.js} +2 -2
- package/dist/{chunk-H4DWZIU7.js → chunk-56UTQ4FU.js} +2 -2
- package/dist/chunk-5FFNFW4C.js +20 -0
- package/dist/chunk-5FFNFW4C.js.map +1 -0
- package/dist/{chunk-MIUITI47.js → chunk-64IVC2G6.js} +2 -2
- package/dist/{chunk-IHFOW4JF.js → chunk-AOPNASCE.js} +2 -2
- package/dist/chunk-BXK5S2KK.js +13 -0
- package/dist/chunk-BXK5S2KK.js.map +1 -0
- package/dist/{chunk-QOGZD6Z3.js → chunk-ELC3M5WS.js} +318 -316
- package/dist/chunk-ELC3M5WS.js.map +1 -0
- package/dist/{chunk-PSYHAO57.js → chunk-FFLMSNTN.js} +2 -2
- package/dist/{chunk-JLH73NRM.js → chunk-GEKEILPL.js} +5 -5
- package/dist/{chunk-JLH73NRM.js.map → chunk-GEKEILPL.js.map} +1 -1
- package/dist/{chunk-J2R47R56.js → chunk-I4FXWN7I.js} +2 -2
- package/dist/{chunk-CSC45PA7.js → chunk-IP67DTXX.js} +2 -2
- package/dist/chunk-KBSQRQPF.js +10 -0
- package/dist/chunk-KBSQRQPF.js.map +1 -0
- package/dist/{chunk-4BYJN2A3.js → chunk-LLNLDZNA.js} +2 -2
- package/dist/{chunk-N476XZD3.js → chunk-LSFLSB7C.js} +2 -2
- package/dist/{chunk-4ZD2C76P.js → chunk-M42GMRZF.js} +2 -2
- package/dist/{chunk-JKMFKNGS.js → chunk-MFZNBE65.js} +2 -2
- package/dist/{chunk-4DCQIHWU.js → chunk-NFUHYIYG.js} +2 -2
- package/dist/chunk-O2YDS2P3.js +8 -0
- package/dist/chunk-O2YDS2P3.js.map +1 -0
- package/dist/{chunk-B7HDWFKR.js → chunk-OJ4RUZZY.js} +2 -2
- package/dist/chunk-PZ2F6J2E.js +134 -0
- package/dist/chunk-PZ2F6J2E.js.map +1 -0
- package/dist/{chunk-CAH6TNC6.js → chunk-Q432O462.js} +2 -2
- package/dist/{chunk-Z7632XS3.js → chunk-QEOGWSRR.js} +2 -2
- package/dist/{chunk-QR3P5RG7.js → chunk-QGRIW7SE.js} +2 -2
- package/dist/{chunk-JEBU5JUM.js → chunk-RKKAP4EY.js} +2 -2
- package/dist/{chunk-HY4PE6R3.js → chunk-SJJ7QEFE.js} +2 -2
- package/dist/{chunk-6UTOBSEA.js → chunk-SYIDD7CI.js} +2 -2
- package/dist/{chunk-7AFXLWWW.js → chunk-WHAMZPEG.js} +141 -87
- package/dist/chunk-WHAMZPEG.js.map +1 -0
- package/dist/{chunk-QMICGPM6.js → chunk-X2GBLX3E.js} +2 -2
- package/dist/{chunk-M4H2RYP4.js → chunk-XQH4LCZR.js} +2 -2
- package/dist/{chunk-Q7Y5VQGX.js → chunk-YXGZSVPY.js} +2 -2
- package/dist/{chunk-ZRBTLW2B.js → chunk-Z5HYCMDF.js} +2 -2
- package/dist/cli.js +1 -1
- package/dist/client-UPXDV3SM.js +2 -0
- package/dist/config-LAM4HUTA.js +2 -0
- package/dist/config-mutate-P4QLFUVH.js +2 -0
- package/dist/config-mutator-RIPSMYAO.js +2 -0
- package/dist/{contributions-FXUTKU6R.js → contributions-SHSEI3TX.js} +2 -2
- package/dist/{doctor-GP2KVKWE.js → doctor-TLDBNHYM.js} +2 -2
- package/dist/{follow-up-tool-C4PLLZIT.js → follow-up-tool-VM4ZDRC5.js} +2 -2
- package/dist/{follow-up-tool-C4PLLZIT.js.map → follow-up-tool-VM4ZDRC5.js.map} +1 -1
- package/dist/{grants-U2734ZHZ.js → grants-ZA35QVTX.js} +2 -2
- package/dist/hub-7Y6ZUVJV.js +2 -0
- package/dist/index.d.ts +375 -295
- package/dist/index.js +1 -1
- package/dist/org-tool-TOHI7MBS.js +2 -0
- package/dist/{org-tool-6PPIGWH2.js.map → org-tool-TOHI7MBS.js.map} +1 -1
- package/dist/{program-WSGVQTFM.js → program-QZKK3Y2W.js} +310 -310
- package/dist/program-QZKK3Y2W.js.map +1 -0
- package/dist/{promote-CXXMZWWH.js → promote-OBTQ3ZUN.js} +2 -2
- package/dist/push-bridge-T5HZZRA2.js +1 -1
- package/dist/{query-RPZIRN3X.js → query-K6NR3GQE.js} +2 -2
- package/dist/{query-settings-EBOBWOAL.js → query-settings-NIZBB73K.js} +2 -2
- package/dist/{registry-KRU6AWVW.js → registry-B7X6YGS7.js} +2 -2
- package/dist/{request-planner-LNNKTY7K.js → request-planner-YDIX4BQW.js} +2 -2
- package/dist/{review-candidates-HQBKXAJA.js → review-candidates-3QCCHXWM.js} +2 -2
- package/dist/routing-BGMIY5JY.js +2 -0
- package/dist/schedule-tool-P6XM6W3S.js +2 -0
- package/dist/scheduler-PUKN5YSL.js +2 -0
- package/dist/{seat-BSWBTNCP.js → seat-OTAJJ5BP.js} +2 -2
- package/dist/{select-T4F42G6W.js → select-KKMXIVVL.js} +2 -2
- package/dist/{set-enabled-UK4TPVC7.js → set-enabled-BNF427ZN.js} +2 -2
- package/dist/{sprint-tool-DN3BKLUY.js → sprint-tool-Y72HTX5X.js} +2 -2
- package/dist/{sprint-tool-DN3BKLUY.js.map → sprint-tool-Y72HTX5X.js.map} +1 -1
- package/dist/{tool-L3CQUOAZ.js → tool-DW6MYEG2.js} +2 -2
- package/dist/{tool-L3CQUOAZ.js.map → tool-DW6MYEG2.js.map} +1 -1
- package/dist/tool-EA4FWTH6.js +2 -0
- package/dist/{tool-ZVYUWVJQ.js → tool-F4ZVMX4J.js} +2 -2
- package/dist/{tool-ZVYUWVJQ.js.map → tool-F4ZVMX4J.js.map} +1 -1
- package/dist/{tool-ZCSGJ2ZF.js → tool-HUOT3I42.js} +2 -2
- package/dist/{tool-ZCSGJ2ZF.js.map → tool-HUOT3I42.js.map} +1 -1
- package/dist/tool-QDAD4ACK.js +4 -0
- package/dist/{tool-JJGEGQF3.js.map → tool-QDAD4ACK.js.map} +1 -1
- package/dist/wiki-J6MSHSVD.js +2 -0
- package/dist/wiki-enrich-3Y3TZ6ZK.js +2 -0
- package/dist/{workspace-setup-VGXHYCD5.js → workspace-setup-CQ5FMT2B.js} +2 -2
- package/dist/workspace-setup-CQ5FMT2B.js.map +1 -0
- package/package.json +1 -1
- package/dist/board-dashboard-NVQUQSWI.js.map +0 -1
- package/dist/chunk-35UGFFHA.js +0 -20
- package/dist/chunk-35UGFFHA.js.map +0 -1
- package/dist/chunk-7AFXLWWW.js.map +0 -1
- package/dist/chunk-KAM4ZWRE.js +0 -133
- package/dist/chunk-KAM4ZWRE.js.map +0 -1
- package/dist/chunk-OQQTV3OF.js +0 -12
- package/dist/chunk-OQQTV3OF.js.map +0 -1
- package/dist/chunk-QOGZD6Z3.js.map +0 -1
- package/dist/chunk-RKPAVWXF.js +0 -2
- package/dist/chunk-RKPAVWXF.js.map +0 -1
- package/dist/chunk-UUOCCLIL.js +0 -8
- package/dist/chunk-UUOCCLIL.js.map +0 -1
- package/dist/client-U3OFNJ5W.js +0 -2
- package/dist/config-S522VXLI.js +0 -2
- package/dist/config-mutate-KBZV2T4X.js +0 -2
- package/dist/config-mutator-YNNEGRV3.js +0 -2
- package/dist/hub-V2AGLA7T.js +0 -2
- package/dist/org-tool-6PPIGWH2.js +0 -2
- package/dist/program-WSGVQTFM.js.map +0 -1
- package/dist/routing-XXA7GIBA.js +0 -2
- package/dist/schedule-tool-65TFOUWK.js +0 -2
- package/dist/scheduler-DIPOBJBF.js +0 -2
- package/dist/tool-JJGEGQF3.js +0 -4
- package/dist/wiki-IDLRJ6WL.js +0 -2
- package/dist/wiki-enrich-XWLDJAZI.js +0 -2
- /package/dist/{App-OUWMH6QG.js.map → App-IXJCCCGN.js.map} +0 -0
- /package/dist/{ChatApp-EZ5A47FV.js.map → ChatApp-4YCCRL5M.js.map} +0 -0
- /package/dist/{absorb-eval-WM6JQGYG.js.map → absorb-eval-YE57HA6N.js.map} +0 -0
- /package/dist/{adapter-W26OC6ET.js.map → adapter-CRVWPQBN.js.map} +0 -0
- /package/dist/{agent-KOKQSRAH.js.map → agent-CTZN3P2K.js.map} +0 -0
- /package/dist/{chunk-OQNJIIR2.js.map → chunk-2F7KQ4DJ.js.map} +0 -0
- /package/dist/{chunk-XHON5WB5.js.map → chunk-2MAKXLK2.js.map} +0 -0
- /package/dist/{chunk-GGAEFVXL.js.map → chunk-3B7RH3IK.js.map} +0 -0
- /package/dist/{chunk-ACPGDZOV.js.map → chunk-3C6UDZDX.js.map} +0 -0
- /package/dist/{chunk-H4DWZIU7.js.map → chunk-56UTQ4FU.js.map} +0 -0
- /package/dist/{chunk-MIUITI47.js.map → chunk-64IVC2G6.js.map} +0 -0
- /package/dist/{chunk-IHFOW4JF.js.map → chunk-AOPNASCE.js.map} +0 -0
- /package/dist/{chunk-PSYHAO57.js.map → chunk-FFLMSNTN.js.map} +0 -0
- /package/dist/{chunk-J2R47R56.js.map → chunk-I4FXWN7I.js.map} +0 -0
- /package/dist/{chunk-CSC45PA7.js.map → chunk-IP67DTXX.js.map} +0 -0
- /package/dist/{chunk-4BYJN2A3.js.map → chunk-LLNLDZNA.js.map} +0 -0
- /package/dist/{chunk-N476XZD3.js.map → chunk-LSFLSB7C.js.map} +0 -0
- /package/dist/{chunk-4ZD2C76P.js.map → chunk-M42GMRZF.js.map} +0 -0
- /package/dist/{chunk-JKMFKNGS.js.map → chunk-MFZNBE65.js.map} +0 -0
- /package/dist/{chunk-4DCQIHWU.js.map → chunk-NFUHYIYG.js.map} +0 -0
- /package/dist/{chunk-B7HDWFKR.js.map → chunk-OJ4RUZZY.js.map} +0 -0
- /package/dist/{chunk-CAH6TNC6.js.map → chunk-Q432O462.js.map} +0 -0
- /package/dist/{chunk-Z7632XS3.js.map → chunk-QEOGWSRR.js.map} +0 -0
- /package/dist/{chunk-QR3P5RG7.js.map → chunk-QGRIW7SE.js.map} +0 -0
- /package/dist/{chunk-JEBU5JUM.js.map → chunk-RKKAP4EY.js.map} +0 -0
- /package/dist/{chunk-HY4PE6R3.js.map → chunk-SJJ7QEFE.js.map} +0 -0
- /package/dist/{chunk-6UTOBSEA.js.map → chunk-SYIDD7CI.js.map} +0 -0
- /package/dist/{chunk-QMICGPM6.js.map → chunk-X2GBLX3E.js.map} +0 -0
- /package/dist/{chunk-M4H2RYP4.js.map → chunk-XQH4LCZR.js.map} +0 -0
- /package/dist/{chunk-Q7Y5VQGX.js.map → chunk-YXGZSVPY.js.map} +0 -0
- /package/dist/{chunk-ZRBTLW2B.js.map → chunk-Z5HYCMDF.js.map} +0 -0
- /package/dist/{client-U3OFNJ5W.js.map → client-UPXDV3SM.js.map} +0 -0
- /package/dist/{config-S522VXLI.js.map → config-LAM4HUTA.js.map} +0 -0
- /package/dist/{config-mutate-KBZV2T4X.js.map → config-mutate-P4QLFUVH.js.map} +0 -0
- /package/dist/{config-mutator-YNNEGRV3.js.map → config-mutator-RIPSMYAO.js.map} +0 -0
- /package/dist/{contributions-FXUTKU6R.js.map → contributions-SHSEI3TX.js.map} +0 -0
- /package/dist/{doctor-GP2KVKWE.js.map → doctor-TLDBNHYM.js.map} +0 -0
- /package/dist/{grants-U2734ZHZ.js.map → grants-ZA35QVTX.js.map} +0 -0
- /package/dist/{hub-V2AGLA7T.js.map → hub-7Y6ZUVJV.js.map} +0 -0
- /package/dist/{promote-CXXMZWWH.js.map → promote-OBTQ3ZUN.js.map} +0 -0
- /package/dist/{query-RPZIRN3X.js.map → query-K6NR3GQE.js.map} +0 -0
- /package/dist/{query-settings-EBOBWOAL.js.map → query-settings-NIZBB73K.js.map} +0 -0
- /package/dist/{registry-KRU6AWVW.js.map → registry-B7X6YGS7.js.map} +0 -0
- /package/dist/{request-planner-LNNKTY7K.js.map → request-planner-YDIX4BQW.js.map} +0 -0
- /package/dist/{review-candidates-HQBKXAJA.js.map → review-candidates-3QCCHXWM.js.map} +0 -0
- /package/dist/{routing-XXA7GIBA.js.map → routing-BGMIY5JY.js.map} +0 -0
- /package/dist/{schedule-tool-65TFOUWK.js.map → schedule-tool-P6XM6W3S.js.map} +0 -0
- /package/dist/{scheduler-DIPOBJBF.js.map → scheduler-PUKN5YSL.js.map} +0 -0
- /package/dist/{seat-BSWBTNCP.js.map → seat-OTAJJ5BP.js.map} +0 -0
- /package/dist/{select-T4F42G6W.js.map → select-KKMXIVVL.js.map} +0 -0
- /package/dist/{set-enabled-UK4TPVC7.js.map → set-enabled-BNF427ZN.js.map} +0 -0
- /package/dist/{wiki-IDLRJ6WL.js.map → tool-EA4FWTH6.js.map} +0 -0
- /package/dist/{wiki-enrich-XWLDJAZI.js.map → wiki-J6MSHSVD.js.map} +0 -0
- /package/dist/{workspace-setup-VGXHYCD5.js.map → wiki-enrich-3Y3TZ6ZK.js.map} +0 -0
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{a as
|
|
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]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var
|
|
3
|
-
`),
|
|
4
|
-
`).pop()?.slice(0,300)||"no output";async function
|
|
5
|
-
`,{mode:384}),
|
|
1
|
+
import{a as xt}from"./chunk-GTJIKXDB.js";import{H as Wr,O as Xr,k as Y}from"./chunk-2F7KQ4DJ.js";import{f as Br,g as Hr,h as Vr,l as qr}from"./chunk-FFLMSNTN.js";import{b as jr}from"./chunk-2VDO2HEK.js";import{t as Fr,u as Ur}from"./chunk-RKKAP4EY.js";import{d as Pr,e as Mr}from"./chunk-AQASR6KR.js";import{h as he,j as Er,l as $r,m as _r,n as Ar}from"./chunk-RX5O5637.js";import{a as Rr,c as Tr,e as Ir,f as ht,h as Dr,j as Cr,k as Nr,l as bt,m as yt,n as wt}from"./chunk-5ELIX7BQ.js";import{c as Or,d as Lr}from"./chunk-IP67DTXX.js";import{a as br,c as yr}from"./chunk-KP7KDLZ2.js";import{Aa as mr,Ba as W,Ca as fe,Ea as ft,b as pt,f as cr,s as gt,u as mt,za as Oe}from"./chunk-3B7RH3IK.js";import{a as Ce,b as me,e as dr}from"./chunk-7AB3QUGH.js";import{h as wr,i as xr,j as kr,l as vr,m as Sr}from"./chunk-56UTQ4FU.js";import{s as gr}from"./chunk-Q432O462.js";import{a as ur,b as Ne,e as pr}from"./chunk-LSFLSB7C.js";import{c as Le,d as fr,e as hr}from"./chunk-XVV7ZZ77.js";import{b as ne}from"./chunk-5ONH4ITT.js";import{a as lr,c as ut}from"./chunk-ILEC3IAV.js";import{a as er,j as sr,m as ir,o as ct,p as dt,s as ge,t as te,v as ar}from"./chunk-BXK5S2KK.js";import{a as tr,b as nr,d as rr,e as or}from"./chunk-4NZ4T3TQ.js";import{a as Zn}from"./chunk-7IW25T4K.js";import{a as Qn}from"./chunk-QUFIUXMQ.js";import{Bc as Jn,Fa as De,Ha as qn,I as ot,J as C,L as Te,M as $,N as pe,O as jn,R as Bn,S as st,Xa as Xn,b as In,c as Dn,cb as zn,d as Cn,e as Nn,eb as Kn,f as On,fa as Ie,fb as Xi,fc as lt,g as Ln,ga as Hn,h as G,ha as Vn,i as Pn,ia as Hi,j as Mn,k as Fn,l as rt,qc as Gn,rc as Yn,s as Un,w as ji,x as Wn,y as Bi}from"./chunk-PZ2F6J2E.js";import{a as it,h as Vi}from"./chunk-KEUW6YLL.js";import{j as at,r as qi}from"./chunk-N47Y5ADQ.js";import{existsSync as zi,readdirSync as Ki,readFileSync as Gi,statSync as Yi}from"fs";import{resolve as Ji}from"path";function zr(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)??[],d=a.filter(m=>n-m.at<=o),l=a.filter(m=>n-m.at>o&&n-m.at<=o*2),c=d.filter(m=>m.status==="failed").length,p=a.filter(m=>m.status==="paused").length,u=a.length?Math.max(...a.map(m=>m.at)):null,g=a.length?l.length>0&&d.length===0?"dormant":d.length>0&&c*2>=d.length?"failing":d.length>0?"active":"quiet":"never";return{id:i.id,name:i.name||i.id,state:g,lastRunAt:u,recent:d.length,prior:l.length,failed:c,paused:p}}).sort((i,a)=>{let d={dormant:0,failing:1,active:2,quiet:3,never:4};return d[i.state]-d[a.state]||(a.lastRunAt??0)-(i.lastRunAt??0)})}var Pe=new Map;function np(t,e=1e3){if(!zi(t))return[];let n=Ki(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ji(t,s);return{path:i,mtime:Yi(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Pe.keys())r.has(s)||Pe.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Pe.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Qi(s,i);Pe.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Qi(t,e){try{let n=Gi(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]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Kr=7,Zi={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},T={routines:200,summary:160,filters:6,filterValue:60,text:120},ea=(t,e,n)=>{try{return gr(t,e,n)}catch{return null}},Gr=864e5;function ip(t){let e=t.now??Date.now(),n={...Zi,...t.thresholds},r=t.nextFire??ea,o=[];for(let a of t.crons){let d=t.cronRuns.get(a.id)??[],l=a.timezone||"UTC",c=d.map(g=>({at:Date.parse(g.startedAt),status:g.status})),p=d[0],u={id:`cron:${a.id}`,source:"cron",kind:"schedule",name:F(a.id,T.text),trigger:{schedule:F(a.schedule,T.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?kt(a.nextRun)??kt(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:ia(p.status==="success"?void 0:p.errorSummary,T.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Yr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Kr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Jr(u,c,a.schedule,l,null,e,n,r),o.push(Qr(u))}let s=new Map(zr(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 d=i.get(a.workflowId);d?d.push(a):i.set(a.workflowId,[a])}for(let a of t.workflows){let d=a.nodes.find(k=>k.type.startsWith("trigger."));if(!d||d.type!=="trigger.cron"&&d.type!=="trigger.hook")continue;let l=d.config??{},c=a.state||"active",p=c==="active",u=(i.get(a.id)??[]).slice().sort((k,S)=>S.at-k.at),g=u.map(k=>({at:k.at,status:ra(k.status)})),m=g[0],f=d.type==="trigger.cron",w=typeof l.spec=="string"?l.spec:"",x=typeof l.timezone=="string"?l.timezone:"UTC",b={id:`workflow:${a.id}`,source:"workflow",kind:f?"schedule":"event",name:F(a.title||a.id,T.text),trigger:f?{schedule:F(w,T.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",T.text),filters:sa(l.filter,a)},agent:oa(a),enabled:p,state:c,nextRunAt:f&&p&&w?kt(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(S=>S.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Yr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Kr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Jr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):ta(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Qr(b))}return o.sort(na).slice(0,T.routines)}function Yr(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 Jr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=eo(l,o,s,i);return u&&d.push(u),d}if(t.consecutiveFailures>=i.failStreak&&d.push({reason:"failing",detail:`${t.consecutiveFailures} failed attempts in a row`}),l===null)return d.push({reason:"never-ran",detail:"No persisted attempt"}),d;let c=new Date(l),p=null;for(let u=0;u<i.missedFires&&(p=a(n,c,r),!!p);u++)c=p;return p&&s>p.getTime()+i.graceMs&&d.push({reason:"overdue",detail:`No attempt since ${new Date(l).toISOString()}; ${i.missedFires} scheduled fires missed`}),d}function ta(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=eo(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 eo(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Gr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Gr)} days`:"Disabled and never ran"}}function Qr(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 Zr={critical:0,warning:1,info:2};function na(t,e){let n=t.attention?Zr[t.attention]:3,r=e.attention?Zr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function ra(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 oa(t){if(t.ownerAgent)return F(t.ownerAgent,T.text);let e=t.nodes.find(n=>n.type==="agent"&&typeof n.config?.agentId=="string"&&n.config.agentId);return e?F(String(e.config.agentId),T.text):null}function sa(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,T.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(F(`${o}=${i.join(",")}`,T.filterValue))}return n.slice(0,T.filters)}function kt(t){if(!t)return null;let e=t instanceof Date?t:new Date(t);return Number.isFinite(e.getTime())?e.toISOString():null}function F(t,e){return t.length<=e?t:t.slice(0,e-3)+"..."}function ia(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as aa,readFileSync as la,renameSync as ca,writeFileSync as da}from"fs";import{resolve as ua}from"path";function to(t){return ua(dt(t),"_state.json")}function N(t){try{let e=JSON.parse(la(to(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 be(t,e){aa(dt(t),{recursive:!0});let n=to(t),r=`${n}.${process.pid}.tmp`;da(r,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),ca(r,n)}function no(t,e,n,r=Date.now()){let o=N(t),s={};for(let[i,a]of Object.entries(o.snoozed))Date.parse(a)>r&&(s[i]=a);s[e]=n.toISOString(),be(t,{...o,snoozed:s})}function up(t,e){be(t,{...N(t),lastDigest:e})}function vt(t,e,n,r=Date.now()){let o=N(t),s=new Set(n),i={};for(let[d,l]of Object.entries(o.popped??{}))s.has(d)&&(i[d]=l);i[e]=new Date(r).toISOString();let a=(o.wanted??[]).filter(d=>d!==e&&s.has(d));be(t,{...o,popped:i,wanted:a})}function ro(t,e){let n=N(t);be(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function pp(t,e=Date.now()){be(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as pa,readFileSync as ga}from"fs";Jn();Vi();function oo(t){let e=ur(t),n={};if(pa(e))try{n=Gn(JSON.parse(ga(e,"utf-8")))}catch{n={}}let r=lt.safeParse(n?.requests);return r.success?r.data:lt.parse(void 0)}async function yp(t,e={}){let n=(t.channels??[]).filter(r=>!it.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...it].join(", ")}`}:Ne(r=>{let o=r.requests??={};for(let s of["enabled","channels","from","staleAfterHours","retentionDays","settleHandedBack","homeCloses","releaseOnOwnerTurn"])t[s]!==void 0&&(o[s]=t[s]);if(t.plans){let s=o.plans??={};for(let i of["enabled","stallMinutes","maxNudges","approveKinds","disabledAgents","requireForWork","requireOverMinutes"])t.plans[i]!==void 0&&(s[i]=t.plans[i])}if(t.headlines?.enabled!==void 0&&((o.headlines??={}).enabled=t.headlines.enabled),t.catchPromises){let s=o.catchPromises??={};for(let i of["enabled","dailyCap"])t.catchPromises[i]!==void 0&&(s[i]=t.catchPromises[i])}if(t.autoResend){let s=o.autoResend??={};for(let i of["enabled","afterMinutes","holdMaxHours"])t.autoResend[i]!==void 0&&(s[i]=t.autoResend[i])}if(t.flow){let s=o.flow??={};for(let i of["timeZone","days"])t.flow[i]!==void 0&&(s[i]=t.flow[i])}if(t.checkers){let s=o.checkers??={};for(let i of["enabled","checkEveryMinutes"])t.checkers[i]!==void 0&&(s[i]=t.checkers[i])}},{configPath:e.configPath,reload:e.reload})}import{existsSync as V,readdirSync as Da,readFileSync as $t,statSync as Ca}from"fs";import{dirname as So,resolve as R}from"path";import{randomBytes as ao}from"crypto";import{existsSync as fa,mkdirSync as ha,readdirSync as ba,readFileSync as ya,renameSync as lo,unlinkSync as wa,writeFileSync as xa}from"fs";import{resolve as co}from"path";function so(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var ma=t=>t.trim().split(`
|
|
4
|
+
`).pop()?.slice(0,300)||"no output";async function io(t,e,n,r=xt){let o=await r(t.bin,[...so(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${ma(o.stderr||o.stdout)}`}}async function kp(t,e,n,r,o=xt){return(await o(t.bin,[...so(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var ka=2e3,va=t=>io(t.wacli,t.to,t.text);function St(t){return co(t,".agentx","whatsapp-triage","drafts")}var Sa=t=>/^[a-z0-9-]{8,64}$/.test(t),Me=(t,e)=>co(St(t),`${e}.json`);function uo(t,e){ha(St(t),{recursive:!0});let n=Me(t,e.id),r=`${n}.${process.pid}.tmp`;xa(r,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384}),lo(r,n)}function Ap(t,e,n=Date.now()){let r=e.text.trim().slice(0,ka);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${ao(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return uo(t,o),o}function Fe(t,e){if(!Sa(e))return null;try{return JSON.parse(ya(Me(t,e),"utf-8"))}catch{return null}}function po(t,e){let n=St(t);return fa(n)?ba(n).filter(r=>r.endsWith(".json")).map(r=>Fe(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function go(t,e,n,r={}){let o=Fe(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${Me(t,e)}.${process.pid}.${ao(3).toString("hex")}.claim`;try{lo(Me(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??va)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}uo(t,i);try{wa(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as Ea,writeFileSync as $a}from"fs";import{resolve as fo}from"path";var ho="ready",_a="202510";function Aa(t){let e=t.date??t.created_at.slice(0,10);return fo(t.workspace,ho,`${e}-${t.platform}-${t.id}.txt`)}function mo(t){let e=Aa(t);return Ea(fo(t.workspace,ho),{recursive:!0}),$a(e,t.text.endsWith(`
|
|
6
6
|
`)?t.text:`${t.text}
|
|
7
|
-
`),e}function Yr(t,e,n){let r=Nn(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 Qr(t,e,n){return Yr(t,e,n)!==null}async function na(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??ea),"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 ra(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 oa(t,e){let n=Yr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Kr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await na(t.text,n,r):await ra(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Kr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function Zr(t){return e=>oa(e,t)}wi();xi();var oo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],aa=280;function N(t,e=aa){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function te(t){if(t.configPath)return _(t.configPath);let e=[_(t.root,"agentx.json"),_(t.root,".agentx","config.json")];return e.find(n=>V(n))??e[0]}function q(t){return t.wikiDir?_(t.wikiDir):_(t.root,".agentx","wiki")}function la(t){return Z(t.root,"pending").map(ca)}function ca(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:N([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function da(t){let e=te(t);if(!V(e))return[];let n;try{n=JSON.parse(wt(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 d=i.timezone||"UTC",l=i.schedule?er(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:N(`${p}${u&&i.schedule?` \xB7 first run ${nr(tr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function so(t){let e=_(t,".agentx","memory");return V(e)?sa(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ua(t){let e=so(t.root);if(e.length===0)return[];let n=new it(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:N(s.content),more:`agentx memory facts held --agent ${o}`});return r}function pa(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 ga(t){return yr(q(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:N(`${pa(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var eo=new Map;function io(t,e){let n=ia(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=eo.get(t);if(o?.version===r)return o.value;let s=e();return eo.set(t,{version:r,value:s}),s}function fa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${N(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:N(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function ma(t,e){let n=q(t);if(!V(_(n,"_facts.json")))return;let r=Ie(new ee(n),"pending").find(o=>o.id===e);return r?fa(r):void 0}function ha(t){let e=_(q(t),"_facts.json");if(!V(e))return;let n=io(e,()=>Ie(new ee(ro(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function ba(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function ao(t){let e=q(t),n=new st(e);if(!V(n.path))return[];let r=io(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:ba(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function ya(t){return zr(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:N(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function wa(t){return $r(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:N(`Last try not sent: ${e.error}`)}:{}}))}function xa(t){let e=Object.entries(at(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Ne(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:N(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Ne(t){try{return JSON.parse(wt(te(t),"utf-8"))}catch{return{}}}function yt(t){let e={};try{e=Object.fromEntries(On(wt(_(ro(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function ka(t){let e=ar(t.root,"pending");if(e.length===0)return[];let n=Ne(t),r=yt(t);return e.map(o=>{let s=pe[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:Qr({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:N(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:sr(o.text)}})}function G(t){if(t.requests)return t.requests;if(_(t.root)!==process.cwd()||!V(_(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=to.get(e);return!n&&!Rn(e)?null:(n||to.set(e,n=new Tn(e)),n)}var to=new WeakMap;function _p(t){if(t.plans)return t.plans;if(t.requests||_(t.root)!==process.cwd()||!V(_(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!mr(e))return null;let n=no.get(e);return n||no.set(e,n=new hr(e)),n}var no=new WeakMap;function va(t){let e=G(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:K(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:N(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var lo={card:la,schedule:da,agent:xa,memory:ua,wiki:ga,fact:()=>[],question:ao,whatsapp:ya,email:wa,content:ka,request:va};function Sa(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 co(t,e={}){let n=t.now??Date.now(),{snoozed:r}=O(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??oo){if(d==="fact"){try{let c=ha(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=lo[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Sa),{items:o,snoozed:a,errors:s,backlog:i}}function uo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!oo.includes(n)||!r?null:{kind:n,ref:r}}function $a(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return br(q(t),n)?.status==="pending";case"whatsapp":return Oe(t.root,n)?.status==="pending";case"email":return Sr(t.root,n)?.status==="pending";case"content":return ir(t.root,n)?.status==="pending";default:return!!po(t,e,n)}}function po(t,e,n){return e==="fact"?ma(t,n):lo[e](t).find(r=>r.key===`${e}:${n}`)}async function go(t,e,n,r={}){let o=n==="later"?null:uo(e),s;if(o)try{s=po(t,o.kind,o.ref)}catch{s=void 0}let i=await Ea(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Ln(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:i.verdict??n,...a?{choice:a}:{},...r.text&&i.verdict!=="no"?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ea(t,e,n,r){let o=uo(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(),d=r.by??"operator";if(n==="later"){if(!$a(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return Mr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Bn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});if(!c.ok)return c;let p=c.card.verdict??(l?"yes":"no"),u=l&&p==="no"?", an option that means no":"";return{ok:!0,verdict:p,message:`${e}: ${c.card.raised_by} will be told ${p}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""}${u})`:""}`}}case"schedule":{let c=await(l?rr:or)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(at(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return lt(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 c=[],p=await Re(u=>{Xn(u,`agents.${i}`);for(let[g,f]of Object.entries(u.crons??{}))f?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(lt(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!so(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new it(t.root);return g.held(p).some(f=>f.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=q(t),p=l?wr(c,i,{by:d,force:r.force,now:a}):xr(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Aa(t,e,i,l,d,r);case"question":return Ra(t,e,i,l,d,r);case"whatsapp":{let c=await Xr(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??Ar(Ne(t),yt(t)),p=await Er(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??Zr({config:Ne(t),env:yt(t)}),p=await lr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Wr(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.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."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?_n:d),{ok:!0,message:`${e}: dropped`})}}}function Aa(t,e,n,r,o,s){let i=new ee(q(t));try{let a=Ie(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Yn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Jn(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function _a(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function Ra(t,e,n,r,o,s){let i=q(t),a=new st(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Hn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=ao(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=_a(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,f)=>`${f+1}. ${g}`).join(", ")}`};let p=new ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var Ta=3,Ia=7,Da=50,kt=120,Ca=280,xt=600,mo=36e5,Oa=24*mo;function Ip(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 ne(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var Le=t=>new Date(t).toISOString();function Na(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:ne(e.title,kt),...e.ask?{ask:ne(e.ask,xt)}:{},...e.detail?{facts:ne(e.detail,Ca)}:{},...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 La={done:"Done",declined:"Declined",dropped:"Dropped"};function ho(t,e,n){let{record:r,links:o}=e,s=K(r,kt),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:ne(s.said,xt)}:{},agent:r.agentId,askedAt:Le(r.createdAt),changedAt:Le(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:ne(r.question,xt)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??Ta)*mo;return{...i,column:a||d?"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:Le(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:La[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Pa(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 Ma(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,kt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Pa(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,fo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function vt(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(Na(o,s,o.node===t.node))}let r=bo(t,e);for(let o of t.requests??[]){let s=ho(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function bo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Dp(t){let e=vt(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=bo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=ho(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Ia)*Oa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(Ma(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,Da),c=fo(n,"askedAt"),p=fo(i,"changedAt");return{ts:Le(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function Fa(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 Wa(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 Lp(t,e){let n=t.now??Date.now(),r=[],o=co(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=G(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=vt({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Fa)}],requests:a,deferred:i});return Wa(d,i.size,[...r,...l])}import{readFileSync as Ua}from"fs";var ja=1e4,yo=/^[0-9a-f]{7,64}$/i;function Fp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&yo.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(ja)})}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"&&yo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Wp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Ua(n.tokenFile,"utf-8").trim().split(`
|
|
8
|
-
`)[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
|
|
7
|
+
`),e}function bo(t,e,n){let r=Zn(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 yo(t,e,n){return bo(t,e,n)!==null}async function Ra(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??_a),"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 Ta(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 Ia(t,e){let n=bo(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:mo(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await Ra(t.text,n,r):await Ta(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=mo(t);return{ok:!1,error:`not posted on ${he[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function wo(t){return e=>Ia(e,t)}qi();Xi();var Eo=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],Na=280;function O(t,e=Na){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function re(t){if(t.configPath)return R(t.configPath);let e=[R(t.root,"agentx.json"),R(t.root,".agentx","config.json")];return e.find(n=>V(n))??e[0]}function q(t){return t.wikiDir?R(t.wikiDir):R(t.root,".agentx","wiki")}function Oa(t){return te(t.root,"pending").map(La)}function La(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:O([t.context,t.draft?`Suggested message: ${t.draft}`:""].filter(Boolean).join(" \xB7 "))}:{}}}function Pa(t){let e=re(t);if(!V(e))return[];let n;try{n=JSON.parse($t(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 d=i.timezone||"UTC",l=i.schedule?wr(i.schedule):"",c=i.schedule?`${l.charAt(0).toLowerCase()}${l.slice(1)} (${i.schedule})`:"no schedule",p=String(i.prompt??i.command??""),u=a.action==="create";o.push({key:`schedule:${s}`,kind:"schedule",title:u?`New schedule "${s}" for ${i.agent??"an agent"}`:`Delete schedule "${s}"`,ask:u?`Let ${i.agent??"the agent"} run this ${c}?`:`Remove the schedule "${s}" (${c})?`,yes:u?"enable it":"remove it",no:u?"drop the request":"keep the schedule",raised_by:String(a.requestedBy??"unknown"),created_at:String(a.requestedAt??""),detail:O(`${p}${u&&i.schedule?` \xB7 first run ${kr(xr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function $o(t){let e=R(t,".agentx","memory");return V(e)?Da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function Ma(t){let e=$o(t.root);if(e.length===0)return[];let n=new pt(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:O(s.content),more:`agentx memory facts held --agent ${o}`});return r}function Fa(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 Ua(t){return Mr(q(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:O(`${Fa(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var xo=new Map;function _o(t,e){let n=Ca(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=xo.get(t);if(o?.version===r)return o.value;let s=e();return xo.set(t,{version:r,value:s}),s}function Wa(t){let e=t.subject&&t.attribute&&t.value;return{key:`fact:${t.id}`,kind:"fact",title:e?`${t.subject} \xB7 ${t.attribute}: ${t.value}`:`Claim from ${t.agentId}'s summary`,ask:`Is this true? Check it at its source first. "${O(t.claim,200)}"`,yes:e?"record it as a fact you confirmed":"nothing until you give the subject, attribute and value in the terminal",no:"drop the claim",raised_by:t.agentId,created_at:t.createdAt,detail:O(`From ${t.origin}. Source: ${t.source}.${e?"":" AgentX could not read a subject, attribute and value from it."}`),more:"agentx wiki facts proposals list"}}function ja(t,e){let n=q(t);if(!V(R(n,"_facts.json")))return;let r=Le(new ne(n),"pending").find(o=>o.id===e);return r?Wa(r):void 0}function Ba(t){let e=R(q(t),"_facts.json");if(!V(e))return;let n=_o(e,()=>Le(new ne(So(e)),"pending").map(a=>Date.parse(a.createdAt)||0));if(n.length===0)return;let r=t.now??Date.now(),o=n.filter(a=>r-a<864e5).length,s=Math.max(...n),i=n.length.toLocaleString("en-US");return{kind:"fact",count:n.length,new_today:o,...s?{newest:new Date(s).toISOString()}:{},title:`${i} wiki claim${n.length===1?"":"s"} wait for a check${o?` (${o} new today)`:""}`,more:"agentx wiki facts proposals list"}}function Ha(t){return t.kind==="contradiction"?`${t.subject}: two values disagree`:t.kind==="article"?`No article yet for ${t.subject}`:`${t.subject}: ${t.field??"a field"} is missing`}function Ao(t){let e=q(t),n=new ut(e);if(!V(n.path))return[];let r=_o(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ne(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Ha(s),ask:s.question,yes:i?"record the value you pick, confirmed by you":`answer it in the terminal: agentx wiki answer ${s.id} "<value>"`,no:"dismiss it; the wiki keeps its value",raised_by:s.agentId,created_at:s.asked,...i?{choices:i}:{},more:"agentx wiki questions"}})}function Va(t){return po(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:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function qa(t){return Hr(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:O(`Last try not sent: ${e.error}`)}:{}}))}function Xa(t){let e=Object.entries(gt(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Ue(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:O(`Workspace: ${s.workspace||"?"}. Instructions: ${s.systemPrompt||"(none)"}`),more:"agentx agent list"}})}function Ue(t){try{return JSON.parse($t(re(t),"utf-8"))}catch{return{}}}function Et(t){let e={};try{e=Object.fromEntries(Qn($t(R(So(re(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function za(t){let e=_r(t.root,"pending");if(e.length===0)return[];let n=Ue(t),r=Et(t);return e.map(o=>{let s=he[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:yo({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:O(`Follows your past posts: ${o.samples.join(", ")}`),more:`agentx content show ${o.id}`,text_hash:Er(o.text)}})}function J(t){if(t.requests)return t.requests;if(R(t.root)!==process.cwd()||!V(R(t.root,".agentx","db.sqlite")))return null;let e=at({quiet:!0});if(!e)return null;let n=ko.get(e);return!n&&!zn(e)?null:(n||ko.set(e,n=new Kn(e)),n)}var ko=new WeakMap;function ig(t){if(t.plans)return t.plans;if(t.requests||R(t.root)!==process.cwd()||!V(R(t.root,".agentx","db.sqlite")))return null;let e=at({quiet:!0});if(!e||!Or(e))return null;let n=vo.get(e);return n||vo.set(e,n=new Lr(e)),n}var vo=new WeakMap;function Ka(t){let e=J(t);return e?e.listByState("needs_attention").map(n=>({key:`request:${n.id}`,kind:"request",title:Y(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:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var Ro={card:Oa,schedule:Pa,agent:Xa,memory:Ma,wiki:Ua,fact:()=>[],question:Ao,whatsapp:Va,email:qa,content:za,request:Ka};function Ga(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 To(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??Eo){if(d==="fact"){try{let c=Ba(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=Ro[d](t)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)});continue}for(let c of l){let p=r[c.key];if(p&&Date.parse(p)>n){if(!e.includeSnoozed){a++;continue}c.snoozed_until=p}o.push(c)}}return o.sort(Ga),{items:o,snoozed:a,errors:s,backlog:i}}function Io(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!Eo.includes(n)||!r?null:{kind:n,ref:r}}function Ya(t,e,n){switch(e){case"card":return ge(t.root,n)?.status==="pending";case"wiki":return Pr(q(t),n)?.status==="pending";case"whatsapp":return Fe(t.root,n)?.status==="pending";case"email":return Br(t.root,n)?.status==="pending";case"content":return $r(t.root,n)?.status==="pending";default:return!!Do(t,e,n)}}function Do(t,e,n){return e==="fact"?ja(t,n):Ro[e](t).find(r=>r.key===`${e}:${n}`)}async function Co(t,e,n,r={}){let o=n==="later"?null:Io(e),s;if(o)try{s=Do(t,o.kind,o.ref)}catch{s=void 0}let i=await Ja(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;er(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:i.verdict??n,...a?{choice:a}:{},...r.text&&i.verdict!=="no"?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ja(t,e,n,r){let o=Io(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(),d=r.by??"operator";if(n==="later"){if(!Ya(t,s,i))return{ok:!1,error:`nothing waiting for "${e}"`};let c=r.laterHours&&r.laterHours>0?r.laterHours:24,p=new Date(a+c*36e5);return no(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=ar(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});if(!c.ok)return c;let p=c.card.verdict??(l?"yes":"no"),u=l&&p==="no"?", an option that means no":"";return{ok:!0,verdict:p,message:`${e}: ${c.card.raised_by} will be told ${p}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""}${u})`:""}`}}case"schedule":{let c=await(l?vr:Sr)(i,{configPath:re(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(gt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return mt(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 c=[],p=await Ne(u=>{pr(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:re(t),reload:t.reload});return p.success?(mt(t.root,i),{ok:!0,message:`${e}: removed from agentx.json${c.length?`, with its schedules ${c.join(", ")}`:""}; its folder is kept`}):{ok:!1,error:p.error||"could not remove it from agentx.json"}}case"memory":{let c=i.indexOf("/");if(c<=0)return{ok:!1,error:"memory keys look like memory:<agent>/<fact-id>"};let p=i.slice(0,c),u=i.slice(c+1);if(!$o(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new pt(t.root);return g.held(p).some(m=>m.id===u)?(g.review(p,u,l?"approved":"rejected",d),{ok:!0,message:`${e} ${l?"approved: the agent may use it":"rejected: it stays out of prompts"}`}):{ok:!1,error:`fact "${u}" isn't waiting for review`}}case"wiki":{let c=q(t),p=l?Fr(c,i,{by:d,force:r.force,now:a}):Ur(c,i,{by:d,reason:r.note,now:a});return p.ok?{ok:!0,message:l?`${p.proposal.article.path} written to the shared wiki`:`${e} rejected`}:p}case"fact":return Qa(t,e,i,l,d,r);case"question":return el(t,e,i,l,d,r);case"whatsapp":{let c=await go(t.root,i,l?"yes":"no",{by:d,now:a,send:t.sendWhatsApp});return c.ok?{ok:!0,message:l?`${e}: sent to ${c.draft.chat_name||c.draft.to}`:`${e}: dropped, nothing sent`}:c}case"email":{let c=t.sendEmail??qr(Ue(t),Et(t)),p=await Vr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,send:c});return p.ok?{ok:!0,message:l?`${e}: sent to ${p.draft.to}${p.draft.edited?" (as you edited it)":""}`:`${e}: dropped, nothing sent`}:p}case"content":{let c=t.publishContent??wo({config:Ue(t),env:Et(t)}),p=await Ar(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=he[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=J(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?oo(re(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.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."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?Xn:d),{ok:!0,message:`${e}: dropped`})}}}function Qa(t,e,n,r,o,s){let i=new ne(q(t));try{let a=Le(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return hr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=fr(i,a.id,o);return{ok:!0,message:`${e}: ${d.write.fact.subject} \xB7 ${d.write.fact.attribute} recorded as "${d.write.fact.value}"`}}catch(a){return{ok:!1,error:String(a?.message??a)}}}function Za(t,e){if(e===void 0||e==="")return;let n=typeof e=="number"?e:/^\d+$/.test(String(e).trim())?Number(e):NaN;if(Number.isInteger(n))return t[n-1];let r=String(e).trim().toLowerCase();return t.find(o=>o.toLowerCase()===r)}function el(t,e,n,r,o,s){let i=q(t),a=new ut(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(lr(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=Ao(t).find(g=>g.key===e);if(!l?.choices)return{ok:!1,error:`answer it in the terminal: agentx wiki answer ${d.id} "<value>"`};let c=Za(l.choices,s.choice);if(!c)return{ok:!1,error:`pick one of: ${l.choices.map((g,m)=>`${m+1}. ${g}`).join(", ")}`};let p=new ne(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var tl=3,nl=7,rl=50,At=120,ol=280,_t=600,Oo=36e5,sl=24*Oo;function cg(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 oe(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}var We=t=>new Date(t).toISOString();function il(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:oe(e.title,At),...e.ask?{ask:oe(e.ask,_t)}:{},...e.detail?{facts:oe(e.detail,ol)}:{},...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 al={done:"Done",declined:"Declined",dropped:"Dropped"};function Lo(t,e,n){let{record:r,links:o}=e,s=Y(r,At),i={key:`request:${r.id}`,kind:"request",node:t.node,nodeName:t.nodeName,title:s.headline,need:s.need,...r.headline?{said:oe(s.said,_t)}:{},agent:r.agentId,askedAt:We(r.createdAt),changedAt:We(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:oe(r.question,_t)}:{},can:{answer:!1,later:!1,reply:!0}};case"in_progress":case"waiting_other":{let a=o.some(l=>l.kind==="run"&&!!t.liveRuns?.has(l.ref)),d=t.now-r.updatedAt<(t.quietHours??tl)*Oo;return{...i,column:a||d?"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:We(r.closedAt??r.stateChangedAt??r.updatedAt),outcome:al[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ll(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 cl(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:oe(e.title,At),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ll(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,No=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(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(il(o,s,o.node===t.node))}let r=Po(t,e);for(let o of t.requests??[]){let s=Lo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function Po(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function dg(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=Po(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=Lo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??nl)*sl;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(cl(t,u));s.sort((u,g)=>L(g.changedAt)-L(u.changedAt)),i.sort((u,g)=>L(u.changedAt)-L(g.changedAt)),a.sort((u,g)=>L(g.changedAt)-L(u.changedAt));let l=a.filter(u=>L(u.changedAt)>=d).slice(0,rl),c=No(n,"askedAt"),p=No(i,"changedAt");return{ts:We(t.now),cards:[...n,...s,...i,...l],figures:{yours:{count:n.length,...c?{oldest:c}:{},...t.owner?.later?{later:t.owner.later}:{}},agent:{count:s.length},quiet:{count:i.length,...p?{oldest:p}:{}},done:{count:l.length}},errors:r}}function dl(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 ul(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 mg(t,e){let n=t.now??Date.now(),r=[],o=To(t,{includeSnoozed:!0});for(let c of o.errors)r.push(`What waits (${c.kind}) could not be read: ${c.error}`);let s=o.items.filter(c=>!c.snoozed_until),i=new Set(o.items.filter(c=>c.snoozed_until).map(c=>c.key)),a=null;try{let c=J(t);c&&(a=c.listByState("waiting_owner").map(p=>({record:p,links:c.links(p.id)})))}catch(c){r.push(`Requests could not be read: ${c?.message??c}`)}let{cards:d,errors:l}=Rt({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(dl)}],requests:a,deferred:i});return ul(d,i.size,[...r,...l])}import{readFileSync as pl}from"fs";var gl=1e4,Mo=/^[0-9a-f]{7,64}$/i;function bg(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&Mo.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(gl)})}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"&&Mo.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function yg(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=pl(n.tokenFile,"utf-8").trim().split(`
|
|
8
|
+
`)[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 je=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function xg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||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"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"||t==="/lookup"}function kg(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 vg(t){return je.has(t)}function Sg(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(je.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 Eg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&je.has(t.remoteAddress)}function $g(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:je.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function _g(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 Ag(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 ml(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function fl(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function Tg(t,e=fl()){let n=Be(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=ml(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 Ig(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var Tt="/api/admin/pictures",hl=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,bl=/^\/api\/admin\/pictures\/(agent|person)\/([^/]+)$/;function _(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}function yl(t){let e={agent:{},person:{}};for(let n of Rr)for(let[r,o]of Object.entries(Dr(t,n)))e[n][r]=Cr(n,r,o);return e}function Ng(t,e,n,r,o){let s=n.match(hl);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=Nr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":Tr,"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):(_(e,404,{error:"no such picture"}),!0)}async function Og(t,e,n,r){if(n!==Tt&&!n.startsWith(`${Tt}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===Tt)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...yl(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(bl);if(!s)return _(e,404,{error:"not found"}),!0;if(o!=="PUT"&&o!=="DELETE")return _(e,405,{error:"PUT or DELETE only"}),!0;let i=t.headers["x-requested-with"];if(i!=="agentx-board"&&i!=="agentx-admin")return _(e,400,{error:"missing X-Requested-With: agentx-board"}),!0;let a=s[1],d=decodeURIComponent(s[2]),l=a==="agent"?r.agentIds():r.personIds();if(!Ir.test(d)||!l.includes(d))return _(e,404,{error:a==="agent"?`no agent "${d}" in agentx.json`:`no person "${d}" in agentx.json`}),!0;if(o==="DELETE"){let c=yt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await wt(t),p=await bt(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof ht)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function Lg(t,e,n,r){let o=(t.method||"GET").toUpperCase();if(o!=="PUT"&&o!=="DELETE"){_(e,405,{error:"PUT or DELETE only"});return}let s=n.searchParams.get("agent")?.trim()||void 0,i=r.provenAgent(s);if(!i){_(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){_(e,403,{error:`An agent can only change its own picture: this run is "${i}", not "${s}".`});return}if(o==="DELETE"){_(e,200,{ok:!0,agent:i,removed:yt(r.root,"agent",i)});return}try{let a=await bt(r.root,"agent",i,await wt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof ht){_(e,a.status,{error:a.message});return}throw a}}var Fo={};function Fg(t){Fo=t}function Ug(){return Fo}var Wg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
9
9
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
10
10
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
11
11
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
12
12
|
<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">
|
|
13
|
-
<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>`,
|
|
13
|
+
<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>`,jg=`
|
|
14
14
|
.ax-topbar{display:flex;align-items:center;justify-content:space-between;
|
|
15
15
|
padding:8px 18px;border-bottom:1px solid var(--ax-border);
|
|
16
16
|
background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
|
|
@@ -91,7 +91,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./ch
|
|
|
91
91
|
background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
|
|
92
92
|
flex-wrap:wrap}
|
|
93
93
|
.ax-subheader > * {flex-shrink:0}
|
|
94
|
-
.ax-subheader .spacer{flex:1}`,
|
|
94
|
+
.ax-subheader .spacer{flex:1}`,Bg=`<script>
|
|
95
95
|
(function(){
|
|
96
96
|
function wireTheme(){
|
|
97
97
|
var sw = document.querySelectorAll('[data-theme-opt]');
|
|
@@ -286,16 +286,16 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./ch
|
|
|
286
286
|
document.addEventListener('DOMContentLoaded', wire);
|
|
287
287
|
} else { wire(); }
|
|
288
288
|
})();
|
|
289
|
-
</script>`;function
|
|
289
|
+
</script>`;function Hg(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 wl='<span class="ax-build" hidden></span>';function Vg(t){let e=t.peers&&t.peers.length>0?t.peers:[{id:"local",name:"this daemon",dashboardUrl:"",primary:!0}],n=t.currentPeerId||e.find(l=>l.primary)?.id||e[0].id,r=e.find(l=>l.id===n)||e[0],o=e.map(l=>{let c=l.id===n,p=l.primary?' <span style="color:var(--ax-muted);font-size:10px">\xB7 primary</span>':"",u=!!l.tokenScope&&!l.primary,g=u?"#":l.dashboardUrl?`${l.dashboardUrl.replace(/\/+$/,"")}/admin`:"#",m=u?` data-peer-id="${j(l.id)}" data-peer-action="proxy"`:l.primary?' data-peer-id="primary" data-peer-action="proxy"':"",f=u?'<div class="url" style="color:var(--ax-accent)">manage from this dashboard \u2713</div>':l.tokenScope?`<div class="url">${j(l.tokenScope)}</div>`:l.dashboardUrl?'<div class="url" style="color:var(--ax-muted)">(open peer dashboard \u2197)</div>':"";return`<a href="${j(g)}" class="${c?"is-current":""}"${m}>
|
|
290
290
|
<div class="row"><span class="dot"></span><span>${j(l.name)}${p}</span></div>
|
|
291
291
|
${l.dashboardUrl?`<div class="url">${j(l.dashboardUrl)}</div>`:""}
|
|
292
|
-
${
|
|
292
|
+
${f}
|
|
293
293
|
</a>`}).join(""),s=`<div class="ax-mesh-sel" aria-haspopup="menu">
|
|
294
294
|
<span class="lbl">managing</span>
|
|
295
295
|
<span class="name">${j(r.name)}</span>
|
|
296
296
|
<span class="chev">\u25BE</span>
|
|
297
297
|
<div class="ax-mesh-menu" role="menu">${o}</div>
|
|
298
|
-
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:
|
|
298
|
+
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:Ce,href:me},{id:"live",label:"Live",href:`${me}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:dr},{id:"people",label:"People",href:`${me}#page=people`},{id:"org",label:"Org",href:"/org"},{id:"activity",label:"Activity",href:"/activity"},{id:"workflows",label:"Workflows",href:"/workflows"},{id:"admin",label:"Settings",href:`${me}#page=settings`}]}].map(l=>{let c=l.tabs.map(p=>{let u=p.id===t.activeTab?"ax-topbar__tab is-active":"ax-topbar__tab",g=p.external?' target="_blank" rel="noopener"':"",m=p.external?' <span style="font-size:9px;opacity:0.6">\u2197</span>':"";return`<a href="${p.href}" class="${u}"${g}>${p.label}${m}</a>`}).join("");return`<div class="ax-topbar__group" title="${j(l.name)} tier"><span class="ax-topbar__group-label">${j(l.name)}</span>${c}</div>`}).join("");return`<header class="ax-topbar">
|
|
299
299
|
<div class="ax-topbar__left">
|
|
300
300
|
<div class="ax-brand">
|
|
301
301
|
<span class="ax-brand__mark">AX</span>
|
|
@@ -306,14 +306,14 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as kr,O as _r,k as K}from"./ch
|
|
|
306
306
|
</div>
|
|
307
307
|
<div class="ax-topbar__right">
|
|
308
308
|
${t.rightExtras||""}
|
|
309
|
-
${
|
|
309
|
+
${wl}
|
|
310
310
|
${s}
|
|
311
311
|
<div class="ax-theme-switch" role="tablist" aria-label="Theme">
|
|
312
312
|
<button data-theme-opt="dark">Dark</button>
|
|
313
313
|
<button data-theme-opt="light">Light</button>
|
|
314
314
|
</div>
|
|
315
315
|
</div>
|
|
316
|
-
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as
|
|
316
|
+
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as cs,mkdirSync as Kl,readFileSync as Gl,renameSync as Yl,writeFileSync as Jl}from"fs";import{homedir as Ql}from"os";import{dirname as Zl,join as ec}from"path";import{execFile as Il,execFileSync as Dl}from"child_process";import{execFileSync as xl}from"child_process";import{existsSync as Wo,mkdirSync as kl,readdirSync as vl,readFileSync as jo,renameSync as Sl,writeFileSync as El}from"fs";import{homedir as Bo}from"os";import{join as Dt}from"path";var P="siri:",Ho="com.apple.ttsbundle.gryphon-neural_",Vo=t=>!!t&&t.startsWith(Ho),$l=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],_l=()=>{try{return xl("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},It;function Ct(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=Wo,prefDomain:o=_l}=t,s=n==="darwin"&&$l.every(i=>r(i))&&o();return e||(It=s),s}var qo=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Xo={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"},Nt=t=>Xo[t.toLowerCase()]??null;function He(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 Al=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function Rl(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(Al)){let i=`${r}-${o}`,a=`${Ho}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Xo[s]??null,siri:!0})}return[...e.values()]}function Ve(t=qo,e={}){if(!Ct(e))return[];let n=[];for(let r of t){let o;try{o=vl(r)}catch{continue}for(let s of o)try{n.push(jo(Dt(r,s,"Info.plist"),"latin1"))}catch{}}return Rl(n)}var Uo=`#!/bin/sh
|
|
317
317
|
# Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
|
|
318
318
|
# siri-say.sh [voice] < text speak one line. A Siri voice id switches
|
|
319
319
|
# the OS default for it; any other id is
|
|
@@ -325,7 +325,7 @@ D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
|
|
|
325
325
|
dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
|
|
326
326
|
stops="$dir/stop"
|
|
327
327
|
read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
|
|
328
|
-
assets=\${AGENTX_SIRI_ASSET_DIRS:-"${
|
|
328
|
+
assets=\${AGENTX_SIRI_ASSET_DIRS:-"${qo.join(" ")}"}
|
|
329
329
|
if [ "$1" = --stop ]; then
|
|
330
330
|
mkdir -p "$dir" || exit 1
|
|
331
331
|
# Queued lines see this change and drop. The owner's trap stops say,
|
|
@@ -418,20 +418,20 @@ wait "$say_pid"
|
|
|
418
418
|
status=$?
|
|
419
419
|
say_pid=
|
|
420
420
|
finish $status
|
|
421
|
-
`,
|
|
421
|
+
`,Tl=(t=Bo())=>Dt(t,".agentx","voice","siri-say.sh");function zo(t=Bo()){let e=Tl(t);return Wo(e)&&jo(e,"utf8")===Uo||(kl(Dt(t,".agentx","voice"),{recursive:!0}),El(`${e}.tmp`,Uo,{mode:493}),Sl(`${e}.tmp`,e)),e}var Ko=`ObjC.import("AVFoundation")
|
|
422
422
|
const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
|
|
423
423
|
for (let i = 0; i < vs.count; i++) {
|
|
424
424
|
const v = vs.objectAtIndex(i)
|
|
425
425
|
out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
|
|
426
426
|
}
|
|
427
|
-
out.join("\\n")`,
|
|
428
|
-
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!
|
|
429
|
-
`)[0]}`),
|
|
430
|
-
`),
|
|
431
|
-
${
|
|
427
|
+
out.join("\\n")`,Cl=new Set(["Fred","Kathy","Ralph","Junior"]),Nl={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 Go(t){let e=[];for(let n of t.split(`
|
|
428
|
+
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!Cl.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":Nl[o]??null})}return e}var Ol=10*60*1e3,Zg=60*1e3,se=null,Ot=!1;function Lt(t=Date.now(),e=Ol){if(process.platform!=="darwin")return[];if(se)t-se.at>e&&!Ot&&(Ot=!0,Il("osascript",["-l","JavaScript","-e",Ko],{timeout:1e4},(n,r)=>{Ot=!1,n||(se={at:Date.now(),voices:[...Go(String(r)),...Ve()]})}));else try{se={at:t,voices:[...Go(Dl("osascript",["-l","JavaScript","-e",Ko],{encoding:"utf8",timeout:1e4})),...Ve()]}}catch(n){Pt(`[voice] could not list system voices: ${String(n?.message??n).split(`
|
|
429
|
+
`)[0]}`),se={at:t,voices:Ve()}}return se.voices}var Pt=t=>process.stderr.write(t+`
|
|
430
|
+
`),qe=new Set;function em(t){Pt=t}function Q(t,e){qe.has(t)||(qe.add(t),Pt(e))}function Qo(t){for(let e of qe)t(e)&&qe.delete(e)}var Zo=()=>{};function tm(t){Zo=t}function es(t){try{Zo(t)}catch(e){Q("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var Ll={premium:3,enhanced:2,standard:1},Pl=new Set(["Grandma","Grandpa"]);function Yo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!Pl.has(t.name)?1:0;return Ll[t.quality]*10+e}var ie=t=>t.toLowerCase().split(/[-_]/)[0],Jo=t=>t.id.startsWith("com.apple.voice.");function Mt(t,e,n,r=new Set){let o=ye(t.filter(a=>!a.siri&&ie(a.locale)===ie(e)),e);if(o.some(Jo)&&(o=o.filter(Jo)),n==="female"||n==="male"){let a=o.filter(d=>d.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 ye(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=ie(e),o=t.filter(s=>ie(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Yo(i)-Yo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function we(t,e,n="en"){let r=t.trim();if(!r)return null;let o=e.find(l=>l.id===r);if(o)return o;if(r.toLowerCase().startsWith(P)){let l=r.slice(P.length).trim().toLowerCase(),c=ye(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=we(l,e.filter(u=>ie(u.locale)===ie(n)),n);return p&&Q(`siri:${l}`,`[voice] Siri voice "${l}" is not installed; speaking with ${p.name} (${p.locale}) instead.`),p}e=e.filter(l=>!l.siri);let s=/^(.+?)\s*\((premium|enhanced)\)$/i.exec(r),i=(s?s[1]:r.replace(/\s*\(.*\)\s*$/,"")).trim().toLowerCase(),a=ye(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function ts(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",d=a?i.gender:s,l=e.filter(p=>!o.has(p.name.toLowerCase())),c=l.find(p=>p.gender===d)??(a?e.find(p=>p.gender===d):void 0)??l[0]??e[r.size%e.length];r.set(i.id,c),o.add(c.name.toLowerCase()),a||(s=s==="female"?"male":"female")}return r}Hn();var Ft="system",Ml=t=>t.trim().toLowerCase()===Ft,Fl="21m00Tcm4TlvDq8ikWAM";function Ut(t,e,n={},r=Lt()){let o=e[t],s=o?.name||t,i=o?.voice,a=jt(e,n,r).get(t)??null,d=Bl(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?ze(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Vl(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var ze=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function Ul(t,e,n,r){if(!e||!n.length)return null;let o=we(e,n,r);return o||(Q(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),es(e)),o}function ss(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:Nt(n.slice(P.length).trim())};let r=He(n);return r?{locale:r.locale,gender:Nt(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var is=t=>t.toLowerCase().split(/[-_]/)[0],ns=(t,e)=>typeof t=="string"?t:t?.[is(e)];function Xe(t,e,n,r){if(e!==void 0)return Ml(e)?null:Ul(t,e,n,r)??void 0}var Wt=(t,e)=>!t||!t.gender||t.gender==="neutral"||!e||e==="neutral"||t.gender===e;function Wl(t,e,n,r=new Set){let o=e.locale??"en",s=new Map,i=[],a=Xe("voice.system",ns(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=ns(c.system,o),u=Xe(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?jl(c,p,o,a,n,d()):a!==void 0&&Wt(a,c.gender)?a:void 0;g!==void 0?s.set(c.id,g):i.push({id:c.id,gender:c.gender??null})}let l=d();for(let[c,p]of ts(i,ye(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function jl(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=Xe(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Wt(r,t.gender))return r;let i=ss(e,n);return Mt(o,i.locale,t.gender??i.gender,s)??void 0}function Bl(t,e,n,r,o){if(typeof e=="string")return{};let s={},i=(a,d,l)=>{if(!(!d||typeof d=="string"))for(let[c,p]of Object.entries(d)){let u=Xe(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Mt(o,c,n??ss(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[is(c)]=u)}};return i("voice.system",r.system,a=>Wt(a,n)),i(t,e,()=>!0),s}function im(t,e){let n=e?Ie(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?ze(r):null}}function jt(t,e={},n=Lt()){let r=Object.entries(t).map(([o,s])=>({id:o,system:s.voice?.system,gender:s.voice?.gender,fallbacks:s.voice?.fallbacks}));return Wl(r,e,n)}function Bt(t,e){let n={provider:t.provider,elevenlabs:Hl(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 Hl(t,e){return t||e||process.env.AGENTX_VOICE_ID||Fl}function Vl(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 ql=8*60*60*1e3,Xl=500,rs=class{constructor(e=ql){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(os(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=os(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>Xl&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},os=(t,e)=>`${t}\0${e}`;function as(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 am(t,e,n,r={}){let o=e[t],s=Ut(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:as(s,n)}}var zl="[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 lm(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`${zl}
|
|
431
|
+
${as(o,e.voice.introduce===!0&&!!r)}`}var tc="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",ds=(t=Ql())=>ec(t,".agentx","voice","health.json");function nc(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Ft)return!0;if(r.toLowerCase().startsWith(P)){let o=r.slice(P.length).trim().toLowerCase();return e.some(s=>s.siri&&s.name.toLowerCase()===o)}return we(r,e,n)!==null}function rc(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 oc(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of rc(t)){if(nc(s,e,i))continue;r??=jt(t.agents,t.voice,e);let d=n.get(s)??{voice:s,agents:[],speaksWith:{}};d.agents.includes(o)||d.agents.push(o);let l=r.get(o);o!=="voice.system"&&!a&&(d.speaksWith[o]=l?ze(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Ht(t){let e=He(t);if(e)return`Siri ${e.name[0].toUpperCase()}${e.name.slice(1)} (${e.locale})`;if(t.toLowerCase().startsWith(P)){let n=t.slice(P.length).trim();return`Siri ${n[0]?.toUpperCase()??""}${n.slice(1)}`}return t}function sc(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Ht(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
|
|
432
432
|
`)}
|
|
433
|
-
Reinstall in ${
|
|
434
|
-
`)
|
|
433
|
+
Reinstall in ${tc}. Agents switch back on their own once it is installed.`}}function ic(t=ds()){if(!cs(t))return null;try{let e=JSON.parse(Gl(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function ac(t,e){Kl(Zl(t),{recursive:!0}),Jl(`${t}.tmp`,JSON.stringify(e,null,2)+`
|
|
434
|
+
`),Yl(`${t}.tmp`,t)}var ls=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??ds(),s=new Map((ic(o)?.missing??[]).map(p=>[p.voice,p])),i=oc(e,n),a=i.map(p=>({...p,since:s.get(p.voice)?.since??r.toISOString(),...s.get(p.voice)?.notifiedAt?{notifiedAt:s.get(p.voice).notifiedAt}:{}})),d=[...s.keys()].filter(p=>!i.some(u=>u.voice===p));for(let p of d)this.deps.log(`[voice] ${Ht(p)} is installed again; its agents speak with it again`);d.length&&Qo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=sc(l);try{await this.deps.notify(p,u);for(let g of l)g.notifiedAt=r.toISOString();this.deps.log(`[voice] told the owner: ${l.map(g=>Ht(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 c={checkedAt:r.toISOString(),missing:a};return(!cs(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&ac(o,c),c}finally{this.running=!1}}};import{randomBytes as us}from"crypto";var Z={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:W.perMessage},lc=/^[a-f0-9]{32}$/,cc=/^c[a-z0-9]{8,32}$/,dc=/^#[0-9a-fA-F]{6}$/;function Vt(t){return cc.test(t)}var ps=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
|
|
435
435
|
id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
|
|
436
436
|
node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
|
|
437
437
|
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
@@ -444,34 +444,34 @@ Reinstall in ${Tl}. Agents switch back on their own once it is installed.`}}func
|
|
|
444
444
|
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
|
|
445
445
|
path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
446
446
|
CREATE INDEX IF NOT EXISTS app_chat_files_conversation ON app_chat_files(conversation_id);`),e.prepare("PRAGMA table_info(app_chat_messages)").all().some(o=>o.name==="files")||e.exec("ALTER TABLE app_chat_messages ADD COLUMN files TEXT");let r=e.prepare("PRAGMA table_info(app_chat_conversations)").all();r.some(o=>o.name==="read_at")||e.transaction(()=>{e.prepare("PRAGMA table_info(app_chat_conversations)").all().some(s=>s.name==="read_at")||(e.exec("ALTER TABLE app_chat_conversations ADD COLUMN read_at INTEGER"),e.exec("UPDATE app_chat_conversations SET read_at = updated_at"))}).immediate(),r.some(o=>o.name==="color")||e.exec("ALTER TABLE app_chat_conversations ADD COLUMN color TEXT"),e.exec(`CREATE TABLE IF NOT EXISTS app_chat_delivered (
|
|
447
|
-
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return
|
|
448
|
-
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!
|
|
447
|
+
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Vt(e)?this.db.prepare("SELECT device_id FROM app_chat_conversations WHERE id = ?").get(e)?.device_id??null:null}appendOnce(e,n,r,o,s=[],i=Date.now()){return!r||r.length>200?null:this.db.transaction(()=>!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e)||this.db.prepare("INSERT OR IGNORE INTO app_chat_delivered (key, conversation_id, at) VALUES (?, ?, ?)").run(r,n,i).changes===0?null:(this.db.prepare("DELETE FROM app_chat_delivered WHERE at < ?").run(i-30*24*60*6e4),this.appendWithFiles(e,n,o,s))).immediate()}create(e,n,r,o=Date.now()){let s=`c${o.toString(36)}${us(4).toString("hex")}`,{color:i,...a}=n,d=i&&dc.test(i)?i:void 0,l={id:s,title:ms(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
|
|
448
|
+
(id, device_id, title, node, node_name, agent, agent_name, color, created_at, updated_at, read_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,e,l.title,l.node,l.nodeName,l.agent,l.agentName??null,d??null,o,o,o),this.pruneDevice(e),l}get(e,n){if(!Vt(n))return null;let r=this.db.prepare("SELECT * FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e);if(!r)return null;let o=this.db.prepare("SELECT * FROM app_chat_messages WHERE conversation_id = ? ORDER BY id").all(n).map(uc);return{...gs(r),messages:o}}list(e,n=Z.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
|
|
449
449
|
(SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
|
|
450
450
|
(SELECT substr(m.content, 1, 240) FROM app_chat_messages m WHERE m.conversation_id = c.id ORDER BY m.id DESC LIMIT 1) AS last
|
|
451
|
-
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...
|
|
451
|
+
FROM app_chat_conversations c WHERE c.device_id = ? ORDER BY c.updated_at DESC, c.rowid DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>{let s=typeof o.last=="string"?o.last.replace(/\s+/g," ").trim().slice(0,120):"";return{...gs(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Vt(n)&&this.db.prepare("UPDATE app_chat_conversations SET read_at = MAX(COALESCE(read_at, 0), ?) WHERE id = ? AND device_id = ?").run(r,n,e)}latestWith(e,n){let r=this.db.prepare(`SELECT id, device_id FROM app_chat_conversations WHERE node = ? AND agent = ?
|
|
452
452
|
ORDER BY updated_at DESC, rowid DESC LIMIT 1`).get(e,n);return r?{id:r.id,deviceId:r.device_id}:null}latestDevice(){return this.db.prepare("SELECT device_id FROM app_chat_conversations ORDER BY updated_at DESC, rowid DESC LIMIT 1").get()?.device_id??null}unread(e,n){return this.db.prepare(`SELECT c.id, c.title, c.agent, c.agent_name, c.color,
|
|
453
453
|
substr(m.content, 1, 240) AS answer, m.status, m.at
|
|
454
454
|
FROM app_chat_conversations c
|
|
455
455
|
JOIN app_chat_messages m ON m.id = (SELECT MAX(id) FROM app_chat_messages WHERE conversation_id = c.id)
|
|
456
456
|
WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
|
|
457
|
-
ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>
|
|
457
|
+
ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>Z.content?r.content.slice(0,Z.content)+`
|
|
458
458
|
|
|
459
|
-
[Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,
|
|
459
|
+
[Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,Z.toolsPerMessage),d=[];for(let u of o){if(d.length>=Z.filesPerMessage)break;let g=u.filename.trim(),m=fe(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:us(16).toString("hex"),name:f,mime:m.mime,kind:m.kind,path:g})}let l=d.map(u=>({id:u.id,name:u.name,mime:u.mime,kind:u.kind})),c=this.db.prepare(`INSERT INTO app_chat_messages (conversation_id, role, content, status, error, ui, tools, files, at)
|
|
460
460
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),p=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
|
|
461
461
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`);for(let u of d)p.run(u.id,n,Number(c.lastInsertRowid),u.path,u.name,u.mime,u.kind,r.at);return this.db.prepare(`DELETE FROM app_chat_messages WHERE conversation_id = ? AND id NOT IN
|
|
462
|
-
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,
|
|
463
|
-
(SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!
|
|
462
|
+
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,Z.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
|
|
463
|
+
(SELECT id FROM app_chat_messages WHERE conversation_id = ?)`).run(n,n),this.db.prepare("UPDATE app_chat_conversations SET updated_at = ? WHERE id = ?").run(r.at,n),l}getFile(e,n){if(!lc.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
|
|
464
464
|
JOIN app_chat_conversations c ON c.id = f.conversation_id WHERE f.id = ? AND c.device_id = ?`).get(n,e);return r?{id:r.id,name:r.name,mime:r.mime,kind:r.kind,path:r.path,conversationId:r.conversation_id,node:r.node,agent:r.agent}:null}pruneDevice(e){let n=this.db.prepare(`SELECT id FROM app_chat_conversations WHERE device_id = ?
|
|
465
|
-
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,
|
|
466
|
-
`),
|
|
467
|
-
`)}};function
|
|
468
|
-
`):[]}writeMd(e){let n=
|
|
469
|
-
`))}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(
|
|
470
|
-
`);for(let i=0;i<s.length;i++){let a=s[i].match(
|
|
471
|
-
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),
|
|
472
|
-
`)))}},zt=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(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d: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`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}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)),d=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(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.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 l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}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 c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.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 d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,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 l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.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",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.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 Yg(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Vt(r.path,e,n);case"wiki":return new qt(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 zt(o.host,o.token,i,s,n)}}}Ze();var Xt="unmapped";function Kt(t,e=[]){if(!t)return Xt;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 Zl(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of le(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,Kt(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 d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function ec(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 ef(t,e){let n=ec(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Kt(t.project,e.projects);if(t.agentId){let r=Zl(e).get(t.agentId);if(r)return r}return Xt}function tf(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 tc=t=>t===Xt?"internal":"client";function nc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??tc(t),respondWithinMinutes:rc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function nf(t){let e=new Set;for(let n of t.projects??[])e.add(Kt(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=>nc(n,t))}function rc(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 oc}from"crypto";var sf={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},sc=40,ic=20,af=90,ac=2e3,ns=36e5;function lc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
473
|
-
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<
|
|
474
|
-
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function
|
|
465
|
+
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,Z.conversationsPerDevice);for(let{id:r}of n)this.db.prepare("DELETE FROM app_chat_files WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_messages WHERE conversation_id = ?").run(r),this.db.prepare("DELETE FROM app_chat_conversations WHERE id = ?").run(r)}};function gs(t){return{id:t.id,title:t.title,node:t.node,nodeName:t.node_name,agent:t.agent,...t.agent_name?{agentName:t.agent_name}:{},...t.color?{color:t.color}:{},createdAt:t.created_at,updatedAt:t.updated_at}}function uc(t){let e=s=>{if(s)try{return JSON.parse(s)}catch{return}},n=e(t.ui),r=e(t.tools),o=e(t.files);return{role:t.role,content:t.content,at:t.at,...t.status?{status:t.status}:{},...t.error?{error:t.error}:{},...n?{ui:n}:{},...r?{tools:r}:{},...o?{files:o}:{}}}function ms(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return ms(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as Xt,writeFileSync as xs,existsSync as zt,readdirSync as kc,statSync as vc}from"fs";import{resolve as Kt,join as Sc}from"path";import{existsSync as fs,mkdirSync as pc,readFileSync as gc,writeFileSync as hs}from"fs";import{dirname as mc,resolve as bs}from"path";import{z as v}from"zod";var fc=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),hc=v.object({id:v.string(),title:v.string(),description:v.string().optional(),assignee:v.string().optional(),labels:v.array(v.string()).default([]),milestone:v.string().optional(),status:v.enum(["todo","doing","blocked","done"]).default("todo"),priority:v.number().int().optional(),estimatedSeconds:v.number().int().optional(),source:fc.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),bc=v.object({version:v.literal(1),items:v.array(hc).default([])}),Ke=class{constructor(e){this.path=e}jsonPath(){return bs(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return bs(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return fs(this.jsonPath())}load(){let e=this.jsonPath();if(!fs(e))return{version:1,items:[]};let n=gc(e,"utf-8");try{return bc.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();pc(mc(n),{recursive:!0}),hs(n,JSON.stringify(e,null,2)+`
|
|
466
|
+
`),hs(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 d=s==="done"?"x":" ",l=a.assignee?`@${a.assignee} `:"",c=a.estimatedSeconds?` [time: ${Math.round(a.estimatedSeconds/60)}m]`:"",p=a.source?` (${a.source.type}: ${a.source.project}#${a.source.iid})`:"";n.push(`- [${d}] ${l}${a.title}${c}${p}`),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(`
|
|
467
|
+
`)}};function Sm(t){return`${t.type}:${t.project}:${t.iid}`}function ys(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 qt(t,e,n,r=()=>{}){return t.source?yc(t.source,e,n,r):{ok:!0,attempts:[]}}async function yc(t,e,n,r=()=>{}){return t.type==="gitlab"?wc(t,e,n,r):t.type==="github"?xc(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function wc(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=[],d=async(g,m={})=>fetch(`${i}/api/v4${g}`,{...m,headers:{"PRIVATE-TOKEN":s,"Content-Type":"application/json",...m.headers||{}}}),l=encodeURIComponent(t.project),c;e.assigneeUsernames!==void 0&&(c=(await Promise.all(e.assigneeUsernames.map(async m=>{try{let f=await fetch(`${i}/api/v4/users?username=${encodeURIComponent(m)}`,{headers:{"PRIVATE-TOKEN":s}});if(!f.ok)return null;let w=await f.json();return Array.isArray(w)&&w[0]?.id?w[0].id:null}catch{return null}}))).filter(m=>typeof m=="number"));let p;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")p=0;else try{let g=await d(`/projects/${l}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);if(g.ok){let m=await g.json();Array.isArray(m)&&m[0]?.id&&(p=m[0].id)}}catch(g){r(`[backlog-sync] milestone lookup failed: ${g.message}`)}let u={};if(e.title!==void 0&&(u.title=e.title),e.description!==void 0&&(u.description=e.description),e.labels!==void 0&&(u.labels=e.labels.join(",")),e.addLabels?.length&&(u.add_labels=e.addLabels.join(",")),e.removeLabels?.length&&(u.remove_labels=e.removeLabels.join(",")),c!==void 0&&(u.assignee_ids=c),p!==void 0&&(u.milestone_id=p),e.state&&(u.state_event=e.state==="closed"?"close":"reopen"),Object.keys(u).length)try{let g=await d(`/projects/${l}/issues/${t.iid}`,{method:"PUT",body:JSON.stringify(u)});if(a.push({kind:"PUT issue",ok:g.ok,status:g.status}),!g.ok){let m=await g.text().catch(()=>"");return{ok:!1,attempts:a,error:`PUT issue ${g.status}: ${m.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 d(`/projects/${l}/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 xc(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(u,g={})=>fetch(`https://api.github.com${u}`,{...g,headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...g.headers||{}}}),d=t.project,l;if(e.milestoneTitle!==void 0)if(e.milestoneTitle===null||e.milestoneTitle==="")l=null;else try{let u=await a(`/repos/${d}/milestones?state=all&per_page=100`);if(u.ok){let g=await u.json(),m=Array.isArray(g)?g.find(f=>f.title===e.milestoneTitle):null;m?.number&&(l=m.number)}}catch(u){r(`[backlog-sync] github milestone lookup failed: ${u.message}`)}let c;if(e.labels!==void 0)c=e.labels;else if(e.addLabels?.length||e.removeLabels?.length){try{let u=await a(`/repos/${d}/issues/${t.iid}`);if(u.ok){let g=await u.json(),m=Array.isArray(g.labels)?g.labels.map(w=>typeof w=="string"?w:w.name):[],f=new Set([...m,...e.addLabels??[]]);for(let w of e.removeLabels??[])f.delete(w);c=[...f]}}catch(u){r(`[backlog-sync] github label fetch failed: ${u.message}`)}if(c===void 0)return{ok:!1,attempts:i,error:"could not read the issue's labels; nothing written",url:t.url}}let p={};if(e.title!==void 0&&(p.title=e.title),e.description!==void 0&&(p.body=e.description),c!==void 0&&(p.labels=c),e.assigneeUsernames!==void 0&&(p.assignees=e.assigneeUsernames),l!==void 0&&(p.milestone=l),e.state&&(p.state=e.state),Object.keys(p).length)try{let u=await a(`/repos/${d}/issues/${t.iid}`,{method:"PATCH",body:JSON.stringify(p)});if(i.push({kind:"PATCH issue",ok:u.ok,status:u.status}),!u.ok){let g=await u.text().catch(()=>"");return{ok:!1,attempts:i,error:`PATCH issue ${u.status}: ${g.slice(0,200)}`,url:t.url}}}catch(u){return i.push({kind:"PATCH issue",ok:!1,error:u.message}),{ok:!1,attempts:i,error:u.message,url:t.url}}if(e.note)try{let u=await a(`/repos/${d}/issues/${t.iid}/comments`,{method:"POST",body:JSON.stringify({body:e.note})});i.push({kind:"POST comment",ok:u.ok,status:u.status})}catch(u){i.push({kind:"POST comment",ok:!1,error:u.message})}return{ok:i.every(u=>u.ok),attempts:i,url:t.url}}var Gt=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Ge=/@([a-z0-9_-]+)/i,ws=/\[time:\s*([0-9hm\s]+)\]/i;function Ec(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 Yt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new Ke(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Kt(process.cwd(),this.path);return zt(e)?Xt(e,"utf-8").split(`
|
|
468
|
+
`):[]}writeMd(e){let n=Kt(process.cwd(),this.path);xs(n,e.join(`
|
|
469
|
+
`))}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(Gt);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(Ge);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(ws),c=a.replace(Ge,"").replace(ws,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?Ec(l[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=ys([o.assignee||e],o.source,this.daemon);qt(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 d=this.store.update(e,a);if(d.source&&this.daemon){let l={};n.status==="done"?(l.addLabels=["Done"],l.removeLabels=["Doing"]):n.status==="blocked"&&(l.addLabels=["Blocked"]),n.note&&(l.note=n.note),Object.keys(l).length&&qt(d,l,this.daemon,this.log).catch(c=>this.log(`[backlog-sync] report failed for ${e}: ${c?.message??c}`))}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(Gt))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"}}},Jt=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(zt(e))for(let r of kc(e)){let o=Sc(e,r);vc(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(Kt(process.cwd(),this.root),n);let r=[];for(let o of n){let s=Xt(o,"utf-8").split(`
|
|
470
|
+
`);for(let i=0;i<s.length;i++){let a=s[i].match(Gt);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(Ge);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(Ge,"").trim(),assignee:d[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(!zt(s))return;let i=Xt(s,"utf-8").split(`
|
|
471
|
+
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),xs(s,i.join(`
|
|
472
|
+
`)))}},Qt=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(l=>({name:l.name,color:l.color,text_color:l.text_color})),o=s.map(l=>l.name)):o=e.labels);let a=(Array.isArray(e.assignees)&&e.assignees.length?e.assignees:e.assignee?[e.assignee]:[]).map(l=>({username:l.username,name:l.name,avatarUrl:l.avatar_url})),d=a[0]?.username;return{id:`gitlab:${r}:issue:${e.iid}`,title:e.title,description:e.description||void 0,assignee:d?this.usernameToAgent(d)||d: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`,d=i==="__ALL__"?`/issues?${a}`:`/projects/${encodeURIComponent(i)}/issues?${a}`,l=await this.api(d);for(let c of l){let p=this.mapIssue(c,i);p.assignee=e,r.push(p)}}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)),d=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(d)}`,{method:"POST"})}catch(l){this.log(`[business] add_spent_time failed: ${l.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 l of i)try{let c=l==="__ALL__"?`/issues?${o.toString()}`:`/projects/${encodeURIComponent(l)}/issues?${o.toString()}`,p=await this.api(c);for(let u of p)a.push(this.mapIssue(u,l))}catch(c){this.log(`[business] GitLab listAll failed on ${l}: ${c.message}`)}let d=a;if(e.notLabels?.length){let l=new Set(e.notLabels);d=d.filter(c=>!(c.labels||[]).some(p=>l.has(p)))}if(e.withoutScopedPrefix){let l=e.withoutScopedPrefix+"::";d=d.filter(c=>!(c.labels||[]).some(p=>p.startsWith(l)))}return d}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 c=>{try{let p=await this.api(`/users?username=${encodeURIComponent(c)}`);return Array.isArray(p)&&p[0]?.id?p[0].id:null}catch{return null}}))).filter(c=>typeof c=="number"));let i;if(n.milestoneTitle!==void 0)if(n.milestoneTitle===null||n.milestoneTitle==="")i=0;else try{let l=await this.api(`/projects/${encodeURIComponent(r)}/milestones?title=${encodeURIComponent(n.milestoneTitle)}`);Array.isArray(l)&&l[0]?.id&&(i=l[0].id)}catch(l){this.log(`[board] milestone lookup failed for "${n.milestoneTitle}": ${l.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 d=await this.api(`/projects/${encodeURIComponent(r)}/issues/${o}`,{method:"PUT",body:JSON.stringify(a)});return this.mapIssue(d,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 l=>{try{let c=await this.api(`/users?username=${encodeURIComponent(l)}`);return Array.isArray(c)&&c[0]?.id?c[0].id:null}catch(c){return this.log(`[board] user lookup failed for ${l}: ${c.message}`),null}}))).filter(l=>typeof l=="number"));let s;if(e.milestoneTitle)try{let d=await this.api(`/projects/${encodeURIComponent(n)}/milestones?title=${encodeURIComponent(e.milestoneTitle)}`);Array.isArray(d)&&d[0]?.id&&(s=d[0].id)}catch(d){this.log(`[board] milestone lookup failed for "${e.milestoneTitle}": ${d.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",d=new URLSearchParams;n.length&&d.set("add_labels",n.join(",")),r.length&&d.set("remove_labels",r.join(",")),d.toString()&&await this.api(`/projects/${encodeURIComponent(o)}/${a}/${s}?${d.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 Im(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Yt(r.path,e,n);case"wiki":return new Jt(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 Qt(o.host,o.token,i,s,n)}}}st();var Zt="unmapped";function en(t,e=[]){if(!t)return Zt;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 $c(t){let e=new Map,n=t.projects??[],r=t.orgChart??{},o=new Map;for(let i of pe(t)){let a=C(i.from),d=C(i.to);i.type==="reports-to"&&a.kind==="agent"&&d.kind==="agent"&&o.set(a.id,d.id)}for(let i of n)i.pm&&(e.has(i.pm)||e.set(i.pm,en(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 d=o.get(i);if(!d)return;let l=s(d,a);return l&&e.set(i,l),l};for(let i of Object.keys(r))s(i);return e}function _c(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 Nm(t,e){let n=_c(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return en(t.project,e.projects);if(t.agentId){let r=$c(e).get(t.agentId);if(r)return r}return Zt}function Om(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 Ac=t=>t===Zt?"internal":"client";function Rc(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??Ac(t),respondWithinMinutes:Tc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function Lm(t){let e=new Set;for(let n of t.projects??[])e.add(en(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=>Rc(n,t))}function Tc(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 Ic}from"crypto";var Fm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},Dc=40,Cc=20,Um=90,Nc=2e3,ks=36e5;function Oc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
473
|
+
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<Dc?null:`text:${Ic("sha256").update(r).digest("hex").slice(0,24)}`}function Wm(t){let e=t.indexOf(`
|
|
474
|
+
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function tn(t){t.exec(`
|
|
475
475
|
CREATE TABLE IF NOT EXISTS owner_told (
|
|
476
476
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
477
477
|
at INTEGER NOT NULL,
|
|
@@ -489,34 +489,34 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<sc?null:`text:${o
|
|
|
489
489
|
CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
|
|
490
490
|
CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
|
|
491
491
|
CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
|
|
492
|
-
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of
|
|
493
|
-
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,
|
|
492
|
+
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of Lc)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 Lc=[["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 Ye(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 vs=class{constructor(e){this.db=e;tn(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)
|
|
493
|
+
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,Nc),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?Ye(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?Ye(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(Ye)}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(Ye)}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,
|
|
494
494
|
SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
|
|
495
495
|
SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
|
|
496
|
-
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}},
|
|
496
|
+
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}},Ss=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=Oc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,Cc):r.repeatWindowHours)*ks,d=r.digestNags&&r.digestAvailable!==!1,l="send";!n.urgent&&s&&this.ledger.lastTold(s,o-a,d)?l="repeat":!n.urgent&&i==="nag"&&d&&(l="digest");let c=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:l==="send"?"sent":l,urgent:n.urgent===!0});return{verdict:l,key:s,rowId:c}}outcome(e,n){this.ledger.setOutcome(e,n)}digestLine(){let e=this.ledger.waitingForDigest();return e.length?{line:Pc(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*ks)}};function jm(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 Pc(t,e=5,n=3){let r=new Map;for(let a of t){let[d,...l]=a.title.split(": "),c=l.join(": ").trim(),p=r.get(d.trim())??{count:0,names:[]};p.count++,c&&!p.names.includes(c)&&p.names.push(c),r.set(d.trim(),p)}let o=[...r.entries()].sort((a,d)=>d[1].count-a[1].count),s=o.slice(0,e).map(([a,{count:d,names:l}])=>{let c=l.length?` (${l.slice(0,n).join(", ")}${l.length>n?", \u2026":""})`:"";return`${a}${d>1?` \xD7${d}`:""}${c}`}),i=o.length>e?`; ${o.length-e} more kinds`:"";return`${t.length} notice${t.length===1?"":"s"} held for this digest: ${s.join("; ")}${i}.`}function Hm(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 Mc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var Es=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(X)),this.log=r,this.cleanupTimer=setInterval(()=>this.cleanupExpired(),1e4)}pendingKey(e,n){return`${e}|${X(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 d=Date.now(),l=a.filter(c=>c.expiresAt>d);for(let{signal:c}of l)this.deliverTo(o,c);this.pending.delete(i),l.length&&this.log(`flushed ${l.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
|
|
497
497
|
data: ${JSON.stringify(n)}
|
|
498
498
|
|
|
499
|
-
`):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=
|
|
500
|
-
`),
|
|
499
|
+
`):e.sink.deliver(n),!0}catch{return!1}}async handleOutgoing(e){let n=X(e.to);if(n===X(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&&X(r.recipient)===n)return!0;return!1}handleIncoming(e){if((e.kind==="offer"||e.kind==="ring")&&this.allowedCallers.size>0&&!this.allowedCallers.has(X(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+Mc),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=X(e.to);for(let o of this.subs)o.callId===e.callId&&X(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 Fc,readFileSync as $s,renameSync as Uc,rmSync as Wc,writeFileSync as jc}from"fs";import{homedir as Bc}from"os";import{dirname as Hc,join as Vc}from"path";var _s=Vc(Bc(),".agentx","call.json");function qc(t=_s,e=Date.now()){try{let n=JSON.parse($s(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 As(t=br,e=qc){let n=t();return n.active?n:e()}function Gm(t,e,n=_s,r=Date.now()){let o=null;try{o=JSON.parse($s(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&Wc(n,{force:!0});return}Fc(Hc(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;jc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
|
|
500
|
+
`),Uc(s,n)}var Rs="owner",Je=6e4,Ns=60*Je,Xc=24*Ns,zc=7*24*Ns,Kc=2*Je,Qm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Gc(t){t.exec(`
|
|
501
501
|
CREATE TABLE IF NOT EXISTS owner_presence (
|
|
502
502
|
person TEXT NOT NULL,
|
|
503
503
|
surface TEXT NOT NULL,
|
|
504
504
|
at INTEGER NOT NULL,
|
|
505
505
|
PRIMARY KEY (person, surface)
|
|
506
506
|
);
|
|
507
|
-
`)}var
|
|
507
|
+
`)}var Ts=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Gc(e)}written=new Map;touch(e,n=Rs){let r=this.now(),o=`${n}
|
|
508
508
|
${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 (?, ?, ?)
|
|
509
|
-
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=
|
|
509
|
+
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=Rs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Zm(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var Is=class{constructor(e,n=Date.now){this.db=e;this.now=n;tn(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
|
|
510
510
|
WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
|
|
511
|
-
ORDER BY at DESC LIMIT 500`).all(this.now()-
|
|
512
|
-
WHERE seen_at IS NULL AND (${
|
|
513
|
-
WHERE answered_at IS NULL AND (${
|
|
511
|
+
ORDER BY at DESC LIMIT 500`).all(this.now()-zc)}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,d=o.all(s.at-Kc,s.at).find(l=>l.title===s.title||i!==s.title&&l.title.startsWith(i));d&&r.push(d.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 = ?
|
|
512
|
+
WHERE seen_at IS NULL AND (${Ds(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, ?)
|
|
513
|
+
WHERE answered_at IS NULL AND (${Ds(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 Ds(t){let e=t.map(()=>"?").join(", ");return`id IN (${e}) OR escalation_of IN (${e}) OR id IN (SELECT escalation_of FROM owner_told WHERE id IN (${e}) AND escalation_of IS NOT NULL)`}function ef(t,e,n){let r=t.ladder.length?t.ladder:[...e.channels.map(s=>`${s}:default`),...e.addresses],o=[];for(let s of r){let i=s.trim(),a=xe(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function xe(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Yc(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Jc(t){return xe(t)==="push"?["phone","desk"]:[t]}function tf(t,e,n){let r=t.filter(s=>n(xe(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Jc(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 Qc(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(xe(s)))??null}var Zc=3;async function nf(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*Je,i=e.prepare(`SELECT id FROM owner_told
|
|
514
514
|
WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
|
|
515
515
|
AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
|
|
516
516
|
AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
|
|
517
|
-
ORDER BY at LIMIT 20`).all(Math.max(o-
|
|
517
|
+
ORDER BY at LIMIT 20`).all(Math.max(o-Zc*s,o-Xc),o-s),a=e.prepare("UPDATE owner_told SET escalated_at = ? WHERE id = ? AND escalated_at IS NULL"),d=0;for(let{id:l}of i){if(a.run(o,l).changes!==1)continue;let c=n.get(l);if(!c)continue;let p=`${c.channel}:${c.chatId}`,u=Qc(t.stops,p,t.up);if(!u){t.log(`[reach] urgent "${c.title.slice(0,80)}" ${c.outcome==="failed"?"failed":"unseen"} on ${p}; no other address to try`);continue}let g=Math.round((o-c.at)/Je),m=c.outcome==="failed"?`it could not be sent on ${c.channel}`:`not seen on ${c.channel} for ${g} min`,f=`${c.text?`${c.text}
|
|
518
518
|
|
|
519
|
-
`:""}(Sent again here: ${f}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:$c(u),from:c.from,title:c.title,text:m,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,m),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${f}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var gs=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}};function Rc(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function Af(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function Tc(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,S=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[S]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,S)=>'<option value="'+r(h)+'">'+r(S)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(S=>!p[S.ref]).map(S=>i(S.ref,S.name)).join(""),f=g(l.agents),m=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(f||m?(f?'<optgroup label="Agents">'+f+"</optgroup>":"")+(m?'<optgroup label="People">'+m+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(f||m?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,S)=>{if(h.kind!=="agent")return"";let Ye=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+S+'">Start <input type="time" id="oe-start-'+S+'" value="'+r(Ye.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+S+'">End <input type="time" id="oe-end-'+S+'" value="'+r(Ye.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Se=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+S+'" value="'+Se[0]+'"'+(Ye.days.indexOf(Se[0])>=0?" checked":"")+' aria-label="'+Se[2]+'">'+Se[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,S)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+S+'"><span class="org-kind">Role</span><input id="oe-role-'+S+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+S+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,S)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,D=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',ae=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),ve=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+ae+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+ae+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+D+ve+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function _f(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?Rc(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>Tc(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var Rf=`
|
|
519
|
+
`:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:xe(u),chatId:Yc(u),from:c.from,title:c.title,text:f,outcome:"sent",urgent:!0,escalationOf:c.id});try{await t.send(u,c,f),d++,t.log(`[reach] urgent "${c.title.slice(0,80)}": ${m}; sent once to ${u}`)}catch(x){n.setOutcome(w,"failed"),t.log(`[reach] urgent "${c.title.slice(0,80)}": escalation to ${u} failed: ${x?.message??x}`)}}return d}var Cs=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}};function ed(t,e){let n={"reports-to":"report to","dotted-line":"have a dotted line to","acts-for":"act for"},r={};for(let l of t.members)r[l.ref]=l;let o=l=>l&&r[l]?r[l].name:String(l||"").replace(/^(agent|person):/,""),s=l=>!!l&&!!r[l]&&r[l].kind==="agent",i=l=>l.length<2?l.join(""):l.slice(0,-1).join(", ")+" and "+l[l.length-1],a=o(e.from),d=o(e.to);if(e.op==="add-relation"&&e.type==="reports-to"){let l=t.relations.find(p=>p.type==="reports-to"&&p.from===e.from),c=s(e.from)?" When "+a+" is stuck, it asks "+d+" first.":"";return l&&l.to!==e.to&&e.from!==e.to?{text:a+" will report to "+d+", not "+o(l.to)+"."+c,steps:[{op:"remove-relation",from:l.from,type:"reports-to",to:l.to},e],undo:[{op:"add-relation",from:l.from,type:"reports-to",to:l.to}]}:{text:a+" will report to "+d+"."+c,steps:[e],undo:[]}}if(e.op==="add-relation")return{text:a+" will "+(n[e.type||""]||e.type)+" "+d+".",steps:[e],undo:[]};if(e.op==="remove-relation"){let l=e.type==="reports-to"&&s(e.from)?" When "+a+" is stuck, it no longer asks "+d+".":"";return{text:a+" will no longer "+(n[e.type||""]||e.type)+" "+d+"."+l,steps:[e],undo:[]}}if(e.op==="remove-member"){let l=t.relations.filter(p=>p.from===e.member||p.to===e.member).length,c=t.relations.filter(p=>p.type==="reports-to"&&p.to===e.member).map(p=>o(p.from));return{text:o(e.member)+" will leave the org chart"+(l?", with "+l+" "+(l===1?"line":"lines"):"")+"."+(c.length?" "+i(c)+" will report to no one.":""),steps:[e],undo:[]}}return null}function of(t){let e=c=>String(c??"").replace(/[&<>"']/g,p=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[p]),n={"dotted-line":"dotted line to","acts-for":"acts for"};if(!t||!t.members.length)return"";let r={};for(let c of t.members)r[c.ref]=c;let o={};for(let c of t.relations)c.type==="reports-to"&&r[c.to]&&(o[c.from]=c.to);let s=c=>r[c]?r[c].name:c.replace(/^(agent|person):/,""),i={},a=c=>{i[c.ref]=!0;let p=t.relations.filter(g=>g.from===c.ref&&g.type!=="reports-to").map(g=>(n[g.type]||g.type)+" "+s(g.to)),u=t.members.filter(g=>o[g.ref]===c.ref&&!i[g.ref]);return"<li><b>"+e(c.name)+'</b> <span class="org-kind">'+(c.kind==="person"?"Person":"Agent")+(c.title?" \xB7 "+e(c.title):"")+"</span>"+(p.length?" <small>"+e(p.join(", "))+"</small>":"")+(u.length?"<ul>"+u.map(a).join("")+"</ul>":"")+"</li>"};return'<ul class="oe-tree" aria-label="Org chart">'+t.members.filter(c=>!o[c.ref]).map(a).join("")+t.members.filter(c=>!i[c.ref]).map(a).join("")+"</ul>"}function td(t,e,n){let r=h=>String(h??"").replace(/[&<>"']/g,E=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[E]),o={"reports-to":"Reports to","dotted-line":"Dotted line to","acts-for":"Acts for"},s={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"},i=(h,E)=>'<option value="'+r(h)+'">'+r(E)+"</option>";if(!t)return'<p class="org-quiet">Loading\u2026</p>';if(!t.canEdit||!t.setup||!t.choices)return"";let a='<p class="oe-msg'+(e.bad?" is-bad":"")+'" role="status">'+r(e.text)+"</p>",d=n?'<div class="oe-confirm" id="oe-confirm" role="group" aria-label="Confirm the change"><p class="oe-confirm-text">'+r(n)+'</p><span class="oe-acts"><button type="button" class="ax-btn ax-btn--primary" id="oe-confirm-save" data-oe="confirm">Save the move</button><button type="button" class="ax-btn" data-oe="cancel">Cancel</button></span></div>':"",l=t.choices,c=t.setup.members,p={};for(let h of c)p[h.ref]=h;let u=h=>p[h]?p[h].name:h.replace(/^(agent|person):/,""),g=h=>h.filter(E=>!p[E.ref]).map(E=>i(E.ref,E.name)).join(""),m=g(l.agents),f=g(l.people),w='<div class="oe-form" role="group" aria-label="Add a member"><label for="oe-add-member">Member <select id="oe-add-member">'+(m||f?(m?'<optgroup label="Agents">'+m+"</optgroup>":"")+(f?'<optgroup label="People">'+f+"</optgroup>":""):'<option value="">Everyone is in the chart</option>')+'</select></label><label for="oe-add-role">Role <input id="oe-add-role" list="oe-roles" maxlength="80" placeholder="Engineer" autocomplete="off"></label><button type="button" class="ax-btn" data-oe="add-member"'+(m||f?"":" disabled")+'>Add</button></div><datalist id="oe-roles">'+l.roles.map(h=>i(h.title,h.key)).join("")+"</datalist>",x=[["mon","Mon","Monday"],["tue","Tue","Tuesday"],["wed","Wed","Wednesday"],["thu","Thu","Thursday"],["fri","Fri","Friday"],["sat","Sat","Saturday"],["sun","Sun","Sunday"]],b=(h,E)=>{if(h.kind!=="agent")return"";let nt=h.schedule||{start:"",end:"",days:[]};return'<fieldset class="oe-hours"><legend class="org-kind">Working hours of '+r(h.name)+'</legend><label for="oe-start-'+E+'">Start <input type="time" id="oe-start-'+E+'" value="'+r(nt.start)+'" aria-label="Start time of '+r(h.name)+'"></label><label for="oe-end-'+E+'">End <input type="time" id="oe-end-'+E+'" value="'+r(nt.end)+'" aria-label="End time of '+r(h.name)+'"></label><span class="oe-days" role="group" aria-label="Working days of '+r(h.name)+'">'+x.map(Re=>'<label class="oe-day"><input type="checkbox" name="oe-days-'+E+'" value="'+Re[0]+'"'+(nt.days.indexOf(Re[0])>=0?" checked":"")+' aria-label="'+Re[2]+'">'+Re[1]+"</label>").join("")+'</span><button type="button" class="ax-btn" data-oe="set-schedule" data-oe-i="'+E+'" data-oe-member="'+r(h.ref)+'">Save hours</button></fieldset>'},y=c.length?'<ul class="oe-rows">'+c.map((h,E)=>'<li class="oe-row"><span class="oe-who"><b>'+r(h.name)+'</b><span class="org-kind">'+(h.kind==="person"?"Person":"Agent")+'</span></span><label class="oe-role" for="oe-role-'+E+'"><span class="org-kind">Role</span><input id="oe-role-'+E+'" list="oe-roles" maxlength="80" value="'+r(h.title||"")+'" aria-label="Role of '+r(h.name)+'"></label><span class="oe-acts"><button type="button" class="ax-btn" data-oe="set-role" data-oe-i="'+E+'" data-oe-member="'+r(h.ref)+'">Save role</button><button type="button" class="ax-btn" data-oe="remove-member" data-oe-member="'+r(h.ref)+'" aria-label="Remove '+r(h.name)+'">Remove</button><a class="ax-btn" href="/hub#page=settings&section=agents&under='+encodeURIComponent(h.ref)+'" aria-label="Add an agent who reports to '+r(h.name)+'">Add agent here</a></span>'+b(h,E)+"</li>").join("")+"</ul>":'<p class="org-quiet">No one in the org chart yet. Add a member above.</p>',k=t.setup.relations,S=k.length?'<ul class="oe-rows">'+k.map(h=>'<li class="oe-row"><span class="oe-who">'+r(u(h.from))+' <span class="org-kind">'+r(s[h.type]||h.type)+"</span> "+r(u(h.to))+'</span><span class="oe-acts"><button type="button" class="ax-btn" data-oe="remove-relation" data-oe-from="'+r(h.from)+'" data-oe-type="'+r(h.type)+'" data-oe-to="'+r(h.to)+'" aria-label="Remove: '+r(u(h.from)+" "+(s[h.type]||h.type)+" "+u(h.to))+'">Remove</button></span></li>').join("")+"</ul>":'<p class="org-quiet">No relations yet.</p>',K=c.map(h=>i(h.ref,h.name+(h.kind==="person"?" (person)":""))).join(""),Ae=c.length>=2?'<div class="oe-form" role="group" aria-label="Add a relation"><label for="oe-rel-from">Member <select id="oe-rel-from">'+K+'</select></label><label for="oe-rel-type">Relation <select id="oe-rel-type">'+l.types.map(h=>i(h,o[h]||h)).join("")+'</select></label><label for="oe-rel-to">Target <select id="oe-rel-to">'+K+'</select></label><button type="button" class="ax-btn" data-oe="add-relation">Add relation</button></div>':'<p class="org-quiet">Add two members to link them.</p>';return'<p class="oe-lead">Each change is checked, saved to agentx.json with a backup, and used at once, with no restart. A change to a line, or a removal, asks you first.</p>'+a+d+'<h2 class="org-h2">Add a member</h2>'+w+'<h2 class="org-h2">Members <span class="org-kind">'+c.length+"</span></h2>"+y+'<h2 class="org-h2">Relations <span class="org-kind">'+k.length+"</span></h2>"+S+Ae+'<dl class="oe-legend"><dt>Reports to</dt><dd>The line manager, one at most. Work an agent cannot finish goes up this line.</dd><dt>Dotted line to</dt><dd>A second manager for one topic or project.</dd><dt>Acts for</dt><dd>An agent works on behalf of a person.</dd><dt>Working hours</dt><dd>When an agent is on the clock. An empty start or end, or no day ticked, goes back to 09:00 to 17:00, Monday to Friday.</dd></dl>'}function sf(t){let e={msg:"",bad:!1,pending:null,focus:!1},n=i=>{let a=document.getElementById(i);return a?a.value:""};async function r(i,a,d){d&&(d.disabled=!0);let l=0,c={};try{for(;l<i.length;l++)c=await t.post(i[l]);e.msg=(c.summary||"Saved")+". Saved.",e.bad=!1}catch(p){if(e.msg=p.message,e.bad=!0,l>0)try{for(let u of a)await t.post(u);e.msg+=" Nothing was changed."}catch(u){e.msg+=" Putting the old line back failed too: "+u.message+". Check the chart below."}}await t.reload(),t.paint(),d&&(d.disabled=!1)}function o(i,a){let d=t.org(),l=d&&d.setup?ed(d.setup,i):null;if(!l){r([i],[],a);return}e.pending=l,e.msg="",e.bad=!1,e.focus=!0,t.paint()}function s(){e.pending=null,e.msg="Cancelled. Nothing changed.",e.bad=!1,t.paint()}return{E:e,html:()=>td(t.org(),{text:e.msg,bad:e.bad},e.pending?e.pending.text:""),focus(){if(e.focus){let i=document.getElementById("oe-confirm-save");i&&i.focus()}e.focus=!1},click(i){let a=i&&i.closest?i.closest("[data-oe]"):null;if(!a)return!1;let d=a.getAttribute("data-oe")||"",l=c=>a.getAttribute("data-oe-"+c)||"";if(d==="confirm"){let c=e.pending;if(!c)return!0;e.pending=null,r(c.steps,c.undo,a)}else if(d==="cancel")s();else if(d==="add-member")n("oe-add-member")&&r([{op:d,member:n("oe-add-member"),role:n("oe-add-role")}],[],a);else if(d==="set-role")r([{op:d,member:l("member"),role:n("oe-role-"+l("i"))}],[],a);else if(d==="set-schedule"){let c=[];document.querySelectorAll('input[name="oe-days-'+l("i")+'"]').forEach(p=>{p.checked&&c.push(p.value)}),r([{op:d,member:l("member"),start:n("oe-start-"+l("i")),end:n("oe-end-"+l("i")),days:c}],[],a)}else d==="add-relation"?o({op:d,from:n("oe-rel-from"),type:n("oe-rel-type"),to:n("oe-rel-to")},a):d==="remove-member"?o({op:d,member:l("member")},a):d==="remove-relation"&&o({op:d,from:l("from"),type:l("type"),to:l("to")},a);return!0},key(i){i.key==="Escape"&&e.pending&&(i.preventDefault(),s())}}}var af=`
|
|
520
520
|
.oe-tree, .oe-tree ul { list-style: none; margin: 0; padding: 0; font-size: var(--ax-fs-sm); }
|
|
521
521
|
.oe-tree ul { margin-left: 10px; padding-left: 12px; border-left: var(--ax-border-w) solid var(--ax-border-2); }
|
|
522
522
|
.oe-tree li { padding: 3px 0; }
|
|
@@ -549,7 +549,61 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
|
|
|
549
549
|
.oe-form > *, .oe-role { flex: 1 1 100%; }
|
|
550
550
|
.oe-legend { grid-template-columns: 1fr; }
|
|
551
551
|
}
|
|
552
|
-
`;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map($))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:$(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ms(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&$e(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=$e(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let f=s(u);if(f)return`Department ${l.name} cannot list ${f.name}: ${i(f)}`;let m=a.get(u);if(m)return`"${u}" is in both department ${m} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=hs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=$e(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function hs(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function Df(t,e){let n=new Set,r=hs(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}Ze();var bs=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Xe=["mon","tue","wed","thu","fri","sat","sun"],Yt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Ic(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",be.start),r=e(t.end,"end",be.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Xe.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Xe.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Dc(t){let e=Xe.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Xe.indexOf(r)===e+o))return`${Yt[t[0]]} to ${Yt[t[t.length-1]]}`;let n=t.map(r=>Yt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Qt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function Zt(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function vs(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Cc(t){let e=t?.business?.roles??{};return{agents:[...vs(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...Zt(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Qe}}function Oc(t){let e=t?.business??{},n=e.roles??{},r=vs(t),o=Zt(t),s=le(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...be.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...Jt(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function ys(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(Zt(t).keys()),o=Sn(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return vn(le(e),n,r,o)??ms(Jt(e),n,r,o,i)}function Nc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&$(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>$(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>$(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function ws(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function xs(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>bs)throw new Error(`Keep the role under ${bs} characters.`);return e}function Lc(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function ks(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:$(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:$(o.from),to:$(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function Lf(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=ys(n),s=Oc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Cc(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?$(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:f}=C(u),m=d.get(u);if(!m)throw new Error(g==="agent"?`There is no agent "${f}" on this computer.`:`There is no person "${f}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${m} is already in the org chart.`);let w=xs(e.role);if(g==="agent"&&!w)throw new Error(`Give ${m} a role.`);let x=w?ws(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[f]={role:x,schedule:{...be},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[f]=x?{role:x}:{}),c=`${m} added to the org chart`;break}case"set-role":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=xs(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let f=g?ws(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=f:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=f?{role:f}:{}),c=f?`${u.name} is now ${r.roles[f]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let f=ks(r,w=>w.from===u.ref||w.to===u.ref),m=Nc(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(f?`, with ${f} ${f===1?"line":"lines"}`:"")+(m.length?` and out of ${m.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!Qe.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[f,m]=g.map($);for(let x of[f,m])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(f===m)throw new Error(`${l(f)} cannot be linked to themself.`);let w={from:f,to:m,type:u};if(s.relations.some(x=>x.from===f&&x.to===m&&x.type===u))throw new Error(`${l(f)} already ${Qt[u]} ${l(m)}.`);if(u==="acts-for"&&i.get(f).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(f)} is a person.`);if(u==="acts-for"&&i.get(m).kind!=="person")throw new Error(`An agent acts for a person: ${l(m)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===f);if(x)throw new Error(`${l(f)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(Lc(s.relations,m,f))throw new Error(`${l(f)} cannot report to ${l(m)}: ${l(m)} already reports up to ${l(f)}.`)}if(u==="reports-to"&&i.get(f).kind==="agent"){let x=C(m);r.orgChart[C(f).id].reportsTo=x.kind==="agent"?x.id:m}else r.relations=[...r.relations??[],w];c=`${l(f)} ${Qt[u]} ${l(m)}`;break}case"remove-relation":{let u={from:$(String(e.from??"")),to:$(String(e.to??"")),type:String(e.type??"")};if(!ks(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${Qt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=Ic(e),f=r.orgChart[u.id];f.schedule={...f.schedule??{},...g},c=`${u.name} works ${Dc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=ys(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}var Pc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ss=class{constructor(e=Pc,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)}},Mc="That code didn't work. Check it, or run agentx app pair for a new one.",Fc=400;async function Ff(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await vr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Wc(n,e.minMs??Fc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Mc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Wc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as nd}from"child_process";import{mkdtempSync as Gc,rmSync as Jc,writeFileSync as Yc}from"fs";import{tmpdir as Qc}from"os";import{join as Rs}from"path";import{randomBytes as Uc}from"crypto";function T(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},en={height:56,keep:52},$s=`
|
|
552
|
+
`;st();function nn(t){let e=n=>[...new Set((n??[]).filter(Boolean).map($))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:$(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function Os(t,e,n,r=new Set,o=new Map){let s=l=>{let c=C(l);return c.kind==="person"?o.get(c.id):void 0},i=l=>`${l.name} is a ${l.role}, and only owners and members of the organisation can be in a department`,a=new Map;for(let l of t){let c=l.head&&Te(l.head,`Department ${l.name} is headed by`,e,n,r);if(c)return c;let p=l.head?s(l.head):void 0;if(p)return`Department ${l.name} cannot be headed by ${p.name}: ${i(p)}`;for(let u of l.members){let g=Te(u,`Department ${l.name} lists`,e,n,r);if(g)return g;let m=s(u);if(m)return`Department ${l.name} cannot list ${m.name}: ${i(m)}`;let f=a.get(u);if(f)return`"${u}" is in both department ${f} and ${l.name}; a member is in one department`;a.set(u,l.name)}}let d=Ls(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Te(c,`Department ${l.name} also lists`,e,n,r);if(p)return p;let u=s(c);if(u)return`Department ${l.name} cannot also list ${u.name}: ${i(u)}`;let g=d.get(c);if(g===l.id)return`"${c}" is a member of department ${l.name} already; alsoMembers is for members whose home is another department`;if(c===l.head)return`"${c}" heads department ${l.name} already; alsoMembers is for members whose home is another department`;if(!g)return`"${c}" is in alsoMembers of department ${l.name} but has no home; list them in the members of one department first`}}function Ls(t){let e=new Map;for(let n of t)for(let r of n.members)e.has(r)||e.set(r,n.id);for(let n of t)n.head&&!e.has(n.head)&&e.set(n.head,n.id);return e}function df(t,e){let n=new Set,r=Ls(t),o=new Map(t.map(i=>[i.id,i.name]));return{boxes:t.map(i=>{i.head&&n.add(i.head);for(let d of i.members)n.add(d);let a=(i.alsoMembers??[]).flatMap(d=>{let l=r.get(d);return l&&l!==i.id&&d!==i.head?[{key:d,home:o.get(l)}]:[]});return{id:i.id,name:i.name,...i.head?{head:i.head}:{},members:i.members.filter(d=>d!==i.head),...a.length?{also:a}:{}}}),rest:[...new Set(e)].filter(i=>!n.has(i))}}st();var Ps=80,ke={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Qe=["mon","tue","wed","thu","fri","sat","sun"],rn={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function nd(t){let e=(a,d,l)=>{let c=String(a??"").trim();if(!c)return l;if(!/^([01]\d|2[0-3]):[0-5]\d$/.test(c))throw new Error(`The ${d} time "${c}" is not a time. Write it as HH:MM, for example 09:00.`);return c},n=e(t.start,"start",ke.start),r=e(t.end,"end",ke.end);if(r<=n)throw new Error(`The end time (${r}) must be after the start time (${n}).`);if(t.days!=null&&!Array.isArray(t.days))throw new Error("Pick the working days from Monday to Sunday.");let o=(t.days??[]).map(a=>String(a).trim().toLowerCase()),s=o.find(a=>!Qe.includes(a));if(s)throw new Error(`"${s}" is not a day. Use mon, tue, wed, thu, fri, sat or sun.`);let i=o.length?Qe.filter(a=>o.includes(a)):[...ke.days];return{start:n,end:r,days:i}}function rd(t){let e=Qe.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Qe.indexOf(r)===e+o))return`${rn[t[0]]} to ${rn[t[t.length-1]]}`;let n=t.map(r=>rn[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var on={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function sn(t){let e=Array.isArray(t?.people)?t.people:[],n=new Map;for(let r of e)r?.id&&n.set(String(r.id),String(r.name||r.id));return n}function js(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function od(t){let e=t?.business?.roles??{};return{agents:[...js(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...sn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:ot}}function sd(t){let e=t?.business??{},n=e.roles??{},r=js(t),o=sn(t),s=pe(e),i=(c,p,u,g)=>({ref:`${c}:${p}`,kind:c,id:p,name:(c==="agent"?r.get(p):o.get(p))??p,...u?{role:u,title:String(n[u]?.title||u)}:{},...g&&typeof g=="object"?{schedule:{start:String(g.start??""),end:String(g.end??""),days:Array.isArray(g.days)?g.days.map(String):[...ke.days]}}:{}}),a=[...Object.entries(e.orgChart??{}).map(([c,p])=>i("agent",c,p?.role,p?.schedule)),...Object.entries(e.orgPeople??{}).map(([c,p])=>i("person",c,p?.role))],d=new Set(a.map(c=>c.ref)),l=[...s.flatMap(c=>[c.from,c.to]),...nn(e).flatMap(c=>[...c.head?[c.head]:[],...c.members])];for(let c of l){let p=C(c);p.kind==="person"&&!d.has(c)&&(d.add(c),a.push(i("person",p.id,void 0)))}return{members:a,relations:s}}function Ms(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(sn(t).keys()),o=Bn(t),s=Array.isArray(t?.people)?t.people:[],i=new Map(s.flatMap(a=>a?.id&&(a.role==="client"||a.role==="guest")?[[String(a.id),{name:String(a.name||a.id),role:a.role}]]:[]));return jn(pe(e),n,r,o)??Os(nn(e),n,r,o,i)}function id(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&$(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>$(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>$(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Fs(t,e){let n=t.business.roles=t.business.roles||{};if(n[e])return e;let r=e.toLowerCase(),o=Object.entries(n).find(([,a])=>String(a?.title||"").toLowerCase()===r);if(o)return o[0];let s=r.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"role",i=s;for(let a=2;n[i];a++)i=`${s}-${a}`;return n[i]={title:e},i}function Us(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>Ps)throw new Error(`Keep the role under ${Ps} characters.`);return e}function ad(t,e,n){let r=new Set;for(let o=e;o&&!r.has(o);o=t.find(s=>s.type==="reports-to"&&s.from===o)?.to){if(o===n)return!0;r.add(o)}return!1}function Ws(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:$(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:$(o.from),to:$(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function mf(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Ms(n),s=sd(n),i=new Map(s.members.map(u=>[u.ref,u])),a=od(n),d=new Map([...a.agents,...a.people].map(u=>[u.ref,u.name])),l=u=>i.get(u)?.name??d.get(u)??C(u).id,c;switch(e?.op){case"add-member":{let u=/^(agent|person):[^\s:]+$/.test(String(e.member??"").trim())?$(String(e.member).trim()):"";if(!u)throw new Error("Pick an agent or a person to add.");let{kind:g,id:m}=C(u),f=d.get(u);if(!f)throw new Error(g==="agent"?`There is no agent "${m}" on this computer.`:`There is no person "${m}" in your people list. Add them on the People page first.`);if(i.has(u))throw new Error(`${f} is already in the org chart.`);let w=Us(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Fs(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...ke},utilizationTarget:.8}):(r.orgPeople=r.orgPeople||{},r.orgPeople[m]=x?{role:x}:{}),c=`${f} added to the org chart`;break}case"set-role":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Us(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Fs(n,g):void 0;u.kind==="agent"?r.orgChart[u.id].role=m:(r.orgPeople=r.orgPeople||{},r.orgPeople[u.id]=m?{role:m}:{}),c=m?`${u.name} is now ${r.roles[m]?.title||g}`:`${u.name} has no role now`;break}case"remove-member":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=u.kind==="agent"?(r.projects??[]).find(w=>w?.pm===u.id):void 0;if(g)throw new Error(`${u.name} is the project manager of "${g.id}". Give that project another manager first.`);let m=Ws(r,w=>w.from===u.ref||w.to===u.ref),f=id(r,u.ref);u.kind==="agent"?delete r.orgChart[u.id]:r.orgPeople&&(delete r.orgPeople[u.id],Object.keys(r.orgPeople).length===0&&delete r.orgPeople),c=`${u.name} removed from the org chart`+(m?`, with ${m} ${m===1?"line":"lines"}`:"")+(f.length?` and out of ${f.join(", ")}`:"");break}case"add-relation":{let u=String(e.type??"").trim(),g=[String(e.from??"").trim(),String(e.to??"").trim()];if(!g[0]||!g[1]||!u)throw new Error("Pick a member, a kind of relation and a target.");if(!ot.includes(u))throw new Error(`"${u}" is not a kind of relation. Pick reports to, dotted line or acts for.`);let[m,f]=g.map($);for(let x of[m,f])if(!i.has(x))throw new Error(`${l(x)} is not in the org chart. Add them first.`);if(m===f)throw new Error(`${l(m)} cannot be linked to themself.`);let w={from:m,to:f,type:u};if(s.relations.some(x=>x.from===m&&x.to===f&&x.type===u))throw new Error(`${l(m)} already ${on[u]} ${l(f)}.`);if(u==="acts-for"&&i.get(m).kind!=="agent")throw new Error(`Only an agent can act for someone: ${l(m)} is a person.`);if(u==="acts-for"&&i.get(f).kind!=="person")throw new Error(`An agent acts for a person: ${l(f)} is an agent.`);if(u==="reports-to"){let x=s.relations.find(b=>b.type==="reports-to"&&b.from===m);if(x)throw new Error(`${l(m)} already reports to ${l(x.to)}. Remove that line first: each member has one boss.`);if(ad(s.relations,f,m))throw new Error(`${l(m)} cannot report to ${l(f)}: ${l(f)} already reports up to ${l(m)}.`)}if(u==="reports-to"&&i.get(m).kind==="agent"){let x=C(f);r.orgChart[C(m).id].reportsTo=x.kind==="agent"?x.id:f}else r.relations=[...r.relations??[],w];c=`${l(m)} ${on[u]} ${l(f)}`;break}case"remove-relation":{let u={from:$(String(e.from??"")),to:$(String(e.to??"")),type:String(e.type??"")};if(!Ws(r,g=>g.from===u.from&&g.to===u.to&&g.type===u.type))throw new Error("That line is not in the org chart any more. Reload the page.");c=`${l(u.from)} no longer ${on[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get($(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);if(u.kind!=="agent")throw new Error(`Working hours are for agents: ${u.name} is a person.`);let g=nd(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${rd(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Ms(n);if(p&&p!==o)throw new Error(p);for(let u of Object.keys(t))delete t[u];return Object.assign(t,n),c}rt();ji();function Bs(t){let e=[];try{let n=JSON.parse(t.tags??"[]");Array.isArray(n)&&(e=n.filter(r=>typeof r=="string"))}catch{}return{id:t.id,name:t.name,ownerAgent:t.owner_agent??null,unit:t.unit??null,target:t.target===null||t.target===void 0?null:{value:t.target,direction:t.direction==="down"?"down":"up"},rhythm:t.rhythm,source:Un(t.source_spec),tags:e,origin:t.origin,lastReadAt:t.last_read_at??null,lastError:t.last_error??null,createdAt:t.created_at,updatedAt:t.updated_at,archivedAt:t.archived_at??null}}function Hs(t){return{numberId:t.number_id,streakStart:t.streak_start,raisedAt:t.raised_at,cardId:t.card_id??null,raisedFor:t.raised_for??null,reviewer:t.reviewer??null,error:t.error??null}}function an(t){return{numberId:t.number_id,value:t.value??null,error:t.error??null,readAt:t.read_at,periodStart:t.period_start,periodEnd:t.period_end,by:t.by,note:t.note??null}}var Vs=class{constructor(e){this.db=e;e.exec(`
|
|
553
|
+
CREATE TABLE IF NOT EXISTS numbers (
|
|
554
|
+
id TEXT PRIMARY KEY,
|
|
555
|
+
name TEXT NOT NULL,
|
|
556
|
+
owner_agent TEXT,
|
|
557
|
+
unit TEXT,
|
|
558
|
+
target REAL,
|
|
559
|
+
direction TEXT NOT NULL DEFAULT 'up',
|
|
560
|
+
rhythm TEXT NOT NULL DEFAULT 'weekly',
|
|
561
|
+
source_spec TEXT,
|
|
562
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
563
|
+
origin TEXT NOT NULL,
|
|
564
|
+
last_read_at INTEGER,
|
|
565
|
+
last_error TEXT,
|
|
566
|
+
created_at INTEGER NOT NULL,
|
|
567
|
+
updated_at INTEGER NOT NULL,
|
|
568
|
+
archived_at INTEGER
|
|
569
|
+
);
|
|
570
|
+
CREATE TABLE IF NOT EXISTS number_readings (
|
|
571
|
+
number_id TEXT NOT NULL,
|
|
572
|
+
value REAL,
|
|
573
|
+
error TEXT,
|
|
574
|
+
read_at INTEGER NOT NULL,
|
|
575
|
+
period_start INTEGER NOT NULL,
|
|
576
|
+
period_end INTEGER NOT NULL,
|
|
577
|
+
by TEXT NOT NULL,
|
|
578
|
+
note TEXT,
|
|
579
|
+
PRIMARY KEY (number_id, period_start, period_end)
|
|
580
|
+
);
|
|
581
|
+
CREATE INDEX IF NOT EXISTS idx_number_readings_end ON number_readings(number_id, period_end);
|
|
582
|
+
CREATE TABLE IF NOT EXISTS number_alerts (
|
|
583
|
+
number_id TEXT NOT NULL,
|
|
584
|
+
streak_start INTEGER NOT NULL,
|
|
585
|
+
raised_at INTEGER NOT NULL,
|
|
586
|
+
card_id TEXT,
|
|
587
|
+
raised_for TEXT,
|
|
588
|
+
reviewer TEXT,
|
|
589
|
+
error TEXT,
|
|
590
|
+
PRIMARY KEY (number_id, streak_start)
|
|
591
|
+
);
|
|
592
|
+
`)}get(e){let n=this.db.prepare("SELECT * FROM numbers WHERE id = ?").get(e);return n?Bs(n):null}list(e={}){let n=this.db.prepare(`SELECT * FROM numbers ${e.archived?"":"WHERE archived_at IS NULL"} ORDER BY name COLLATE NOCASE, id`).all().map(Bs),r=(e.tags??[]).map(o=>o.toLowerCase());return r.length?n.filter(o=>r.every(s=>o.tags.includes(s))):n}upsert(e,n){let r=this.get(e.id),o=e.target!==void 0?e.target:r?.target??null,s={id:e.id,name:e.name||r?.name||e.id,owner:e.ownerAgent!==void 0?e.ownerAgent:r?.ownerAgent??null,unit:e.unit!==void 0?e.unit:r?.unit??null,target:o?o.value:null,direction:o?o.direction:"up",rhythm:e.rhythm??r?.rhythm??"weekly",source:JSON.stringify(e.source??r?.source??{kind:"manual"}),tags:JSON.stringify(e.tags??r?.tags??[]),origin:e.origin};return this.db.prepare(`
|
|
593
|
+
INSERT INTO numbers (id, name, owner_agent, unit, target, direction, rhythm, source_spec, tags, origin, created_at, updated_at)
|
|
594
|
+
VALUES (@id, @name, @owner, @unit, @target, @direction, @rhythm, @source, @tags, @origin, @now, @now)
|
|
595
|
+
ON CONFLICT(id) DO UPDATE SET name = @name, owner_agent = @owner, unit = @unit, target = @target, direction = @direction,
|
|
596
|
+
rhythm = @rhythm, source_spec = @source, tags = @tags, origin = @origin, updated_at = @now, archived_at = NULL
|
|
597
|
+
`).run({...s,now:n}),this.get(e.id)}archive(e,n){return this.db.prepare("UPDATE numbers SET archived_at = ?, updated_at = ? WHERE id = ? AND archived_at IS NULL").run(n,n,e).changes>0}record(e){this.db.prepare(`
|
|
598
|
+
INSERT INTO number_readings (number_id, value, error, read_at, period_start, period_end, by, note)
|
|
599
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
600
|
+
ON CONFLICT(number_id, period_start, period_end) DO UPDATE SET
|
|
601
|
+
value = excluded.value, error = excluded.error, read_at = excluded.read_at, by = excluded.by, note = excluded.note
|
|
602
|
+
WHERE excluded.value IS NOT NULL OR number_readings.value IS NULL
|
|
603
|
+
`).run(e.numberId,e.value,e.value===null?(e.error??"the read failed").slice(0,300):null,e.readAt,e.periodStart,e.periodEnd,e.by,e.note?e.note.slice(0,300):null)}markRead(e,n,r){this.db.prepare("UPDATE numbers SET last_read_at = ?, last_error = ? WHERE id = ?").run(r,n?n.slice(0,300):null,e)}readings(e,n=50){return this.db.prepare("SELECT * FROM number_readings WHERE number_id = ? ORDER BY period_end DESC, period_start DESC LIMIT ?").all(e,n).map(an)}readingOf(e,n,r){let o=this.db.prepare("SELECT * FROM number_readings WHERE number_id = ? AND period_start = ? AND period_end = ?").get(e,n,r);return o?an(o):null}latestValue(e){let n=this.db.prepare("SELECT * FROM number_readings WHERE number_id = ? AND value IS NOT NULL ORDER BY period_end DESC, period_start DESC LIMIT 1").get(e);return n?an(n):null}alertOf(e,n){let r=this.db.prepare("SELECT * FROM number_alerts WHERE number_id = ? AND streak_start = ?").get(e,n);return r?Hs(r):null}lastAlert(e){let n=this.db.prepare("SELECT * FROM number_alerts WHERE number_id = ? ORDER BY streak_start DESC LIMIT 1").get(e);return n?Hs(n):null}recordAlert(e){this.db.prepare(`
|
|
604
|
+
INSERT OR IGNORE INTO number_alerts (number_id, streak_start, raised_at, card_id, raised_for, reviewer, error)
|
|
605
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
606
|
+
`).run(e.numberId,e.streakStart,e.raisedAt,e.cardId,e.raisedFor,e.reviewer,e.error?e.error.slice(0,300):null)}status(e,n){return G(e,this.readings(e.id,2),n)}};rt();var qs=["missed_twice","missed","no_reading"];function ld(t){return qs.includes(t)}var cd=200;function dd(t,e){let n=null;for(let r of e)if(r.value!==null){if(Ln(r.value,t))break;n=r.periodStart}return n}function Xs(t,e,n={}){let r=[];for(let s of t.list({tags:n.tags})){let i=t.readings(s.id,2),a=G(s,i,e);ld(a)&&r.push({number:s,status:a,latest:i[0]??null,card:t.lastAlert(s.id)})}let o=s=>qs.indexOf(s);return r.sort((s,i)=>o(s.status)-o(i.status))}function ud(t,e,n){let r=t.ownerAgent&&n(t.ownerAgent)?t.ownerAgent:null,o=e&&n(e)?e:null,s=r??o;return s?{raisedFor:s,reviewer:o&&o!==s?o:null}:{error:`no card: ${t.ownerAgent?`its owner ${t.ownerAgent} is not an agent on this node`:"it has no owner agent"}, and numbers.reviewer ${e?`(${e}) is not an agent on this node`:"is not set"}`}}var ve=(t,e)=>t.length>e?`${t.slice(0,e-1)}\u2026`:t;function pd(t,e,n){let o=e.filter(a=>a.value!==null).slice(0,2).map(a=>`${Pn(a.value,t.unit)} for ${Cn({start:a.periodStart,end:a.periodEnd})}`).join(" and "),s=t.target?Mn(t.target,t.unit):"its target",i=ve(t.name,60);return{title:ve(`${t.name} missed its target twice`,120),ask:ve(`${i} was ${o}, against ${s}. Should ${n.raisedFor} find out why and change the plan?`,300),recommend:ve(`Yes: ${n.raisedFor} reads the readings, finds the cause and says what changes${n.reviewer?`; ${n.reviewer} reviews it`:""}.`,300),if_silent:"keep",source:ve(`agentx numbers show ${t.id}`,500),raised_by:n.raisedFor}}function xf(t,e,n){let r=[];for(let o of t.list()){if(!o.target)continue;let s=t.readings(o.id,cd);if(G(o,s,n)!=="missed_twice")continue;let i=dd(o.target,s);if(i===null||t.alertOf(o.id,i))continue;let a=ud(o,e.reviewer,e.hasAgent);if("error"in a){t.recordAlert({numberId:o.id,streakStart:i,raisedAt:n,cardId:null,raisedFor:null,reviewer:null,error:a.error}),e.log?.(`[numbers] ${o.id} missed twice; ${a.error}`),r.push({numberId:o.id,result:"failed",error:a.error});continue}let d={kind:"number",numberId:o.id,streakStart:i,...a.reviewer?{reviewer:a.reviewer}:{}},l=e.raise(pd(o,s,a),d);if(!l.ok){t.recordAlert({numberId:o.id,streakStart:i,raisedAt:n,cardId:null,raisedFor:a.raisedFor,reviewer:a.reviewer,error:l.error}),e.log?.(`[numbers] ${o.id} missed twice; card refused: ${l.error}`),r.push({numberId:o.id,result:"failed",raisedFor:a.raisedFor,error:l.error});continue}t.recordAlert({numberId:o.id,streakStart:i,raisedAt:n,cardId:l.card.id,raisedFor:a.raisedFor,reviewer:a.reviewer,error:null}),e.log?.(`[numbers] ${o.id} missed twice; card ${l.card.id} raised for ${a.raisedFor}${a.reviewer?`, reviewer ${a.reviewer}`:""}`),r.push({numberId:o.id,result:"raised",cardId:l.card.id,raisedFor:a.raisedFor})}return r}rt();Bi();var le=t=>typeof t=="string"?t.trim():"",ln="***";function gd(t){let e=t.match(/^([^?#]*)(?:\?([^#]*))?(#.*)?$/);if(!e||e[2]===void 0)return t;let n=e[2].split("&").map(r=>r.includes("=")?`${r.slice(0,r.indexOf("="))}=${ln}`:r).join("&");return`${e[1]}?${n}${e[3]??""}`}function md(t){if(t.kind==="http-json"){let{headers:e,...n}=t;return{...n,url:gd(Fn(t.url)),...e?{headers:Object.fromEntries(Object.keys(e).map(r=>[r,ln]))}:{}}}return t.kind==="command"?{...t,command:ln}:t}function ce(t,e,n,r=2){let o=t.readings(e.id,Math.max(2,r)),s=G(e,o,n);return{...e,source:md(e.source),status:s,statusWords:On[s],latest:o[0]??null,...r>2?{readings:o}:{}}}function $f(t,e,n,r,o,s={}){let{store:i}=o,a=o.now??Date.now(),d=e.startsWith("/numbers/")?decodeURIComponent(e.slice(9)):"";if(t==="GET"){if(d){let k=i.get(d);if(!k)return{status:404,body:{error:`no number "${d}"`}};let S=Math.min(200,Math.max(3,Number(n.get("limit"))||20));return{status:200,body:{number:ce(i,k,a,S)}}}let b=In(n.get("tags")??"");if(!Array.isArray(b))return{status:400,body:{error:b.error}};if(n.get("review")==="1"){let k=Xs(i,a,{tags:b});return{status:200,body:{count:k.length,numbers:k.map(S=>({...ce(i,S.number,a),card:S.card}))}}}let y=i.list({archived:n.get("archived")==="1",tags:b});return{status:200,body:{count:y.length,numbers:y.map(k=>ce(i,k,a))}}}if(t!=="POST"||d)return{status:405,body:{error:"use GET /numbers, GET /numbers/:id or POST /numbers"}};let l=r??{},c=le(l.action).toLowerCase();if(!["create","record","archive"].includes(c))return{status:400,body:{error:`unknown action "${c}": use create, record or archive`}};let p=le(l.agentId);if(!p||!o.hasAgent(p))return{status:400,body:{error:"agentId must be an agent on this node"}};if(!o.runningTurn(p,s))return{status:403,body:{error:`no running turn of "${p}" matches this call: record numbers from inside your own run`}};let u=le(l.id),g=u?i.get(u):null,m=g&&g.ownerAgent&&g.ownerAgent!==p?`number "${g.id}" belongs to ${g.ownerAgent}`:null;if(c==="create"){let{action:b,agentId:y,...k}=l,S=Wn(k,"agent");if("error"in S)return{status:400,body:{error:S.error}};if(g?.origin==="config")return{status:409,body:{error:`number "${g.id}" is set up in agentx.json: change it there`}};if(m)return{status:403,body:{error:m}};if(!g&&!S.name)return{status:400,body:{error:"create needs name: what the number counts, in a few plain words"}};if(S.ownerAgent&&!o.hasAgent(S.ownerAgent))return{status:400,body:{error:"owner must be an agent on this node"}};let K=i.upsert({...S,ownerAgent:S.ownerAgent??g?.ownerAgent??p},a);return{status:g?200:201,body:{number:ce(i,K,a)}}}if(!u)return{status:400,body:{error:`${c} needs id: the number's id (list shows them)`}};if(!g)return{status:404,body:{error:`no number "${u}"`}};if(m)return{status:403,body:{error:m}};if(c==="archive")return g.origin==="config"?{status:409,body:{error:`number "${g.id}" is set up in agentx.json: take it out there`}}:(i.archive(g.id,a),{status:200,body:{number:ce(i,i.get(g.id),a)}});let f=typeof l.value=="number"?l.value:le(l.value)?Number(le(l.value).replace(/,/g,"")):NaN;if(!Number.isFinite(f))return{status:400,body:{error:"record needs value: a number (a failed read is not recorded as 0)"}};let w=l.from!==void 0&&l.from!==""?Nn(l.from,l.to):Dn(g.rhythm,a);if("error"in w)return{status:400,body:{error:w.error}};if(w.start>a)return{status:400,body:{error:"the window starts in the future"}};let x=le(l.note).slice(0,300);return i.record({numberId:g.id,value:f,readAt:a,periodStart:w.start,periodEnd:w.end,by:p,note:x||null}),{status:200,body:{number:ce(i,g,a)}}}var fd={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},zs=class{constructor(e=fd,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)}},hd="That code didn't work. Check it, or run agentx app pair for a new one.",bd=400;async function Rf(t,e){let n=Date.now(),r=e.log??(l=>console.log(l)),o=t.socket.remoteAddress||"unknown",s=e.limiter.retryAfter(o);if(s>0)return r(`[app] pair-code refused from ${o}: locked out for ${s}s more`),{status:429,body:{error:"too many attempts",retryAfter:s},retryAfter:s};let i=null;try{i=(await jr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await yd(n,e.minMs??bd),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:hd}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function yd(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as Ld}from"child_process";import{mkdtempSync as Rd,rmSync as Td,writeFileSync as Id}from"fs";import{tmpdir as Dd}from"os";import{join as Qs}from"path";import{randomBytes as wd}from"crypto";function I(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},cn={height:56,keep:52},Ks=`
|
|
553
607
|
:root {
|
|
554
608
|
--ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
|
|
555
609
|
--ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
|
|
@@ -678,33 +732,33 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
|
|
|
678
732
|
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
|
679
733
|
kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
|
|
680
734
|
button.primary kbd { color: inherit; opacity: .7; }
|
|
681
|
-
`;var
|
|
735
|
+
`;var Gs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Ys=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function xd(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Gs(n):Ys(n)}`}function kd(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Ys(n)],Gs(n)].join(" ")}function vd(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 Sd(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var dn=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>`,Ed=dn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),$d=dn('<path d="m6 15 6-6 6 6"/>'),_d=dn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Js(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=wd(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=or(t),l=s.map((u,g)=>`<button class="opt" role="radio" aria-checked="false" data-i="${g}"><span class="n">${g+1}</span><span class="t">${I(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${I(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:nr,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:d.index};return`<!doctype html>
|
|
682
736
|
<html lang="en"><head><meta charset="utf-8">
|
|
683
737
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
|
|
684
738
|
<title>AgentX</title>
|
|
685
|
-
<style>${
|
|
739
|
+
<style>${Ks}</style></head>
|
|
686
740
|
<body><div class="wrap"><main class="card${e.still?" still":""}">
|
|
687
|
-
<div class="head" title="Drag to move"><span class="avatar">${
|
|
688
|
-
<div class="who"><b>${
|
|
741
|
+
<div class="head" title="Drag to move"><span class="avatar">${I(vd(r))}</span>
|
|
742
|
+
<div class="who"><b>${I(r)}</b><span>${I(xd(t.created_at,n))}</span></div>
|
|
689
743
|
<span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
|
|
690
|
-
<button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${
|
|
691
|
-
<div class="body"><h1 dir="auto">${
|
|
692
|
-
${t.context?`<p class="context" dir="auto">${
|
|
693
|
-
<p class="ask" dir="auto">${
|
|
744
|
+
<button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${$d}</button></div>
|
|
745
|
+
<div class="body"><h1 dir="auto">${I(t.title)}</h1>
|
|
746
|
+
${t.context?`<p class="context" dir="auto">${I(t.context)}</p>`:""}
|
|
747
|
+
<p class="ask" dir="auto">${I(t.ask)}</p>
|
|
694
748
|
${l||c?`<div class="label-row">${l?'<span class="label">Pick one</span>':""}${c}</div>`:""}
|
|
695
749
|
${l?`<div class="options" role="radiogroup">${l}</div>`:""}
|
|
696
|
-
${d.why?`<p class="why" dir="auto">${
|
|
750
|
+
${d.why?`<p class="why" dir="auto">${I(d.why)}</p>`:""}
|
|
697
751
|
${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>
|
|
698
752
|
<textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
|
|
699
|
-
<div class="notes"><div>${
|
|
700
|
-
<div>${
|
|
753
|
+
<div class="notes"><div>${Ed}<span>${a?`It stays on the ${Ce} until you close it.`:`If you don't answer by ${I(kd(t.expires,n))}: ${I(t.if_silent)}.`}</span></div>
|
|
754
|
+
<div>${_d}<span>Nothing goes out until you click.</span></div></div>
|
|
701
755
|
</div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
|
|
702
756
|
<button class="btn" id="no">${a?"Drop":"No"}</button>
|
|
703
|
-
<button class="btn primary" id="yes">${
|
|
757
|
+
<button class="btn primary" id="yes">${Sd(t)}<kbd>\u2318\u21A9</kbd></button></div>
|
|
704
758
|
</main></div>
|
|
705
759
|
<script type="application/json" id="data">${JSON.stringify(p).replace(/</g,"\\u003c")}</script>
|
|
706
|
-
<script nonce="${o}">${
|
|
707
|
-
</body></html>`}var
|
|
760
|
+
<script nonce="${o}">${Ad}</script>
|
|
761
|
+
</body></html>`}var Ad=`
|
|
708
762
|
(function () {
|
|
709
763
|
var d = JSON.parse(document.getElementById("data").textContent);
|
|
710
764
|
var root = document.documentElement;
|
|
@@ -793,10 +847,10 @@ ${t.draft?`<div class="label-row" id="msg"><span class="label">Message</span><sp
|
|
|
793
847
|
});
|
|
794
848
|
} catch (e) {}
|
|
795
849
|
})();
|
|
796
|
-
`;var
|
|
850
|
+
`;var Cd=440,Nd=`
|
|
797
851
|
ObjC.import("Cocoa"); ObjC.import("WebKit")
|
|
798
852
|
function run(argv) {
|
|
799
|
-
var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+
|
|
853
|
+
var path = argv[0], side = ${B.side}, gripTop = ${B.top}, gripEnd = ${B.top+cn.height}, keep = ${cn.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
|
|
800
854
|
var app = $.NSApplication.sharedApplication
|
|
801
855
|
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
|
|
802
856
|
ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
|
|
@@ -868,29 +922,29 @@ function run(argv) {
|
|
|
868
922
|
}
|
|
869
923
|
function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
|
|
870
924
|
function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
871
|
-
`;function
|
|
872
|
-
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&
|
|
873
|
-
`).trim():"",!i||i.length>
|
|
874
|
-
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function
|
|
875
|
-
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function
|
|
925
|
+
`;function Od(t,e){let n=t.trim().split(`
|
|
926
|
+
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&ei.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,`
|
|
927
|
+
`).trim():"",!i||i.length>tr.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Zs(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=Rd(Qs(Dd(),"agentx-card-"));try{let s=Qs(o,"card.html");Id(s,Js(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",Nd,s,String(Cd),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?Od(a.stdout,t):null}finally{Td(o,{recursive:!0,force:!0})}}var ei=["not now","timed out","closed"],Pd=(t,e,n)=>new Promise(r=>{try{Ld(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),ti=160,un=15e3;function ni(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>ti?e.slice(0,ti):e}async function Md(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?Wr(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],un),!!e.speak)if(o){let a;await Promise.race([o(ni(t)),new Promise(d=>{a=setTimeout(d,un)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",ni(t)],un)}}function si(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function Fd(t,e,n){return si(["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 ri(t,e,n,r,o){return si(["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(`
|
|
928
|
+
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function oi(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
|
|
929
|
+
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function pn(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
|
|
876
930
|
|
|
877
|
-
`)}async function
|
|
931
|
+
`)}async function ii(t,e,n={}){let r=n.run??Pd,o=(e.style??"card")==="card",s=Md(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Zs(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,Ud(t,e,r)}async function Ud(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 l=await n("/usr/bin/osascript",Fd(s,pn(t),t.choices),o);if(i=l.stdout.replace(/\n$/,""),!l.ok||!t.choices.includes(i))return{action:"dismiss"};if(!t.draft)return{action:"yes",choice:i}}if(t.draft){let l=i?`${i}
|
|
878
932
|
|
|
879
|
-
Message (edit it if you like):`:`${
|
|
933
|
+
Message (edit it if you like):`:`${pn(t)}
|
|
880
934
|
|
|
881
|
-
Message (edit it if you like):`,p=await n("/usr/bin/osascript",
|
|
882
|
-
Answer it on the Desk.`}}import{closeSync as
|
|
883
|
-
`)[0]}); Siri voices will not switch`),null}}var
|
|
884
|
-
`).pop()?.slice(0,160)??""}`))})})}
|
|
885
|
-
`)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function
|
|
886
|
-
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function
|
|
935
|
+
Message (edit it if you like):`,p=await n("/usr/bin/osascript",ri(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,rr(t.draft,i)),o),u=p.ok?oi(p.stdout):null;if(u?.button==="Send"){let g=u.text.trim();return g?{action:"yes",...i?{choice:i}:{},text:g}:{action:"dismiss"}}return u?.button==="No"?{action:"no"}:{action:"dismiss"}}let a=await n("/usr/bin/osascript",ri(s,pn(t),["Not now","No","Yes"],r),o),d=a.ok?oi(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var fn=24*36e5,gn=!1,Wd=10*6e4,ai=-1/0;function li(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o,passAt:s,wanted:i=[]}=N(t.root),a=s?Date.parse(s):NaN,d=te(t.root,"pending").filter(c=>Date.parse(c.expires)>n),l=d.find(c=>i.includes(`card:${c.id}`));if(l)return l;for(let c of d){let p=`card:${c.id}`;if(r[p]||!e(c)||Xr(t.root,c.id,n))continue;let u=o[p];if(u&&Date.parse(u)>n)continue;let g=Date.parse(c.created_at);if(!(n-g>fn&&!(g<=a)))return c}return null}function mn(t){try{return J(t)?.listByState("needs_attention")??[]}catch{return[]}}var ci=new Map;function jd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?mn(t).find(s=>{let i=`request:${s.id}`,a=o[i];return ci.get(s.id)===Y(s,ct.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=fn})??null:null}function Bd(t,e){return{id:t.id,title:Y(t,ct.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+fn).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function ih(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(gn)return"busy";let o=li(e,t.reaches)?null:jd(e,t.reaches),s=o?Bd(o,e.now??Date.now()):li(e,t.reaches);if(!s)return"none";let i=(t.focus??As)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:sr(s);if(d){if(o)ci.set(o.id,s.title);else{let l=[...te(e.root,"pending").map(c=>`card:${c.id}`),...mn(e).map(c=>`request:${c.id}`)];vt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,ir(s,d)),"returned"}gn=!0;try{let l=[...te(e.root,"pending").map(w=>`card:${w.id}`),...mn(e).map(w=>`request:${w.id}`)];vt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-ai<Wd;o&&n.speak&&(ai=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??ii)(s,p?{...n,speak:!1}:n,{from:u,speak:t.speak});if(g.action==="dismiss")return r(`[approvals] popup: ${a} left waiting: ${g.why??"no answer"} (${yr(i)} when shown)`),"shown";if(!(o?J(e)?.get(o.id)?.state==="needs_attention":ge(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await Co(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{gn=!1}}function ah(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:")?ge(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(ro(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 Hd,mkdirSync as Vd,readFileSync as qd,renameSync as Xd,writeFileSync as zd}from"fs";import{dirname as Kd,resolve as Gd}from"path";var Yd=["all","urgent","off"],Jd=24*36e5,di=24*36e5,Qd=30*24*36e5,ui=t=>Yd.includes(t);function uh(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:ui(e)?e:"off",computer:ui(n)?n:t.popupEnabled?"all":"off"}}function gi(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Jd}function pi(t,e,n){return t==="all"||t==="urgent"&&gi(e,n)}function mi(t){return Gd(t,".agentx","desk-routed.json")}function Zd(t){let e=mi(t);if(!Hd(e))return null;try{let n=JSON.parse(qd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function hn(t,e){let n=mi(t);Vd(Kd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;zd(r,JSON.stringify(e,null,2)),Xd(r,n)}async function ph(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Zd(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return hn(e,{items:p}),i.primed=!0,i}let l=[],c=[];for(let p of r.items){let u=d.items[p.key];if(u){u.seen=a,u.computerHeld&&n-Date.parse(u.at)>di&&delete u.computerHeld,u.computerHeld&&c.push(p);continue}d.items[p.key]={at:a,seen:a};let g=p.askedAt?Date.parse(p.askedAt):n;n-g<=di&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Qd&&delete d.items[p];hn(e,d);for(let p of l)if(pi(o.phone,p,n))try{await t.phone(p,gi(p,n)),i.phone.push(p.key)}catch(u){s(`[desk] ${p.key}: not sent to the phone: ${u?.message??u}`)}if(t.computer){let p=!1;for(let u of[...c,...l]){let g=d.items[u.key];if(!pi(o.computer,u,n)){g.computerHeld&&(delete g.computerHeld,p=!0);continue}try{let m=await t.computer(u);m&&i.computer.push(u.key),m&&g.computerHeld&&(delete g.computerHeld,p=!0),!m&&!g.computerHeld&&(g.computerHeld=!0,p=!0)}catch(m){s(`[desk] ${u.key}: not shown on this computer: ${m?.message??m}`),g.computerHeld&&(delete g.computerHeld,p=!0)}}p&&hn(e,d)}return(i.phone.length||i.computer.length)&&s(`[desk] routed: ${i.phone.length} to the phone, ${i.computer.length} to this computer`),i}function gh(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
|
|
936
|
+
Answer it on the Desk.`}}import{closeSync as Se,createReadStream as eu,fstatSync as tu,openSync as nu,realpathSync as fi}from"fs";import{isAbsolute as ru,resolve as hi,sep as bi}from"path";var wh="/app-files",ou=/^[A-Za-z0-9_.:-]{1,64}$/;function su(t,e,n=process.cwd()){if(!e||e.length>W.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 ${ft}/ first`};if(!fe(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=fi(hi(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=fi(ru(e)?e:hi(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+bi))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${ft}/ first`};let s=fe(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function iu(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 au(t,e,n){return{"Content-Type":t,"Content-Disposition":iu(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 lu(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 xh(t,e,n,r){let o=(x,b)=>{e.writeHead(x,{"Content-Type":"application/json","Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),e.end(JSON.stringify(b))};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(!ou.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 d=su(a,i,r.cwd);if(!d.ok)return r.log?.(`[app-files] refused ${JSON.stringify(i.slice(0,200))} from ${s}: ${d.error}`),o(d.status,{error:d.error});let l;try{l=nu(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=tu(l);if(!x.isFile())return Se(l),o(404,{error:"not a file"});c=x.size}catch{return Se(l),o(404,{error:"file not found"})}if(c>W.bytes)return Se(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(bi).pop()||"file",u=au(d.mime,p,d.kind),g=lu(t.headers.range,c);if(g==="unsatisfiable"){Se(l),e.writeHead(416,{...u,"Content-Range":`bytes */${c}`}),e.end();return}let{start:m,end:f}=g??{start:0,end:c-1};if(e.writeHead(g?206:200,{...u,"Content-Length":String(c?f-m+1:0),...g?{"Content-Range":`bytes ${m}-${f}/${c}`}:{}}),t.method==="HEAD"||c===0){Se(l),e.end();return}let w=eu("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as Ee}from"child_process";import{readFileSync as cu,writeFileSync as du}from"fs";import{tmpdir as uu}from"os";import{join as pu}from"path";Hn();var yi=t=>t&&t!==1?Math.round(175*t):null,Ze=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function gu(){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=cu(t,"utf8").trim();if(e)return e}catch{}return null}function Th(t=gu()){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",...Ze(n.voice.rate)?{voice_settings:{speed:Ze(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=pu(uu(),`agentx-say-${process.pid}-${++e}.mp3`);return du(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Q(`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 wi(t,e){let n=t.languages&&Ie(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var mu=(t,e="")=>{let n=wi(t,e),r=yi(t.rate);return[...n&&!Vo(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function fu(t,e,n){if(!n)return["say",mu(t,e)];let r=wi(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Ih(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function Dh(t=bn()){if(t)try{Ee("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function Ch(t=bn()){if(t)try{Ee("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function bn(t={},e){if(!Ct(t))return null;try{return zo(e)}catch(n){return Q("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
|
|
937
|
+
`)[0]}); Siri voices will not switch`),null}}var Nh=(t,e)=>{if(!t){let[n,r]=fu(e.voice,e.text,bn()),o=yi(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=Ee(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?Ee("afplay",[t],{stdio:"ignore"}):Ee("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as xi}from"child_process";import{accessSync as hu,constants as bu,readFileSync as ki}from"fs";import{homedir as yu}from"os";import{basename as de,delimiter as vi,dirname as wu,extname as xu,join as yn}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function Si(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)>z.ms+2e3?{status:413,error:xn()}:null}var xn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,ku={"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 Ei(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return ku[e]??null}function $i(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 kn(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 wn(t,e,n=process.env.PATH??""){let r=yu(),o=[yn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(vi).filter(Boolean)];for(let s of[e,...o.map(i=>yn(i,t))])if(s)try{return hu(s,bu.X_OK),s}catch{}return null}function Uh(t){return{key:t,mlx:wn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:wn("whisper",process.env.AGENTX_WHISPER),ffmpeg:vu()}}var vu=()=>wn("ffmpeg",process.env.AGENTX_FFMPEG);async function _i(t,e){return e?Su(t,e):null}async function Su(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await Eu(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 Ai(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ki(t)],{type:e}),de(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 Ri(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:`${wu(r)}${vi}${process.env.PATH??""}`};await $u(e,s,12e4,i);try{return ki(yn(o,de(n,xu(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Eu(t,e,n){return new Promise((r,o)=>{let s=xi(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${de(t)} took too long`))},n);s.stderr.on("data",d=>{i=(i+d).slice(-8192)}),s.on("error",d=>{clearTimeout(a),o(d)}),s.on("exit",d=>{clearTimeout(a),d===0?r(i):o(new Error(`${de(t)} exited ${d}`))})})}function $u(t,e,n,r=process.env){return new Promise((o,s)=>{let i=xi(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${de(t)} took longer than ${n/1e3}s`))},n);i.stdout.on("data",c=>{a.length<4096&&(a+=c)}),i.stderr.on("data",c=>{d.length<4096&&(d+=c)}),i.on("error",c=>{clearTimeout(l),s(c)}),i.on("exit",c=>{clearTimeout(l),c===0?o(a):s(new Error(`${de(t)} exited ${c}: ${d.trim().split(`
|
|
938
|
+
`).pop()?.slice(0,160)??""}`))})})}qn();Hi();import{mkdtemp as _u,rm as Au,writeFile as Ru}from"fs/promises";import{tmpdir as Tu}from"os";import{join as Ti}from"path";var Iu=64*1024,Du=2,vn=0;function Yh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Jh(t,e,n,r){return t.method!=="POST"?A(e,405,{error:"POST"}):n==="/voice/transcribe"?Cu(t,e,r):Lu(t,e,r)}async function Cu(t,e,n){let r=String(t.headers["content-type"]||""),o=Ei(r);if(!o)return A(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=Si(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),A(e,s.status,{error:s.error});let i=await Ii(t,z.bytes);if(!i)return A(e,413,{error:Fu()});if(!i.length)return A(e,400,{error:"The recording is empty."});if(vn>=Du)return A(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=$i(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+kn(a,d);return A(e,503,{error:"Voice input isn't set up on this computer.",hint:`Install ffmpeg ${p} for voice input from the phone.${u}`,setup:!1})}if(!l.length)return A(e,503,{error:"Voice input isn't set up on this computer.",hint:kn(a,d),setup:!1});vn++;let c;try{let p=await _u(Ti(Tu(),"agentx-phone-voice-"));try{c=await Nu(p,`speech.${o}`,i,r,d,l,n)}finally{await Au(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{vn--}A(e,c[0],c[1])}async function Nu(t,e,n,r,o,s,i){let a=Ti(t,e);if(await Ru(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??_i)(a,o.ffmpeg);if(l==null)return[422,{error:"This computer couldn't read the recording. Try again."}];if(l*1e3>z.ms+2e3)return[413,{error:xn()}]}let d=[];for(let l of s)try{let c=await Ou(l,a,r,o,t,i);return i.log(`[voice] phone recording transcribed with ${l} (${Math.round(n.length/1024)} KB)`),c?[200,{text:c,engine:l}]:[422,{error:"No words were heard. Hold the orb and speak, then let go.",engine:l}]}catch(c){let p=String(c?.message??c).split(`
|
|
939
|
+
`)[0].slice(0,200);d.push(`${l}: ${p}`),i.log(`[voice] phone transcription with ${l} failed: ${p}`)}return[502,{error:"Speech to text failed on this computer.",detail:d.join("; ")}]}function Ou(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return Ai(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return Ri(t,a,e,r.ffmpeg,o)}async function Lu(t,e,n){let r=await Ii(t,Iu);if(!r)return A(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return A(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 A(e,400,{error:"agent is required"});let a=Pu(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return A(e,422,{error:"Nothing in this answer can be said aloud."});let d=n.pronounce?n.pronounce(a):a,l=n.voiceOf(s,i);if(!l)return A(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>A(e,g,{fallback:"browser",reason:u,text:d});if(l.provider!=="elevenlabs")return c("This agent speaks with a system voice, which only plays on the computer.");let p=n.elevenLabsKey();if(!p)return c("No ElevenLabs key is set on this computer.");try{let u=await(n.synth??Mu)(p,l,d);e.writeHead(200,{"Content-Type":"audio/mpeg","Content-Length":u.length,"Cache-Control":"no-store","X-Spoken-Chars":String(d.length)}),e.end(u)}catch(u){return n.log(`[voice] phone answer synthesis failed: ${String(u?.message??u).split(`
|
|
940
|
+
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function Pu(t,e){let n=De(Oe(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Vn(n,e)}async function Mu(t,e,n){let r=Ze(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 Fu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function Qh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Bt(Ut(t,o,n.voice)):null}function Ii(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 A(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}qn();var Uu="[Live voice call on the owner's watch or headset. Your answer is read aloud to them and they can't see a screen. Answer what they just said, in a few short spoken sentences.]",Wu="operator",ju=50,Di=4,Ci=500;function Bu(t){let e={channel:"app",chatId:t.chatId,sender:Wu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${Uu}
|
|
887
941
|
|
|
888
|
-
${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function
|
|
942
|
+
${t.message}`:t.message;return t.node==="local"?{path:"/task",body:{agent:t.agent,message:n,stream:!0,context:e}}:{path:"/mesh/task",body:{peer:t.node,agent:t.agent,message:n,stream:!0,context:e}}}async function rb(t,e,n,r){let{path:o,body:s}=Bu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:mr(u,m),artifacts:[]}:Oe(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?De(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:Vu(x);return{status:p,text:w,tools:d,files:f.artifacts,...b?{ui:b}:{},...g?{error:g}:{}}};try{let p=await fetch(t.url.replace(/\/+$/,"")+o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...t.token?{Authorization:`Bearer ${t.token}`}:{},...t.operatorKey?{"X-AgentX-Operator":t.operatorKey}:{}},body:JSON.stringify(s),signal:n});if(!p.ok||!p.body){let u=await p.json().then(g=>g?.error).catch(()=>"");return c("error",i,u||`AgentX answered HTTP ${p.status}.`)}for await(let u of qu(p.body)){r(u.event,u.data);let g=u.data??{};if(u.event==="start")a=g.rich===!1;else if(u.event==="text"&&typeof g.text=="string")i+=g.text;else if(u.event==="tool"&&g.status==="start"&&d.length<ju){let m={name:String(g.name||"tool").slice(0,80),...g.arg?{arg:String(g.arg).slice(0,80)}:{}};d.push(m),g.id&&l.set(String(g.id),m)}else if(u.event==="tool"&&g.status==="result"&&g.error===!0&&l.has(String(g.id)))l.get(String(g.id)).error=!0;else{if(u.event==="done")return c("done",typeof g.content=="string"&&g.content?g.content:i);if(u.event==="error")return c("error",i,Hu(g.error))}}return n.aborted?c("stopped",i):c("error",i,"The connection to the agent closed before it answered.")}catch(p){return n.aborted?c("stopped",i):c("error",i,`Could not reach AgentX: ${p?.message||p}`)}}function Hu(t){let e=String(t||"The agent could not answer.");return cr(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function Vu(t){if(!t)return;let e=i=>/^https?:\/\//i.test(i)&&i.length<=2048,n={},r=(t.buttons??[]).filter(i=>e(i.url)).slice(0,8).map(i=>({label:i.label.slice(0,80),url:i.url}));r.length&&(n.buttons=r),t.poll&&(n.poll={question:t.poll.question.slice(0,300),options:t.poll.options.slice(0,10).map(i=>i.slice(0,100)),multiple:t.poll.multiple===!0}),t.media&&e(t.media.url)&&(n.media={type:t.media.type,url:t.media.url,...t.media.caption?{caption:t.media.caption.slice(0,300)}:{}});let o=(t.quickReplies??[]).slice(0,Di).map(i=>i.slice(0,Ci));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,Di).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,Ci)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*qu(t){let e=t.getReader(),n=new TextDecoder,r="";try{for(;;){let{done:o,value:s}=await e.read();if(o)break;r+=n.decode(s,{stream:!0}).replace(/\r\n/g,`
|
|
889
943
|
`);let i;for(;(i=r.indexOf(`
|
|
890
944
|
|
|
891
945
|
`))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
|
|
892
946
|
`))c.startsWith("event:")?d=c.slice(6).trim():c.startsWith("data:")&&l.push(c.slice(5).replace(/^ /,""));if(l.length)try{yield{event:d,data:JSON.parse(l.join(`
|
|
893
|
-
`))}}catch{}}}}finally{e.releaseLock()}}var
|
|
947
|
+
`))}}catch{}}}}finally{e.releaseLock()}}var Ni=["custom","announce"];function sb(t,e){let n=t.nodeName,r=t.recent().filter(s=>Ni.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function ib(t,e={}){let n=e.now??Date.now(),r=Math.max(1,Math.min(200,Math.floor(e.limit||50))),o=new Map;for(let b of t)for(let y of b.events)Ni.includes(y.kind)&&!o.has(y.id)&&o.set(y.id,y);let s=[...o.values()].sort((b,y)=>Date.parse(b.at)-Date.parse(y.at)||b.id.localeCompare(y.id)),i=new Map,a=new Map,d=new Set;for(let b of t)for(let y of b.wakes){let k=y.node||b.node,S=`${k}#${y.agentId}#${y.eventId}`;if(d.has(S))continue;d.add(S);let K=i.get(y.eventId)??[];if(K.push(zu(y,k,n)),i.set(y.eventId,K),y.status!=="skipped"){let Ae=`${y.agentId}#${y.rootId}`,h=a.get(Ae)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(Ae,h)}}for(let b of i.values())b.sort((y,k)=>y.decidedAt-k.decidedAt||y.agentId.localeCompare(k.agentId));let l=new Map,c=[];for(let b of s){let y=Xu(b,o,a,c);y&&y!==b.id&&l.set(b.id,y),c.push(b)}let p=b=>{let y=b;for(let k=0;k<50;k++){let S=l.get(y);if(!S)return y;y=S}return y},u=new Map,g=b=>({event:b,wakes:i.get(b.id)??[]});for(let b of s){let y=p(b.id);y===b.id?u.set(b.id,{...g(b),replies:[]}):u.get(y)?.replies.push(g(b))}let m=b=>Math.max(Date.parse(b.event.at),...b.replies.map(y=>Date.parse(y.event.at))),f=[...u.values()].sort((b,y)=>m(y)-m(b)),w=[...i.values()].flat(),x=b=>w.filter(y=>b.includes(y.status)).length;return{threads:f.slice(0,r),total:f.length,counts:{events:s.length,wakes:w.length,ran:x(["ran"]),waiting:x(["waiting","held","running"]),timedOut:x(["timed-out","dropped"]),failed:x(["failed"]),skipped:x(["skipped"])}}}function Xu(t,e,n,r){if(t.parentId&&e.has(t.parentId))return t.parentId;let o=Date.parse(t.at);if(t.agentId){let s=(n.get(`${t.agentId}#${t.rootId}`)??[]).filter(i=>i.eventId!==t.id&&e.has(i.eventId)&&Date.parse(e.get(i.eventId).at)<=o).sort((i,a)=>a.at-i.at)[0];if(s)return s.eventId}if(t.rootId!==t.id)for(let s=r.length-1;s>=0;s--){let i=r[s];if(i.rootId===t.rootId&&(i.agentId??i.node)!==(t.agentId??t.node))return i.id}}function zu(t,e,n){let r={agentId:t.agentId,node:e,status:t.status,decidedAt:t.decidedAt,attempts:t.attempts};if(t.reason&&(r.reason=t.reason),t.startedAt&&(r.startedAt=t.startedAt),t.endedAt&&(r.endedAt=t.endedAt),t.taskId&&(r.taskId=t.taskId),t.error&&(r.error=t.error),t.status!=="skipped"){let o=t.startedAt??t.endedAt??n;r.waitedMs=Math.max(0,o-t.decidedAt)}return r}import{existsSync as M,readFileSync as _n,writeFileSync as An,mkdirSync as et,readdirSync as $n,rmSync as Ku,statSync as U}from"fs";import{resolve as Oi,relative as Gu,dirname as Rn,join as ee,extname as $e,basename as Tn}from"path";var D=200*1024,Li=new Set([".md",".markdown",".txt"]),ue=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"]),Yu=6,Ju=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function H(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=Oi(t);if(M(n)||et(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=Oi(n,e);if(Gu(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function Pi(t){let e=$e(t).toLowerCase();if(!Li.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function Sn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function db(t){let e=H(t,"."),n=[],r=new Set,o=[];try{o=$n(e)}catch{}for(let a of Ju){let d=ee(e,a);if(M(d)&&U(d).isFile()){let l=U(d).size,c=l>0&&l<D?En(d):"";n.push({path:a,title:Sn(c,a),size:l,exists:!0}),r.add(a)}else n.push({path:a,title:a,size:0,exists:!1}),r.add(a)}for(let a of o){if(r.has(a))continue;let d=ee(e,a);try{let l=U(d);if(!l.isFile()||!Li.has($e(a).toLowerCase()))continue;let c=l.size>0&&l.size<D?En(d):"";n.push({path:a,title:Sn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=ee(e,".claude","skills");if(M(i))try{for(let a of $n(i)){let d=ee(i,a),l;try{l=U(d)}catch{continue}if(!l.isDirectory())continue;let c=ee(d,"SKILL.md");if(!M(c))continue;let p=U(c),u=p.size<D?En(c):"";s.push({slug:a,title:Sn(u,a),size:p.size,path:`.claude/skills/${a}/SKILL.md`})}}catch{}return s.sort((a,d)=>a.slug.localeCompare(d.slug)),{identity:n,skills:s,workspace:e}}function En(t){try{return _n(t,"utf-8")}catch{return""}}function ub(t,e){let n=H(t,e);if(Pi(n),!M(n))return{path:e,content:""};if(U(n).size>D)throw new Error(`File is too large to edit in the admin panel (> ${D/1024} KB).`);return{path:e,content:_n(n,"utf-8")}}function pb(t,e,n){let r=H(t,e);Pi(r);let o=Buffer.from(n,"utf-8");if(o.length>D)throw new Error(`File too large (${o.length} > ${D} bytes).`);return et(Rn(r),{recursive:!0}),An(r,o),{path:e,bytes:o.length}}function gb(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=H(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);et(Rn(o),{recursive:!0});let s=n.content?.trim()?n.content:Qu(e,n.title);return An(o,s),{slug:e,path:r}}function mb(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);if(!U(n).isDirectory())throw new Error(`Skill path is not a directory: ${e}`);return Ku(n,{recursive:!0,force:!0}),{slug:e}}function fb(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(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,d){if(a>Yu)return;let l=[];try{l=$n(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=ee(s,c),u=i?`${i}/${c}`:c,g;try{g=U(p)}catch{continue}if(g.isDirectory())d.push({path:`${u}/`,kind:"dir",size:0,editable:!1}),o(p,u,a+1,d);else if(g.isFile()){let m=$e(c).toLowerCase(),f=ue.has(m)||ue.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:f&&g.size<D})}}}}function hb(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=H(t,`.claude/skills/${e}/${n}`);if(!M(r)||!U(r).isFile())throw new Error(`File not found: ${n}`);let o=$e(r).toLowerCase(),s=Tn(r).toLowerCase();if(!ue.has(o)&&!ue.has(s))throw new Error(`File type not editable: ${n}`);if(U(r).size>D)throw new Error(`File too large to edit (> ${D/1024} KB): ${n}`);return{path:n,content:_n(r,"utf-8")}}function bb(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=H(t,`.claude/skills/${e}/${n}`),s=$e(o).toLowerCase(),i=Tn(o).toLowerCase();if(!ue.has(s)&&!ue.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>D)throw new Error(`File too large (${a.length} > ${D} bytes).`);return et(Rn(o),{recursive:!0}),An(o,a),{path:n,bytes:a.length}}function yb(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=H(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(ee(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 Qu(t,e){return`# ${e?.trim()||t}
|
|
894
948
|
|
|
895
949
|
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.
|
|
896
950
|
|
|
@@ -903,7 +957,7 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
903
957
|
|
|
904
958
|
\`\`\`bash
|
|
905
959
|
# Example invocation
|
|
906
|
-
claude-code ${
|
|
960
|
+
claude-code ${Tn(t)} --arg value
|
|
907
961
|
\`\`\`
|
|
908
|
-
`}
|
|
909
|
-
//# sourceMappingURL=chunk-
|
|
962
|
+
`}Jn();var Mi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function Fi(t){return{...Mi,...t??{},regions:{...t?.regions??{}},buffer:{...Mi.buffer,...t?.buffer??{}}}}function kb(t){try{return Fi(Yn(t).screen)}catch{return Fi(void 0)}}var Zu=/^[a-z][\w-]*$/,Ui=["window","screen","menubar","notifications"];function _e(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 tt=(t,e)=>_e(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function Wi(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 vb(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=tt(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=tt(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=tt(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=_e(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=_e(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(!Zu.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=Wi(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=_e(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=_e(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=tt(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&&!Ui.includes(r)&&!n.regions?.[r])try{Wi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...Ui,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{zr as a,np as b,en as c,$c as d,_c as e,Nm as f,Om as g,Lm as h,Fm as i,Um as j,Wm as k,vs as l,Ss as m,jm as n,Hm as o,X as p,Es as q,T as r,ip as s,As as t,Gm as u,Qm as v,Ts as w,Zm as x,Is as y,ef as z,xe as A,Yc as B,tf as C,nf as D,Cs as E,kp as F,va as G,Ap as H,go as I,N as J,up as K,pp as L,oo as M,yp as N,J as O,ig as P,To as Q,Co as R,ed as S,of as T,td as U,sf as V,af as W,nn as X,Os as Y,df as Z,on as _,od as $,sd as aa,mf as ba,nl as ca,rl as da,cg as ea,dg as fa,dl as ga,mg as ha,Vs as ia,Xs as ja,xf as ka,ce as la,$f as ma,zs as na,Rf as oa,bg as pa,yg as qa,ys as ra,qt as sa,yc as ta,I as ua,ii as va,ih as wa,ah as xa,Yd as ya,uh as za,pi as Aa,ph as Ba,gh as Ca,wh as Da,su as Ea,au as Fa,xh as Ga,xg as Ha,kg as Ia,vg as Ja,Sg as Ka,Eg as La,$g as Ma,_g as Na,Ag as Oa,Tg as Pa,Ig as Qa,Ng as Ra,Og as Sa,Lg as Ta,Fg as Ua,Ug as Va,Wg as Wa,jg as Xa,Bg as Ya,Hg as Za,Vg as _a,Zg as $a,Lt as ab,em as bb,tm as cb,ye as db,we as eb,gu as fb,Th as gb,Ih as hb,Dh as ib,Ch as jb,bn as kb,Nh as lb,Ft as mb,Ut as nb,ze as ob,Wl as pb,Bl as qb,im as rb,jt as sb,Bt as tb,Hl as ub,Vl as vb,rs as wb,as as xb,am as yb,zl as zb,lm as Ab,tc as Bb,oc as Cb,Ht as Db,ic as Eb,ls as Fb,z as Gb,Si as Hb,Ei as Ib,$i as Jb,wn as Kb,Uh as Lb,vu as Mb,Ai as Nb,Ri as Ob,Yh as Pb,Jh as Qb,Fu as Rb,Qh as Sb,Ii as Tb,ps as Ub,rb as Vb,Vu as Wb,sb as Xb,ib as Yb,Ke as Zb,Sm as _b,Qt as $b,Im as ac,db as bc,ub as cc,pb as dc,gb as ec,mb as fc,fb as gc,hb as hc,bb as ic,yb as jc,Mi as kc,Fi as lc,kb as mc,Ui as nc,vb as oc};
|
|
963
|
+
//# sourceMappingURL=chunk-WHAMZPEG.js.map
|