agentix-cli 0.204.0 → 0.205.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-FQRHQT5J.js → App-JDW5V4HT.js} +2 -2
- package/dist/{ChatApp-WBCGSGJM.js → ChatApp-SNM2PORO.js} +2 -2
- package/dist/{absorb-eval-3IU37HZQ.js → absorb-eval-WDAV4AI2.js} +2 -2
- package/dist/{adapter-URFSOOFE.js → adapter-C47BTKT6.js} +2 -2
- package/dist/{agent-P7XUCP3A.js → agent-EVMKJXJO.js} +2 -2
- package/dist/{board-dashboard-AVUFPO5X.js → board-dashboard-VSDTP4Y7.js} +404 -431
- package/dist/board-dashboard-VSDTP4Y7.js.map +1 -0
- package/dist/{chunk-WKR2OSCH.js → chunk-245IOYDJ.js} +2 -2
- package/dist/{chunk-FOWRNDMJ.js → chunk-2LJZHKTY.js} +2 -2
- package/dist/{chunk-P65XGEB7.js → chunk-2P3SHT5I.js} +2 -2
- package/dist/{chunk-JUSQMQ7L.js → chunk-2VSK6FAR.js} +2 -2
- package/dist/chunk-2YDG5CSS.js +2 -0
- package/dist/chunk-2YDG5CSS.js.map +1 -0
- package/dist/{chunk-T7WY5BSJ.js → chunk-5STGF4MI.js} +40 -40
- package/dist/chunk-5STGF4MI.js.map +1 -0
- package/dist/{chunk-Y4YOYOCG.js → chunk-AK46ORUI.js} +2 -2
- package/dist/{chunk-JKT5EFXT.js → chunk-CXFVIDJV.js} +2 -2
- package/dist/{chunk-ZPCSPEGO.js → chunk-CZVCT5ZV.js} +2 -2
- package/dist/{chunk-Y2D6FQBL.js → chunk-DOO4MUTS.js} +2 -2
- package/dist/{chunk-RIBANO2H.js → chunk-DUCYRNCT.js} +3 -3
- package/dist/chunk-DUCYRNCT.js.map +1 -0
- package/dist/{chunk-HX4R7RPR.js → chunk-DV42WUMD.js} +2 -2
- package/dist/{chunk-CAYY2IEV.js → chunk-EFGAPAYZ.js} +2 -2
- package/dist/{chunk-MAQFWGFT.js → chunk-ERVJLPS4.js} +2 -2
- package/dist/{chunk-5VD2J4JN.js → chunk-GWBFEVLO.js} +2 -2
- package/dist/{chunk-IAR5F3T5.js → chunk-IDGEDPRJ.js} +2 -2
- package/dist/chunk-IFNXMUEG.js +115 -0
- package/dist/chunk-IFNXMUEG.js.map +1 -0
- package/dist/{chunk-SLX3OHEW.js → chunk-IU63JGY3.js} +2 -2
- package/dist/{chunk-7QW4RECS.js → chunk-JSCVOB4G.js} +2 -2
- package/dist/{chunk-RUNCUVAH.js → chunk-JT5PIBCM.js} +2 -2
- package/dist/{chunk-EQPMQSJE.js → chunk-KRHVM26D.js} +2 -2
- package/dist/{chunk-WIGH5WMP.js → chunk-KWZ6NMXZ.js} +9 -9
- package/dist/{chunk-VGYW3Q7F.js → chunk-OLKYIKAZ.js} +2 -2
- package/dist/{chunk-RB7M2NPU.js → chunk-PQUK6XEW.js} +2 -2
- package/dist/{chunk-PSOE356C.js → chunk-PQX2VJUA.js} +2 -2
- package/dist/{chunk-TV5BDCQA.js → chunk-PTZNM2JU.js} +2 -2
- package/dist/{chunk-M4VYHPDS.js → chunk-PW3WG6JT.js} +2 -2
- package/dist/{chunk-EMWSFITR.js → chunk-QASIUKZJ.js} +2 -2
- package/dist/{chunk-N6NZBAWR.js → chunk-RXX4MYFL.js} +2 -2
- package/dist/{chunk-C2VZHIIX.js → chunk-S5A7QZVQ.js} +2 -2
- package/dist/{chunk-BIYEGA7Q.js → chunk-S6YN3IBM.js} +2 -2
- package/dist/{chunk-CJI26AJC.js → chunk-SKCOIP5R.js} +3 -3
- package/dist/{chunk-V3FSKTDF.js → chunk-UGRMFQAG.js} +2 -2
- package/dist/{chunk-XPZSEDE3.js → chunk-WDGATQV3.js} +4 -4
- package/dist/{chunk-XPZSEDE3.js.map → chunk-WDGATQV3.js.map} +1 -1
- package/dist/{chunk-QOEO27LF.js → chunk-WJMYBRM5.js} +2 -2
- package/dist/chunk-X6SXZDTY.js +969 -0
- package/dist/chunk-X6SXZDTY.js.map +1 -0
- package/dist/{chunk-EANSYWBQ.js → chunk-ZUHUCSGT.js} +334 -326
- package/dist/chunk-ZUHUCSGT.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{client-EOQLSAUW.js → client-WN7YI7DE.js} +2 -2
- package/dist/{config-SZZQFIJF.js → config-QUXKGIZX.js} +2 -2
- package/dist/{config-mutate-66VDWR46.js → config-mutate-HJH24ITC.js} +2 -2
- package/dist/{config-mutator-OILDQCAJ.js → config-mutator-OLLQR3ZD.js} +2 -2
- package/dist/{connect-AJKMRKXC.js → connect-OOPPXAOD.js} +2 -2
- package/dist/{contributions-LRQCDZCQ.js → contributions-LL7B4BP3.js} +2 -2
- package/dist/daemon-api-QCBFGT7S.js +2 -0
- package/dist/daemon-api-QCBFGT7S.js.map +1 -0
- package/dist/{doctor-EDZO7BUJ.js → doctor-WJ5H7QQW.js} +2 -2
- package/dist/{enrich-NIUEEGPA.js → enrich-MZMIQ3SV.js} +2 -2
- package/dist/{event-levels-D6QSANGF.js → event-levels-PCFARGKL.js} +2 -2
- package/dist/{follow-up-tool-QOO2TIQS.js → follow-up-tool-I2HTKMP4.js} +2 -2
- package/dist/{grants-3UVDASRI.js → grants-5GIY7347.js} +2 -2
- package/dist/{hub-6TKU6CHO.js → hub-7ASBN76I.js} +2 -2
- package/dist/index.d.ts +12 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/org-tool-JCGGJJU6.js +2 -0
- package/dist/org-tool-JCGGJJU6.js.map +1 -0
- package/dist/{program-OFN6YQRH.js → program-7VNYZPRO.js} +238 -238
- package/dist/program-7VNYZPRO.js.map +1 -0
- package/dist/{promote-D3KYLUBD.js → promote-NSPUPPHB.js} +2 -2
- package/dist/providers-D6IUAHQJ.js +2 -0
- package/dist/{query-D2TQ2PUO.js → query-VW63IHDI.js} +2 -2
- package/dist/{query-settings-ILDX3HDF.js → query-settings-RS7DJI4H.js} +2 -2
- package/dist/{registry-N3BY3HSI.js → registry-6KREAROB.js} +2 -2
- package/dist/{request-planner-CVCG5XQR.js → request-planner-HZWQIRZO.js} +2 -2
- package/dist/resolve-LOYZUE2D.js +2 -0
- package/dist/{review-candidates-CKUN4PSY.js → review-candidates-2TXOUASP.js} +2 -2
- package/dist/{routing-OCIRGUKK.js → routing-ZV4VSZDV.js} +2 -2
- package/dist/{rules-A5ES57QT.js → rules-FBOLGE2S.js} +2 -2
- package/dist/schedule-tool-D357NLXS.js +2 -0
- package/dist/{scheduler-D2Z7RSEE.js → scheduler-SAID6RKQ.js} +2 -2
- package/dist/{seat-Z3E2FLDA.js → seat-XHBWBSTS.js} +2 -2
- package/dist/{select-J4ES7Q67.js → select-QUCTTAH3.js} +2 -2
- package/dist/{set-enabled-S22TICYC.js → set-enabled-CGMXLFC6.js} +2 -2
- package/dist/{sprint-tool-NDF47EKV.js → sprint-tool-SWRYSX3Q.js} +2 -2
- package/dist/status-PVYFTNX2.js +2 -0
- package/dist/{tool-6NZIUXI7.js → tool-6G63ZQW4.js} +2 -2
- package/dist/{tool-RCCMOMEY.js → tool-DA25L4ND.js} +2 -2
- package/dist/{tool-52JRXZVA.js → tool-ELGOVIM5.js} +2 -2
- package/dist/{tool-Z2OVFGWW.js → tool-MMH2JNP7.js} +2 -2
- package/dist/{wiki-HQKFZZSX.js → wiki-4ZL4QXA7.js} +2 -2
- package/dist/wiki-enrich-N5MUKDVW.js +2 -0
- package/dist/workspace-setup-QXFJRNSK.js +2 -0
- package/package.json +1 -1
- package/dist/board-dashboard-AVUFPO5X.js.map +0 -1
- package/dist/chunk-B6VASQHD.js +0 -2
- package/dist/chunk-B6VASQHD.js.map +0 -1
- package/dist/chunk-EANSYWBQ.js.map +0 -1
- package/dist/chunk-FCDMB2JA.js +0 -936
- package/dist/chunk-FCDMB2JA.js.map +0 -1
- package/dist/chunk-GDHSJH3T.js +0 -111
- package/dist/chunk-GDHSJH3T.js.map +0 -1
- package/dist/chunk-RIBANO2H.js.map +0 -1
- package/dist/chunk-T7WY5BSJ.js.map +0 -1
- package/dist/daemon-api-OVCXY4QC.js +0 -2
- package/dist/daemon-api-OVCXY4QC.js.map +0 -1
- package/dist/program-OFN6YQRH.js.map +0 -1
- package/dist/providers-AHLCB6R5.js +0 -2
- package/dist/resolve-JKXYBZ6R.js +0 -2
- package/dist/schedule-tool-YFMRYTEO.js +0 -2
- package/dist/status-PKHYFGZK.js +0 -2
- package/dist/wiki-enrich-7SZ5W2LF.js +0 -2
- package/dist/workspace-setup-W5UO2WZI.js +0 -2
- /package/dist/{App-FQRHQT5J.js.map → App-JDW5V4HT.js.map} +0 -0
- /package/dist/{ChatApp-WBCGSGJM.js.map → ChatApp-SNM2PORO.js.map} +0 -0
- /package/dist/{absorb-eval-3IU37HZQ.js.map → absorb-eval-WDAV4AI2.js.map} +0 -0
- /package/dist/{adapter-URFSOOFE.js.map → adapter-C47BTKT6.js.map} +0 -0
- /package/dist/{agent-P7XUCP3A.js.map → agent-EVMKJXJO.js.map} +0 -0
- /package/dist/{chunk-WKR2OSCH.js.map → chunk-245IOYDJ.js.map} +0 -0
- /package/dist/{chunk-FOWRNDMJ.js.map → chunk-2LJZHKTY.js.map} +0 -0
- /package/dist/{chunk-P65XGEB7.js.map → chunk-2P3SHT5I.js.map} +0 -0
- /package/dist/{chunk-JUSQMQ7L.js.map → chunk-2VSK6FAR.js.map} +0 -0
- /package/dist/{chunk-Y4YOYOCG.js.map → chunk-AK46ORUI.js.map} +0 -0
- /package/dist/{chunk-JKT5EFXT.js.map → chunk-CXFVIDJV.js.map} +0 -0
- /package/dist/{chunk-ZPCSPEGO.js.map → chunk-CZVCT5ZV.js.map} +0 -0
- /package/dist/{chunk-Y2D6FQBL.js.map → chunk-DOO4MUTS.js.map} +0 -0
- /package/dist/{chunk-HX4R7RPR.js.map → chunk-DV42WUMD.js.map} +0 -0
- /package/dist/{chunk-CAYY2IEV.js.map → chunk-EFGAPAYZ.js.map} +0 -0
- /package/dist/{chunk-MAQFWGFT.js.map → chunk-ERVJLPS4.js.map} +0 -0
- /package/dist/{chunk-5VD2J4JN.js.map → chunk-GWBFEVLO.js.map} +0 -0
- /package/dist/{chunk-IAR5F3T5.js.map → chunk-IDGEDPRJ.js.map} +0 -0
- /package/dist/{chunk-SLX3OHEW.js.map → chunk-IU63JGY3.js.map} +0 -0
- /package/dist/{chunk-7QW4RECS.js.map → chunk-JSCVOB4G.js.map} +0 -0
- /package/dist/{chunk-RUNCUVAH.js.map → chunk-JT5PIBCM.js.map} +0 -0
- /package/dist/{chunk-EQPMQSJE.js.map → chunk-KRHVM26D.js.map} +0 -0
- /package/dist/{chunk-WIGH5WMP.js.map → chunk-KWZ6NMXZ.js.map} +0 -0
- /package/dist/{chunk-VGYW3Q7F.js.map → chunk-OLKYIKAZ.js.map} +0 -0
- /package/dist/{chunk-RB7M2NPU.js.map → chunk-PQUK6XEW.js.map} +0 -0
- /package/dist/{chunk-PSOE356C.js.map → chunk-PQX2VJUA.js.map} +0 -0
- /package/dist/{chunk-TV5BDCQA.js.map → chunk-PTZNM2JU.js.map} +0 -0
- /package/dist/{chunk-M4VYHPDS.js.map → chunk-PW3WG6JT.js.map} +0 -0
- /package/dist/{chunk-EMWSFITR.js.map → chunk-QASIUKZJ.js.map} +0 -0
- /package/dist/{chunk-N6NZBAWR.js.map → chunk-RXX4MYFL.js.map} +0 -0
- /package/dist/{chunk-C2VZHIIX.js.map → chunk-S5A7QZVQ.js.map} +0 -0
- /package/dist/{chunk-BIYEGA7Q.js.map → chunk-S6YN3IBM.js.map} +0 -0
- /package/dist/{chunk-CJI26AJC.js.map → chunk-SKCOIP5R.js.map} +0 -0
- /package/dist/{chunk-V3FSKTDF.js.map → chunk-UGRMFQAG.js.map} +0 -0
- /package/dist/{chunk-QOEO27LF.js.map → chunk-WJMYBRM5.js.map} +0 -0
- /package/dist/{client-EOQLSAUW.js.map → client-WN7YI7DE.js.map} +0 -0
- /package/dist/{config-SZZQFIJF.js.map → config-QUXKGIZX.js.map} +0 -0
- /package/dist/{config-mutate-66VDWR46.js.map → config-mutate-HJH24ITC.js.map} +0 -0
- /package/dist/{config-mutator-OILDQCAJ.js.map → config-mutator-OLLQR3ZD.js.map} +0 -0
- /package/dist/{connect-AJKMRKXC.js.map → connect-OOPPXAOD.js.map} +0 -0
- /package/dist/{contributions-LRQCDZCQ.js.map → contributions-LL7B4BP3.js.map} +0 -0
- /package/dist/{doctor-EDZO7BUJ.js.map → doctor-WJ5H7QQW.js.map} +0 -0
- /package/dist/{enrich-NIUEEGPA.js.map → enrich-MZMIQ3SV.js.map} +0 -0
- /package/dist/{event-levels-D6QSANGF.js.map → event-levels-PCFARGKL.js.map} +0 -0
- /package/dist/{follow-up-tool-QOO2TIQS.js.map → follow-up-tool-I2HTKMP4.js.map} +0 -0
- /package/dist/{grants-3UVDASRI.js.map → grants-5GIY7347.js.map} +0 -0
- /package/dist/{hub-6TKU6CHO.js.map → hub-7ASBN76I.js.map} +0 -0
- /package/dist/{promote-D3KYLUBD.js.map → promote-NSPUPPHB.js.map} +0 -0
- /package/dist/{providers-AHLCB6R5.js.map → providers-D6IUAHQJ.js.map} +0 -0
- /package/dist/{query-D2TQ2PUO.js.map → query-VW63IHDI.js.map} +0 -0
- /package/dist/{query-settings-ILDX3HDF.js.map → query-settings-RS7DJI4H.js.map} +0 -0
- /package/dist/{registry-N3BY3HSI.js.map → registry-6KREAROB.js.map} +0 -0
- /package/dist/{request-planner-CVCG5XQR.js.map → request-planner-HZWQIRZO.js.map} +0 -0
- /package/dist/{resolve-JKXYBZ6R.js.map → resolve-LOYZUE2D.js.map} +0 -0
- /package/dist/{review-candidates-CKUN4PSY.js.map → review-candidates-2TXOUASP.js.map} +0 -0
- /package/dist/{routing-OCIRGUKK.js.map → routing-ZV4VSZDV.js.map} +0 -0
- /package/dist/{rules-A5ES57QT.js.map → rules-FBOLGE2S.js.map} +0 -0
- /package/dist/{schedule-tool-YFMRYTEO.js.map → schedule-tool-D357NLXS.js.map} +0 -0
- /package/dist/{scheduler-D2Z7RSEE.js.map → scheduler-SAID6RKQ.js.map} +0 -0
- /package/dist/{seat-Z3E2FLDA.js.map → seat-XHBWBSTS.js.map} +0 -0
- /package/dist/{select-J4ES7Q67.js.map → select-QUCTTAH3.js.map} +0 -0
- /package/dist/{set-enabled-S22TICYC.js.map → set-enabled-CGMXLFC6.js.map} +0 -0
- /package/dist/{sprint-tool-NDF47EKV.js.map → sprint-tool-SWRYSX3Q.js.map} +0 -0
- /package/dist/{status-PKHYFGZK.js.map → status-PVYFTNX2.js.map} +0 -0
- /package/dist/{tool-6NZIUXI7.js.map → tool-6G63ZQW4.js.map} +0 -0
- /package/dist/{tool-RCCMOMEY.js.map → tool-DA25L4ND.js.map} +0 -0
- /package/dist/{tool-52JRXZVA.js.map → tool-ELGOVIM5.js.map} +0 -0
- /package/dist/{tool-Z2OVFGWW.js.map → tool-MMH2JNP7.js.map} +0 -0
- /package/dist/{wiki-HQKFZZSX.js.map → wiki-4ZL4QXA7.js.map} +0 -0
- /package/dist/{wiki-enrich-7SZ5W2LF.js.map → wiki-enrich-N5MUKDVW.js.map} +0 -0
- /package/dist/{workspace-setup-W5UO2WZI.js.map → workspace-setup-QXFJRNSK.js.map} +0 -0
|
@@ -0,0 +1,969 @@
|
|
|
1
|
+
import{a as mt}from"./chunk-GTJIKXDB.js";import{H as br,O as Ar,k as K}from"./chunk-GWBFEVLO.js";import{f as Er,g as _r,h as $r,l as Tr}from"./chunk-PQUK6XEW.js";import{a as Sr}from"./chunk-JSCVOB4G.js";import{a as wr,i as xr,l as kr,n as pt,o as gt,q as pe,r as ee,t as vr}from"./chunk-WDGATQV3.js";import{b as yr}from"./chunk-2VDO2HEK.js";import{t as fr,u as hr}from"./chunk-PW3WG6JT.js";import{d as gr,e as mr}from"./chunk-AQASR6KR.js";import{a as Zn,b as er,d as tr,e as nr}from"./chunk-MNG2AMKZ.js";import{h as ue,j as rr,l as or,m as sr,n as ir}from"./chunk-RX5O5637.js";import{h as Kn,i as Gn,j as Yn,l as Jn,m as Qn}from"./chunk-KRHVM26D.js";import{a as ar,c as lr,e as cr,f as lt,h as dr,j as ur,k as pr,l as ct,m as dt,n as ut}from"./chunk-5ELIX7BQ.js";import{a as Xn,c as zn}from"./chunk-KP7KDLZ2.js";import{c as Re,d as Hn,e as Vn}from"./chunk-XVV7ZZ77.js";import{Aa as de,Ca as at,b as ot,f as Fn,s as st,u as it,xa as Ae,ya as Bn,za as W}from"./chunk-JT5PIBCM.js";import{a as $e,b as ce,e as Un}from"./chunk-7AB3QUGH.js";import{s as qn}from"./chunk-IDGEDPRJ.js";import{a as Wn,b as Te,e as jn}from"./chunk-2P3SHT5I.js";import{b as Z}from"./chunk-5ONH4ITT.js";import{a as Mn,c as rt}from"./chunk-ILEC3IAV.js";import{a as Pn}from"./chunk-QUFIUXMQ.js";import{E as _e,F as _n,G as $n,Gb as Nn,H as ki,Hb as On,Rb as Ln,f as Qe,g as C,i as Ee,j as E,k as le,l as Sn,o as En,p as Ze,ta as Rn,ua as In,wa as Dn,xa as Cn,xb as nt}from"./chunk-DUCYRNCT.js";import{a as et,h as vi}from"./chunk-VJ5HC63R.js";import{j as tt,q as Tn,r as An}from"./chunk-UEEB3UTU.js";import{existsSync as Si,readdirSync as Ei,readFileSync as _i,statSync as $i}from"fs";import{resolve as Ti}from"path";function Rr(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 Ie=new Map;function Du(t,e=1e3){if(!Si(t))return[];let n=Ei(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ti(t,s);return{path:i,mtime:$i(i).mtimeMs}}).sort((s,i)=>i.mtime-s.mtime).slice(0,e),r=new Set(n.map(s=>s.path));for(let s of Ie.keys())r.has(s)||Ie.delete(s);let o=[];for(let{path:s,mtime:i}of n){let a=Ie.get(s);if(a&&a.mtime===i){a.summary&&o.push(a.summary);continue}let d=Ai(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ai(t,e){try{let n=_i(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 Ir=7,Ri={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Ii=(t,e,n)=>{try{return qn(t,e,n)}catch{return null}},Dr=864e5;function Lu(t){let e=t.now??Date.now(),n={...Ri,...t.thresholds},r=t.nextFire??Ii,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,A.text),trigger:{schedule:F(a.schedule,A.text),timezone:l},agent:a.agent||null,enabled:a.enabled,state:a.enabled?"enabled":"disabled",nextRunAt:a.enabled?ft(a.nextRun)??ft(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Pi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Cr(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Ir).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Nr(u,c,a.schedule,l,null,e,n,r),o.push(Or(u))}let s=new Map(Rr(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,D)=>D.at-k.at),g=u.map(k=>({at:k.at,status:Ni(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,A.text),trigger:f?{schedule:F(w,A.text),timezone:x}:{event:F(typeof l.event=="string"?l.event:"",A.text),filters:Li(l.filter,a)},agent:Oi(a),enabled:p,state:c,nextRunAt:f&&p&&w?ft(r(w,new Date(e),x)):null,lastRun:m?{at:new Date(m.at).toISOString(),status:m.status}:null,lastSuccessAt:(()=>{let k=g.find(D=>D.status==="success");return k?new Date(k.at).toISOString():null})(),consecutiveFailures:Cr(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Ir).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Nr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Di(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Or(b))}return o.sort(Ci).slice(0,A.routines)}function Cr(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 Nr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Pr(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 Di(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Pr(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 Pr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Dr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Dr)} days`:"Disabled and never ran"}}function Or(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 Lr={critical:0,warning:1,info:2};function Ci(t,e){let n=t.attention?Lr[t.attention]:3,r=e.attention?Lr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Ni(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 Oi(t){if(t.ownerAgent)return F(t.ownerAgent,A.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),A.text):null}function Li(t,e){let n=[],r=e?.project;if(r&&n.push(F(`project=${r}`,A.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(",")}`,A.filterValue))}return n.slice(0,A.filters)}function ft(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 Pi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Mi,readFileSync as Fi,renameSync as Ui,writeFileSync as Wi}from"fs";import{resolve as ji}from"path";function Mr(t){return ji(gt(t),"_state.json")}function N(t){try{let e=JSON.parse(Fi(Mr(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 ge(t,e){Mi(gt(t),{recursive:!0});let n=Mr(t),r=`${n}.${process.pid}.tmp`;Wi(r,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),Ui(r,n)}function Fr(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(),ge(t,{...o,snoozed:s})}function Wu(t,e){ge(t,{...N(t),lastDigest:e})}function ht(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));ge(t,{...o,popped:i,wanted:a})}function Ur(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function ju(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Bi}from"fs";Ln();vi();function Wr(t){let e=Wn(t),n={};if(qi(e))try{n=Nn(JSON.parse(Bi(e,"utf-8")))}catch{n={}}let r=nt.safeParse(n?.requests);return r.success?r.data:nt.parse(void 0)}async function zu(t,e={}){let n=(t.channels??[]).filter(r=>!et.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...et].join(", ")}`}:Te(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 H,readdirSync as da,readFileSync as xt,statSync as ua}from"fs";import{dirname as io,resolve as T}from"path";import{randomBytes as Br}from"crypto";import{existsSync as Vi,mkdirSync as Xi,readdirSync as zi,readFileSync as Ki,renameSync as Hr,unlinkSync as Gi,writeFileSync as Yi}from"fs";import{resolve as Vr}from"path";function jr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Hi=t=>t.trim().split(`
|
|
4
|
+
`).pop()?.slice(0,300)||"no output";async function qr(t,e,n,r=mt){let o=await r(t.bin,[...jr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Hi(o.stderr||o.stdout)}`}}async function Yu(t,e,n,r,o=mt){return(await o(t.bin,[...jr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Ji=2e3,Qi=t=>qr(t.wacli,t.to,t.text);function bt(t){return Vr(t,".agentx","whatsapp-triage","drafts")}var Zi=t=>/^[a-z0-9-]{8,64}$/.test(t),De=(t,e)=>Vr(bt(t),`${e}.json`);function Xr(t,e){Xi(bt(t),{recursive:!0});let n=De(t,e.id),r=`${n}.${process.pid}.tmp`;Yi(r,JSON.stringify(e,null,2)+`
|
|
5
|
+
`,{mode:384}),Hr(r,n)}function np(t,e,n=Date.now()){let r=e.text.trim().slice(0,Ji);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Br(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Xr(t,o),o}function Ce(t,e){if(!Zi(e))return null;try{return JSON.parse(Ki(De(t,e),"utf-8"))}catch{return null}}function zr(t,e){let n=bt(t);return Vi(n)?zi(n).filter(r=>r.endsWith(".json")).map(r=>Ce(t,r.slice(0,-5))).filter(r=>!!r&&(!e||r.status===e)).sort((r,o)=>r.created_at.localeCompare(o.created_at)):[]}async function Kr(t,e,n,r={}){let o=Ce(t,e);if(!o||o.status!=="pending")return{ok:!1,error:`no reply draft "${e}" is waiting`};let s=`${De(t,e)}.${process.pid}.${Br(3).toString("hex")}.claim`;try{Hr(De(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??Qi)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Xr(t,i);try{Gi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ea,writeFileSync as ta}from"fs";import{resolve as Yr}from"path";var Jr="ready",na="202510";function ra(t){let e=t.date??t.created_at.slice(0,10);return Yr(t.workspace,Jr,`${e}-${t.platform}-${t.id}.txt`)}function Gr(t){let e=ra(t);return ea(Yr(t.workspace,Jr),{recursive:!0}),ta(e,t.text.endsWith(`
|
|
6
|
+
`)?t.text:`${t.text}
|
|
7
|
+
`),e}function Qr(t,e,n){let r=Sr(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 Zr(t,e,n){return Qr(t,e,n)!==null}async function oa(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??na),"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 sa(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=Qr(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Gr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await oa(t.text,n,r):await sa(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Gr(t);return{ok:!1,error:`not posted on ${ue[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function eo(t){return e=>ia(e,t)}An();Cn();Cn();An();var up=["done","skipped"],aa=1e3;function la(t){t.exec(`
|
|
8
|
+
CREATE TABLE IF NOT EXISTS request_plans (
|
|
9
|
+
request_id TEXT PRIMARY KEY,
|
|
10
|
+
created_by TEXT NOT NULL,
|
|
11
|
+
created_at INTEGER NOT NULL,
|
|
12
|
+
state TEXT NOT NULL,
|
|
13
|
+
finished_at INTEGER,
|
|
14
|
+
notified_at INTEGER,
|
|
15
|
+
FOREIGN KEY (request_id) REFERENCES requests(id) ON DELETE CASCADE
|
|
16
|
+
);
|
|
17
|
+
CREATE INDEX IF NOT EXISTS idx_request_plans_state ON request_plans(state);
|
|
18
|
+
CREATE TABLE IF NOT EXISTS request_plan_steps (
|
|
19
|
+
request_id TEXT NOT NULL,
|
|
20
|
+
idx INTEGER NOT NULL,
|
|
21
|
+
name TEXT NOT NULL,
|
|
22
|
+
kind TEXT NOT NULL,
|
|
23
|
+
agent_id TEXT NOT NULL,
|
|
24
|
+
done_when TEXT NOT NULL,
|
|
25
|
+
state TEXT NOT NULL,
|
|
26
|
+
needs_approval INTEGER NOT NULL DEFAULT 0,
|
|
27
|
+
approval TEXT NOT NULL DEFAULT 'none',
|
|
28
|
+
card_id TEXT,
|
|
29
|
+
message TEXT,
|
|
30
|
+
to_channel TEXT,
|
|
31
|
+
to_chat TEXT,
|
|
32
|
+
to_account TEXT,
|
|
33
|
+
check_url TEXT,
|
|
34
|
+
check_contains TEXT,
|
|
35
|
+
stall_minutes REAL,
|
|
36
|
+
evidence TEXT,
|
|
37
|
+
note TEXT,
|
|
38
|
+
dispatched_at INTEGER,
|
|
39
|
+
updated_at INTEGER NOT NULL,
|
|
40
|
+
nudges INTEGER NOT NULL DEFAULT 0,
|
|
41
|
+
last_nudge_at INTEGER,
|
|
42
|
+
notified_at INTEGER,
|
|
43
|
+
PRIMARY KEY (request_id, idx),
|
|
44
|
+
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
45
|
+
);
|
|
46
|
+
CREATE TABLE IF NOT EXISTS request_plan_events (
|
|
47
|
+
request_id TEXT NOT NULL,
|
|
48
|
+
step INTEGER,
|
|
49
|
+
at INTEGER NOT NULL,
|
|
50
|
+
kind TEXT NOT NULL,
|
|
51
|
+
detail TEXT NOT NULL,
|
|
52
|
+
FOREIGN KEY (request_id) REFERENCES request_plans(request_id) ON DELETE CASCADE
|
|
53
|
+
);
|
|
54
|
+
CREATE INDEX IF NOT EXISTS idx_request_plan_events ON request_plan_events(request_id, at);
|
|
55
|
+
CREATE TABLE IF NOT EXISTS request_plan_continues (
|
|
56
|
+
goal_key TEXT NOT NULL,
|
|
57
|
+
day TEXT NOT NULL,
|
|
58
|
+
turns INTEGER NOT NULL DEFAULT 0,
|
|
59
|
+
cost_usd REAL NOT NULL DEFAULT 0,
|
|
60
|
+
told_at INTEGER,
|
|
61
|
+
PRIMARY KEY (goal_key, day)
|
|
62
|
+
);
|
|
63
|
+
`),Tn(t,"request_plan_steps",[["check_count","TEXT"],["last_count","INTEGER"],["last_count_at","INTEGER"]])}function no(t){return!!t.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'request_plans'").get()}function yt(t){return{requestId:t.request_id,createdBy:t.created_by,createdAt:t.created_at,state:t.state,finishedAt:t.finished_at??null,notifiedAt:t.notified_at??null}}function to(t){return{requestId:t.request_id,idx:t.idx,name:t.name,kind:t.kind,agentId:t.agent_id,doneWhen:t.done_when,state:t.state,needsApproval:!!t.needs_approval,approval:t.approval,cardId:t.card_id??null,message:t.message??null,toChannel:t.to_channel??null,toChat:t.to_chat??null,toAccount:t.to_account??null,checkUrl:t.check_url??null,checkContains:t.check_contains??null,stallMinutes:t.stall_minutes??null,checkCount:t.check_count??null,lastCount:t.last_count??null,lastCountAt:t.last_count_at??null,evidence:t.evidence??null,note:t.note??null,dispatchedAt:t.dispatched_at??null,updatedAt:t.updated_at,nudges:t.nudges,lastNudgeAt:t.last_nudge_at??null,notifiedAt:t.notified_at??null}}var ca={state:"state",approval:"approval",cardId:"card_id",message:"message",evidence:"evidence",note:"note",dispatchedAt:"dispatched_at",updatedAt:"updated_at",nudges:"nudges",lastNudgeAt:"last_nudge_at",notifiedAt:"notified_at",lastCount:"last_count",lastCountAt:"last_count_at"},Ne=class{constructor(e){this.db=e;la(e)}create(e,n,r,o){let s=this.db.prepare("INSERT INTO request_plans (request_id, created_by, created_at, state) VALUES (?, ?, ?, 'active')"),i=this.db.prepare(`INSERT INTO request_plan_steps (request_id, idx, name, kind, agent_id, done_when, state, needs_approval, message,
|
|
64
|
+
to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
|
|
65
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,d)=>{let l=d===0,c=l&&a.agentId===n&&a.kind!=="message";i.run(e,d+1,a.name,a.kind,a.agentId,a.doneWhen,l?"active":"pending",a.needsApproval?1:0,a.message??null,a.toChannel??null,a.toChat??null,a.toAccount??null,a.checkUrl??null,a.checkContains??null,a.stallMinutes??null,c?o:null,o,a.checkCount??null)}),this.event(e,null,"created",`${r.length} steps, written by ${n}`,o)})()}get(e){let n=this.db.prepare("SELECT * FROM request_plans WHERE request_id = ?").get(e);return n?yt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(to)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?to(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(yt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=ca[i];!d||a===void 0||(o.push(`${d} = ?`),s.push(typeof a=="boolean"?a?1:0:a))}o.length&&this.db.prepare(`UPDATE request_plan_steps SET ${o.join(", ")} WHERE request_id = ? AND idx = ?`).run(...s,e,n)}finish(e,n,r){return this.db.prepare("UPDATE request_plans SET state = ?, finished_at = ? WHERE request_id = ? AND state = 'active'").run(n,r,e).changes>0}markNotified(e,n){this.db.prepare("UPDATE request_plans SET notified_at = ? WHERE request_id = ?").run(n,e)}awaitingSummary(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'done' AND notified_at IS NULL ORDER BY finished_at").all().map(yt)}event(e,n,r,o,s){this.db.prepare("INSERT INTO request_plan_events (request_id, step, at, kind, detail) VALUES (?, ?, ?, ?, ?)").run(e,n,s,r,o.replace(/\s+/g," ").trim().slice(0,aa))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
|
|
66
|
+
ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
|
|
67
|
+
told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},pp=Rn;var ao=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],pa=280;function O(t,e=pa){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(t.configPath);let e=[T(t.root,"agentx.json"),T(t.root,".agentx","config.json")];return e.find(n=>H(n))??e[0]}function V(t){return t.wikiDir?T(t.wikiDir):T(t.root,".agentx","wiki")}function ga(t){return ee(t.root,"pending").map(ma)}function ma(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 fa(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(xt(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?Kn(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 ${Yn(Gn(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function lo(t){let e=T(t,".agentx","memory");return H(e)?da(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ha(t){let e=lo(t.root);if(e.length===0)return[];let n=new ot(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 ba(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 ya(t){return mr(V(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(`${ba(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var ro=new Map;function co(t,e){let n=ua(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=ro.get(t);if(o?.version===r)return o.value;let s=e();return ro.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 xa(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new Z(n),"pending").find(o=>o.id===e);return r?wa(r):void 0}function ka(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=co(e,()=>Re(new Z(io(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 va(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 uo(t){let e=V(t),n=new rt(e);if(!H(n.path))return[];let r=co(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new Z(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:va(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 Sa(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:O(`${e.triage}: ${e.summary}`),more:"agentx whatsapp triage log"}))}function Ea(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:O(`Last try not sent: ${e.error}`)}:{}}))}function _a(t){let e=Object.entries(st(t.root)).filter(([,r])=>r.kind==="approval");if(e.length===0)return[];let n=Oe(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 Oe(t){try{return JSON.parse(xt(te(t),"utf-8"))}catch{return{}}}function wt(t){let e={};try{e=Object.fromEntries(Pn(xt(T(io(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function $a(t){let e=sr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=wt(t);return e.map(o=>{let s=ue[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:Zr({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:rr(o.text)}})}function G(t){if(t.requests)return t.requests;if(T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e)return null;let n=oo.get(e);return!n&&!In(e)?null:(n||oo.set(e,n=new Dn(e)),n)}var oo=new WeakMap;function Wp(t){if(t.plans)return t.plans;if(t.requests||T(t.root)!==process.cwd()||!H(T(t.root,".agentx","db.sqlite")))return null;let e=tt({quiet:!0});if(!e||!no(e))return null;let n=so.get(e);return n||so.set(e,n=new Ne(e)),n}var so=new WeakMap;function Ta(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:O(`${n.attentionReason??"It needs attention"}. You said (${n.channel}): ${n.text}`),more:`agentx requests show ${n.id}`})):[]}var po={card:ga,schedule:fa,agent:_a,memory:ha,wiki:ya,fact:()=>[],question:uo,whatsapp:Sa,email:Ea,content:$a,request:Ta};function Aa(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 go(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??ao){if(d==="fact"){try{let c=ka(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=po[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(Aa),{items:o,snoozed:a,errors:s,backlog:i}}function mo(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!ao.includes(n)||!r?null:{kind:n,ref:r}}function Ra(t,e,n){switch(e){case"card":return pe(t.root,n)?.status==="pending";case"wiki":return gr(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return Er(t.root,n)?.status==="pending";case"content":return or(t.root,n)?.status==="pending";default:return!!fo(t,e,n)}}function fo(t,e,n){return e==="fact"?xa(t,n):po[e](t).find(r=>r.key===`${e}:${n}`)}async function ho(t,e,n,r={}){let o=n==="later"?null:mo(e),s;if(o)try{s=fo(t,o.kind,o.ref)}catch{s=void 0}let i=await Ia(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;wr(t.root,{key:e,kind:o.kind,title:s?.title??e,raised_by:s?.raised_by??"",answer:n,...a?{choice:a}:{},...r.text?{text:r.text}:{},by:r.by??"operator",at:new Date(t.now??Date.now()).toISOString()})}return i}async function Ia(t,e,n,r){let o=mo(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(!Ra(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 Fr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=vr(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text});return c.ok?{ok:!0,message:`${e}: ${c.card.raised_by} will be told ${l?"yes":"no"}${c.card.choice?` (${c.card.choice}${c.card.choice_suggested?", the suggested option":""})`:""}`}:c}case"schedule":{let c=await(l?Jn:Qn)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(st(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return it(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 Te(u=>{jn(u,`agents.${i}`);for(let[g,m]of Object.entries(u.crons??{}))m?.agent===i&&(delete u.crons[g],c.push(g))},{configPath:te(t),reload:t.reload});return p.success?(it(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(!lo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new ot(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=V(t),p=l?fr(c,i,{by:d,force:r.force,now:a}):hr(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 Da(t,e,i,l,d,r);case"question":return Na(t,e,i,l,d,r);case"whatsapp":{let c=await Kr(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??Tr(Oe(t),wt(t)),p=await $r(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??eo({config:Oe(t),env:wt(t)}),p=await ir(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=ue[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),{ok:!0,message:`${e}: dropped`})}}}function Da(t,e,n,r,o,s){let i=new Z(V(t));try{let a=Re(i,"pending").find(l=>l.id===n);if(!a)return{ok:!1,error:`nothing waiting for "${e}"`};if(!r)return Vn(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=Hn(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 Ca(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 Na(t,e,n,r,o,s){let i=V(t),a=new rt(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Mn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=uo(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=Ca(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 Z(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 Oa=3,La=7,Pa=50,vt=120,Ma=280,kt=600,yo=36e5,Fa=24*yo;function Bp(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 Ua(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,vt),...e.ask?{ask:ne(e.ask,kt)}:{},...e.detail?{facts:ne(e.detail,Ma)}:{},...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 Wa={done:"Done",declined:"Declined",dropped:"Dropped"};function wo(t,e,n){let{record:r,links:o}=e,s=K(r,vt),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,kt)}:{},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,kt)}:{},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??Oa)*yo;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:Wa[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function ja(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 qa(t,e){return{key:`card:${e.id}`,kind:"card",column:"done",node:t.node,nodeName:t.nodeName,title:ne(e.title,vt),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:ja(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,bo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function St(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(Ua(o,s,o.node===t.node))}let r=xo(t,e);for(let o of t.requests??[]){let s=wo(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function xo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Hp(t){let e=St(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=xo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=wo(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??La)*Fa;for(let u of t.cards)u.status!=="pending"&&L(u.decided_at)>=d&&a.push(qa(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,Pa),c=bo(n,"askedAt"),p=bo(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 Ba(t){return{key:t.key,title:t.title,ask:t.ask,recommend:t.recommend,yes:t.yes,no:t.no,raisedBy:t.raised_by,expires:t.expires,...t.if_silent?{ifSilent:t.if_silent}:{},...t.choices?{choices:t.choices}:{},...t.draft?{draft:t.draft}:{},...t.detail?{detail:t.detail}:{},...t.created_at?{createdAt:t.created_at}:{}}}function Ha(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 Kp(t,e){let n=t.now??Date.now(),r=[],o=go(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}=St({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ba)}],requests:a,deferred:i});return Ha(d,i.size,[...r,...l])}import{readFileSync as Va}from"fs";var Xa=1e4,ko=/^[0-9a-f]{7,64}$/i;function Jp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&ko.test(i)?{source:n,commit:i}:{source:n,commit:null,error:"this build does not carry its commit (run from source?)"}}let r;try{r=await e(n,{signal:AbortSignal.timeout(Xa)})}catch(i){return{source:n,commit:null,error:`could not be reached: ${String(i?.message??i).slice(0,200)}`}}if(!r.ok)return{source:n,commit:null,error:`HTTP ${r.status}`};let o=await r.json().catch(()=>null),s=t.field.split(".").reduce((i,a)=>i&&typeof i=="object"?i[a]:void 0,o);return typeof s=="string"&&ko.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Qp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Va(n.tokenFile,"utf-8").trim().split(`
|
|
68
|
+
`)[0].trim()||void 0}catch{}let o=t.channels.gitlab;return{github:{apiUrl:e?.github?.apiUrl??"https://api.github.com",token:r},gitlab:{url:e?.gitlab?.url??o?.host??"https://gitlab.com",token:e?.gitlab?.token??o?.token}}}var vo=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function eg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||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"}function tg(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 ng(t){return vo.has(t)}function rg(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(vo.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 og(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 sg(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 Pe(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function za(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ka(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function ag(t,e=Ka()){let n=Pe(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=za(n),s=[Pe(t.host),Pe(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Pe(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function lg(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var Et="/api/admin/pictures",Ga=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ya=/^\/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 Ja(t){let e={agent:{},person:{}};for(let n of ar)for(let[r,o]of Object.entries(dr(t,n)))e[n][r]=ur(n,r,o);return e}function ug(t,e,n,r,o){let s=n.match(Ga);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=pr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":lr,"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 pg(t,e,n,r){if(n!==Et&&!n.startsWith(`${Et}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===Et)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Ja(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ya);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(!cr.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=dt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await ut(t),p=await ct(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof lt)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function gg(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:dt(r.root,"agent",i)});return}try{let a=await ct(r.root,"agent",i,await ut(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof lt){_(e,a.status,{error:a.message});return}throw a}}var So={};function hg(t){So=t}function bg(){return So}var yg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
69
|
+
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
70
|
+
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
71
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
72
|
+
<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">
|
|
73
|
+
<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>`,wg=`
|
|
74
|
+
.ax-topbar{display:flex;align-items:center;justify-content:space-between;
|
|
75
|
+
padding:8px 18px;border-bottom:1px solid var(--ax-border);
|
|
76
|
+
background:var(--ax-bg-elev);position:sticky;top:0;z-index:20;gap:10px;flex-wrap:nowrap}
|
|
77
|
+
.ax-topbar__left{display:flex;align-items:center;gap:18px;min-width:0}
|
|
78
|
+
.ax-brand{display:flex;align-items:center;gap:10px;font-weight:600;letter-spacing:-0.01em;flex-shrink:0}
|
|
79
|
+
.ax-brand__mark{font-family:var(--ax-mono);font-size:12px;padding:2px 8px;
|
|
80
|
+
border:1px solid var(--ax-border-2);color:var(--ax-accent);border-radius:4px}
|
|
81
|
+
.ax-brand__name{font-size:14px}
|
|
82
|
+
.ax-brand__subtitle{font-size:11px;color:var(--ax-muted);
|
|
83
|
+
border-left:1px solid var(--ax-border);padding-left:12px;margin-left:4px}
|
|
84
|
+
.ax-topbar__tabs{display:flex;gap:14px;min-width:0;overflow-x:auto;align-items:center}
|
|
85
|
+
/* Tier groups (System / Processes / Procedures) \u2014 visual separators
|
|
86
|
+
* mirror the docs/architecture/three-tier.md hierarchy. */
|
|
87
|
+
.ax-topbar__group{display:flex;align-items:center;gap:0;padding:0 4px;
|
|
88
|
+
border-left:1px solid var(--ax-border);position:relative}
|
|
89
|
+
.ax-topbar__group:first-child{border-left:none;padding-left:0}
|
|
90
|
+
.ax-topbar__group-label{font:inherit;font-family:var(--ax-mono);font-size:9px;
|
|
91
|
+
letter-spacing:0.08em;text-transform:uppercase;color:var(--ax-muted);
|
|
92
|
+
padding:0 8px;white-space:nowrap;opacity:0.7}
|
|
93
|
+
.ax-topbar__tab{background:transparent;border:none;color:var(--ax-text-2);
|
|
94
|
+
padding:8px 12px;font:inherit;cursor:pointer;font-size:12px;text-decoration:none;
|
|
95
|
+
border-bottom:2px solid transparent;letter-spacing:-0.005em;white-space:nowrap}
|
|
96
|
+
.ax-topbar__tab:hover{color:var(--ax-text)}
|
|
97
|
+
.ax-topbar__tab.is-active{color:var(--ax-text);border-bottom-color:var(--ax-accent)}
|
|
98
|
+
.ax-topbar__right{display:flex;align-items:center;gap:10px;font-size:11px;
|
|
99
|
+
color:var(--ax-muted);flex-shrink:0}
|
|
100
|
+
.ax-topbar__right .ax-mono{color:var(--ax-text-2)}
|
|
101
|
+
|
|
102
|
+
/* Running build: version, commit, running since; warns when the code on
|
|
103
|
+
* disk has moved on. */
|
|
104
|
+
.ax-build{display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
|
|
105
|
+
.ax-build[hidden]{display:none}
|
|
106
|
+
/* Two short lines, so the tabs keep their room on a laptop screen. */
|
|
107
|
+
.ax-build__lines{display:flex;flex-direction:column;font-size:10px;line-height:1.3}
|
|
108
|
+
.ax-build__stale{color:var(--ax-warn,var(--ax-accent));border:1px solid currentColor;
|
|
109
|
+
border-radius:4px;padding:1px 6px}
|
|
110
|
+
|
|
111
|
+
/* Mesh selector */
|
|
112
|
+
.ax-mesh-sel{position:relative;display:inline-flex;align-items:center;gap:6px;
|
|
113
|
+
padding:4px 10px;border:1px solid var(--ax-border-2);border-radius:4px;
|
|
114
|
+
background:var(--ax-surface);cursor:pointer;font:inherit;font-size:11px;
|
|
115
|
+
color:var(--ax-text-2);white-space:nowrap}
|
|
116
|
+
.ax-mesh-sel:hover{border-color:var(--ax-accent);color:var(--ax-text)}
|
|
117
|
+
.ax-mesh-sel.is-proxy{background:color-mix(in oklch,var(--ax-accent) 14%,var(--ax-surface));
|
|
118
|
+
border-color:color-mix(in oklch,var(--ax-accent) 45%,var(--ax-border-2));color:var(--ax-accent)}
|
|
119
|
+
.ax-mesh-sel .lbl{font-size:9px;letter-spacing:0.06em;text-transform:uppercase;color:var(--ax-muted);margin-right:2px}
|
|
120
|
+
.ax-mesh-sel .name{font-weight:500;color:var(--ax-text)}
|
|
121
|
+
.ax-mesh-sel .chev{font-size:9px;opacity:0.6;margin-left:2px}
|
|
122
|
+
.ax-mesh-menu{position:absolute;top:calc(100% + 4px);right:0;min-width:240px;
|
|
123
|
+
background:var(--ax-surface);border:1px solid var(--ax-border-2);
|
|
124
|
+
border-radius:6px;box-shadow:0 8px 24px rgba(0,0,0,0.4);padding:4px;z-index:30;display:none}
|
|
125
|
+
.ax-mesh-sel.is-open .ax-mesh-menu{display:block}
|
|
126
|
+
.ax-mesh-menu a{display:block;padding:7px 10px;border-radius:4px;text-decoration:none;
|
|
127
|
+
color:var(--ax-text-2);font-size:12px}
|
|
128
|
+
.ax-mesh-menu a:hover{background:var(--ax-surface-2);color:var(--ax-text)}
|
|
129
|
+
.ax-mesh-menu a.is-current{background:color-mix(in oklch,var(--ax-accent) 12%,var(--ax-surface));
|
|
130
|
+
color:var(--ax-accent);border:1px solid color-mix(in oklch,var(--ax-accent) 30%,var(--ax-border-2))}
|
|
131
|
+
.ax-mesh-menu a .row{display:flex;align-items:center;gap:8px}
|
|
132
|
+
.ax-mesh-menu a .row .dot{width:6px;height:6px;border-radius:50%;background:var(--ax-accent)}
|
|
133
|
+
.ax-mesh-menu a.is-offline .row .dot{background:var(--ax-border-2)}
|
|
134
|
+
.ax-mesh-menu a .url{font-family:var(--ax-mono);font-size:10px;color:var(--ax-muted);margin-top:2px}
|
|
135
|
+
|
|
136
|
+
/* Theme switcher segmented control */
|
|
137
|
+
.ax-theme-switch{display:inline-flex;border:1px solid var(--ax-border-2);
|
|
138
|
+
border-radius:4px;overflow:hidden}
|
|
139
|
+
.ax-theme-switch button{background:transparent;border:none;color:var(--ax-muted);
|
|
140
|
+
padding:3px 9px;font:inherit;font-size:10px;cursor:pointer;letter-spacing:0.04em;
|
|
141
|
+
text-transform:uppercase;font-family:var(--ax-mono);border-right:1px solid var(--ax-border-2)}
|
|
142
|
+
.ax-theme-switch button:last-child{border-right:none}
|
|
143
|
+
.ax-theme-switch button:hover{color:var(--ax-text);background:var(--ax-surface-2,var(--ax-surface))}
|
|
144
|
+
.ax-theme-switch button.is-active{color:var(--ax-accent);
|
|
145
|
+
background:color-mix(in oklch,var(--ax-accent) 12%,var(--ax-surface))}
|
|
146
|
+
|
|
147
|
+
/* Subheader \u2014 page-specific toolbar below the main topbar. Kanban uses it
|
|
148
|
+
* for the board picker + search + filters; others can use it for context
|
|
149
|
+
* bars if they want. */
|
|
150
|
+
.ax-subheader{display:flex;align-items:center;gap:10px;padding:10px 18px;
|
|
151
|
+
background:var(--ax-bg-elev);border-bottom:1px solid var(--ax-border);
|
|
152
|
+
flex-wrap:wrap}
|
|
153
|
+
.ax-subheader > * {flex-shrink:0}
|
|
154
|
+
.ax-subheader .spacer{flex:1}`,xg=`<script>
|
|
155
|
+
(function(){
|
|
156
|
+
function wireTheme(){
|
|
157
|
+
var sw = document.querySelectorAll('[data-theme-opt]');
|
|
158
|
+
if (!sw.length) return;
|
|
159
|
+
var current = document.documentElement.getAttribute('data-theme') || 'dark';
|
|
160
|
+
sw.forEach(function(b){
|
|
161
|
+
if (b.dataset.wired) return; b.dataset.wired = '1';
|
|
162
|
+
if (b.getAttribute('data-theme-opt') === current) b.classList.add('is-active');
|
|
163
|
+
b.addEventListener('click', function(){
|
|
164
|
+
var t = b.getAttribute('data-theme-opt');
|
|
165
|
+
document.documentElement.setAttribute('data-theme', t);
|
|
166
|
+
try { localStorage.setItem('ax-theme', t); } catch (e) {}
|
|
167
|
+
sw.forEach(function(x){ x.classList.toggle('is-active', x === b); });
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function currentPeer(){
|
|
172
|
+
try { return localStorage.getItem('ax-peer') || 'primary'; } catch { return 'primary'; }
|
|
173
|
+
}
|
|
174
|
+
function setCurrentPeer(id){
|
|
175
|
+
try {
|
|
176
|
+
if (id && id !== 'primary') localStorage.setItem('ax-peer', id);
|
|
177
|
+
else localStorage.removeItem('ax-peer');
|
|
178
|
+
} catch {}
|
|
179
|
+
}
|
|
180
|
+
function reflectPeerPill(){
|
|
181
|
+
var sel = document.querySelector('.ax-mesh-sel');
|
|
182
|
+
if (!sel) return;
|
|
183
|
+
var cur = currentPeer();
|
|
184
|
+
sel.classList.toggle('is-proxy', cur !== 'primary');
|
|
185
|
+
// If a proxy is active, update the visible pill label + highlight.
|
|
186
|
+
var picked = null;
|
|
187
|
+
sel.querySelectorAll('.ax-mesh-menu a').forEach(function(a){
|
|
188
|
+
a.classList.toggle('is-current', a.getAttribute('data-peer-id') === cur || (cur === 'primary' && a.getAttribute('data-peer-id') === 'primary'));
|
|
189
|
+
if (a.getAttribute('data-peer-id') === cur) picked = a;
|
|
190
|
+
});
|
|
191
|
+
if (picked) {
|
|
192
|
+
var name = picked.querySelector('span'); // first <span> inside .row
|
|
193
|
+
var visibleName = sel.querySelector('.name');
|
|
194
|
+
if (name && visibleName) visibleName.textContent = name.textContent.replace(/ \xB7 primary/, '');
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function wireMesh(){
|
|
198
|
+
var sel = document.querySelector('.ax-mesh-sel');
|
|
199
|
+
if (!sel || sel.dataset.wired) return; sel.dataset.wired = '1';
|
|
200
|
+
sel.addEventListener('click', function(e){
|
|
201
|
+
var link = e.target.closest('.ax-mesh-menu a[data-peer-action="proxy"]');
|
|
202
|
+
if (link) {
|
|
203
|
+
e.preventDefault();
|
|
204
|
+
setCurrentPeer(link.getAttribute('data-peer-id'));
|
|
205
|
+
reflectPeerPill();
|
|
206
|
+
sel.classList.remove('is-open');
|
|
207
|
+
// Reload so the admin panel re-reads state from the selected peer.
|
|
208
|
+
location.reload();
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (e.target.closest('.ax-mesh-menu a')) return; // plain navigate anchor
|
|
212
|
+
sel.classList.toggle('is-open');
|
|
213
|
+
});
|
|
214
|
+
document.addEventListener('click', function(e){
|
|
215
|
+
if (!sel.contains(e.target)) sel.classList.remove('is-open');
|
|
216
|
+
});
|
|
217
|
+
reflectPeerPill();
|
|
218
|
+
}
|
|
219
|
+
function wireHostRewrite(){
|
|
220
|
+
try {
|
|
221
|
+
var h = location.hostname || 'localhost';
|
|
222
|
+
document.querySelectorAll('.ax-topbar__tab[href*="__HOST__"]').forEach(function(a){
|
|
223
|
+
a.href = a.getAttribute('href').replace(/__HOST__/g, h);
|
|
224
|
+
});
|
|
225
|
+
} catch (e) {}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Make the topbar peer selector actually drive page content. When the
|
|
229
|
+
* operator picks a non-primary peer, every /api/admin/* request gets an
|
|
230
|
+
* X-Agentx-Peer header (and every EventSource on that path gets a ?peer=
|
|
231
|
+
* query, since EventSource can't set headers). The dashboard's existing
|
|
232
|
+
* proxy handler picks it up and forwards to the chosen peer.
|
|
233
|
+
*
|
|
234
|
+
* Without this hook, the activity-graph (and other admin pages) silently
|
|
235
|
+
* keep showing only the local node's data even after the operator picks
|
|
236
|
+
* a different peer in the topbar.
|
|
237
|
+
*/
|
|
238
|
+
function wirePeerProxy(){
|
|
239
|
+
if (window.__axPeerWired) return; window.__axPeerWired = true;
|
|
240
|
+
// Path-prefix allowlist for the peer-proxy interceptor. Extend here
|
|
241
|
+
// when a new admin-side surface needs to follow the mesh selector.
|
|
242
|
+
// /api/workflows is the workflow dashboard's read/write API \u2014 it
|
|
243
|
+
// lives outside /api/admin for legacy reasons, but the page is part
|
|
244
|
+
// of the admin surface and should proxy when a non-primary peer is
|
|
245
|
+
// selected (otherwise the workflows page on Mac shows local-only
|
|
246
|
+
// YAMLs while the runtime lives on peer).
|
|
247
|
+
function shouldProxy(url){
|
|
248
|
+
if (!url) return false;
|
|
249
|
+
// Admin-side surfaces that follow the mesh selector. Each entry
|
|
250
|
+
// is a path-prefix match. Extend when a new admin surface lands
|
|
251
|
+
// outside /api/admin/* but should still proxy when the operator
|
|
252
|
+
// picks a non-primary peer.
|
|
253
|
+
// /api/admin/ \u2014 original admin surface (activity, ledger, \u2026)
|
|
254
|
+
// /api/workflows \u2014 workflow editor + observability page
|
|
255
|
+
// /api/agents \u2014 agent dropdowns inside the workflow editor +
|
|
256
|
+
// anywhere else the page asks "which agents
|
|
257
|
+
// exist on the selected node?"
|
|
258
|
+
return url.indexOf('/api/admin/') >= 0
|
|
259
|
+
|| url.indexOf('/api/workflows') >= 0
|
|
260
|
+
|| url.indexOf('/api/agents') >= 0;
|
|
261
|
+
}
|
|
262
|
+
// The dashboard checks dashboard.token before it proxies to a peer
|
|
263
|
+
// (#1201), so a proxied call needs it even where the local route has no
|
|
264
|
+
// gate (/api/agents, /api/workflows). Same source as the pages use.
|
|
265
|
+
function localToken(){
|
|
266
|
+
if (window.AX_LOCAL_TOKEN) return window.AX_LOCAL_TOKEN;
|
|
267
|
+
try { return localStorage.getItem('ax_token') || ''; } catch (e) { return ''; }
|
|
268
|
+
}
|
|
269
|
+
var origFetch = window.fetch.bind(window);
|
|
270
|
+
window.fetch = function(input, init){
|
|
271
|
+
try {
|
|
272
|
+
var peer = currentPeer();
|
|
273
|
+
if (peer && peer !== 'primary') {
|
|
274
|
+
var url = typeof input === 'string' ? input : (input && input.url) || '';
|
|
275
|
+
if (shouldProxy(url)) {
|
|
276
|
+
init = init || {};
|
|
277
|
+
init.headers = new Headers(init.headers || (input && typeof input !== 'string' && input.headers) || {});
|
|
278
|
+
init.headers.set('X-Agentx-Peer', peer);
|
|
279
|
+
var tok = localToken();
|
|
280
|
+
if (tok && !init.headers.has('Authorization')) init.headers.set('Authorization', 'Bearer ' + tok);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
} catch (e) {}
|
|
284
|
+
return origFetch(input, init);
|
|
285
|
+
};
|
|
286
|
+
var OrigES = window.EventSource;
|
|
287
|
+
if (OrigES) {
|
|
288
|
+
window.EventSource = function(url, cfg){
|
|
289
|
+
try {
|
|
290
|
+
var peer = currentPeer();
|
|
291
|
+
if (peer && peer !== 'primary' && typeof url === 'string' && shouldProxy(url)) {
|
|
292
|
+
url += (url.indexOf('?') >= 0 ? '&' : '?') + 'peer=' + encodeURIComponent(peer);
|
|
293
|
+
}
|
|
294
|
+
} catch (e) {}
|
|
295
|
+
return new OrigES(url, cfg);
|
|
296
|
+
};
|
|
297
|
+
window.EventSource.prototype = OrigES.prototype;
|
|
298
|
+
window.EventSource.CONNECTING = OrigES.CONNECTING;
|
|
299
|
+
window.EventSource.OPEN = OrigES.OPEN;
|
|
300
|
+
window.EventSource.CLOSED = OrigES.CLOSED;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// wirePeerProxy() is synchronous and DOM-independent \u2014 it just wraps
|
|
304
|
+
// window.fetch + window.EventSource. Fire it IMMEDIATELY (before
|
|
305
|
+
// DOMContentLoaded) so deferred page bundles that issue their first
|
|
306
|
+
// fetch on bundle-parse (e.g. the workflow editor's React useEffect)
|
|
307
|
+
// see the wrapped fetch and pick up the X-Agentx-Peer header. Without
|
|
308
|
+
// this, the workflow editor's load on Mac:4202 hit local /api/workflows
|
|
309
|
+
// (instead of proxying to the selected peer), got a 404, and silently
|
|
310
|
+
// fell back to blank-graph state \u2014 looking like a "new workflow".
|
|
311
|
+
wirePeerProxy();
|
|
312
|
+
// Which build the daemon is running and since when, on every page; says
|
|
313
|
+
// so when the code on disk is newer. Asked again every minute, so a
|
|
314
|
+
// rebuild or a restart shows without a reload.
|
|
315
|
+
function wireBuild(){
|
|
316
|
+
var el = document.querySelector('.ax-build');
|
|
317
|
+
if (!el || el.dataset.wired) return; el.dataset.wired = '1';
|
|
318
|
+
function span(cls, text){ var s = document.createElement('span'); if (cls) s.className = cls; s.textContent = text; return s; }
|
|
319
|
+
function load(){
|
|
320
|
+
fetch('/api/node/build').then(function(r){ return r.ok ? r.json() : null; }).then(function(b){
|
|
321
|
+
if (!b || !b.version) return;
|
|
322
|
+
el.textContent = '';
|
|
323
|
+
var lines = span('ax-build__lines', '');
|
|
324
|
+
lines.appendChild(span('ax-mono', b.version + (b.commit ? ' \xB7 ' + b.commit : '')));
|
|
325
|
+
var d = b.startedAt ? new Date(b.startedAt) : null;
|
|
326
|
+
if (d && !isNaN(d.getTime())) {
|
|
327
|
+
lines.appendChild(span('', 'since ' + d.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
|
328
|
+
}
|
|
329
|
+
el.appendChild(lines);
|
|
330
|
+
if (b.diskNewer) {
|
|
331
|
+
var w = span('ax-build__stale', 'restart pending');
|
|
332
|
+
w.setAttribute('role', 'status');
|
|
333
|
+
el.appendChild(w);
|
|
334
|
+
}
|
|
335
|
+
el.title = (b.diskNewer
|
|
336
|
+
? 'The code on disk is newer than the running daemon. Restart the daemon to load it.'
|
|
337
|
+
: 'The build the daemon is running, and when it started.') + (b.node ? ' Node: ' + b.node : '');
|
|
338
|
+
el.hidden = false;
|
|
339
|
+
}).catch(function(){});
|
|
340
|
+
}
|
|
341
|
+
load();
|
|
342
|
+
setInterval(load, 60000);
|
|
343
|
+
}
|
|
344
|
+
function wire(){ wireHostRewrite(); wireTheme(); wireMesh(); wireBuild(); /* wirePeerProxy already ran */ }
|
|
345
|
+
if (document.readyState === 'loading') {
|
|
346
|
+
document.addEventListener('DOMContentLoaded', wire);
|
|
347
|
+
} else { wire(); }
|
|
348
|
+
})();
|
|
349
|
+
</script>`;function kg(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 Qa='<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}>
|
|
350
|
+
<div class="row"><span class="dot"></span><span>${j(l.name)}${p}</span></div>
|
|
351
|
+
${l.dashboardUrl?`<div class="url">${j(l.dashboardUrl)}</div>`:""}
|
|
352
|
+
${f}
|
|
353
|
+
</a>`}).join(""),s=`<div class="ax-mesh-sel" aria-haspopup="menu">
|
|
354
|
+
<span class="lbl">managing</span>
|
|
355
|
+
<span class="name">${j(r.name)}</span>
|
|
356
|
+
<span class="chev">\u25BE</span>
|
|
357
|
+
<div class="ax-mesh-menu" role="menu">${o}</div>
|
|
358
|
+
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:ce},{id:"live",label:"Live",href:`${ce}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:Un},{id:"people",label:"People",href:`${ce}#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:`${ce}#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">
|
|
359
|
+
<div class="ax-topbar__left">
|
|
360
|
+
<div class="ax-brand">
|
|
361
|
+
<span class="ax-brand__mark">AX</span>
|
|
362
|
+
<span class="ax-brand__name">AgentX</span>
|
|
363
|
+
<span class="ax-brand__subtitle">${j(t.subtitle)}</span>
|
|
364
|
+
</div>
|
|
365
|
+
<nav class="ax-topbar__tabs">${a}</nav>
|
|
366
|
+
</div>
|
|
367
|
+
<div class="ax-topbar__right">
|
|
368
|
+
${t.rightExtras||""}
|
|
369
|
+
${Qa}
|
|
370
|
+
${s}
|
|
371
|
+
<div class="ax-theme-switch" role="tablist" aria-label="Theme">
|
|
372
|
+
<button data-theme-opt="dark">Dark</button>
|
|
373
|
+
<button data-theme-opt="light">Light</button>
|
|
374
|
+
</div>
|
|
375
|
+
</div>
|
|
376
|
+
</header>${t.subheader?`<div class="ax-subheader">${t.subheader}</div>`:""}`}function j(t){return String(t||"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}import{existsSync as Ko,mkdirSync as Tl,readFileSync as Al,renameSync as Rl,writeFileSync as Il}from"fs";import{homedir as Dl}from"os";import{dirname as Cl,join as Nl}from"path";import{execFile as cl,execFileSync as dl}from"child_process";import{execFileSync as Za}from"child_process";import{existsSync as _o,mkdirSync as el,readdirSync as tl,readFileSync as $o,renameSync as nl,writeFileSync as rl}from"fs";import{homedir as To}from"os";import{join as $t}from"path";var P="siri:",Ao="com.apple.ttsbundle.gryphon-neural_",Ro=t=>!!t&&t.startsWith(Ao),ol=["/usr/bin/say","/usr/bin/defaults","/usr/bin/plutil"],sl=()=>{try{return Za("/usr/bin/defaults",["read","com.apple.Accessibility"],{stdio:"ignore",timeout:5e3}),!0}catch{return!1}},_t;function Tt(t={}){let e=t.platform!==void 0||t.exists!==void 0||t.prefDomain!==void 0;if(!e&&_t!==void 0)return _t;let{platform:n=process.platform,exists:r=_o,prefDomain:o=sl}=t,s=n==="darwin"&&ol.every(i=>r(i))&&o();return e||(_t=s),s}var Io=["/System/Library/AssetsV2/com_apple_MobileAsset_Trial_Siri_SiriTextToSpeech/purpose_auto","/System/Library/AssetsV2/com_apple_MobileAsset_UAF_Siri_TextToSpeech/purpose_auto"],Do={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"},At=t=>Do[t.toLowerCase()]??null;function Me(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 il=/com\.apple\.siri\.tts\.voice\.([a-z]{2})_([A-Z]{2})\.([a-z]+)\.neural\.premium/g;function al(t){let e=new Map;for(let n of t)for(let[,r,o,s]of n.matchAll(il)){let i=`${r}-${o}`,a=`${Ao}${s}_${i}_premium`;e.has(a)||e.set(a,{id:a,name:s[0].toUpperCase()+s.slice(1),locale:i,quality:"premium",gender:Do[s]??null,siri:!0})}return[...e.values()]}function Fe(t=Io,e={}){if(!Tt(e))return[];let n=[];for(let r of t){let o;try{o=tl(r)}catch{continue}for(let s of o)try{n.push($o($t(r,s,"Info.plist"),"latin1"))}catch{}}return al(n)}var Eo=`#!/bin/sh
|
|
377
|
+
# Written by agentx; shared by the daemon and AgentX Voice. Do not edit.
|
|
378
|
+
# siri-say.sh [voice] < text speak one line. A Siri voice id switches
|
|
379
|
+
# the OS default for it; any other id is
|
|
380
|
+
# passed to say -v.
|
|
381
|
+
# siri-say.sh --stop silence the line speaking, drop the queue.
|
|
382
|
+
# siri-say.sh --restore put back a voice a killed line left switched.
|
|
383
|
+
# AGENTX_SAY_RATE=<words a minute> sets the speed; unset, say's own.
|
|
384
|
+
D=com.apple.Accessibility K=SpokenContentDefaultVoiceSelectionsByLanguage
|
|
385
|
+
dir="$HOME/.agentx/voice" lock="$HOME/.agentx/voice/siri.lock" saved="$HOME/.agentx/voice/siri-saved.plist"
|
|
386
|
+
stops="$dir/stop"
|
|
387
|
+
read_s=\${AGENTX_SAY_READ_S:-5} stale_s=\${AGENTX_SAY_STALE_S:-30} max_s=\${AGENTX_SAY_MAX_S:-300}
|
|
388
|
+
assets=\${AGENTX_SIRI_ASSET_DIRS:-"${Io.join(" ")}"}
|
|
389
|
+
if [ "$1" = --stop ]; then
|
|
390
|
+
mkdir -p "$dir" || exit 1
|
|
391
|
+
# Queued lines see this change and drop. The owner's trap stops say,
|
|
392
|
+
# restores the voice, and frees the lock.
|
|
393
|
+
echo "$$ $(date +%s)" > "$stops"
|
|
394
|
+
owner=$(cat "$lock/pid" 2>/dev/null)
|
|
395
|
+
[ -n "$owner" ] && kill "$owner" 2>/dev/null
|
|
396
|
+
exit 0
|
|
397
|
+
fi
|
|
398
|
+
mode=speak
|
|
399
|
+
[ "$1" = --restore ] && { mode=restore; set --; }
|
|
400
|
+
case "$1" in com.apple.ttsbundle.gryphon-neural_*) siri=$1 voice= ;; *) siri= voice=$1 ;; esac
|
|
401
|
+
rate=\${AGENTX_SAY_RATE:-}
|
|
402
|
+
case "$rate" in *[!0-9]*) rate= ;; esac
|
|
403
|
+
case "$siri" in *[!A-Za-z0-9._-]*) echo "bad voice id" >&2; exit 2;; esac
|
|
404
|
+
# Not macOS, or no pref tools: speak as is and never touch a pref.
|
|
405
|
+
if [ "$(uname)" != Darwin ] || ! command -v defaults >/dev/null || ! command -v plutil >/dev/null; then
|
|
406
|
+
[ "$mode" = restore ] && exit 0
|
|
407
|
+
if [ -n "$voice" ]; then exec say \${rate:+-r "$rate"} -v "$voice"; else exec say \${rate:+-r "$rate"}; fi
|
|
408
|
+
fi
|
|
409
|
+
mkdir -p "$dir" || exit 1
|
|
410
|
+
mine=$(cat "$stops" 2>/dev/null)
|
|
411
|
+
stopped() { [ "$(cat "$stops" 2>/dev/null)" != "$mine" ]; }
|
|
412
|
+
txt=$(mktemp "\${TMPDIR:-/tmp}/agentx-say.XXXXXX") || exit 1
|
|
413
|
+
say_pid= dog=
|
|
414
|
+
restore() {
|
|
415
|
+
[ -f "$saved" ] || return 0
|
|
416
|
+
if [ -s "$saved" ]; then defaults write $D $K "$(cat "$saved")"; else defaults delete $D $K 2>/dev/null; fi
|
|
417
|
+
rm -f "$saved"
|
|
418
|
+
}
|
|
419
|
+
finish() {
|
|
420
|
+
[ -n "$say_pid" ] && kill "$say_pid" 2>/dev/null
|
|
421
|
+
[ -n "$dog" ] && { pkill -P "$dog" 2>/dev/null; kill "$dog" 2>/dev/null; }
|
|
422
|
+
restore; rm -rf "$lock"; rm -f "$txt"; exit "$1"
|
|
423
|
+
}
|
|
424
|
+
drop() { rm -f "$txt"; exit 75; }
|
|
425
|
+
# A Siri voice whose asset macOS purged: switching to it makes the OS
|
|
426
|
+
# speak a fallback of its own (Eloquence Flo), so leave the pref alone.
|
|
427
|
+
if [ -n "$siri" ]; then
|
|
428
|
+
s=\${siri#com.apple.ttsbundle.gryphon-neural_} ; name=\${s%%_*} ; s=\${s#*_} ; loc=$(printf %s "\${s%%_*}" | tr - _)
|
|
429
|
+
found=
|
|
430
|
+
for a in $assets; do
|
|
431
|
+
grep -aqs "com.apple.siri.tts.voice.$loc.$name.neural.premium" "$a"/*/Info.plist && { found=1; break; }
|
|
432
|
+
done
|
|
433
|
+
[ -z "$found" ] && { echo "Siri voice $siri is not installed; speaking with the OS default" >&2; siri=; }
|
|
434
|
+
fi
|
|
435
|
+
# The whole text first, before the lock: a writer that never closes stdin
|
|
436
|
+
# must not hold up every other speaker.
|
|
437
|
+
[ "$mode" = restore ] && exec 0</dev/null
|
|
438
|
+
exec 3<&0 0</dev/null
|
|
439
|
+
cat <&3 > "$txt" & cat_pid=$!
|
|
440
|
+
exec 3<&-
|
|
441
|
+
n=0
|
|
442
|
+
while kill -0 "$cat_pid" 2>/dev/null; do
|
|
443
|
+
if [ $n -ge $((read_s * 10)) ]; then
|
|
444
|
+
kill "$cat_pid" 2>/dev/null; echo "stdin never closed; nothing said" >&2; rm -f "$txt"; exit 3
|
|
445
|
+
fi
|
|
446
|
+
sleep 0.1; n=$((n + 1))
|
|
447
|
+
done
|
|
448
|
+
# One speaker at a time. A lock whose owner died is taken over. A line
|
|
449
|
+
# that waits past stale_s, or that a stop overtook, is dropped unsaid.
|
|
450
|
+
n=0
|
|
451
|
+
while ! mkdir "$lock" 2>/dev/null; do
|
|
452
|
+
stopped && drop
|
|
453
|
+
if [ $n -ge $((stale_s * 10)) ]; then echo "waited \${stale_s}s for the speaker; dropped" >&2; drop; fi
|
|
454
|
+
owner=$(cat "$lock/pid" 2>/dev/null)
|
|
455
|
+
if [ -n "$owner" ] && ! kill -0 "$owner" 2>/dev/null; then rm -rf "$lock"
|
|
456
|
+
elif [ -z "$owner" ] && [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then rm -rf "$lock"
|
|
457
|
+
else sleep 0.1; n=$((n + 1)); fi
|
|
458
|
+
done
|
|
459
|
+
echo $$ > "$lock/pid"
|
|
460
|
+
trap 'finish 143' TERM INT HUP
|
|
461
|
+
stopped && finish 75
|
|
462
|
+
[ "$mode" = restore ] && finish 0
|
|
463
|
+
restore
|
|
464
|
+
if [ -n "$siri" ]; then
|
|
465
|
+
lang=$(defaults read -g AppleLanguages 2>/dev/null | sed -n '2s/^[^A-Za-z]*\\([A-Za-z]*\\).*/\\1/p')
|
|
466
|
+
defaults export $D - 2>/dev/null | plutil -extract $K xml1 -o "$saved.tmp" - 2>/dev/null || : > "$saved.tmp"
|
|
467
|
+
mv "$saved.tmp" "$saved"
|
|
468
|
+
defaults write $D $K -array "\${lang:-en}" "{ _type = \\"Speech.VoiceSelection\\"; _version = 0; voiceId = \\"$siri\\"; }"
|
|
469
|
+
fi
|
|
470
|
+
# A watchdog: no line runs past its length's worth of speech (a hung say
|
|
471
|
+
# held the lock for minutes), capped at max_s.
|
|
472
|
+
limit=$((5 + $(wc -w < "$txt") * 6 / 10))
|
|
473
|
+
[ $limit -gt $max_s ] && limit=$max_s
|
|
474
|
+
if [ -n "$voice" ]; then say \${rate:+-r "$rate"} -v "$voice" -f "$txt" & else say \${rate:+-r "$rate"} -f "$txt" & fi
|
|
475
|
+
say_pid=$!
|
|
476
|
+
( sleep "$limit"; echo "say ran past \${limit}s; stopped" >&2; kill "$say_pid" 2>/dev/null ) & dog=$!
|
|
477
|
+
wait "$say_pid"
|
|
478
|
+
status=$?
|
|
479
|
+
say_pid=
|
|
480
|
+
finish $status
|
|
481
|
+
`,ll=(t=To())=>$t(t,".agentx","voice","siri-say.sh");function Co(t=To()){let e=ll(t);return _o(e)&&$o(e,"utf8")===Eo||(el($t(t,".agentx","voice"),{recursive:!0}),rl(`${e}.tmp`,Eo,{mode:493}),nl(`${e}.tmp`,e)),e}var No=`ObjC.import("AVFoundation")
|
|
482
|
+
const vs = $.AVSpeechSynthesisVoice.speechVoices, out = []
|
|
483
|
+
for (let i = 0; i < vs.count; i++) {
|
|
484
|
+
const v = vs.objectAtIndex(i)
|
|
485
|
+
out.push([v.identifier.js, v.name.js, v.language.js, Number(v.quality), Number(v.gender)].join("\\t"))
|
|
486
|
+
}
|
|
487
|
+
out.join("\\n")`,ul=new Set(["Fred","Kathy","Ralph","Junior"]),pl={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 Oo(t){let e=[];for(let n of t.split(`
|
|
488
|
+
`)){let[r,o,s,i,a]=n.split(" ");!r||!o||!s||r.includes(".siri_")||r.startsWith("com.apple.speech.synthesis.voice.")&&!ul.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":pl[o]??null})}return e}var gl=10*60*1e3,Dg=60*1e3,re=null,Rt=!1;function It(t=Date.now(),e=gl){if(process.platform!=="darwin")return[];if(re)t-re.at>e&&!Rt&&(Rt=!0,cl("osascript",["-l","JavaScript","-e",No],{timeout:1e4},(n,r)=>{Rt=!1,n||(re={at:Date.now(),voices:[...Oo(String(r)),...Fe()]})}));else try{re={at:t,voices:[...Oo(dl("osascript",["-l","JavaScript","-e",No],{encoding:"utf8",timeout:1e4})),...Fe()]}}catch(n){Dt(`[voice] could not list system voices: ${String(n?.message??n).split(`
|
|
489
|
+
`)[0]}`),re={at:t,voices:Fe()}}return re.voices}var Dt=t=>process.stderr.write(t+`
|
|
490
|
+
`),Ue=new Set;function Cg(t){Dt=t}function Y(t,e){Ue.has(t)||(Ue.add(t),Dt(e))}function Mo(t){for(let e of Ue)t(e)&&Ue.delete(e)}var Fo=()=>{};function Ng(t){Fo=t}function Uo(t){try{Fo(t)}catch(e){Y("missing-hook",`[voice] missing-voice check failed: ${e?.message??e}`)}}var ml={premium:3,enhanced:2,standard:1},fl=new Set(["Grandma","Grandpa"]);function Lo(t){let e=t.id.startsWith("com.apple.voice.")?2:t.id.startsWith("com.apple.eloquence.")&&!fl.has(t.name)?1:0;return ml[t.quality]*10+e}var oe=t=>t.toLowerCase().split(/[-_]/)[0],Po=t=>t.id.startsWith("com.apple.voice.");function Ct(t,e,n,r=new Set){let o=me(t.filter(a=>!a.siri&&oe(a.locale)===oe(e)),e);if(o.some(Po)&&(o=o.filter(Po)),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 me(t,e="en"){let n=e.toLowerCase().replace("_","-"),r=oe(e),o=t.filter(s=>oe(s.locale)===r);return(o.length?o:t).slice().sort((s,i)=>Lo(i)-Lo(s)||+(i.locale.toLowerCase()===n)-+(s.locale.toLowerCase()===n)||s.name.localeCompare(i.name)||s.locale.localeCompare(i.locale))}function fe(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=me(e.filter(u=>u.siri&&u.name.toLowerCase()===l),n)[0];if(c||!l)return c??null;let p=fe(l,e.filter(u=>oe(u.locale)===oe(n)),n);return p&&Y(`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=me(e.filter(l=>l.name.toLowerCase()===i),n);return(s?a.find(l=>l.quality===s[2].toLowerCase()):void 0)??a[0]??null}function Wo(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}_n();var Nt="system",hl=t=>t.trim().toLowerCase()===Nt,bl="21m00Tcm4TlvDq8ikWAM";function Ot(t,e,n={},r=It()){let o=e[t],s=o?.name||t,i=o?.voice,a=Pt(e,n,r).get(t)??null,d=kl(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?je(a):null,systemByLanguage:d,fallback:(n.fallback??"system")==="system",gender:i?.gender??null,style:i?.style||null,intro:i?.intro||Sl(s,o?.systemPrompt),...i?.rate?{rate:i.rate}:{},...i?.priority?{priority:i.priority}:{}}}var je=t=>`${t.name}${t.siri?" (Siri)":t.quality==="standard"?"":` (${t.quality[0].toUpperCase()}${t.quality.slice(1)})`} ${t.locale}`;function yl(t,e,n,r){if(!e||!n.length)return null;let o=fe(e,n,r);return o||(Y(`${t}:${e}`,`[voice] ${t}: system voice "${e}" is not installed; using the next choice. Run \`agentx voice list\` to see installed voices.`),Uo(e)),o}function Ho(t,e){let n=t.trim();if(n.toLowerCase().startsWith(P))return{locale:e,gender:At(n.slice(P.length).trim())};let r=Me(n);return r?{locale:r.locale,gender:At(r.name)}:{locale:/^com\.apple\.voice\.[a-z]+\.([a-z]{2}-[A-Z]{2})\./.exec(n)?.[1]??e,gender:null}}var Vo=t=>t.toLowerCase().split(/[-_]/)[0],jo=(t,e)=>typeof t=="string"?t:t?.[Vo(e)];function We(t,e,n,r){if(e!==void 0)return hl(e)?null:yl(t,e,n,r)??void 0}var Lt=(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=We("voice.system",jo(e.system,o),n,o),d=()=>new Set([...r,...[...s.values()].flatMap(c=>c?[c.name]:[])]);for(let c of t){let p=jo(c.system,o),u=We(c.id,p,n,o),g=u!==void 0?u:p!==void 0&&n.length?xl(c,p,o,a,n,d()):a!==void 0&&Lt(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 Wo(i,me(n.filter(u=>!u.siri),o),l))s.set(c,p);return s}function xl(t,e,n,r,o,s){for(let a of t.fallbacks??[]){let d=We(`${t.id}.fallbacks`,a,o,n);if(d!==void 0)return d}if(r!==void 0&&Lt(r,t.gender))return r;let i=Ho(e,n);return Ct(o,i.locale,t.gender??i.gender,s)??void 0}function kl(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=We(`${a}.${c}`,p,o,c);u===void 0&&o.length&&(u=Ct(o,c,n??Ho(p,c).gender)??void 0),u!==void 0&&l(u)&&(s[Vo(c)]=u)}};return i("voice.system",r.system,a=>Lt(a,n)),i(t,e,()=>!0),s}function Fg(t,e){let n=e?_e(e):null;if(!n||!(n in t.systemByLanguage))return t;let r=t.systemByLanguage[n];return{...t,systemVoice:r?.id??null,systemVoiceName:r?je(r):null}}function Pt(t,e={},n=It()){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 Mt(t,e){let n={provider:t.provider,elevenlabs:vl(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 vl(t,e){return t||e||process.env.AGENTX_VOICE_ID||bl}function Sl(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 El=8*60*60*1e3,_l=500,qo=class{constructor(e=El){this.gapMs=e}lastSpoke=new Map;needsIntro(e,n,r=Date.now()){let o=this.lastSpoke.get(Bo(e,n));return o===void 0||r-o>this.gapMs}spoke(e,n,r=Date.now()){let o=Bo(e,n);this.lastSpoke.delete(o),this.lastSpoke.set(o,r),this.lastSpoke.size>_l&&this.lastSpoke.delete(this.lastSpoke.keys().next().value)}},Bo=(t,e)=>`${t}\0${e}`;function Xo(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 Ug(t,e,n,r={}){let o=e[t],s=Ot(t,e,r),i=(o?.systemPrompt??"").split(/\n\s*\n/)[0].slice(0,600).trim();return{agentId:t,name:s.name,voice:Mt(s),persona:i||`You are ${s.name}.`,introLine:Xo(s,n)}}var $l="[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 Wg(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`${$l}
|
|
491
|
+
${Xo(o,e.voice.introduce===!0&&!!r)}`}var Ol="System Settings \u203A Accessibility \u203A Spoken Content \u203A System voice \u203A Manage Voices",Go=(t=Dl())=>Nl(t,".agentx","voice","health.json");function Ll(t,e,n){let r=t.trim();if(!r||r.toLowerCase()===Nt)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 fe(r,e,n)!==null}function Pl(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 Ml(t,e){if(!e.length)return[];let n=new Map,r;for(let{owner:o,name:s,locale:i,perLanguage:a}of Pl(t)){if(Ll(s,e,i))continue;r??=Pt(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?je(l):"the OS default voice"),n.set(s,d)}return[...n.values()]}function Ft(t){let e=Me(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 Fl(t){let e=t.map(n=>{let r=n.agents.map(o=>n.speaksWith[o]?`${o} (now ${n.speaksWith[o]})`:o).join(", ");return`\u2022 ${Ft(n.voice)}: ${r}`});return{title:t.length===1?"AgentX: a voice is not installed":`AgentX: ${t.length} voices are not installed`,message:`${e.join(`
|
|
492
|
+
`)}
|
|
493
|
+
Reinstall in ${Ol}. Agents switch back on their own once it is installed.`}}function Ul(t=Go()){if(!Ko(t))return null;try{let e=JSON.parse(Al(t,"utf8"));return e&&Array.isArray(e.missing)?e:null}catch{return null}}function Wl(t,e){Tl(Cl(t),{recursive:!0}),Il(`${t}.tmp`,JSON.stringify(e,null,2)+`
|
|
494
|
+
`),Rl(`${t}.tmp`,t)}var zo=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??Go(),s=new Map((Ul(o)?.missing??[]).map(p=>[p.voice,p])),i=Ml(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] ${Ft(p)} is installed again; its agents speak with it again`);d.length&&Mo(p=>d.some(u=>p===u||p.endsWith(`:${u}`)));let l=a.filter(p=>!p.notifiedAt);if(l.length){let{title:p,message:u}=Fl(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=>Ft(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(!Ko(o)||JSON.stringify(a)!==JSON.stringify([...s.values()]))&&Wl(o,c),c}finally{this.running=!1}}};import{randomBytes as Yo}from"crypto";var J={content:32e3,messagesPerConversation:200,conversationsPerDevice:100,toolsPerMessage:50,filesPerMessage:W.perMessage},jl=/^[a-f0-9]{32}$/,ql=/^c[a-z0-9]{8,32}$/,Bl=/^#[0-9a-fA-F]{6}$/;function Ut(t){return ql.test(t)}var Jo=class{constructor(e){this.db=e;e.exec(`CREATE TABLE IF NOT EXISTS app_chat_conversations (
|
|
495
|
+
id TEXT PRIMARY KEY, device_id TEXT NOT NULL, title TEXT NOT NULL,
|
|
496
|
+
node TEXT NOT NULL, node_name TEXT NOT NULL, agent TEXT NOT NULL, agent_name TEXT,
|
|
497
|
+
created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);
|
|
498
|
+
CREATE INDEX IF NOT EXISTS app_chat_conversations_device ON app_chat_conversations(device_id, updated_at);
|
|
499
|
+
CREATE TABLE IF NOT EXISTS app_chat_messages (
|
|
500
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, conversation_id TEXT NOT NULL, role TEXT NOT NULL,
|
|
501
|
+
content TEXT NOT NULL, status TEXT, error TEXT, ui TEXT, tools TEXT, at INTEGER NOT NULL);
|
|
502
|
+
CREATE INDEX IF NOT EXISTS app_chat_messages_conversation ON app_chat_messages(conversation_id, id);
|
|
503
|
+
CREATE TABLE IF NOT EXISTS app_chat_files (
|
|
504
|
+
id TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, message_id INTEGER NOT NULL,
|
|
505
|
+
path TEXT NOT NULL, name TEXT NOT NULL, mime TEXT NOT NULL, kind TEXT NOT NULL, created_at INTEGER NOT NULL);
|
|
506
|
+
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 (
|
|
507
|
+
key TEXT PRIMARY KEY, conversation_id TEXT NOT NULL, at INTEGER NOT NULL)`)}ownerOf(e){return Ut(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)}${Yo(4).toString("hex")}`,{color:i,...a}=n,d=i&&Bl.test(i)?i:void 0,l={id:s,title:Zo(r),...a,...d?{color:d}:{},createdAt:o,updatedAt:o,messages:[]};return this.db.prepare(`INSERT INTO app_chat_conversations
|
|
508
|
+
(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(!Ut(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(Hl);return{...Qo(r),messages:o}}list(e,n=J.conversationsPerDevice){return this.db.prepare(`SELECT c.*,
|
|
509
|
+
(SELECT COUNT(*) FROM app_chat_messages m WHERE m.conversation_id = c.id) AS n,
|
|
510
|
+
(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
|
|
511
|
+
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{...Qo(o),messages:o.n,...s?{last:s}:{}}})}markRead(e,n,r=Date.now()){Ut(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 = ?
|
|
512
|
+
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,
|
|
513
|
+
substr(m.content, 1, 240) AS answer, m.status, m.at
|
|
514
|
+
FROM app_chat_conversations c
|
|
515
|
+
JOIN app_chat_messages m ON m.id = (SELECT MAX(id) FROM app_chat_messages WHERE conversation_id = c.id)
|
|
516
|
+
WHERE c.device_id = ? AND m.role = 'assistant' AND m.at > COALESCE(c.read_at, 0)
|
|
517
|
+
ORDER BY m.at DESC, m.id DESC LIMIT ?`).all(e,Math.max(0,n)).map(o=>({id:o.id,title:o.title,agent:o.agent,...o.agent_name?{agentName:o.agent_name}:{},...o.color?{color:o.color}:{},answer:String(o.answer??"").trim(),status:o.status==="error"||o.status==="stopped"?o.status:"done",at:o.at}))}append(e,n,r){return this.appendWithFiles(e,n,r)!==null}appendWithFiles(e,n,r,o=[]){if(!this.db.prepare("SELECT 1 FROM app_chat_conversations WHERE id = ? AND device_id = ?").get(n,e))return null;let i=r.content.length>J.content?r.content.slice(0,J.content)+`
|
|
518
|
+
|
|
519
|
+
[Cut here: the full answer is in the agent's task history.]`:r.content,a=r.tools?.slice(0,J.toolsPerMessage),d=[];for(let u of o){if(d.length>=J.filesPerMessage)break;let g=u.filename.trim(),m=de(g);if(!m||!g||g.length>W.pathChars||g.includes("\0"))continue;let f=(g.split(/[\\/]/).pop()||g).slice(0,120);d.push({id:Yo(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)
|
|
520
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,r.role,i,r.status??null,r.error?.slice(0,500)??null,r.ui?JSON.stringify(r.ui):null,a?.length?JSON.stringify(a):null,l.length?JSON.stringify(l):null,r.at),p=this.db.prepare(`INSERT INTO app_chat_files (id, conversation_id, message_id, path, name, mime, kind, created_at)
|
|
521
|
+
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
|
|
522
|
+
(SELECT id FROM app_chat_messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?)`).run(n,n,J.messagesPerConversation),this.db.prepare(`DELETE FROM app_chat_files WHERE conversation_id = ? AND message_id NOT IN
|
|
523
|
+
(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(!jl.test(n))return null;let r=this.db.prepare(`SELECT f.*, c.node, c.agent FROM app_chat_files f
|
|
524
|
+
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 = ?
|
|
525
|
+
ORDER BY updated_at DESC, rowid DESC LIMIT -1 OFFSET ?`).all(e,J.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 Qo(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 Hl(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 Zo(t){let e=/^\[Call answered\][^"]*"([^"]+)"/.exec(t);if(e)return Zo(`Call: ${e[1]}`);let n=t.replace(/\s+/g," ").trim();return(n.length>60?n.slice(0,59)+"\u2026":n)||"Untitled"}import{readFileSync as jt,writeFileSync as ss,existsSync as qt,readdirSync as ec,statSync as tc}from"fs";import{resolve as Bt,join as nc}from"path";import{existsSync as es,mkdirSync as Vl,readFileSync as Xl,writeFileSync as ts}from"fs";import{dirname as zl,resolve as ns}from"path";import{z as v}from"zod";var Kl=v.object({type:v.enum(["gitlab","github"]),host:v.string().optional(),project:v.string(),iid:v.number().int().positive(),url:v.string()}),Gl=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:Kl.optional(),importedAt:v.string().optional(),createdAt:v.string(),updatedAt:v.string(),blocker:v.string().optional(),doneNote:v.string().optional()}),Yl=v.object({version:v.literal(1),items:v.array(Gl).default([])}),qe=class{constructor(e){this.path=e}jsonPath(){return ns(process.cwd(),this.path).replace(/\.md$/i,".json")}mdPath(){return ns(process.cwd(),this.path).replace(/\.json$/i,".md")}exists(){return es(this.jsonPath())}load(){let e=this.jsonPath();if(!es(e))return{version:1,items:[]};let n=Xl(e,"utf-8");try{return Yl.parse(JSON.parse(n))}catch(r){throw new Error(`Backlog file invalid (${e}): ${r.message}`)}}save(e){let n=this.jsonPath();Vl(zl(n),{recursive:!0}),ts(n,JSON.stringify(e,null,2)+`
|
|
526
|
+
`),ts(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(`
|
|
527
|
+
`)}};function tm(t){return`${t.type}:${t.project}:${t.iid}`}function rs(t,e,n){let r=[];if(e.type==="gitlab"){let o=n.channels.gitlab?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.gitlabUsernames?.length?r.push(i.gitlabUsernames[0]):r.push(s)}}else if(e.type==="github"){let o=n.channels.github?.agentMappings??[];for(let s of t){let i=o.find(a=>a.agentId===s);i?.githubUsernames?.length?r.push(i.githubUsernames[0]):r.push(s)}}return r}async function Wt(t,e,n,r=()=>{}){return t.source?Jl(t.source,e,n,r):{ok:!0,attempts:[]}}async function Jl(t,e,n,r=()=>{}){return t.type==="gitlab"?Ql(t,e,n,r):t.type==="github"?Zl(t,e,n,r):{ok:!1,error:`unknown source.type ${t.type}`,attempts:[]}}async function Ql(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 Zl(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 Ht=/^(\s*)-\s*\[( |x|X)\]\s*(.*)$/,Be=/@([a-z0-9_-]+)/i,os=/\[time:\s*([0-9hm\s]+)\]/i;function rc(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 Vt=class{constructor(e,n,r=()=>{}){this.path=e;this.daemon=n;this.log=r;this.store=new qe(this.path)}type="backlog";capabilities={listAll:!0,create:!1,transition:!1,labels:!0,search:!1};store;getStore(){return this.store}readMd(){let e=Bt(process.cwd(),this.path);return qt(e)?jt(e,"utf-8").split(`
|
|
528
|
+
`):[]}writeMd(e){let n=Bt(process.cwd(),this.path);ss(n,e.join(`
|
|
529
|
+
`))}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(Ht);if(!s||s[2].toLowerCase()==="x")continue;let a=s[3],d=a.match(Be);if(d&&d[1].toLowerCase()!==e.toLowerCase())continue;let l=a.match(os),c=a.replace(Be,"").replace(os,"").trim();r.push({id:`backlog:${o}`,title:c||`Task at line ${o+1}`,assignee:d?d[1]:void 0,estimatedSeconds:l?rc(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=rs([o.assignee||e],o.source,this.daemon);Wt(o,{assigneeUsernames:s,addLabels:["Doing"],removeLabels:["To Do"]},this.daemon,this.log).catch(i=>this.log(`[backlog-sync] claim failed for ${n}: ${i?.message??i}`))}}async report(e,n){if(this.store.exists()&&this.store.findById(e)){let a={};n.status==="done"?a.status="done":n.status==="blocked"?(a.status="blocked",a.blocker=n.blocker||n.note||void 0):n.status==="in-progress"&&(a.status="doing"),n.timeSeconds&&(a.estimatedSeconds=n.timeSeconds);let 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&&Wt(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(Ht))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"}}},Xt=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(qt(e))for(let r of ec(e)){let o=nc(e,r);tc(o).isDirectory()?this.walk(o,n):r.endsWith(".md")&&n.push(o)}}async listOpen(e){let n=[];this.walk(Bt(process.cwd(),this.root),n);let r=[];for(let o of n){let s=jt(o,"utf-8").split(`
|
|
530
|
+
`);for(let i=0;i<s.length;i++){let a=s[i].match(Ht);if(!a||a[2].toLowerCase()==="x")continue;let d=a[3].match(Be);!d||d[1].toLowerCase()!==e.toLowerCase()||r.push({id:`wiki:${o}:${i}`,title:a[3].replace(Be,"").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(!qt(s))return;let i=jt(s,"utf-8").split(`
|
|
531
|
+
`);n.status==="done"&&i[o]&&(i[o]=i[o].replace(/- \[ \]/,"- [x]"),ss(s,i.join(`
|
|
532
|
+
`)))}},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 lm(t,e,n){let r=t.workSource;switch(r.type){case"backlog":return new Vt(r.path,e,n);case"wiki":return new Xt(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 Kt="unmapped";function Gt(t,e=[]){if(!t)return Kt;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 oc(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,Gt(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 sc(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 um(t,e){let n=sc(t.channel,{chatId:t.chatId,username:t.username},e.contactMap);if(n)return n.client;if(t.project)return Gt(t.project,e.projects);if(t.agentId){let r=oc(e).get(t.agentId);if(r)return r}return Kt}function pm(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 ic=t=>t===Kt?"internal":"client";function ac(t,e){let n=e.clients?.[t];return{id:t,name:n?.name||t,kind:n?.kind??ic(t),respondWithinMinutes:lc(n?.respondWithin),standing:n?.standing??[],declared:!!n}}function gm(t){let e=new Set;for(let n of t.projects??[])e.add(Gt(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=>ac(n,t))}function lc(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 cc}from"crypto";var hm={enabled:!0,repeatWindowHours:24,channels:["push","ntfy"],addresses:[],digestNags:!0},dc=40,uc=20,bm=90,pc=2e3,is=36e5;function gc(t,e,n){if(t.key?.trim())return t.key.trim().slice(0,200);if(!t.textKey)return null;let r=`${e}
|
|
533
|
+
${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<dc?null:`text:${cc("sha256").update(r).digest("hex").slice(0,24)}`}function ym(t){let e=t.indexOf(`
|
|
534
|
+
`);return e<0?{title:t.trim(),body:""}:{title:t.slice(0,e).trim(),body:t.slice(e+1).trim()}}function Yt(t){t.exec(`
|
|
535
|
+
CREATE TABLE IF NOT EXISTS owner_told (
|
|
536
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
537
|
+
at INTEGER NOT NULL,
|
|
538
|
+
item_key TEXT NOT NULL,
|
|
539
|
+
request_id TEXT,
|
|
540
|
+
kind TEXT NOT NULL,
|
|
541
|
+
channel TEXT NOT NULL,
|
|
542
|
+
chat_id TEXT NOT NULL,
|
|
543
|
+
sender TEXT,
|
|
544
|
+
title TEXT NOT NULL,
|
|
545
|
+
text TEXT NOT NULL,
|
|
546
|
+
outcome TEXT NOT NULL,
|
|
547
|
+
digested_at INTEGER
|
|
548
|
+
);
|
|
549
|
+
CREATE INDEX IF NOT EXISTS idx_owner_told_key_at ON owner_told(item_key, at);
|
|
550
|
+
CREATE INDEX IF NOT EXISTS idx_owner_told_at ON owner_told(at);
|
|
551
|
+
CREATE INDEX IF NOT EXISTS idx_owner_told_digest ON owner_told(outcome, digested_at);
|
|
552
|
+
`);let e=new Set(t.prepare("PRAGMA table_info(owner_told)").all().map(n=>n.name));for(let[n,r]of mc)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 mc=[["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 He(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 as=class{constructor(e){this.db=e;Yt(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)
|
|
553
|
+
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,pc),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?He(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?He(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(He)}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(He)}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,
|
|
554
|
+
SUM(CASE WHEN answered_at IS NULL AND seen_at IS NOT NULL THEN 1 ELSE 0 END) AS seen,
|
|
555
|
+
SUM(CASE WHEN answered_at IS NOT NULL THEN 1 ELSE 0 END) AS answered
|
|
556
|
+
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}},ls=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=gc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,uc):r.repeatWindowHours)*is,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:fc(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*is)}};function wm(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 fc(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}.`}var hc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,bc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Ve(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(bc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=yc(r);if(!o)return{cleanText:t};let s=n.index??0,i=n[1]??"";return{cleanText:(t.slice(0,s)+i+t.slice(s+n[0].length)).trim(),ui:o}}function km(t){if(!t||!t.includes("agentx:ui"))return t;let e=hc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function yc(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n={};if(Array.isArray(e.buttons)){let r=[],o=[],s=[];for(let i of e.buttons)!i||typeof i.label!="string"||(typeof i.url=="string"&&/^https?:\/\//i.test(i.url)?r.push({label:i.label,url:i.url}):typeof i.reply=="string"&&i.reply.trim()?o.push({label:i.label,reply:i.reply.trim()}):i.action!=null&&s.push(i.label));r.length&&(n.buttons=r),o.length&&(n.replies=o),s.length&&(n.skippedActions=s)}if(e.poll&&typeof e.poll=="object"){let r=e.poll.question,o=e.poll.options;typeof r=="string"&&r.trim()&&Array.isArray(o)&&o.filter(s=>typeof s=="string").length>=2&&(n.poll={question:r,options:o.filter(s=>typeof s=="string"),multiple:e.poll.multiple===!0})}if(e.media&&typeof e.media=="object"){let{type:r,url:o,caption:s}=e.media;["image","document","audio","video"].includes(r)&&typeof o=="string"&&o&&(n.media={type:r,url:o,...typeof s=="string"?{caption:s}:{}})}if(Array.isArray(e.quickReplies)){let r=e.quickReplies.filter(o=>typeof o=="string"&&o.trim()).map(o=>o.trim());r.length&&(n.quickReplies=r)}return!n.buttons&&!n.poll&&!n.media&&!n.quickReplies&&!n.replies&&!n.skippedActions?null:n}function Sm(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 wc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var cs=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
|
|
557
|
+
data: ${JSON.stringify(n)}
|
|
558
|
+
|
|
559
|
+
`):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+wc),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 xc,readFileSync as ds,renameSync as kc,rmSync as vc,writeFileSync as Sc}from"fs";import{homedir as Ec}from"os";import{dirname as _c,join as $c}from"path";var us=$c(Ec(),".agentx","call.json");function Tc(t=us,e=Date.now()){try{let n=JSON.parse(ds(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 ps(t=Xn,e=Tc){let n=t();return n.active?n:e()}function Rm(t,e,n=us,r=Date.now()){let o=null;try{o=JSON.parse(ds(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&vc(n,{force:!0});return}xc(_c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Sc(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
|
|
560
|
+
`),kc(s,n)}var gs="owner",Xe=6e4,ys=60*Xe,Ac=24*ys,Rc=7*24*ys,Ic=2*Xe,Cm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Dc(t){t.exec(`
|
|
561
|
+
CREATE TABLE IF NOT EXISTS owner_presence (
|
|
562
|
+
person TEXT NOT NULL,
|
|
563
|
+
surface TEXT NOT NULL,
|
|
564
|
+
at INTEGER NOT NULL,
|
|
565
|
+
PRIMARY KEY (person, surface)
|
|
566
|
+
);
|
|
567
|
+
`)}var ms=class{constructor(e,n=Date.now,r=3e4){this.db=e;this.now=n;this.throttleMs=r;Dc(e)}written=new Map;touch(e,n=gs){let r=this.now(),o=`${n}
|
|
568
|
+
${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 (?, ?, ?)
|
|
569
|
+
ON CONFLICT(person, surface) DO UPDATE SET at = MAX(at, excluded.at)`).run(n,e.slice(0,200),r))}list(e=gs){return this.db.prepare("SELECT surface, at FROM owner_presence WHERE person = ? ORDER BY at DESC").all(e)}};function Nm(t,e){let n=t.toLowerCase().split("@")[0];return n==="app"?"phone":n==="dashboard"||n==="voice"||n==="webrtc"?"computer":`${n}:${e}`}var fs=class{constructor(e,n=Date.now){this.db=e;this.now=n;Yt(e)}openRequestRows(){return this.db.prepare(`SELECT id, request_id AS requestId, at FROM owner_told
|
|
570
|
+
WHERE request_id IS NOT NULL AND answered_at IS NULL AND outcome IN ('sent', 'held') AND at >= ?
|
|
571
|
+
ORDER BY at DESC LIMIT 500`).all(this.now()-Rc)}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-Ic,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 = ?
|
|
572
|
+
WHERE seen_at IS NULL AND (${hs(e)})`).run(r,n,...e,...e,...e).changes:0}answered(e,n,r=this.now()){return e.length?this.db.prepare(`UPDATE owner_told SET answered_at = ?, answered_via = ?, seen_at = COALESCE(seen_at, ?), seen_via = COALESCE(seen_via, ?)
|
|
573
|
+
WHERE answered_at IS NULL AND (${hs(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 hs(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 Om(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=he(i);a&&n(a)&&!o.includes(i)&&o.push(i)}return o}function he(t){let e=t.indexOf(":");return e>0?t.slice(0,e):""}function Cc(t){let e=t.indexOf(":");return e>0?t.slice(e+1):"default"}function Nc(t){return he(t)==="push"?["phone","desk"]:[t]}function Lm(t,e,n){let r=t.filter(s=>n(he(s)));if(!r.length)return null;let o=null;for(let s of r){let i=Math.max(-1/0,...e.filter(a=>Nc(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 Oc(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(he(s)))??null}var Lc=3;async function Pm(t){let{db:e,ledger:n,settings:r,now:o}=t;if(!r.enabled||!(r.escalateAfterMinutes>0))return 0;let s=r.escalateAfterMinutes*Xe,i=e.prepare(`SELECT id FROM owner_told
|
|
574
|
+
WHERE urgent = 1 AND seen_at IS NULL AND answered_at IS NULL
|
|
575
|
+
AND escalated_at IS NULL AND escalation_of IS NULL AND at >= ?
|
|
576
|
+
AND ((outcome = 'sent' AND at <= ?) OR outcome = 'failed')
|
|
577
|
+
ORDER BY at LIMIT 20`).all(Math.max(o-Lc*s,o-Ac),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=Oc(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)/Xe),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}
|
|
578
|
+
|
|
579
|
+
`:""}(Sent again here: ${m}.)`,w=n.add({at:o,key:c.key,requestId:c.requestId,kind:c.kind,channel:he(u),chatId:Cc(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 bs=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 Pc(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 Fm(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 Mc(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(""),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,S)=>{if(h.kind!=="agent")return"";let Je=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(Je.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(Je.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]+'"'+(Je.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 Um(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?Pc(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:()=>Mc(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 Wm=`
|
|
580
|
+
.oe-tree, .oe-tree ul { list-style: none; margin: 0; padding: 0; font-size: var(--ax-fs-sm); }
|
|
581
|
+
.oe-tree ul { margin-left: 10px; padding-left: 12px; border-left: var(--ax-border-w) solid var(--ax-border-2); }
|
|
582
|
+
.oe-tree li { padding: 3px 0; }
|
|
583
|
+
.oe-tree small { color: var(--ax-text-2); }
|
|
584
|
+
.org-edit { margin: 0 0 24px; padding: 12px 16px 16px; border: var(--ax-border-w) solid var(--ax-border); border-radius: var(--ax-radius); background: var(--ax-surface); font-size: var(--ax-fs-sm); }
|
|
585
|
+
.oe-lead { margin: 0 0 6px; color: var(--ax-text-2); }
|
|
586
|
+
.oe-msg { min-height: 1.4em; margin: 0 0 6px; }
|
|
587
|
+
.oe-msg.is-bad { color: var(--ax-red-ink); }
|
|
588
|
+
.oe-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 0 0 8px; padding: 10px 12px; border: var(--ax-border-w) solid var(--ax-border-2); border-radius: var(--ax-radius); background: var(--ax-surface-2); }
|
|
589
|
+
.oe-confirm-text { flex: 1 1 240px; margin: 0; }
|
|
590
|
+
.oe-form { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 8px 12px; margin: 6px 0 10px; }
|
|
591
|
+
.oe-form label, .oe-role { display: flex; flex-direction: column; gap: 2px; min-width: 0; font-size: var(--ax-fs-xs); color: var(--ax-text-2); }
|
|
592
|
+
.org-edit select, .org-edit input { font: inherit; font-size: var(--ax-fs-sm); min-width: 0; max-width: 100%; padding: 5px 8px; border-radius: var(--ax-radius-sm); border: var(--ax-border-w) solid var(--ax-border-2); background: var(--ax-bg); color: var(--ax-text); }
|
|
593
|
+
.oe-rows { list-style: none; margin: 0; padding: 0; }
|
|
594
|
+
.oe-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; padding: 8px 0; border-bottom: var(--ax-border-w) solid var(--ax-border); }
|
|
595
|
+
.oe-who { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 8px; flex: 1 1 160px; min-width: 0; }
|
|
596
|
+
.oe-role { flex: 0 1 200px; }
|
|
597
|
+
.oe-acts { display: flex; flex-wrap: wrap; gap: 6px; }
|
|
598
|
+
.oe-hours { flex: 1 1 100%; display: flex; flex-wrap: wrap; align-items: flex-end; gap: 6px 12px; min-width: 0; margin: 0; padding: 0; border: 0; }
|
|
599
|
+
.oe-hours legend { padding: 0; margin: 0 0 2px; }
|
|
600
|
+
.oe-hours > label { display: flex; flex-direction: column; gap: 2px; font-size: var(--ax-fs-xs); color: var(--ax-text-2); }
|
|
601
|
+
.oe-days { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: center; padding: 5px 0; }
|
|
602
|
+
.oe-day { display: inline-flex; align-items: center; gap: 4px; font-size: var(--ax-fs-xs); color: var(--ax-text); }
|
|
603
|
+
.org-edit .oe-day input { padding: 0; }
|
|
604
|
+
.oe-legend { display: grid; grid-template-columns: max-content 1fr; gap: 4px 12px; margin: 16px 0 0; padding: 10px 12px; border: var(--ax-border-w) solid var(--ax-border); border-radius: var(--ax-radius); }
|
|
605
|
+
.oe-legend dt { font-weight: 600; }
|
|
606
|
+
.oe-legend dd { margin: 0; color: var(--ax-text-2); }
|
|
607
|
+
@media (max-width: 640px) {
|
|
608
|
+
.org-edit { padding: 10px 12px 14px; }
|
|
609
|
+
.oe-form > *, .oe-role { flex: 1 1 100%; }
|
|
610
|
+
.oe-legend { grid-template-columns: 1fr; }
|
|
611
|
+
}
|
|
612
|
+
`;Ze();function Jt(t){let e=n=>[...new Set((n??[]).filter(Boolean).map(E))];return Object.entries(t?.departments??{}).map(([n,r])=>{let o=e(r?.alsoMembers);return{id:n,name:r?.name?.trim()||n,...r?.head?{head:E(r.head)}:{},members:e(r?.members),...o.length?{alsoMembers:o}:{}}}).sort((n,r)=>n.name.localeCompare(r.name)||n.id.localeCompare(r.id))}function ws(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&&Ee(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=Ee(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=xs(t);for(let l of t)for(let c of l.alsoMembers??[]){let p=Ee(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 xs(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 Bm(t,e){let n=new Set,r=xs(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 ks=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},ze=["mon","tue","wed","thu","fri","sat","sun"],Qt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Fc(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=>!ze.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?ze.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Uc(t){let e=ze.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>ze.indexOf(r)===e+o))return`${Qt[t[0]]} to ${Qt[t[t.length-1]]}`;let n=t.map(r=>Qt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var Zt={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function en(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 $s(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function Wc(t){let e=t?.business?.roles??{};return{agents:[...$s(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...en(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 jc(t){let e=t?.business??{},n=e.roles??{},r=$s(t),o=en(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 vs(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(en(t).keys()),o=En(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 Sn(le(e),n,r,o)??ws(Jt(e),n,r,o,i)}function qc(t,e){let n=[];for(let[r,o]of Object.entries(t.departments??{})){let s=!1;if(o?.head&&E(o.head)===e&&(delete o.head,s=!0),Array.isArray(o?.members)){let i=o.members.filter(a=>E(a)!==e);i.length!==o.members.length&&(o.members=i,s=!0)}if(Array.isArray(o?.alsoMembers)){let i=o.alsoMembers.filter(a=>E(a)!==e);i.length!==o.alsoMembers.length&&(o.alsoMembers=i,s=!0)}s&&n.push(String(o?.name||r))}return n}function Ss(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 Es(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>ks)throw new Error(`Keep the role under ${ks} characters.`);return e}function Bc(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 _s(t,e){let n=0;for(let[o,s]of Object.entries(t.orgChart??{}))s?.reportsTo&&e({from:`agent:${o}`,to:E(s.reportsTo),type:"reports-to"})&&(delete s.reportsTo,n++);let r=(t.relations??[]).length;return t.relations=(t.relations??[]).filter(o=>!e({from:E(o.from),to:E(o.to),type:o.type})),n+=r-t.relations.length,t.relations.length===0&&delete t.relations,n}function zm(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=vs(n),s=jc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=Wc(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())?E(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=Es(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Ss(n,w):void 0;g==="agent"?(r.orgChart=r.orgChart||{},r.orgChart[m]={role:x,schedule:{...be},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(E(String(e.member??"")));if(!u)throw new Error(`${e.member} is not in the org chart.`);let g=Es(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Ss(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(E(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=_s(r,w=>w.from===u.ref||w.to===u.ref),f=qc(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(!Qe.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(E);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 ${Zt[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(Bc(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)} ${Zt[u]} ${l(f)}`;break}case"remove-relation":{let u={from:E(String(e.from??"")),to:E(String(e.to??"")),type:String(e.type??"")};if(!_s(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 ${Zt[u.type]??u.type} ${l(u.to)}`;break}case"set-schedule":{let u=i.get(E(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=Fc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Uc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=vs(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 Hc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},Ts=class{constructor(e=Hc,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)}},Vc="That code didn't work. Check it, or run agentx app pair for a new one.",Xc=400;async function Ym(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 yr(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await zc(n,e.minMs??Xc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Vc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function zc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as dd}from"child_process";import{mkdtempSync as rd,rmSync as od,writeFileSync as sd}from"fs";import{tmpdir as id}from"os";import{join as Cs}from"path";import{randomBytes as Kc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var q={top:8,side:32,bottom:60},tn={height:56,keep:52},As=`
|
|
613
|
+
:root {
|
|
614
|
+
--ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
|
|
615
|
+
--ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
|
|
616
|
+
--ac-primary: #1e3a8a; --ac-primary-deep: #172554;
|
|
617
|
+
--ac-blue: #1e3a8a; --ac-blue-2: #1d4ed8;
|
|
618
|
+
--ac-accent: #14b8a6; --ac-accent-deep: #0f766e;
|
|
619
|
+
--ac-rim: rgba(11,20,19,.10);
|
|
620
|
+
--ac-shadow: 0 0 0 .5px rgba(11,20,19,.05), 0 24px 48px -16px rgba(11,20,19,.30), 0 2px 6px rgba(11,20,19,.06);
|
|
621
|
+
--ac-lift: 0 12px 40px rgba(30,58,138,.20), 0 2px 6px rgba(11,20,19,.06);
|
|
622
|
+
--ac-font: "Geist", -apple-system, BlinkMacSystemFont, "Noto Sans Arabic", system-ui, sans-serif;
|
|
623
|
+
--ac-mono: "Geist Mono", ui-monospace, "SF Mono", Menlo, monospace;
|
|
624
|
+
color-scheme: light;
|
|
625
|
+
}
|
|
626
|
+
[data-theme="dark"] {
|
|
627
|
+
--ac-paper: #111c1b; --ac-soft: #172322; --ac-edge: #263433;
|
|
628
|
+
--ac-text: #e8eeed; --ac-muted: #a7b3b1; --ac-subtle: #83918f;
|
|
629
|
+
--ac-primary: #2563eb; --ac-primary-deep: #1d4ed8;
|
|
630
|
+
--ac-blue: #93c5fd; --ac-blue-2: #60a5fa;
|
|
631
|
+
--ac-accent-deep: #5eead4;
|
|
632
|
+
--ac-rim: rgba(255,255,255,.09);
|
|
633
|
+
--ac-shadow: 0 0 0 .5px rgba(0,0,0,.6), 0 28px 56px -16px rgba(0,0,0,.65), 0 2px 8px rgba(0,0,0,.3);
|
|
634
|
+
color-scheme: dark;
|
|
635
|
+
}
|
|
636
|
+
* { box-sizing: border-box; }
|
|
637
|
+
html, body { margin: 0; background: transparent; }
|
|
638
|
+
body {
|
|
639
|
+
font: 13.5px/1.5 var(--ac-font); color: var(--ac-text); font-feature-settings: "ss01", "cv11";
|
|
640
|
+
-webkit-font-smoothing: antialiased; -webkit-user-select: none; user-select: none; cursor: default;
|
|
641
|
+
}
|
|
642
|
+
.wrap { padding: ${q.top}px ${q.side}px ${q.bottom}px; }
|
|
643
|
+
.card {
|
|
644
|
+
background: var(--ac-paper); border: 1px solid var(--ac-rim); border-radius: 18px;
|
|
645
|
+
box-shadow: var(--ac-shadow); overflow: hidden; animation: ac-in .26s cubic-bezier(.65,0,.35,1);
|
|
646
|
+
position: relative; display: flex; flex-direction: column; max-height: calc(100vh - ${q.top+q.bottom}px);
|
|
647
|
+
}
|
|
648
|
+
.card::before {
|
|
649
|
+
content: ""; position: absolute; top: 6px; left: 50%; width: 32px; height: 4px; margin-left: -16px;
|
|
650
|
+
border-radius: 2px; background: var(--ac-edge);
|
|
651
|
+
}
|
|
652
|
+
@keyframes ac-in { from { transform: translateY(14px); opacity: 0; } }
|
|
653
|
+
.card.still { animation: none; }
|
|
654
|
+
@media (prefers-reduced-motion: reduce) { .card { animation: none; } }
|
|
655
|
+
.head { flex: none; display: flex; align-items: center; gap: 10px; padding: 18px 20px 0; cursor: grab; }
|
|
656
|
+
.body { padding: 14px 20px 16px; min-height: 0; overflow-y: auto; }
|
|
657
|
+
.fold {
|
|
658
|
+
flex: none; width: 24px; height: 24px; display: grid; place-items: center; padding: 0; border-radius: 6px;
|
|
659
|
+
border: 1px solid var(--ac-edge); background: var(--ac-soft); color: var(--ac-subtle); cursor: pointer;
|
|
660
|
+
}
|
|
661
|
+
.fold:hover { color: var(--ac-text); border-color: var(--ac-subtle); }
|
|
662
|
+
.folded .fold svg { transform: rotate(180deg); }
|
|
663
|
+
.folded .body > :not(h1), .folded .foot { display: none; }
|
|
664
|
+
.avatar {
|
|
665
|
+
flex: none; width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center;
|
|
666
|
+
font-size: 14px; font-weight: 600; color: #fff;
|
|
667
|
+
background: linear-gradient(135deg, var(--ac-blue-2), var(--ac-accent));
|
|
668
|
+
}
|
|
669
|
+
.who { display: flex; flex-direction: column; gap: 1px; min-width: 0; flex: 1; }
|
|
670
|
+
.who b { font-size: 13.5px; font-weight: 560; letter-spacing: -.008em; line-height: 1.25; }
|
|
671
|
+
.who span { font-size: 12px; line-height: 1.3; color: var(--ac-subtle); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
672
|
+
.label, .kind, .edited { font-family: var(--ac-mono); font-size: 10.5px; letter-spacing: .06em; text-transform: uppercase; }
|
|
673
|
+
.kind {
|
|
674
|
+
padding: 3px 8px; border-radius: 999px; white-space: nowrap;
|
|
675
|
+
color: var(--ac-muted); background: var(--ac-soft); border: 1px solid var(--ac-edge);
|
|
676
|
+
}
|
|
677
|
+
.kind.decision {
|
|
678
|
+
color: var(--ac-blue); background: color-mix(in oklab, var(--ac-blue-2) 10%, var(--ac-paper));
|
|
679
|
+
border-color: color-mix(in oklab, var(--ac-blue-2) 22%, var(--ac-edge));
|
|
680
|
+
}
|
|
681
|
+
h1 { margin: 0; font-size: 18.5px; line-height: 1.3; font-weight: 540; letter-spacing: -.018em; text-wrap: balance; }
|
|
682
|
+
h1:dir(rtl) { letter-spacing: 0; }
|
|
683
|
+
.context { margin: 6px 0 0; color: var(--ac-muted); white-space: pre-wrap; unicode-bidi: plaintext; text-wrap: pretty; }
|
|
684
|
+
.ask { margin: 10px 0 0; font-weight: 500; unicode-bidi: plaintext; }
|
|
685
|
+
.label-row { margin-top: 16px; display: flex; align-items: center; gap: 8px; min-height: 18px; }
|
|
686
|
+
.label { color: var(--ac-subtle); margin-inline-end: auto; }
|
|
687
|
+
.dot { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--ac-accent); }
|
|
688
|
+
.rec { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ac-subtle); }
|
|
689
|
+
.why { margin: 8px 0 0; font-size: 12px; line-height: 1.4; color: var(--ac-subtle); unicode-bidi: plaintext; }
|
|
690
|
+
.options { margin-top: 8px; display: flex; flex-wrap: wrap; gap: 6px; }
|
|
691
|
+
.opt {
|
|
692
|
+
display: inline-flex; align-items: center; gap: 8px; padding: 5px 12px 5px 5px; padding-inline: 5px 12px;
|
|
693
|
+
border-radius: 999px; border: 1px solid var(--ac-edge); background: var(--ac-paper); color: var(--ac-text);
|
|
694
|
+
font: inherit; font-size: 13px; line-height: 1.35; text-align: start; cursor: pointer;
|
|
695
|
+
transition: background .15s ease, border-color .15s ease, transform .15s ease;
|
|
696
|
+
}
|
|
697
|
+
.opt:hover { transform: translateY(-1px); }
|
|
698
|
+
.opt .n {
|
|
699
|
+
flex: none; width: 20px; height: 20px; display: grid; place-items: center; border-radius: 6px;
|
|
700
|
+
border: 1px solid var(--ac-edge); border-bottom-width: 2px; background: var(--ac-soft); color: var(--ac-subtle);
|
|
701
|
+
font-family: var(--ac-mono); font-size: 10.5px;
|
|
702
|
+
}
|
|
703
|
+
.opt .t { unicode-bidi: plaintext; }
|
|
704
|
+
.opt[aria-checked="true"] { background: var(--ac-primary); border-color: var(--ac-primary); color: #fff; }
|
|
705
|
+
.opt[aria-checked="true"] .n { background: rgba(255,255,255,.16); border-color: rgba(255,255,255,.28); color: #fff; }
|
|
706
|
+
.opt[aria-checked="true"] .dot { background: #5eead4; }
|
|
707
|
+
.edited { display: none; align-items: center; gap: 5px; color: var(--ac-accent-deep); }
|
|
708
|
+
.edited .dot { width: 5px; height: 5px; }
|
|
709
|
+
.reset { display: none; border: 0; background: none; padding: 0; font: inherit; font-size: 12px; color: var(--ac-muted); cursor: pointer; }
|
|
710
|
+
.reset:hover { color: var(--ac-text); }
|
|
711
|
+
.touched .edited { display: inline-flex; }
|
|
712
|
+
.touched .reset { display: inline; }
|
|
713
|
+
textarea {
|
|
714
|
+
margin-top: 6px; display: block; width: 100%; min-height: 60px; max-height: 240px; resize: none; overflow-y: auto;
|
|
715
|
+
padding: 10px 12px; border: 1px solid var(--ac-edge); border-radius: 10px; background: var(--ac-soft);
|
|
716
|
+
color: var(--ac-text); font: inherit; line-height: 1.45; outline: none; unicode-bidi: plaintext;
|
|
717
|
+
-webkit-user-select: text; user-select: text; cursor: text; transition: border-color .15s ease, box-shadow .15s ease;
|
|
718
|
+
}
|
|
719
|
+
textarea::placeholder { color: var(--ac-subtle); }
|
|
720
|
+
textarea:focus {
|
|
721
|
+
border-color: var(--ac-accent); background: var(--ac-paper);
|
|
722
|
+
box-shadow: 0 0 0 4px color-mix(in oklab, var(--ac-accent) 18%, transparent);
|
|
723
|
+
}
|
|
724
|
+
.notes { margin-top: 14px; display: flex; flex-direction: column; gap: 5px; font-size: 12px; line-height: 1.4; color: var(--ac-subtle); }
|
|
725
|
+
.notes div { display: flex; gap: 7px; align-items: flex-start; }
|
|
726
|
+
.notes svg { flex: none; margin-top: 1.5px; }
|
|
727
|
+
.foot { flex: none; display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--ac-edge); background: var(--ac-soft); }
|
|
728
|
+
.foot .later { margin-inline-end: auto; }
|
|
729
|
+
button.btn {
|
|
730
|
+
display: inline-flex; align-items: center; gap: 8px; padding: 9px 14px; border-radius: 999px;
|
|
731
|
+
font: inherit; font-weight: 500; letter-spacing: -.005em; white-space: nowrap; cursor: pointer;
|
|
732
|
+
background: transparent; color: var(--ac-text); border: 1px solid var(--ac-edge);
|
|
733
|
+
transition: transform .15s ease, background .15s ease, box-shadow .15s ease, border-color .15s ease;
|
|
734
|
+
}
|
|
735
|
+
button.btn:hover { background: var(--ac-soft); border-color: var(--ac-subtle); }
|
|
736
|
+
button.primary, button.primary:hover { background: var(--ac-primary); border-color: transparent; color: #fff; }
|
|
737
|
+
button.primary:hover:not(:disabled) { transform: translateY(-1px); background: var(--ac-primary-deep); box-shadow: var(--ac-lift); }
|
|
738
|
+
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
|
739
|
+
kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
|
|
740
|
+
button.primary kbd { color: inherit; opacity: .7; }
|
|
741
|
+
`;var Rs=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Is=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Gc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Rs(n):Is(n)}`}function Yc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Is(n)],Rs(n)].join(" ")}function Jc(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 Qc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var nn=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>`,Zc=nn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),ed=nn('<path d="m6 15 6-6 6 6"/>'),td=nn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Ds(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Kc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=nr(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">${R(u)}</span>${g===d.index?'<i class="dot"></i>':""}</button>`).join(""),c=t.recommend?`<span class="rec"><i class="dot"></i>${R(r)} recommends</span>`:"",p={choices:s,draft:t.draft??"",placeholder:er,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>
|
|
742
|
+
<html lang="en"><head><meta charset="utf-8">
|
|
743
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
|
|
744
|
+
<title>AgentX</title>
|
|
745
|
+
<style>${As}</style></head>
|
|
746
|
+
<body><div class="wrap"><main class="card${e.still?" still":""}">
|
|
747
|
+
<div class="head" title="Drag to move"><span class="avatar">${R(Jc(r))}</span>
|
|
748
|
+
<div class="who"><b>${R(r)}</b><span>${R(Gc(t.created_at,n))}</span></div>
|
|
749
|
+
<span class="kind${i?"":" decision"}">${i?"Reminder":a?"Request":"Decision"}</span>
|
|
750
|
+
<button class="fold" id="fold" title="Shrink" aria-label="Shrink the card" aria-expanded="true">${ed}</button></div>
|
|
751
|
+
<div class="body"><h1 dir="auto">${R(t.title)}</h1>
|
|
752
|
+
${t.context?`<p class="context" dir="auto">${R(t.context)}</p>`:""}
|
|
753
|
+
<p class="ask" dir="auto">${R(t.ask)}</p>
|
|
754
|
+
${l||c?`<div class="label-row">${l?'<span class="label">Pick one</span>':""}${c}</div>`:""}
|
|
755
|
+
${l?`<div class="options" role="radiogroup">${l}</div>`:""}
|
|
756
|
+
${d.why?`<p class="why" dir="auto">${R(d.why)}</p>`:""}
|
|
757
|
+
${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>
|
|
758
|
+
<textarea id="text" dir="auto" rows="2" spellcheck="true"></textarea>`:""}
|
|
759
|
+
<div class="notes"><div>${Zc}<span>${a?`It stays on the ${$e} until you close it.`:`If you don't answer by ${R(Yc(t.expires,n))}: ${R(t.if_silent)}.`}</span></div>
|
|
760
|
+
<div>${td}<span>Nothing goes out until you click.</span></div></div>
|
|
761
|
+
</div><div class="foot"><button class="btn later" id="later">Not now<kbd>esc</kbd></button>
|
|
762
|
+
<button class="btn" id="no">${a?"Drop":"No"}</button>
|
|
763
|
+
<button class="btn primary" id="yes">${Qc(t)}<kbd>\u2318\u21A9</kbd></button></div>
|
|
764
|
+
</main></div>
|
|
765
|
+
<script type="application/json" id="data">${JSON.stringify(p).replace(/</g,"\\u003c")}</script>
|
|
766
|
+
<script nonce="${o}">${nd}</script>
|
|
767
|
+
</body></html>`}var nd=`
|
|
768
|
+
(function () {
|
|
769
|
+
var d = JSON.parse(document.getElementById("data").textContent);
|
|
770
|
+
var root = document.documentElement;
|
|
771
|
+
var dark = d.theme === "dark" || (d.theme === "system" && matchMedia("(prefers-color-scheme: dark)").matches);
|
|
772
|
+
if (dark) root.setAttribute("data-theme", "dark");
|
|
773
|
+
var opts = [].slice.call(document.querySelectorAll(".opt"));
|
|
774
|
+
var box = document.getElementById("text");
|
|
775
|
+
var msg = document.getElementById("msg");
|
|
776
|
+
var yes = document.getElementById("yes");
|
|
777
|
+
var card = document.querySelector(".card");
|
|
778
|
+
var body = document.querySelector(".body");
|
|
779
|
+
var fold = document.getElementById("fold");
|
|
780
|
+
var pick = -1, touched = false, done = false;
|
|
781
|
+
|
|
782
|
+
function fill(i) { return d.draft.split(d.placeholder).join(i >= 0 ? d.choices[i] : "").trim(); }
|
|
783
|
+
function send(a) { if (done) return; done = true; window.agentxAnswer = JSON.stringify(a); document.title = "agentx:answer"; }
|
|
784
|
+
// What the card needs, not what it has: in a window too short for it, its middle scrolls.
|
|
785
|
+
function fit() {
|
|
786
|
+
// The title carries the answer signal once sent: a late resize must not write over it.
|
|
787
|
+
if (done) return;
|
|
788
|
+
var wrap = document.querySelector(".wrap"), head = document.querySelector(".head"), foot = document.querySelector(".foot");
|
|
789
|
+
document.title = "agentx:size:" + Math.ceil(wrap.offsetHeight - card.clientHeight + head.offsetHeight + body.scrollHeight + foot.offsetHeight);
|
|
790
|
+
}
|
|
791
|
+
function mark() { touched = box.value.trim() !== fill(pick); msg.classList.toggle("touched", touched); }
|
|
792
|
+
function update() {
|
|
793
|
+
opts.forEach(function (o, i) { o.setAttribute("aria-checked", String(i === pick)); });
|
|
794
|
+
yes.disabled = (d.choices.length > 0 && pick < 0) || (box && !box.value.trim());
|
|
795
|
+
}
|
|
796
|
+
function grow() { if (!box) return; box.style.height = "auto"; box.style.height = box.scrollHeight + 4 + "px"; }
|
|
797
|
+
// quiet: the pick made on open. The box is not focused, so the number keys still pick.
|
|
798
|
+
function choose(i, quiet) {
|
|
799
|
+
// An edited message keeps the edits, with the old pick swapped for the new one.
|
|
800
|
+
if (box && touched && pick >= 0) box.value = box.value.split(d.choices[pick]).join(d.choices[i]);
|
|
801
|
+
else if (box) box.value = fill(i);
|
|
802
|
+
pick = i;
|
|
803
|
+
if (box) { grow(); mark(); }
|
|
804
|
+
update();
|
|
805
|
+
if (box && !quiet) box.focus();
|
|
806
|
+
}
|
|
807
|
+
opts.forEach(function (o, i) { o.addEventListener("click", function () { choose(i); }); });
|
|
808
|
+
if (box) {
|
|
809
|
+
box.value = d.choices.length ? "" : fill(-1);
|
|
810
|
+
box.placeholder = d.choices.length ? "Pick an option above" : "";
|
|
811
|
+
grow();
|
|
812
|
+
box.addEventListener("input", function () { grow(); mark(); update(); });
|
|
813
|
+
document.getElementById("reset").addEventListener("click", function () { box.value = fill(pick); grow(); mark(); update(); box.focus(); });
|
|
814
|
+
}
|
|
815
|
+
yes.addEventListener("click", function () {
|
|
816
|
+
if (yes.disabled) return;
|
|
817
|
+
var a = { action: "yes" };
|
|
818
|
+
if (pick >= 0) a.choice = d.choices[pick];
|
|
819
|
+
if (box) a.text = box.value.trim();
|
|
820
|
+
send(a);
|
|
821
|
+
});
|
|
822
|
+
document.getElementById("no").addEventListener("click", function () { send({ action: "no" }); });
|
|
823
|
+
document.getElementById("later").addEventListener("click", function () { send({ action: "dismiss", why: "not now" }); });
|
|
824
|
+
fold.addEventListener("click", function () {
|
|
825
|
+
var shrunk = card.classList.toggle("folded");
|
|
826
|
+
fold.setAttribute("aria-expanded", String(!shrunk));
|
|
827
|
+
fold.title = shrunk ? "Show all" : "Shrink";
|
|
828
|
+
fit();
|
|
829
|
+
});
|
|
830
|
+
document.addEventListener("keydown", function (e) {
|
|
831
|
+
if (e.key === "Escape") return send({ action: "dismiss", why: "not now" });
|
|
832
|
+
// A shrunk card hides its buttons: no answer by key while they can't be seen.
|
|
833
|
+
if (card.classList.contains("folded")) return;
|
|
834
|
+
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); return yes.click(); }
|
|
835
|
+
// preventDefault: choose() focuses the box, and the digit must not be typed into it.
|
|
836
|
+
if (document.activeElement !== box && /^[1-9]$/.test(e.key) && opts[+e.key - 1]) { e.preventDefault(); choose(+e.key - 1); }
|
|
837
|
+
});
|
|
838
|
+
if (d.pick >= 0) choose(d.pick, true); else update();
|
|
839
|
+
requestAnimationFrame(fit);
|
|
840
|
+
if (box) new ResizeObserver(fit).observe(box);
|
|
841
|
+
|
|
842
|
+
if (d.chime) try {
|
|
843
|
+
var ac = new AudioContext(), t = ac.currentTime + 0.05;
|
|
844
|
+
[[783.99, 0], [1046.5, 0.14]].forEach(function (n) {
|
|
845
|
+
[1, 2].forEach(function (h) {
|
|
846
|
+
var o = ac.createOscillator(), g = ac.createGain();
|
|
847
|
+
o.type = "sine"; o.frequency.value = n[0] * h;
|
|
848
|
+
g.gain.setValueAtTime(0, t + n[1]);
|
|
849
|
+
g.gain.linearRampToValueAtTime(d.volume * (h === 1 ? 0.5 : 0.12), t + n[1] + 0.012);
|
|
850
|
+
g.gain.exponentialRampToValueAtTime(0.0001, t + n[1] + 1.4);
|
|
851
|
+
o.connect(g).connect(ac.destination); o.start(t + n[1]); o.stop(t + n[1] + 1.5);
|
|
852
|
+
});
|
|
853
|
+
});
|
|
854
|
+
} catch (e) {}
|
|
855
|
+
})();
|
|
856
|
+
`;var ad=440,ld=`
|
|
857
|
+
ObjC.import("Cocoa"); ObjC.import("WebKit")
|
|
858
|
+
function run(argv) {
|
|
859
|
+
var path = argv[0], side = ${q.side}, gripTop = ${q.top}, gripEnd = ${q.top+tn.height}, keep = ${tn.keep}, w = Number(argv[1]) + 2 * side, h = 420, secs = Number(argv[2]), capture = argv[3] || ""
|
|
860
|
+
var app = $.NSApplication.sharedApplication
|
|
861
|
+
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
|
|
862
|
+
ObjC.registerSubclass({ name: "AgentXCardView", superclass: "WKWebView", methods: {
|
|
863
|
+
"acceptsFirstMouse:": { types: ["bool", ["id"]], implementation: function () { return true } },
|
|
864
|
+
} })
|
|
865
|
+
var vis = $.NSScreen.mainScreen.visibleFrame
|
|
866
|
+
var top = vis.origin.y + vis.size.height - 4, right = vis.origin.x + vis.size.width - 14 + side
|
|
867
|
+
var mask = $.NSWindowStyleMaskTitled | $.NSWindowStyleMaskClosable | $.NSWindowStyleMaskFullSizeContentView | $.NSWindowStyleMaskNonactivatingPanel
|
|
868
|
+
var win = $.NSPanel.alloc.initWithContentRectStyleMaskBackingDefer($.NSMakeRect(right - w, top - h, w, h), mask, $.NSBackingStoreBuffered, false)
|
|
869
|
+
win.titlebarAppearsTransparent = true
|
|
870
|
+
win.titleVisibility = $.NSWindowTitleHidden
|
|
871
|
+
win.movableByWindowBackground = true
|
|
872
|
+
win.level = $.NSFloatingWindowLevel
|
|
873
|
+
win.releasedWhenClosed = false
|
|
874
|
+
win.hidesOnDeactivate = false
|
|
875
|
+
win.collectionBehavior = $.NSWindowCollectionBehaviorCanJoinAllSpaces
|
|
876
|
+
win.opaque = false
|
|
877
|
+
win.backgroundColor = $.NSColor.clearColor
|
|
878
|
+
win.hasShadow = false
|
|
879
|
+
;[$.NSWindowCloseButton, $.NSWindowMiniaturizeButton, $.NSWindowZoomButton].forEach(function (b) { win.standardWindowButton(b).hidden = true })
|
|
880
|
+
var cfg = $.WKWebViewConfiguration.alloc.init
|
|
881
|
+
cfg.mediaTypesRequiringUserActionForPlayback = 0
|
|
882
|
+
var web = $.AgentXCardView.alloc.initWithFrameConfiguration($.NSMakeRect(0, 0, w, h), cfg)
|
|
883
|
+
web.autoresizingMask = $.NSViewWidthSizable | $.NSViewHeightSizable
|
|
884
|
+
web.setValueForKey(false, "drawsBackground")
|
|
885
|
+
win.contentView = web
|
|
886
|
+
var url = $.NSURL.fileURLWithPath(path)
|
|
887
|
+
web.loadFileURLAllowingReadAccessToURL(url, url.URLByDeletingLastPathComponent)
|
|
888
|
+
// No focus taken (#394): shown over the app in use, which keeps the keyboard.
|
|
889
|
+
// A click on the card still lands (acceptsFirstMouse); a click in its text
|
|
890
|
+
// box makes the panel key without bringing anything else forward.
|
|
891
|
+
win.orderFrontRegardless
|
|
892
|
+
var end = Date.now() + secs * 1000, sized = 0, shot = false, seen = "", asked = false, answer = null
|
|
893
|
+
// Every kind of event, as a number. JXA hands the AppKit constant for it over as text, and a
|
|
894
|
+
// loop asking with that gets no event at all: no click, no drag, no key.
|
|
895
|
+
var anyEvent = Number.MAX_SAFE_INTEGER
|
|
896
|
+
while (Date.now() < end) {
|
|
897
|
+
var ev = app.nextEventMatchingMaskUntilDateInModeDequeue(anyEvent, $.NSDate.dateWithTimeIntervalSinceNow(0.05), $.NSDefaultRunLoopMode, true)
|
|
898
|
+
if (ev && !ev.isNil()) {
|
|
899
|
+
if (onGrip(ev)) win.performWindowDragWithEvent(ev); else app.sendEvent(ev)
|
|
900
|
+
}
|
|
901
|
+
if (answer !== null) { win.close; return answer }
|
|
902
|
+
if (!win.isVisible) return gone("closed")
|
|
903
|
+
var t = web.title.js || ""
|
|
904
|
+
if (t === "agentx:answer" && !asked) {
|
|
905
|
+
asked = true
|
|
906
|
+
web.evaluateJavaScriptCompletionHandler("window.agentxAnswer", function (r) { answer = String(ObjC.unwrap(r) || "") })
|
|
907
|
+
}
|
|
908
|
+
if (t !== seen && t.indexOf("agentx:size:") === 0) {
|
|
909
|
+
seen = t
|
|
910
|
+
var want = Math.min(Number(t.slice(12)), vis.size.height - 8)
|
|
911
|
+
var f = win.frame
|
|
912
|
+
if (want > 80) { win.setFrameDisplayAnimate($.NSMakeRect(f.origin.x, f.origin.y + f.size.height - want, w, want), true, true); sized = Date.now() }
|
|
913
|
+
}
|
|
914
|
+
if (capture && !shot && sized && Date.now() - sized > 900) {
|
|
915
|
+
shot = true
|
|
916
|
+
var sa = Application.currentApplication(); sa.includeStandardAdditions = true
|
|
917
|
+
sa.doShellScript("/usr/sbin/screencapture -x -o -l " + win.windowNumber + " " + quoted(capture))
|
|
918
|
+
end = Math.min(end, Date.now() + 300)
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
win.close
|
|
922
|
+
return gone("timed out")
|
|
923
|
+
function onGrip(ev) {
|
|
924
|
+
if (ev.type != $.NSEventTypeLeftMouseDown || ev.windowNumber != win.windowNumber) return false
|
|
925
|
+
var p = ev.locationInWindow, down = win.frame.size.height - p.y
|
|
926
|
+
return down >= gripTop && down <= gripEnd && p.x >= side && p.x <= w - side - keep
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
|
|
930
|
+
function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
931
|
+
`;function cd(t,e){let n=t.trim().split(`
|
|
932
|
+
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Os.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,`
|
|
933
|
+
`).trim():"",!i||i.length>Zn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Ns(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=rd(Cs(id(),"agentx-card-"));try{let s=Cs(o,"card.html");sd(s,Ds(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",ld,s,String(ad),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?cd(a.stdout,t):null}finally{od(o,{recursive:!0,force:!0})}}var Os=["not now","timed out","closed"],ud=(t,e,n)=>new Promise(r=>{try{dd(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ls=160,rn=15e3;function Ps(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ls?e.slice(0,Ls):e}async function pd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?br(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],rn),!!e.speak)if(o){let a;await Promise.race([o(Ps(t)),new Promise(d=>{a=setTimeout(d,rn)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ps(t)],rn)}}function Us(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function gd(t,e,n){return Us(["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 Ms(t,e,n,r,o){return Us(["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(`
|
|
934
|
+
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Fs(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
|
|
935
|
+
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function on(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
|
|
936
|
+
|
|
937
|
+
`)}async function Ws(t,e,n={}){let r=n.run??ud,o=(e.style??"card")==="card",s=pd(t,e,r,o,n.speak).catch(()=>{});if(o){let i=await Ns(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,md(t,e,r)}async function md(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",gd(s,on(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}
|
|
938
|
+
|
|
939
|
+
Message (edit it if you like):`:`${on(t)}
|
|
940
|
+
|
|
941
|
+
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Ms(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,tr(t.draft,i)),o),u=p.ok?Fs(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",Ms(s,on(t),["Not now","No","Yes"],r),o),d=a.ok?Fs(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var ln=24*36e5,sn=!1,fd=10*6e4,js=-1/0;function qs(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=ee(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)||Ar(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>ln&&!(g<=a)))return c}return null}function an(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Bs=new Map;function hd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?an(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Bs.get(s.id)===K(s,pt.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=ln})??null:null}function bd(t,e){return{id:t.id,title:K(t,pt.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+ln).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Rf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(sn)return"busy";let o=qs(e,t.reaches)?null:hd(e,t.reaches),s=o?bd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??ps)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:xr(s);if(d){if(o)Bs.set(o.id,s.title);else{let l=[...ee(e.root,"pending").map(c=>`card:${c.id}`),...an(e).map(c=>`request:${c.id}`)];ht(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,kr(s,d)),"returned"}sn=!0;try{let l=[...ee(e.root,"pending").map(w=>`card:${w.id}`),...an(e).map(w=>`request:${w.id}`)];ht(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-js<fd;o&&n.speak&&(js=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??Ws)(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"} (${zn(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":pe(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await ho(e,a,g.action,{by:"operator (popup)",...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{sn=!1}}function If(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:")?pe(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(Ur(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 yd,mkdirSync as wd,readFileSync as xd,renameSync as kd,writeFileSync as vd}from"fs";import{dirname as Sd,resolve as Ed}from"path";var _d=["all","urgent","off"],$d=24*36e5,Hs=24*36e5,Td=30*24*36e5,Vs=t=>_d.includes(t);function Of(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Vs(e)?e:"off",computer:Vs(n)?n:t.popupEnabled?"all":"off"}}function zs(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=$d}function Xs(t,e,n){return t==="all"||t==="urgent"&&zs(e,n)}function Ks(t){return Ed(t,".agentx","desk-routed.json")}function Ad(t){let e=Ks(t);if(!yd(e))return null;try{let n=JSON.parse(xd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function cn(t,e){let n=Ks(t);wd(Sd(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;vd(r,JSON.stringify(e,null,2)),kd(r,n)}async function Lf(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Ad(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return cn(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)>Hs&&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<=Hs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Td&&delete d.items[p];cn(e,d);for(let p of l)if(Xs(o.phone,p,n))try{await t.phone(p,zs(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(!Xs(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&&cn(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 Pf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
|
|
942
|
+
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Rd,fstatSync as Id,openSync as Dd,realpathSync as Gs}from"fs";import{isAbsolute as Cd,resolve as Ys,sep as Js}from"path";var qf="/app-files",Nd=/^[A-Za-z0-9_.:-]{1,64}$/;function Od(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 ${at}/ first`};if(!de(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Gs(Ys(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Gs(Cd(e)?e:Ys(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Js))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${at}/ first`};let s=de(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Ld(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 Pd(t,e,n){return{"Content-Type":t,"Content-Disposition":Ld(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 Md(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 Bf(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(!Nd.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=Od(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=Dd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Id(l);if(!x.isFile())return ye(l),o(404,{error:"not a file"});c=x.size}catch{return ye(l),o(404,{error:"file not found"})}if(c>W.bytes)return ye(l),o(413,{error:`the file is larger than ${W.bytes/1024/1024} MB`});let p=d.path.split(Js).pop()||"file",u=Pd(d.mime,p,d.kind),g=Md(t.headers.range,c);if(g==="unsatisfiable"){ye(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){ye(l),e.end();return}let w=Rd("",{fd:l,start:m,end:f,autoClose:!0});w.on("error",()=>e.destroy()),e.on("close",()=>w.destroy()),w.pipe(e)}import{spawn as we}from"child_process";import{readFileSync as Fd,writeFileSync as Ud}from"fs";import{tmpdir as Wd}from"os";import{join as jd}from"path";_n();var Qs=t=>t&&t!==1?Math.round(175*t):null,Ke=t=>t&&t!==1?Math.min(1.2,Math.max(.7,t)):null;function qd(){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=Fd(t,"utf8").trim();if(e)return e}catch{}return null}function Qf(t=qd()){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",...Ke(n.voice.rate)?{voice_settings:{speed:Ke(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=jd(Wd(),`agentx-say-${process.pid}-${++e}.mp3`);return Ud(s,Buffer.from(await o.arrayBuffer())),s}catch(o){if(r.aborted||!n.voice.fallback)throw o;return Y(`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 Zs(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Bd=(t,e="")=>{let n=Zs(t,e),r=Qs(t.rate);return[...n&&!Ro(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Hd(t,e,n){if(!n)return["say",Bd(t,e)];let r=Zs(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function Zf(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function eh(t=dn()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function th(t=dn()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function dn(t={},e){if(!Tt(t))return null;try{return Co(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
|
|
943
|
+
`)[0]}); Siri voices will not switch`),null}}var nh=(t,e)=>{if(!t){let[n,r]=Hd(e.voice,e.text,dn()),o=Qs(e.voice.rate),s=o?{...process.env,AGENTX_SAY_RATE:String(o)}:process.env,i=we(n,r,{stdio:["pipe","ignore","ignore"],env:s});return i.stdin?.on("error",()=>{}),i.stdin?.end(e.text),i}return process.platform==="darwin"?we("afplay",[t],{stdio:"ignore"}):we("mpg123",["-q",t],{stdio:"ignore"})};import{spawn as ei}from"child_process";import{accessSync as Vd,constants as Xd,readFileSync as ti}from"fs";import{homedir as zd}from"os";import{basename as se,delimiter as ni,dirname as Kd,extname as Gd,join as un}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function ri(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:gn()}:null}var gn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Yd={"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 oi(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Yd[e]??null}function si(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 mn(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 pn(t,e,n=process.env.PATH??""){let r=zd(),o=[un(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(ni).filter(Boolean)];for(let s of[e,...o.map(i=>un(i,t))])if(s)try{return Vd(s,Xd.X_OK),s}catch{}return null}function lh(t){return{key:t,mlx:pn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:pn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Jd()}}var Jd=()=>pn("ffmpeg",process.env.AGENTX_FFMPEG);async function ii(t,e){return e?Qd(t,e):null}async function Qd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await Zd(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([ti(t)],{type:e}),se(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 li(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:`${Kd(r)}${ni}${process.env.PATH??""}`};await eu(e,s,12e4,i);try{return ti(un(o,se(n,Gd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function Zd(t,e,n){return new Promise((r,o)=>{let s=ei(t,e,{stdio:["ignore","ignore","pipe"]}),i="",a=setTimeout(()=>{s.kill("SIGKILL"),o(new Error(`${se(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(`${se(t)} exited ${d}`))})})}function eu(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ei(t,e,{stdio:["ignore","pipe","pipe"],env:r}),a="",d="",l=setTimeout(()=>{i.kill("SIGKILL"),s(new Error(`${se(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(`${se(t)} exited ${c}: ${d.trim().split(`
|
|
944
|
+
`).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as tu,rm as nu,writeFile as ru}from"fs/promises";import{tmpdir as ou}from"os";import{join as ci}from"path";ki();var su=64*1024,iu=2,fn=0;function wh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function xh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?au(t,e,r):du(t,e,r)}async function au(t,e,n){let r=String(t.headers["content-type"]||""),o=oi(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=ri(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await di(t,z.bytes);if(!i)return $(e,413,{error:gu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(fn>=iu)return $(e,429,{error:"This computer is already writing down other recordings. Try again in a moment."});let a=n.stt(),d=n.host(),l=si(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+mn(a,d);return $(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 $(e,503,{error:"Voice input isn't set up on this computer.",hint:mn(a,d),setup:!1});fn++;let c;try{let p=await tu(ci(ou(),"agentx-phone-voice-"));try{c=await lu(p,`speech.${o}`,i,r,d,l,n)}finally{await nu(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{fn--}$(e,c[0],c[1])}async function lu(t,e,n,r,o,s,i){let a=ci(t,e);if(await ru(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ii)(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:gn()}]}let d=[];for(let l of s)try{let c=await cu(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(`
|
|
945
|
+
`)[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 cu(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 li(t,a,e,r.ffmpeg,o)}async function du(t,e,n){let r=await di(t,su);if(!r)return $(e,413,{error:"request too large"});let o;try{o=JSON.parse(r.toString("utf8")||"{}")}catch{return $(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 $(e,400,{error:"agent is required"});let a=uu(typeof o?.text=="string"?o.text:"",n.spokenMaxChars?.());if(!a)return $(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 $(e,404,{error:`Unknown agent: ${s}`});let c=(u,g=200)=>$(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??pu)(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(`
|
|
946
|
+
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function uu(t,e){let n=Ve(Ae(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return $n(n,e)}async function pu(t,e,n){let r=Ke(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 gu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function kh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Mt(Ot(t,o,n.voice)):null}function di(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 $(t,e,n){t.writeHead(e,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(n))}var mu="[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.]",fu="operator",hu=50,ui=4,pi=500;function bu(t){let e={channel:"app",chatId:t.chatId,sender:fu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${mu}
|
|
947
|
+
|
|
948
|
+
${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 $h(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:Bn(u,m),artifacts:[]}:Ae(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?Ve(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:wu(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 xu(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<hu){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,yu(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 yu(t){let e=String(t||"The agent could not answer.");return Fn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function wu(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,ui).map(i=>i.slice(0,pi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,ui).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,pi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*xu(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,`
|
|
949
|
+
`);let i;for(;(i=r.indexOf(`
|
|
950
|
+
|
|
951
|
+
`))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
|
|
952
|
+
`))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(`
|
|
953
|
+
`))}}catch{}}}}finally{e.releaseLock()}}var gi=["custom","announce"];function Ah(t,e){let n=t.nodeName,r=t.recent().filter(s=>gi.includes(s.kind)).slice(-500),o=(e?.list()??[]).slice(-500).map(s=>({...s,node:n}));return{node:n,events:r,wakes:o}}function Rh(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)gi.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,D=`${k}#${y.agentId}#${y.eventId}`;if(d.has(D))continue;d.add(D);let ae=i.get(y.eventId)??[];if(ae.push(vu(y,k,n)),i.set(y.eventId,ae),y.status!=="skipped"){let ve=`${y.agentId}#${y.rootId}`,h=a.get(ve)??[];h.push({eventId:y.eventId,at:y.decidedAt}),a.set(ve,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=ku(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 D=l.get(y);if(!D)return y;y=D}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 ku(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 vu(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 wn,writeFileSync as xn,mkdirSync as Ge,readdirSync as yn,rmSync as Su,statSync as U}from"fs";import{resolve as mi,relative as Eu,dirname as kn,join as Q,extname as xe,basename as vn}from"path";var I=200*1024,fi=new Set([".md",".markdown",".txt"]),ie=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"]),_u=6,$u=new Set(["CLAUDE.md","SOUL.md","IDENTITY.md","PERSONA.md","AGENT.md","BOOTSTRAP.md"]);function B(t,e){if(!t)throw new Error("Agent workspace is not configured.");let n=mi(t);if(M(n)||Ge(n,{recursive:!0}),!e||e.startsWith("/")||e.match(/^[a-zA-Z]:/))throw new Error(`Path must be relative to the workspace: ${e}`);let r=mi(n,e);if(Eu(n,r).startsWith(".."))throw new Error(`Path escapes the workspace: ${e}`);return r}function hi(t){let e=xe(t).toLowerCase();if(!fi.has(e))throw new Error(`Only text files (.md, .markdown, .txt) can be edited from the admin panel (got ${e}).`)}function hn(t,e){let n=t.split(/\r?\n/).find(r=>r.trim().startsWith("#"));return n&&n.replace(/^#+\s*/,"").trim().slice(0,120)||e}function Nh(t){let e=B(t,"."),n=[],r=new Set,o=[];try{o=yn(e)}catch{}for(let a of $u){let d=Q(e,a);if(M(d)&&U(d).isFile()){let l=U(d).size,c=l>0&&l<I?bn(d):"";n.push({path:a,title:hn(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=Q(e,a);try{let l=U(d);if(!l.isFile()||!fi.has(xe(a).toLowerCase()))continue;let c=l.size>0&&l.size<I?bn(d):"";n.push({path:a,title:hn(c,a),size:l.size,exists:!0})}catch{}}let s=[],i=Q(e,".claude","skills");if(M(i))try{for(let a of yn(i)){let d=Q(i,a),l;try{l=U(d)}catch{continue}if(!l.isDirectory())continue;let c=Q(d,"SKILL.md");if(!M(c))continue;let p=U(c),u=p.size<I?bn(c):"";s.push({slug:a,title:hn(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 bn(t){try{return wn(t,"utf-8")}catch{return""}}function Oh(t,e){let n=B(t,e);if(hi(n),!M(n))return{path:e,content:""};if(U(n).size>I)throw new Error(`File is too large to edit in the admin panel (> ${I/1024} KB).`);return{path:e,content:wn(n,"utf-8")}}function Lh(t,e,n){let r=B(t,e);hi(r);let o=Buffer.from(n,"utf-8");if(o.length>I)throw new Error(`File too large (${o.length} > ${I} bytes).`);return Ge(kn(r),{recursive:!0}),xn(r,o),{path:e,bytes:o.length}}function Ph(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=B(t,r);if(M(o))throw new Error(`Skill "${e}" already exists.`);Ge(kn(o),{recursive:!0});let s=n.content?.trim()?n.content:Tu(e,n.title);return xn(o,s),{slug:e,path:r}}function Mh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=B(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 Su(n,{recursive:!0,force:!0}),{slug:e}}function Fh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=B(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>_u)return;let l=[];try{l=yn(s)}catch{return}for(let c of l){if(c==="node_modules"||c===".git")continue;let p=Q(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=xe(c).toLowerCase(),f=ie.has(m)||ie.has(c.toLowerCase());d.push({path:u,kind:"file",size:g.size,editable:f&&g.size<I})}}}}function Uh(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=B(t,`.claude/skills/${e}/${n}`);if(!M(r)||!U(r).isFile())throw new Error(`File not found: ${n}`);let o=xe(r).toLowerCase(),s=vn(r).toLowerCase();if(!ie.has(o)&&!ie.has(s))throw new Error(`File type not editable: ${n}`);if(U(r).size>I)throw new Error(`File too large to edit (> ${I/1024} KB): ${n}`);return{path:n,content:wn(r,"utf-8")}}function Wh(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=B(t,`.claude/skills/${e}/${n}`),s=xe(o).toLowerCase(),i=vn(o).toLowerCase();if(!ie.has(s)&&!ie.has(i))throw new Error(`File type not editable: ${n}`);let a=Buffer.from(r,"utf-8");if(a.length>I)throw new Error(`File too large (${a.length} > ${I} bytes).`);return Ge(kn(o),{recursive:!0}),xn(o,a),{path:n,bytes:a.length}}function jh(t,e){if(!/^[a-z0-9][a-z0-9_-]*$/.test(e))throw new Error(`Invalid skill slug: ${e}`);let n=B(t,`.claude/skills/${e}`);if(!M(n))throw new Error(`Skill "${e}" not found.`);let r=o=>M(Q(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 Tu(t,e){return`# ${e?.trim()||t}
|
|
954
|
+
|
|
955
|
+
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.
|
|
956
|
+
|
|
957
|
+
## When to use
|
|
958
|
+
- Trigger condition 1
|
|
959
|
+
- Trigger condition 2
|
|
960
|
+
|
|
961
|
+
## How to use
|
|
962
|
+
Document the arguments, commands, or files the skill expects. Example:
|
|
963
|
+
|
|
964
|
+
\`\`\`bash
|
|
965
|
+
# Example invocation
|
|
966
|
+
claude-code ${vn(t)} --arg value
|
|
967
|
+
\`\`\`
|
|
968
|
+
`}Ln();var bi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function yi(t){return{...bi,...t??{},regions:{...t?.regions??{}},buffer:{...bi.buffer,...t?.buffer??{}}}}function Hh(t){try{return yi(On(t).screen)}catch{return yi(void 0)}}var Au=/^[a-z][\w-]*$/,wi=["window","screen","menubar","notifications"];function ke(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 Ye=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function xi(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 Vh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Ye(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Ye(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Ye(e.intervalMs,"intervalMs")),"stableMs"in e&&(n.stableMs=ke(e.stableMs,"stableMs",o=>Number.isInteger(o)&&o>=0,"a whole number, 0 or more")),"changeThreshold"in e&&(n.changeThreshold=ke(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(!Au.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=xi(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=ke(o.seconds,"buffer.seconds",i=>i>0&&i<=120,"above 0 and at most 120")),"fps"in o&&(s.fps=ke(o.fps,"buffer.fps",i=>i>0&&i<=10,"above 0 and at most 10")),"maxPixels"in o&&(s.maxPixels=Ye(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&&!wi.includes(r)&&!n.regions?.[r])try{xi(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...wi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Rr as a,Du as b,Gt as c,oc as d,sc as e,um as f,pm as g,gm as h,hm as i,bm as j,ym as k,as as l,ls as m,wm as n,Ve as o,km as p,Sm as q,X as r,cs as s,A as t,Lu as u,ps as v,Rm as w,Cm as x,ms as y,Nm as z,fs as A,Om as B,he as C,Cc as D,Lm as E,Pm as F,bs as G,Yu as H,Qi as I,np as J,Kr as K,N as L,Wu as M,ju as N,up as O,Ne as P,pp as Q,Wr as R,zu as S,G as T,Wp as U,go as V,ho as W,Pc as X,Fm as Y,Mc as Z,Um as _,Wm as $,Jt as aa,ws as ba,Bm as ca,Zt as da,Wc as ea,jc as fa,zm as ga,La as ha,Pa as ia,Bp as ja,Hp as ka,Ba as la,Kp as ma,Ts as na,Ym as oa,Jp as pa,Qp as qa,rs as ra,Wt as sa,Jl as ta,R as ua,Ws as va,Rf as wa,If as xa,_d as ya,Of as za,Xs as Aa,Lf as Ba,Pf as Ca,qf as Da,Od as Ea,Pd as Fa,Bf as Ga,eg as Ha,tg as Ia,ng as Ja,rg as Ka,og as La,sg as Ma,ag as Na,lg as Oa,ug as Pa,pg as Qa,gg as Ra,hg as Sa,bg as Ta,yg as Ua,wg as Va,xg as Wa,kg as Xa,vg as Ya,Dg as Za,It as _a,Cg as $a,Ng as ab,me as bb,fe as cb,qd as db,Qf as eb,Zf as fb,eh as gb,th as hb,dn as ib,nh as jb,Nt as kb,Ot as lb,je as mb,wl as nb,kl as ob,Fg as pb,Pt as qb,Mt as rb,vl as sb,Sl as tb,qo as ub,Xo as vb,Ug as wb,$l as xb,Wg as yb,Ol as zb,Ml as Ab,Ft as Bb,Ul as Cb,zo as Db,z as Eb,ri as Fb,oi as Gb,si as Hb,pn as Ib,lh as Jb,Jd as Kb,ai as Lb,li as Mb,wh as Nb,xh as Ob,gu as Pb,kh as Qb,di as Rb,Jo as Sb,$h as Tb,wu as Ub,Ah as Vb,Rh as Wb,qe as Xb,tm as Yb,zt as Zb,lm as _b,Nh as $b,Oh as ac,Lh as bc,Ph as cc,Mh as dc,Fh as ec,Uh as fc,Wh as gc,jh as hc,bi as ic,yi as jc,Hh as kc,wi as lc,Vh as mc};
|
|
969
|
+
//# sourceMappingURL=chunk-X6SXZDTY.js.map
|