agentix-cli 0.209.0 → 0.209.2
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-BECRIPJ2.js → App-SWJJHYRX.js} +2 -2
- package/dist/{ChatApp-WBR7IQMG.js → ChatApp-CPUCPJLP.js} +2 -2
- package/dist/absorb-eval-WKLAV4ZX.js +2 -0
- package/dist/{adapter-CO4TVLNV.js → adapter-XXUKXA5L.js} +2 -2
- package/dist/{agent-ISULBG63.js → agent-3U23E65W.js} +2 -2
- package/dist/{board-dashboard-XUY4O2RU.js → board-dashboard-5BPWMIUP.js} +26 -26
- package/dist/{chunk-YYXE2HSO.js → chunk-2KLR4RWJ.js} +2 -2
- package/dist/{chunk-CT3OYNNI.js → chunk-2OW4DTHI.js} +2 -2
- package/dist/{chunk-ECN4ZCMT.js → chunk-3HT5A67F.js} +98 -98
- package/dist/chunk-3HT5A67F.js.map +1 -0
- package/dist/{chunk-I6FDSWP3.js → chunk-6WU5VEVY.js} +2 -2
- package/dist/{chunk-BSDOKMKX.js → chunk-7BCGVPF4.js} +2 -2
- package/dist/{chunk-JSCVOB4G.js → chunk-7IW25T4K.js} +2 -2
- package/dist/{chunk-I5DAFRWA.js → chunk-7X4BZ5VS.js} +3 -3
- package/dist/{chunk-6KSMSSPT.js → chunk-7YEXKWYP.js} +2 -2
- package/dist/{chunk-Y24J3MOQ.js → chunk-B3TH5GYM.js} +2 -2
- package/dist/{chunk-YBYF223R.js → chunk-BIK7QFDR.js} +2 -2
- package/dist/{chunk-DADIYSFN.js → chunk-CWZ4UN7R.js} +2 -2
- package/dist/{chunk-QLHEESVA.js → chunk-DAT6RZ5Q.js} +2 -2
- package/dist/{chunk-2HBEZV7L.js → chunk-DPG6VHPX.js} +2 -2
- package/dist/{chunk-UPNH6RAZ.js → chunk-IGSZ6IZ7.js} +2 -2
- package/dist/{chunk-ITUBW7TE.js → chunk-K7JD6Y4L.js} +2 -2
- package/dist/{chunk-DXXJL4TT.js → chunk-KSO2DLVR.js} +14 -14
- package/dist/chunk-KWWBDLE6.js +13 -0
- package/dist/chunk-KWWBDLE6.js.map +1 -0
- package/dist/chunk-LIY5CHUV.js +4 -0
- package/dist/chunk-LIY5CHUV.js.map +1 -0
- package/dist/{chunk-IYTCKPZI.js → chunk-LW6UWMN6.js} +2 -2
- package/dist/{chunk-XBON7H4I.js → chunk-MOA6SIUK.js} +2 -2
- package/dist/{chunk-7EEWOBIM.js → chunk-NBIOOD7J.js} +2 -2
- package/dist/{chunk-CPOTYJWY.js → chunk-ORBWUTVG.js} +2 -2
- package/dist/{chunk-ZWJ2SUM5.js → chunk-QZ5HG3G5.js} +2 -2
- package/dist/{chunk-TXGUBSM3.js → chunk-RAZKIONL.js} +2 -2
- package/dist/{chunk-WNBGBOBJ.js → chunk-RPRJT4EH.js} +2 -2
- package/dist/{chunk-HLKQGEIA.js → chunk-S6HKRVBX.js} +2 -2
- package/dist/{chunk-NBEWP5UP.js → chunk-SJMVSADX.js} +2 -2
- package/dist/{chunk-AI4JHUOZ.js → chunk-VIC4Q4HD.js} +2 -2
- package/dist/{chunk-SWZC5ZT3.js → chunk-VYZ4X65I.js} +2 -2
- package/dist/{chunk-2LJZHKTY.js → chunk-WMZ4TGMR.js} +2 -2
- package/dist/{chunk-43I75G74.js → chunk-XMPJV6WS.js} +2 -2
- package/dist/{chunk-Y3YQ3IOG.js → chunk-XWXQGOZR.js} +2 -2
- package/dist/{chunk-5A2GI4NQ.js → chunk-Y2GFVSLP.js} +250 -250
- package/dist/chunk-Y2GFVSLP.js.map +1 -0
- package/dist/{chunk-U6CU5MIQ.js → chunk-YFN5DE56.js} +3 -3
- package/dist/chunk-YFN5DE56.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/client-NG226UN4.js +2 -0
- package/dist/{compaction-ZE2WYXHQ.js → compaction-COUQNMWL.js} +2 -2
- package/dist/{config-6BK3H63H.js → config-BFWKCNWV.js} +2 -2
- package/dist/config-mutate-Z3WK32EO.js +2 -0
- package/dist/config-mutator-TZRAR5GG.js +2 -0
- package/dist/{connect-OOPPXAOD.js → connect-AJKMRKXC.js} +2 -2
- package/dist/{contributions-VA2JWVXU.js → contributions-4HEMQ3JO.js} +2 -2
- package/dist/{daemon-api-QCBFGT7S.js → daemon-api-FGX3JS46.js} +2 -2
- package/dist/decision-approvals-NJS2ARAF.js +2 -0
- package/dist/doctor-RBPFWIQJ.js +2 -0
- package/dist/fact-proposals-Z7HJG7QJ.js +1 -1
- package/dist/{follow-up-tool-42BUNUGF.js → follow-up-tool-M6NPAVCR.js} +2 -2
- package/dist/hub-RNAZKK6J.js +2 -0
- package/dist/index.d.ts +33 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/ledger-5GMBLR7W.js +1 -1
- package/dist/memory-extract-WTCX77UH.js +2 -0
- package/dist/{org-tool-TXWIFVG6.js → org-tool-WKGZVVTS.js} +2 -2
- package/dist/owner-decisions-D3MBTX4D.js +2 -0
- package/dist/{program-435UQJ3G.js → program-OBQZUXYI.js} +266 -264
- package/dist/{program-435UQJ3G.js.map → program-OBQZUXYI.js.map} +1 -1
- package/dist/{promote-D6CRK7QJ.js → promote-DMPFCAC3.js} +2 -2
- package/dist/push-bridge-T5HZZRA2.js +1 -1
- package/dist/query-KL7IAGDI.js +2 -0
- package/dist/{query-settings-N7BMIFMM.js → query-settings-ASNC2APT.js} +3 -3
- package/dist/registry-YOZ2J3I5.js +2 -0
- package/dist/{request-planner-UD23KDKU.js → request-planner-4GT4JGV2.js} +2 -2
- package/dist/resolve-AYTQGEP2.js +2 -0
- package/dist/{review-candidates-LKY3BRHH.js → review-candidates-FHXSOGXE.js} +2 -2
- package/dist/{rotation-memo-store-ZH6254YR.js → rotation-memo-store-DO3W5LXB.js} +2 -2
- package/dist/routing-73DPZ65Q.js +2 -0
- package/dist/schedule-tool-XTEBWOCZ.js +2 -0
- package/dist/scheduler-C7OK3NCA.js +2 -0
- package/dist/{seat-VFUCGC5H.js → seat-SMBKX2K7.js} +2 -2
- package/dist/{select-TF6NCI5P.js → select-NPU6TCWK.js} +2 -2
- package/dist/{set-enabled-XBXHGNAF.js → set-enabled-CB5HS7PG.js} +2 -2
- package/dist/{sprint-tool-6YBEN7NP.js → sprint-tool-J2354376.js} +2 -2
- package/dist/status-FK4ESDJS.js +2 -0
- package/dist/{tool-UK4I6GTF.js → tool-LW5PURCD.js} +2 -2
- package/dist/{tool-Q5AMUIPF.js → tool-NXBLFMPT.js} +2 -2
- package/dist/{tool-UM3EQGMA.js → tool-OAEBT36R.js} +2 -2
- package/dist/{tool-YX2TYZB7.js → tool-TVKMQB3M.js} +2 -2
- package/dist/wiki-XJZI4D7Z.js +2 -0
- package/dist/wiki-XJZI4D7Z.js.map +1 -0
- package/dist/wiki-enrich-M7C5UVI7.js +2 -0
- package/dist/wiki-enrich-M7C5UVI7.js.map +1 -0
- package/package.json +1 -1
- package/dist/absorb-eval-RJWKCNR5.js +0 -2
- package/dist/chunk-5A2GI4NQ.js.map +0 -1
- package/dist/chunk-ECN4ZCMT.js.map +0 -1
- package/dist/chunk-U6CU5MIQ.js.map +0 -1
- package/dist/client-LU6JWHHR.js +0 -2
- package/dist/config-mutate-6ZMNQOLS.js +0 -2
- package/dist/config-mutator-RS4ORSMF.js +0 -2
- package/dist/doctor-A47S3SH6.js +0 -2
- package/dist/hub-ZC6J5Y2Q.js +0 -2
- package/dist/memory-extract-QYSXPK22.js +0 -2
- package/dist/query-KI7HTDKX.js +0 -2
- package/dist/registry-NDJ4W62V.js +0 -2
- package/dist/resolve-LOYZUE2D.js +0 -2
- package/dist/routing-UAIHQHP2.js +0 -2
- package/dist/schedule-tool-B573TNKM.js +0 -2
- package/dist/scheduler-ORNTT5P6.js +0 -2
- package/dist/status-PVYFTNX2.js +0 -2
- package/dist/wiki-XN5G2V4I.js +0 -2
- package/dist/wiki-enrich-P2DHIVLD.js +0 -2
- /package/dist/{App-BECRIPJ2.js.map → App-SWJJHYRX.js.map} +0 -0
- /package/dist/{ChatApp-WBR7IQMG.js.map → ChatApp-CPUCPJLP.js.map} +0 -0
- /package/dist/{absorb-eval-RJWKCNR5.js.map → absorb-eval-WKLAV4ZX.js.map} +0 -0
- /package/dist/{adapter-CO4TVLNV.js.map → adapter-XXUKXA5L.js.map} +0 -0
- /package/dist/{agent-ISULBG63.js.map → agent-3U23E65W.js.map} +0 -0
- /package/dist/{board-dashboard-XUY4O2RU.js.map → board-dashboard-5BPWMIUP.js.map} +0 -0
- /package/dist/{chunk-YYXE2HSO.js.map → chunk-2KLR4RWJ.js.map} +0 -0
- /package/dist/{chunk-CT3OYNNI.js.map → chunk-2OW4DTHI.js.map} +0 -0
- /package/dist/{chunk-I6FDSWP3.js.map → chunk-6WU5VEVY.js.map} +0 -0
- /package/dist/{chunk-BSDOKMKX.js.map → chunk-7BCGVPF4.js.map} +0 -0
- /package/dist/{chunk-JSCVOB4G.js.map → chunk-7IW25T4K.js.map} +0 -0
- /package/dist/{chunk-I5DAFRWA.js.map → chunk-7X4BZ5VS.js.map} +0 -0
- /package/dist/{chunk-6KSMSSPT.js.map → chunk-7YEXKWYP.js.map} +0 -0
- /package/dist/{chunk-Y24J3MOQ.js.map → chunk-B3TH5GYM.js.map} +0 -0
- /package/dist/{chunk-YBYF223R.js.map → chunk-BIK7QFDR.js.map} +0 -0
- /package/dist/{chunk-DADIYSFN.js.map → chunk-CWZ4UN7R.js.map} +0 -0
- /package/dist/{chunk-QLHEESVA.js.map → chunk-DAT6RZ5Q.js.map} +0 -0
- /package/dist/{chunk-2HBEZV7L.js.map → chunk-DPG6VHPX.js.map} +0 -0
- /package/dist/{chunk-UPNH6RAZ.js.map → chunk-IGSZ6IZ7.js.map} +0 -0
- /package/dist/{chunk-ITUBW7TE.js.map → chunk-K7JD6Y4L.js.map} +0 -0
- /package/dist/{chunk-DXXJL4TT.js.map → chunk-KSO2DLVR.js.map} +0 -0
- /package/dist/{chunk-IYTCKPZI.js.map → chunk-LW6UWMN6.js.map} +0 -0
- /package/dist/{chunk-XBON7H4I.js.map → chunk-MOA6SIUK.js.map} +0 -0
- /package/dist/{chunk-7EEWOBIM.js.map → chunk-NBIOOD7J.js.map} +0 -0
- /package/dist/{chunk-CPOTYJWY.js.map → chunk-ORBWUTVG.js.map} +0 -0
- /package/dist/{chunk-ZWJ2SUM5.js.map → chunk-QZ5HG3G5.js.map} +0 -0
- /package/dist/{chunk-TXGUBSM3.js.map → chunk-RAZKIONL.js.map} +0 -0
- /package/dist/{chunk-WNBGBOBJ.js.map → chunk-RPRJT4EH.js.map} +0 -0
- /package/dist/{chunk-HLKQGEIA.js.map → chunk-S6HKRVBX.js.map} +0 -0
- /package/dist/{chunk-NBEWP5UP.js.map → chunk-SJMVSADX.js.map} +0 -0
- /package/dist/{chunk-AI4JHUOZ.js.map → chunk-VIC4Q4HD.js.map} +0 -0
- /package/dist/{chunk-SWZC5ZT3.js.map → chunk-VYZ4X65I.js.map} +0 -0
- /package/dist/{chunk-2LJZHKTY.js.map → chunk-WMZ4TGMR.js.map} +0 -0
- /package/dist/{chunk-43I75G74.js.map → chunk-XMPJV6WS.js.map} +0 -0
- /package/dist/{chunk-Y3YQ3IOG.js.map → chunk-XWXQGOZR.js.map} +0 -0
- /package/dist/{client-LU6JWHHR.js.map → client-NG226UN4.js.map} +0 -0
- /package/dist/{compaction-ZE2WYXHQ.js.map → compaction-COUQNMWL.js.map} +0 -0
- /package/dist/{config-6BK3H63H.js.map → config-BFWKCNWV.js.map} +0 -0
- /package/dist/{config-mutate-6ZMNQOLS.js.map → config-mutate-Z3WK32EO.js.map} +0 -0
- /package/dist/{config-mutator-RS4ORSMF.js.map → config-mutator-TZRAR5GG.js.map} +0 -0
- /package/dist/{connect-OOPPXAOD.js.map → connect-AJKMRKXC.js.map} +0 -0
- /package/dist/{contributions-VA2JWVXU.js.map → contributions-4HEMQ3JO.js.map} +0 -0
- /package/dist/{daemon-api-QCBFGT7S.js.map → daemon-api-FGX3JS46.js.map} +0 -0
- /package/dist/{doctor-A47S3SH6.js.map → decision-approvals-NJS2ARAF.js.map} +0 -0
- /package/dist/{hub-ZC6J5Y2Q.js.map → doctor-RBPFWIQJ.js.map} +0 -0
- /package/dist/{follow-up-tool-42BUNUGF.js.map → follow-up-tool-M6NPAVCR.js.map} +0 -0
- /package/dist/{memory-extract-QYSXPK22.js.map → hub-RNAZKK6J.js.map} +0 -0
- /package/dist/{promote-D6CRK7QJ.js.map → memory-extract-WTCX77UH.js.map} +0 -0
- /package/dist/{org-tool-TXWIFVG6.js.map → org-tool-WKGZVVTS.js.map} +0 -0
- /package/dist/{query-KI7HTDKX.js.map → owner-decisions-D3MBTX4D.js.map} +0 -0
- /package/dist/{registry-NDJ4W62V.js.map → promote-DMPFCAC3.js.map} +0 -0
- /package/dist/{resolve-LOYZUE2D.js.map → query-KL7IAGDI.js.map} +0 -0
- /package/dist/{query-settings-N7BMIFMM.js.map → query-settings-ASNC2APT.js.map} +0 -0
- /package/dist/{routing-UAIHQHP2.js.map → registry-YOZ2J3I5.js.map} +0 -0
- /package/dist/{request-planner-UD23KDKU.js.map → request-planner-4GT4JGV2.js.map} +0 -0
- /package/dist/{schedule-tool-B573TNKM.js.map → resolve-AYTQGEP2.js.map} +0 -0
- /package/dist/{review-candidates-LKY3BRHH.js.map → review-candidates-FHXSOGXE.js.map} +0 -0
- /package/dist/{rotation-memo-store-ZH6254YR.js.map → rotation-memo-store-DO3W5LXB.js.map} +0 -0
- /package/dist/{scheduler-ORNTT5P6.js.map → routing-73DPZ65Q.js.map} +0 -0
- /package/dist/{seat-VFUCGC5H.js.map → schedule-tool-XTEBWOCZ.js.map} +0 -0
- /package/dist/{status-PVYFTNX2.js.map → scheduler-C7OK3NCA.js.map} +0 -0
- /package/dist/{wiki-XN5G2V4I.js.map → seat-SMBKX2K7.js.map} +0 -0
- /package/dist/{select-TF6NCI5P.js.map → select-NPU6TCWK.js.map} +0 -0
- /package/dist/{set-enabled-XBXHGNAF.js.map → set-enabled-CB5HS7PG.js.map} +0 -0
- /package/dist/{sprint-tool-6YBEN7NP.js.map → sprint-tool-J2354376.js.map} +0 -0
- /package/dist/{wiki-enrich-P2DHIVLD.js.map → status-FK4ESDJS.js.map} +0 -0
- /package/dist/{tool-UK4I6GTF.js.map → tool-LW5PURCD.js.map} +0 -0
- /package/dist/{tool-Q5AMUIPF.js.map → tool-NXBLFMPT.js.map} +0 -0
- /package/dist/{tool-UM3EQGMA.js.map → tool-OAEBT36R.js.map} +0 -0
- /package/dist/{tool-YX2TYZB7.js.map → tool-TVKMQB3M.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as
|
|
2
|
-
`).filter(Boolean);if(!n.length)return null;let r=JSON.parse(n[0]),o=r.run?.workflowId;if(!o)return null;let s=r.run?.status??"unknown";for(let i=n.length-1;i>=0;i--){let a=JSON.parse(n[i]),d=a.status??a.run?.status;if(d){s=d;break}}return{workflowId:o,status:s,at:e}}catch{return null}}var Cr=7,Ii={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Di=(t,e,n)=>{try{return
|
|
3
|
-
`),Wi(r,n)}function Wr(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 ju(t,e){ge(t,{...N(t),lastDigest:e})}function bt(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 jr(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Bu(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Hi}from"fs";Mn();Si();function Br(t){let e=
|
|
1
|
+
import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Er,O as Ir,k as K}from"./chunk-IGSZ6IZ7.js";import{f as $r,g as Tr,h as Ar,l as Rr}from"./chunk-RAZKIONL.js";import{b as _r}from"./chunk-2VDO2HEK.js";import{t as vr,u as Sr}from"./chunk-VYZ4X65I.js";import{d as xr,e as kr}from"./chunk-AQASR6KR.js";import{h as pe,j as dr,l as ur,m as pr,n as gr}from"./chunk-RX5O5637.js";import{a as mr,c as fr,e as hr,f as ut,h as br,j as yr,k as wr,l as pt,m as gt,n as mt}from"./chunk-5ELIX7BQ.js";import{a as rr,c as or}from"./chunk-KP7KDLZ2.js";import{Aa as ue,Ca as dt,b as at,f as Gn,s as lt,u as ct,xa as Ae,ya as er,za as W}from"./chunk-RPRJT4EH.js";import{a as $e,b as de,e as Yn}from"./chunk-7AB3QUGH.js";import{h as sr,i as ir,j as ar,l as lr,m as cr}from"./chunk-7BCGVPF4.js";import{s as Zn}from"./chunk-B3TH5GYM.js";import{a as Jn,b as Te,e as Qn}from"./chunk-ORBWUTVG.js";import{c as Re,d as tr,e as nr}from"./chunk-XVV7ZZ77.js";import{b as ee}from"./chunk-5ONH4ITT.js";import{a as Kn,c as it}from"./chunk-ILEC3IAV.js";import{a as Wn,i as Vn,l as Xn,n as ot,o as st,r as ce,s as Z,u as zn}from"./chunk-XL7UWG36.js";import{a as jn,b as Bn,d as qn,e as Hn}from"./chunk-MNG2AMKZ.js";import{a as Un}from"./chunk-7IW25T4K.js";import{a as Fn}from"./chunk-QUFIUXMQ.js";import{E as _e,F as $n,G as Tn,H as vi,Hb as Ln,Ib as Pn,Sb as Mn,f as Ze,g as C,i as Ee,j as E,k as le,l as En,o as _n,oa as In,p as et,ua as Dn,va as Cn,xa as Nn,ya as On,yb as rt}from"./chunk-YFN5DE56.js";import{a as tt,h as Si}from"./chunk-KEUW6YLL.js";import{j as nt,q as An,r as Rn}from"./chunk-UEEB3UTU.js";import{existsSync as Ei,readdirSync as _i,readFileSync as $i,statSync as Ti}from"fs";import{resolve as Ai}from"path";function Dr(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 Cu(t,e=1e3){if(!Ei(t))return[];let n=_i(t).filter(s=>s.endsWith(".jsonl")).map(s=>{let i=Ai(t,s);return{path:i,mtime:Ti(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=Ri(s,i);Ie.set(s,{mtime:i,summary:d}),d&&o.push(d)}return o}function Ri(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 Cr=7,Ii={failStreak:3,disabledDays:30,missedFires:2,graceMs:15*6e4},A={routines:200,summary:160,filters:6,filterValue:60,text:120},Di=(t,e,n)=>{try{return Zn(t,e,n)}catch{return null}},Nr=864e5;function Pu(t){let e=t.now??Date.now(),n={...Ii,...t.thresholds},r=t.nextFire??Di,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?ht(a.nextRun)??ht(r(a.schedule,new Date(e),l)):null,lastRun:p?{at:p.startedAt,status:p.status,summary:Mi(p.status==="success"?void 0:p.errorSummary,A.summary)}:null,lastSuccessAt:d.find(g=>g.status==="success")?.startedAt??null,consecutiveFailures:Or(c),sampledRuns:d.length,flags:[],attention:null,recent:d.slice(0,Cr).map(g=>({at:g.startedAt,status:g.status}))};u.flags=Lr(u,c,a.schedule,l,null,e,n,r),o.push(Pr(u))}let s=new Map(Dr(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:Oi(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:Pi(l.filter,a)},agent:Li(a),enabled:p,state:c,nextRunAt:f&&p&&w?ht(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:Or(g),sampledRuns:u.length,flags:[],attention:null,recent:g.slice(0,Cr).map(k=>({at:new Date(k.at).toISOString(),status:k.status}))},y=Date.parse(a.updated||a.created||"");b.flags=f?Lr(b,g,w,x,Number.isFinite(y)?y:null,e,n,r):Ci(b,s.get(a.id)?.state==="dormant",Number.isFinite(y)?y:null,e,n),o.push(Pr(b))}return o.sort(Ni).slice(0,A.routines)}function Or(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 Lr(t,e,n,r,o,s,i,a){let d=[],l=e.length?e[0].at:null;if(!t.enabled){let u=Fr(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 Ci(t,e,n,r,o){let s=[],i=t.lastRun?Date.parse(t.lastRun.at):null;if(!t.enabled){let a=Fr(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 Fr(t,e,n,r){let o=Math.max(t??0,e??0);return o&&n-o<r.disabledDays*Nr?null:{reason:"disabled-long",detail:o?`Disabled; no activity for ${Math.floor((n-o)/Nr)} days`:"Disabled and never ran"}}function Pr(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 Mr={critical:0,warning:1,info:2};function Ni(t,e){let n=t.attention?Mr[t.attention]:3,r=e.attention?Mr[e.attention]:3;return n-r||Number(e.enabled)-Number(t.enabled)||t.name.localeCompare(e.name)}function Oi(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 Li(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 Pi(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 ht(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 Mi(t,e){return t===void 0?void 0:F(t,e)}import{mkdirSync as Fi,readFileSync as Ui,renameSync as Wi,writeFileSync as ji}from"fs";import{resolve as Bi}from"path";function Ur(t){return Bi(st(t),"_state.json")}function N(t){try{let e=JSON.parse(Ui(Ur(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){Fi(st(t),{recursive:!0});let n=Ur(t),r=`${n}.${process.pid}.tmp`;ji(r,JSON.stringify(e,null,2)+`
|
|
3
|
+
`),Wi(r,n)}function Wr(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 ju(t,e){ge(t,{...N(t),lastDigest:e})}function bt(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 jr(t,e){let n=N(t);ge(t,{...n,wanted:[...(n.wanted??[]).filter(r=>r!==e),e]})}function Bu(t,e=Date.now()){ge(t,{...N(t),popped:{},passAt:new Date(e).toISOString()})}import{existsSync as qi,readFileSync as Hi}from"fs";Mn();Si();function Br(t){let e=Jn(t),n={};if(qi(e))try{n=Ln(JSON.parse(Hi(e,"utf-8")))}catch{n={}}let r=rt.safeParse(n?.requests);return r.success?r.data:rt.parse(void 0)}async function Ku(t,e={}){let n=(t.channels??[]).filter(r=>!tt.has(r.toLowerCase().split("@")[0]));return n.length?{success:!1,error:`unknown channel ${n.map(r=>`"${r}"`).join(", ")}: use ${[...tt].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 ua,readFileSync as kt,statSync as pa}from"fs";import{dirname as lo,resolve as T}from"path";import{randomBytes as Vr}from"crypto";import{existsSync as Xi,mkdirSync as zi,readdirSync as Ki,readFileSync as Gi,renameSync as Xr,unlinkSync as Yi,writeFileSync as Ji}from"fs";import{resolve as zr}from"path";function qr(t){return[...t.account?["--account",t.account]:[],...t.store?["--store",t.store]:[]]}var Vi=t=>t.trim().split(`
|
|
4
4
|
`).pop()?.slice(0,300)||"no output";async function Hr(t,e,n,r=ft){let o=await r(t.bin,[...qr(t),"send","text","--to",e,"--message",n,"--no-preview"],{timeoutMs:6e4});return o.code===0?{ok:!0}:{ok:!1,error:`wacli send failed: ${Vi(o.stderr||o.stdout)}`}}async function Ju(t,e,n,r,o=ft){return(await o(t.bin,[...qr(t),"--read-only","media","download","--chat",e,"--id",n,"--output",r],{timeoutMs:12e4})).code===0}var Qi=2e3,Zi=t=>Hr(t.wacli,t.to,t.text);function yt(t){return zr(t,".agentx","whatsapp-triage","drafts")}var ea=t=>/^[a-z0-9-]{8,64}$/.test(t),De=(t,e)=>zr(yt(t),`${e}.json`);function Kr(t,e){zi(yt(t),{recursive:!0});let n=De(t,e.id),r=`${n}.${process.pid}.tmp`;Ji(r,JSON.stringify(e,null,2)+`
|
|
5
5
|
`,{mode:384}),Xr(r,n)}function rp(t,e,n=Date.now()){let r=e.text.trim().slice(0,Qi);if(!r)throw new Error("empty draft");let o={...e,text:r,id:`${n.toString(36)}-${Vr(4).toString("hex")}`,status:"pending",created_at:new Date(n).toISOString()};return Kr(t,o),o}function Ce(t,e){if(!ea(e))return null;try{return JSON.parse(Gi(De(t,e),"utf-8"))}catch{return null}}function Gr(t,e){let n=yt(t);return Xi(n)?Ki(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 Yr(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}.${Vr(3).toString("hex")}.claim`;try{Xr(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??Zi)(o).catch(d=>({ok:!1,error:String(d?.message??d)}));a.ok?i.status="sent":(i.status="failed",i.error=a.error)}Kr(t,i);try{Yi(s)}catch{}return i.status==="failed"?{ok:!1,error:i.error??"send failed"}:{ok:!0,draft:i}}import{mkdirSync as ta,writeFileSync as na}from"fs";import{resolve as Qr}from"path";var Zr="ready",ra="202510";function oa(t){let e=t.date??t.created_at.slice(0,10);return Qr(t.workspace,Zr,`${e}-${t.platform}-${t.id}.txt`)}function Jr(t){let e=oa(t);return ta(Qr(t.workspace,Zr),{recursive:!0}),na(e,t.text.endsWith(`
|
|
6
6
|
`)?t.text:`${t.text}
|
|
7
|
-
`),e}function eo(t,e,n){let r=
|
|
7
|
+
`),e}function eo(t,e,n){let r=Un(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 to(t,e,n){return eo(t,e,n)!==null}async function sa(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??ra),"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 ia(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 aa(t,e){let n=eo(e,t.agent,t.platform);if(!n)return{ok:!0,posted:!1,file:Jr(t)};let r=e.fetch??fetch;try{let o=t.platform==="linkedin"?await sa(t.text,n,r):await ia(t.text,n,r);return{ok:!0,posted:!0,...o.url?{url:o.url}:{}}}catch(o){let s=Jr(t);return{ok:!1,error:`not posted on ${pe[t.platform]}: ${o?.message??o}. Saved to paste by hand: ${s}`,file:s}}}function no(t){return e=>aa(e,t)}Rn();On();On();Rn();var pp=["done","skipped"],la=1e3;function ca(t){t.exec(`
|
|
8
8
|
CREATE TABLE IF NOT EXISTS request_plans (
|
|
9
9
|
request_id TEXT PRIMARY KEY,
|
|
10
10
|
created_by TEXT NOT NULL,
|
|
@@ -64,8 +64,8 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Sr,O as Ir,k as K}from"./ch
|
|
|
64
64
|
to_channel, to_chat, to_account, check_url, check_contains, stall_minutes, dispatched_at, updated_at, check_count)
|
|
65
65
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);this.db.transaction(()=>{s.run(e,n,o),r.forEach((a,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?wt(n):null}steps(e){return this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? ORDER BY idx").all(e).map(ro)}step(e,n){let r=this.db.prepare("SELECT * FROM request_plan_steps WHERE request_id = ? AND idx = ?").get(e,n);return r?ro(r):null}listActive(){return this.db.prepare("SELECT * FROM request_plans WHERE state = 'active' ORDER BY created_at, rowid").all().map(wt)}updateStep(e,n,r){let o=[],s=[];for(let[i,a]of Object.entries(r)){let d=da[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(wt)}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,la))}continues(e,n){let r=this.db.prepare("SELECT turns, cost_usd, told_at FROM request_plan_continues WHERE goal_key = ? AND day = ?").get(e,n);return r?{turns:r.turns,costUsd:r.cost_usd,toldAt:r.told_at??null}:{turns:0,costUsd:0,toldAt:null}}addContinue(e,n,r){this.db.prepare(`INSERT INTO request_plan_continues (goal_key, day, turns, cost_usd, told_at) VALUES (?, ?, ?, ?, ?)
|
|
66
66
|
ON CONFLICT(goal_key, day) DO UPDATE SET turns = turns + excluded.turns, cost_usd = cost_usd + excluded.cost_usd,
|
|
67
|
-
told_at = COALESCE(excluded.told_at, told_at)`).run(e,n,r.turns??0,r.costUsd??0,r.toldAt??null)}events(e,n=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n).reverse().map(r=>({requestId:r.request_id,step:r.step??null,at:r.at,kind:r.kind,detail:r.detail}))}stepEvents(e,n,r,o=200){return this.db.prepare("SELECT request_id, step, at, kind, detail FROM request_plan_events WHERE request_id = ? AND step = ? AND kind = ? ORDER BY at DESC, rowid DESC LIMIT ?").all(e,n,r,o).reverse().map(s=>({requestId:s.request_id,step:s.step??null,at:s.at,kind:s.kind,detail:s.detail}))}},gp=Dn;var co=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],ga=280;function O(t,e=ga){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 ma(t){return Z(t.root,"pending").map(fa)}function fa(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 ha(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(kt(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?or(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 ${ir(sr(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function uo(t){let e=T(t,".agentx","memory");return H(e)?ua(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ba(t){let e=uo(t.root);if(e.length===0)return[];let n=new at(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 ya(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 wa(t){return xr(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(`${ya(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var so=new Map;function po(t,e){let n=pa(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=so.get(t);if(o?.version===r)return o.value;let s=e();return so.set(t,{version:r,value:s}),s}function xa(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 ka(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?xa(r):void 0}function va(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=po(e,()=>Re(new ee(lo(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 Sa(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 go(t){let e=V(t),n=new it(e);if(!H(n.path))return[];let r=po(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Sa(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 Ea(t){return Gr(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 _a(t){return Tr(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(lt(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(kt(te(t),"utf-8"))}catch{return{}}}function xt(t){let e={};try{e=Object.fromEntries(Fn(kt(T(lo(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Ta(t){let e=ur(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=xt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:to({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:cr(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=nt({quiet:!0});if(!e)return null;let n=io.get(e);return!n&&!Cn(e)?null:(n||io.set(e,n=new Nn(e)),n)}var io=new WeakMap;function jp(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=nt({quiet:!0});if(!e||!oo(e))return null;let n=ao.get(e);return n||ao.set(e,n=new Ne(e)),n}var ao=new WeakMap;function Aa(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 mo={card:ma,schedule:ha,agent:$a,memory:ba,wiki:wa,fact:()=>[],question:go,whatsapp:Ea,email:_a,content:Ta,request:Aa};function Ra(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 fo(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??co){if(d==="fact"){try{let c=va(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=mo[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(Ra),{items:o,snoozed:a,errors:s,backlog:i}}function ho(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!co.includes(n)||!r?null:{kind:n,ref:r}}function Ia(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return wr(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return $r(t.root,n)?.status==="pending";case"content":return dr(t.root,n)?.status==="pending";default:return!!bo(t,e,n)}}function bo(t,e,n){return e==="fact"?ka(t,n):mo[e](t).find(r=>r.key===`${e}:${n}`)}async function yo(t,e,n,r={}){let o=n==="later"?null:ho(e),s;if(o)try{s=bo(t,o.kind,o.ref)}catch{s=void 0}let i=await Da(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Un(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 Da(t,e,n,r){let o=ho(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(!Ia(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 Wr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=Xn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});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?ar:lr)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(lt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ct(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?(ct(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(!uo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new at(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?kr(c,i,{by:d,force:r.force,now:a}):vr(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 Ca(t,e,i,l,d,r);case"question":return Oa(t,e,i,l,d,r);case"whatsapp":{let c=await Yr(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??Rr(Oe(t),xt(t)),p=await Ar(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??no({config:Oe(t),env:xt(t)}),p=await pr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Br(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?In:d),{ok:!0,message:`${e}: dropped`})}}}function Ca(t,e,n,r,o,s){let i=new ee(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 tr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=er(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 Na(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 Oa(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(zn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=go(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=Na(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 ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var La=3,Pa=7,Ma=50,St=120,Fa=280,vt=600,xo=36e5,Ua=24*xo;function Hp(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 Wa(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,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Fa)}:{},...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 ja={done:"Done",declined:"Declined",dropped:"Dropped"};function ko(t,e,n){let{record:r,links:o}=e,s=K(r,St),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,vt)}:{},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,vt)}:{},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??La)*xo;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:ja[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ba(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,St),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ba(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,wo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function Et(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(Wa(o,s,o.node===t.node))}let r=vo(t,e);for(let o of t.requests??[]){let s=ko(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function vo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Vp(t){let e=Et(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=vo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=ko(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Pa)*Ua;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,Ma),c=wo(n,"askedAt"),p=wo(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 Ha(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 Va(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 Gp(t,e){let n=t.now??Date.now(),r=[],o=fo(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}=Et({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ha)}],requests:a,deferred:i});return Va(d,i.size,[...r,...l])}import{readFileSync as Xa}from"fs";var za=1e4,So=/^[0-9a-f]{7,64}$/i;function Qp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&So.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(za)})}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"&&So.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Zp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Xa(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 Pe=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function tg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function ng(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 rg(t){return Pe.has(t)}function og(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Pe.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 sg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Pe.has(t.remoteAddress)}function ig(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Pe.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function ag(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 lg(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 Me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ka(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ga(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function dg(t,e=Ga()){let n=Me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ka(n),s=[Me(t.host),Me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function ug(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ya=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ja=/^\/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 Qa(t){let e={agent:{},person:{}};for(let n of
|
|
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}))}},gp=Dn;var co=["card","schedule","agent","memory","wiki","fact","question","whatsapp","email","content","request"],ga=280;function O(t,e=ga){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 ma(t){return Z(t.root,"pending").map(fa)}function fa(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 ha(t){let e=te(t);if(!H(e))return[];let n;try{n=JSON.parse(kt(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?sr(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 ${ar(ir(i.schedule,d,r),d)}`:""}`),more:"agentx schedule list"})}return o}function uo(t){let e=T(t,".agentx","memory");return H(e)?ua(e).filter(n=>n.endsWith(".jsonl")).map(n=>n.slice(0,-6)).sort():[]}function ba(t){let e=uo(t.root);if(e.length===0)return[];let n=new at(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 ya(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 wa(t){return kr(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(`${ya(n)} ${e.article.content}`),more:`agentx wiki proposals show ${e.id}`}})}var so=new Map;function po(t,e){let n=pa(t,{bigint:!0}),r=`${n.mtimeNs}:${n.size}`,o=so.get(t);if(o?.version===r)return o.value;let s=e();return so.set(t,{version:r,value:s}),s}function xa(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 ka(t,e){let n=V(t);if(!H(T(n,"_facts.json")))return;let r=Re(new ee(n),"pending").find(o=>o.id===e);return r?xa(r):void 0}function va(t){let e=T(V(t),"_facts.json");if(!H(e))return;let n=po(e,()=>Re(new ee(lo(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 Sa(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 go(t){let e=V(t),n=new it(e);if(!H(n.path))return[];let r=po(n.path,()=>{let s=n.load();if(s.unreadable)throw new Error(`${n.path} is unreadable: ${s.unreadable}`);return s.questions.filter(i=>i.status==="open"&&i.kind==="contradiction")}),o;return r.map(s=>{let i;if(s.kind==="contradiction"&&s.proposed&&s.factId){let a=(o??=new ee(e)).get(s.factId);a&&(i=[a.value,s.proposed.value])}return{key:`question:${s.id}`,kind:"question",title:Sa(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 Ea(t){return Gr(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 _a(t){return Tr(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(lt(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(kt(te(t),"utf-8"))}catch{return{}}}function xt(t){let e={};try{e=Object.fromEntries(Fn(kt(T(lo(te(t)),".env"),"utf-8")))}catch{}return{...e,...process.env}}function Ta(t){let e=pr(t.root,"pending");if(e.length===0)return[];let n=Oe(t),r=xt(t);return e.map(o=>{let s=pe[o.platform]??o.platform;return{key:`content:${o.id}`,kind:"content",title:`${s} post${o.topic?`: ${o.topic}`:""}${o.date?` (for ${o.date})`:""}`,ask:`Publish this on ${s}? "${o.text}"`,yes:to({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:dr(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=nt({quiet:!0});if(!e)return null;let n=io.get(e);return!n&&!Cn(e)?null:(n||io.set(e,n=new Nn(e)),n)}var io=new WeakMap;function jp(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=nt({quiet:!0});if(!e||!oo(e))return null;let n=ao.get(e);return n||ao.set(e,n=new Ne(e)),n}var ao=new WeakMap;function Aa(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 mo={card:ma,schedule:ha,agent:$a,memory:ba,wiki:wa,fact:()=>[],question:go,whatsapp:Ea,email:_a,content:Ta,request:Aa};function Ra(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 fo(t,e={}){let n=t.now??Date.now(),{snoozed:r}=N(t.root),o=[],s=[],i=[],a=0;for(let d of e.kinds??co){if(d==="fact"){try{let c=va(t);c&&i.push(c)}catch(c){s.push({kind:d,error:String(c?.message??c).slice(0,200)})}continue}let l;try{l=mo[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(Ra),{items:o,snoozed:a,errors:s,backlog:i}}function ho(t){let e=t.indexOf(":");if(e<=0)return null;let n=t.slice(0,e),r=t.slice(e+1);return!co.includes(n)||!r?null:{kind:n,ref:r}}function Ia(t,e,n){switch(e){case"card":return ce(t.root,n)?.status==="pending";case"wiki":return xr(V(t),n)?.status==="pending";case"whatsapp":return Ce(t.root,n)?.status==="pending";case"email":return $r(t.root,n)?.status==="pending";case"content":return ur(t.root,n)?.status==="pending";default:return!!bo(t,e,n)}}function bo(t,e,n){return e==="fact"?ka(t,n):mo[e](t).find(r=>r.key===`${e}:${n}`)}async function yo(t,e,n,r={}){let o=n==="later"?null:ho(e),s;if(o)try{s=bo(t,o.kind,o.ref)}catch{s=void 0}let i=await Da(t,e,n,r);if(i.ok&&o&&n!=="later"){let a=typeof r.choice=="number"?s?.choices?.[r.choice-1]:r.choice;Wn(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 Da(t,e,n,r){let o=ho(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(!Ia(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 Wr(t.root,e,p,a),{ok:!0,message:`${e} put off until ${p.toISOString()}`}}let l=n==="yes";switch(s){case"card":{let c=zn(t.root,i,l?"yes":"no",{by:d,note:r.note,now:a,choice:r.choice,text:r.text,popup:r.popup});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?lr:cr)(i,{configPath:te(t),reload:t.reload});return c.success?{ok:!0,message:c.message}:{ok:!1,error:c.message}}case"agent":{if(lt(t.root)[i]?.kind!=="approval")return{ok:!1,error:`no new agent "${i}" waits for approval`};if(l)return ct(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=>{Qn(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?(ct(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(!uo(t.root).includes(p))return{ok:!1,error:`no memory for agent "${p}"`};let g=new at(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?vr(c,i,{by:d,force:r.force,now:a}):Sr(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 Ca(t,e,i,l,d,r);case"question":return Oa(t,e,i,l,d,r);case"whatsapp":{let c=await Yr(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??Rr(Oe(t),xt(t)),p=await Ar(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??no({config:Oe(t),env:xt(t)}),p=await gr(t.root,i,l?"yes":"no",{by:d,now:a,text:r.text,seen:r.seen,publish:c});if(!p.ok)return p;if(!l)return{ok:!0,message:`${e}: dropped, nothing published`};let u=pe[p.draft.platform];return{ok:!0,message:p.draft.status==="posted"?`${e}: posted on ${u}${p.draft.url?` (${p.draft.url})`:""}`:`${e}: no ${u} connector is set, so it is saved ready to paste: ${p.draft.file}`}}case"request":{let c=G(t),p=c?.get(i);return!c||!p||p.state!=="needs_attention"?{ok:!1,error:`nothing waiting for "${e}"`}:l?Br(te(t)).enabled?(c.requestPickup(i,a),{ok:!0,message:`${e}: ${p.agentId} will be asked to pick it up again`}):{ok:!1,error:"Requests are off, so nothing would hand it back. Turn them on (agentx requests settings --enabled on), or answer no to drop it."}:(c.close(i,"dropped",r.note?.trim()||`dropped by ${d}`,a,null,d==="operator"?In:d),{ok:!0,message:`${e}: dropped`})}}}function Ca(t,e,n,r,o,s){let i=new ee(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 nr(i,a.id,o,s.note),{ok:!0,message:`${e}: claim dropped`};let d=tr(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 Na(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 Oa(t,e,n,r,o,s){let i=V(t),a=new it(i),d=a.list("open").find(l=>l.id===n);if(!d)return{ok:!1,error:`nothing waiting for "${e}"`};try{if(Kn(`${r?"answer":"dismiss"} a wiki question`),!r)return a.resolve(d.id,"dismissed"),{ok:!0,message:`${e}: dismissed`};let l=go(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=Na(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 ee(i),u=d.factId?p.get(d.factId):void 0;return u&&p.write({subject:u.subject,attribute:u.attribute,value:c,source:"owner said",verifiedBy:o,volatility:u.volatility},{confirmedBy:o}),a.resolve(d.id,"answered",c),{ok:!0,message:`${e}: answered "${c}"`}}catch(l){return{ok:!1,error:String(l?.message??l)}}}var La=3,Pa=7,Ma=50,St=120,Fa=280,vt=600,xo=36e5,Ua=24*xo;function Hp(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 Wa(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,St),...e.ask?{ask:ne(e.ask,vt)}:{},...e.detail?{facts:ne(e.detail,Fa)}:{},...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 ja={done:"Done",declined:"Declined",dropped:"Dropped"};function ko(t,e,n){let{record:r,links:o}=e,s=K(r,St),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,vt)}:{},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,vt)}:{},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??La)*xo;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:ja[r.state]??r.state,...a?{evidence:a}:{},can:{answer:!1,later:!1,reply:!1}}}}}function Ba(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,St),ask:e.ask,agent:e.raised_by,askedAt:e.created_at,...e.decided_at?{changedAt:e.decided_at}:{},outcome:Ba(e),...e.resolution?{evidence:e.resolution}:{},can:{answer:!1,later:!1,reply:!1}}}var L=t=>t&&Date.parse(t)||0,wo=(t,e)=>t.map(n=>n[e]).filter(n=>!!L(n)).sort((n,r)=>L(n)-L(r))[0];function Et(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(Wa(o,s,o.node===t.node))}let r=vo(t,e);for(let o of t.requests??[]){let s=ko(t,o,r);s?.column==="yours"&&e.push(s)}return{cards:e,errors:n}}function vo(t,e){return new Set([...e.filter(n=>n.node===t.node).map(n=>n.key),...t.deferred??[]])}function Vp(t){let e=Et(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=vo(t,n),s=[],i=[],a=[];for(let u of t.requests??[]){let g=ko(t,u,o);g&&g.column!=="yours"&&{agent:s,quiet:i,done:a}[g.column].push(g)}let d=t.now-(t.doneDays??Pa)*Ua;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,Ma),c=wo(n,"askedAt"),p=wo(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 Ha(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 Va(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 Gp(t,e){let n=t.now??Date.now(),r=[],o=fo(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}=Et({now:n,node:e.url,nodeName:e.name,inbox:[{node:e.url,nodeName:e.name,items:s.map(Ha)}],requests:a,deferred:i});return Va(d,i.size,[...r,...l])}import{readFileSync as Xa}from"fs";var za=1e4,So=/^[0-9a-f]{7,64}$/i;function Qp(t){let e=t.fetch??fetch;return async n=>{if(n==="self"){let i=t.self();return i&&So.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(za)})}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"&&So.test(s.trim())?{source:n,commit:s.trim()}:{source:n,commit:null,error:`no commit under "${t.field}"`}}}function Zp(t){let e=t.requests.checkers,n=t.channels.github,r=e?.github?.token??n?.token;if(!r&&n?.tokenFile)try{r=Xa(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 Pe=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]);function tg(t){return t==="/api/memory"||t.startsWith("/api/memory/")||t==="/api/assistant"||t.startsWith("/api/assistant/")||t==="/api/agent-picture"||t==="/approvals"||t.startsWith("/approvals/")||t==="/api/org"||t.startsWith("/api/org/")||t==="/content"||t.startsWith("/content/")||t==="/integrations"||t.startsWith("/integrations/")||t==="/screen"||t==="/native/notes"||t==="/requests"||t.startsWith("/requests/")||t==="/watchers"||t.startsWith("/watchers/")||t==="/follow-up"||t.startsWith("/follow-up/")||t==="/events/recent"||t==="/events/hub"||/^\/agents\/[^/]+\/events$/.test(t)||t==="/a2a/delegations"||t.startsWith("/a2a/delegations/")||t==="/traces"||t.startsWith("/traces/")||t==="/voice/history"||t.startsWith("/voice/history/")||t==="/voice/requests"||t.startsWith("/voice/requests/")||t==="/voice/transcribe"||t==="/voice/speak"||t==="/app-files"||t==="/calls"||t.startsWith("/calls/")||t==="/webrtc/camera"||t.startsWith("/webrtc/camera/")||t==="/mesh/guests"||t.startsWith("/mesh/guests/")||t==="/wiki/agents"||t==="/wiki/entries"||t==="/wiki/articles"||t==="/wiki/article"||t==="/wiki/notes"||t==="/api/wiki/curate"||t==="/api/wiki/curate/restore"||t==="/api/signals/stopped"||t.startsWith("/api/signals/stopped/")||t==="/api/review-gate/reviews"||t==="/owner/told"||t==="/owner/presence"}function ng(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 rg(t){return Pe.has(t)}function og(t){if(t.foreignBrowser)return{allowed:!1,reason:"foreign-browser-origin"};if(t.enforcementDisabled)return{allowed:!0,reason:"disabled"};if(Pe.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 sg(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return n&&t.chatSecret&&n===t.chatSecret?!0:t.foreignBrowser?!1:n&&t.acceptedTokens.has(n)?!0:!t.chatSecret&&Pe.has(t.remoteAddress)}function ig(t){let e=t.authorizationHeader||"",n=e.startsWith("Bearer ")?e.slice(7).trim():"";return t.chatSecret?n===t.chatSecret:Pe.has(t.remoteAddress)||!!n&&t.acceptedTokens.has(n)}function ag(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 lg(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 Me(t){return(Array.isArray(t)?t[0]:t)?.trim()??""}function Ka(t){try{return new URL(t).host.toLowerCase()}catch{return null}}function Ga(t=process.env){return new Set((t.AGENTX_ALLOWED_ORIGINS||"").split(",").map(e=>e.trim().replace(/\/+$/,"").toLowerCase()).filter(Boolean))}function dg(t,e=Ga()){let n=Me(t.origin);if(n){if(e.has(n.replace(/\/+$/,"").toLowerCase()))return"same-origin";let o=Ka(n),s=[Me(t.host),Me(t["x-forwarded-host"])].filter(Boolean).map(i=>i.toLowerCase());return o&&s.includes(o)?"same-origin":"foreign"}let r=Me(t["sec-fetch-site"]).toLowerCase();return r==="cross-site"||r==="same-site"?"foreign":"none"}function ug(t){let e=(t||"GET").toUpperCase();return e!=="GET"&&e!=="HEAD"}var _t="/api/admin/pictures",Ya=/^\/api\/pictures\/(agent|person)\/([^/]+)$/,Ja=/^\/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 Qa(t){let e={agent:{},person:{}};for(let n of mr)for(let[r,o]of Object.entries(br(t,n)))e[n][r]=yr(n,r,o);return e}function mg(t,e,n,r,o){let s=n.match(Ya);if(!s)return!1;if((t.method||"GET").toUpperCase()!=="GET")return _(e,405,{error:"GET only"}),!0;let i=decodeURIComponent(s[2]),a=wr(o,s[1],i,r.searchParams.get("v")||"");return a?(e.writeHead(200,{"Content-Type":fr,"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 fg(t,e,n,r){if(n!==_t&&!n.startsWith(`${_t}/`))return!1;let o=(t.method||"GET").toUpperCase();if(n===_t)return o!=="GET"?(_(e,405,{error:"GET only"}),!0):(_(e,200,{...Qa(r.root),editable:{agent:r.agentIds(),person:r.personIds()}}),!0);let s=n.match(Ja);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(!hr.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=gt(r.root,a,d);return _(e,200,{ok:!0,removed:c}),!0}try{let c=await mt(t),p=await pt(r.root,a,d,c);_(e,200,{ok:!0,url:p.url})}catch(c){if(c instanceof ut)return _(e,c.status,{error:c.message}),!0;throw c}return!0}async function hg(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:gt(r.root,"agent",i)});return}try{let a=await pt(r.root,"agent",i,await mt(t));_(e,200,{ok:!0,agent:i,url:a.url})}catch(a){if(a instanceof ut){_(e,a.status,{error:a.message});return}throw a}}var Eo={};function wg(t){Eo=t}function xg(){return Eo}var kg=`<link rel="icon" type="image/svg+xml" href="/favicon.svg">
|
|
69
69
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
|
|
70
70
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
71
71
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
@@ -355,7 +355,7 @@ import{a as ft}from"./chunk-GTJIKXDB.js";import{H as Sr,O as Ir,k as K}from"./ch
|
|
|
355
355
|
<span class="name">${j(r.name)}</span>
|
|
356
356
|
<span class="chev">\u25BE</span>
|
|
357
357
|
<div class="ax-mesh-menu" role="menu">${o}</div>
|
|
358
|
-
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:
|
|
358
|
+
</div>`,a=[{name:"Mesh",tabs:[{id:"wall",label:$e,href:de},{id:"live",label:"Live",href:`${de}#page=live`},{id:"mesh",label:"Operations",href:"/mesh"},{id:"monitor",label:"Monitor",href:"/monitor"},{id:"approvals",label:"Needs you",href:Yn},{id:"people",label:"People",href:`${de}#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:`${de}#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
359
|
<div class="ax-topbar__left">
|
|
360
360
|
<div class="ax-brand">
|
|
361
361
|
<span class="ax-brand__mark">AX</span>
|
|
@@ -556,7 +556,7 @@ ${n}`.replace(/\s+/g," ").trim().toLowerCase();return r.length<uc?null:`text:${d
|
|
|
556
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}},cs=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=mc(n,e.title,e.text),i=n.kind??"notice",a=(s?.startsWith("text:")?Math.min(r.repeatWindowHours,pc):r.repeatWindowHours)*as,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:hc(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*as)}};function vm(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 hc(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 bc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n/i,yc=/(^|\n)[ \t]*```[ \t]*agentx:ui[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*```[ \t]*(?=\n|$)/gi;function Xe(t){if(!t||!t.includes("agentx:ui"))return{cleanText:t};let e=[...t.matchAll(yc)];if(e.length===0)return{cleanText:t};let n=e[e.length-1],r=n[2],o=wc(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 Em(t){if(!t||!t.includes("agentx:ui"))return t;let e=bc.exec(t);return e?t.slice(0,e.index).trimEnd():t}function wc(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 $m(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 xc=5*6e4;function X(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"")}var ds=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
557
|
data: ${JSON.stringify(n)}
|
|
558
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+xc),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 kc,readFileSync as us,renameSync as vc,rmSync as Sc,writeFileSync as Ec}from"fs";import{homedir as _c}from"os";import{dirname as $c,join as Tc}from"path";var ps=Tc(_c(),".agentx","call.json");function Ac(t=ps,e=Date.now()){try{let n=JSON.parse(us(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 gs(t=
|
|
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+xc),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 kc,readFileSync as us,renameSync as vc,rmSync as Sc,writeFileSync as Ec}from"fs";import{homedir as _c}from"os";import{dirname as $c,join as Tc}from"path";var ps=Tc(_c(),".agentx","call.json");function Ac(t=ps,e=Date.now()){try{let n=JSON.parse(us(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 gs(t=rr,e=Ac){let n=t();return n.active?n:e()}function Cm(t,e,n=ps,r=Date.now()){let o=null;try{o=JSON.parse(us(n,"utf-8"))}catch{}if(o&&o.source&&o.source!=="daemon")return;if(!t){o&&Sc(n,{force:!0});return}kc($c(n),{recursive:!0});let s=`${n}.${process.pid}.tmp`;Ec(s,JSON.stringify({active:!0,source:"daemon",reason:t,until:new Date(r+e).toISOString()})+`
|
|
560
560
|
`),vc(s,n)}var ms="owner",ze=6e4,ws=60*ze,Rc=24*ws,Ic=7*24*ws,Dc=2*ze,Lm={enabled:!1,escalateAfterMinutes:10,ladder:[]};function Cc(t){t.exec(`
|
|
561
561
|
CREATE TABLE IF NOT EXISTS owner_presence (
|
|
562
562
|
person TEXT NOT NULL,
|
|
@@ -609,7 +609,7 @@ ${e}`;r-(this.written.get(o)??-1/0)<this.throttleMs||(this.written.set(o,r),this
|
|
|
609
609
|
.oe-form > *, .oe-role { flex: 1 1 100%; }
|
|
610
610
|
.oe-legend { grid-template-columns: 1fr; }
|
|
611
611
|
}
|
|
612
|
-
`;et();function Qt(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 xs(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=ks(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 ks(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 Xm(t,e){let n=new Set,r=ks(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))}}et();var vs=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Ke=["mon","tue","wed","thu","fri","sat","sun"],Zt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Uc(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=>!Ke.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?Ke.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Wc(t){let e=Ke.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Ke.indexOf(r)===e+o))return`${Zt[t[0]]} to ${Zt[t[t.length-1]]}`;let n=t.map(r=>Zt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var en={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function tn(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 Ts(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function jc(t){let e=t?.business?.roles??{};return{agents:[...Ts(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...tn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Ze}}function Bc(t){let e=t?.business??{},n=e.roles??{},r=Ts(t),o=tn(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]),...Qt(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 Ss(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(tn(t).keys()),o=_n(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 En(le(e),n,r,o)??xs(Qt(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 Es(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 _s(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>vs)throw new Error(`Keep the role under ${vs} characters.`);return e}function Hc(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 Ym(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Ss(n),s=Bc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=jc(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=_s(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Es(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=_s(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Es(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(!Ze.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 ${en[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(Hc(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)} ${en[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 ${en[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=Uc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Wc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Ss(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 Vc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},As=class{constructor(e=Vc,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)}},Xc="That code didn't work. Check it, or run agentx app pair for a new one.",zc=400;async function Zm(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 Er(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Kc(n,e.minMs??zc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Xc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Kc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as ud}from"child_process";import{mkdtempSync as od,rmSync as sd,writeFileSync as id}from"fs";import{tmpdir as ad}from"os";import{join as Ns}from"path";import{randomBytes as Gc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},Rs=`
|
|
612
|
+
`;et();function Qt(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 xs(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=ks(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 ks(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 Xm(t,e){let n=new Set,r=ks(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))}}et();var vs=80,be={days:["mon","tue","wed","thu","fri"],start:"09:00",end:"17:00"},Ke=["mon","tue","wed","thu","fri","sat","sun"],Zt={mon:"Monday",tue:"Tuesday",wed:"Wednesday",thu:"Thursday",fri:"Friday",sat:"Saturday",sun:"Sunday"};function Uc(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=>!Ke.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?Ke.filter(a=>o.includes(a)):[...be.days];return{start:n,end:r,days:i}}function Wc(t){let e=Ke.indexOf(t[0]);if(t.length>2&&t.every((r,o)=>Ke.indexOf(r)===e+o))return`${Zt[t[0]]} to ${Zt[t[t.length-1]]}`;let n=t.map(r=>Zt[r]);return n.length<2?n.join(""):n.slice(0,-1).join(", ")+" and "+n[n.length-1]}var en={"reports-to":"reports to","dotted-line":"has a dotted line to","acts-for":"acts for"};function tn(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 Ts(t){return new Map(Object.entries(t?.agents??{}).map(([e,n])=>[e,String(n?.name||e)]))}function jc(t){let e=t?.business?.roles??{};return{agents:[...Ts(t)].map(([n,r])=>({ref:`agent:${n}`,name:r})),people:[...tn(t)].map(([n,r])=>({ref:`person:${n}`,name:r})),roles:Object.entries(e).map(([n,r])=>({key:n,title:String(r?.title||n)})),types:Ze}}function Bc(t){let e=t?.business??{},n=e.roles??{},r=Ts(t),o=tn(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]),...Qt(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 Ss(t){let e=t?.business??{},n=new Set(Object.keys(e.orgChart??{})),r=new Set(tn(t).keys()),o=_n(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 En(le(e),n,r,o)??xs(Qt(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 Es(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 _s(t){let e=String(t??"").replace(/\s+/g," ").trim();if(e.length>vs)throw new Error(`Keep the role under ${vs} characters.`);return e}function Hc(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 Ym(t,e){let n=structuredClone(t??{}),r=n.business=n.business||{},o=Ss(n),s=Bc(n),i=new Map(s.members.map(u=>[u.ref,u])),a=jc(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=_s(e.role);if(g==="agent"&&!w)throw new Error(`Give ${f} a role.`);let x=w?Es(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=_s(e.role);if(u.kind==="agent"&&!g)throw new Error(`${u.name} needs a role.`);let m=g?Es(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(!Ze.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 ${en[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(Hc(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)} ${en[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 ${en[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=Uc(e),m=r.orgChart[u.id];m.schedule={...m.schedule??{},...g},c=`${u.name} works ${Wc(g.days)}, ${g.start} to ${g.end}`;break}default:throw new Error("Unknown change to the org chart.")}let p=Ss(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 Vc={perClient:5,global:10,windowMs:10*60*1e3,lockoutMs:5*60*1e3},As=class{constructor(e=Vc,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)}},Xc="That code didn't work. Check it, or run agentx app pair for a new one.",zc=400;async function Zm(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 _r(t,1024)).code}catch{}let a=e.codes.redeem(i),d=a?e.verify(a.token):null;return await Kc(n,e.minMs??zc),!a||!d?(e.limiter.fail(o),r(`[app] pair-code failed from ${o}`),{status:401,body:{error:Xc}}):(e.limiter.succeed(o),r(`[app] pair-code paired ${a.tokenId} (${d}) from ${o}`),{status:200,body:{device:d},token:a.token})}async function Kc(t,e){let n=t+e-Date.now();n>0&&await new Promise(r=>setTimeout(r,n))}import{execFile as ud}from"child_process";import{mkdtempSync as od,rmSync as sd,writeFileSync as id}from"fs";import{tmpdir as ad}from"os";import{join as Ns}from"path";import{randomBytes as Gc}from"crypto";function R(t){return String(t??"").replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var B={top:8,side:32,bottom:60},nn={height:56,keep:52},Rs=`
|
|
613
613
|
:root {
|
|
614
614
|
--ac-paper: #fafaf9; --ac-soft: #f4f4f2; --ac-edge: #e9e9e6;
|
|
615
615
|
--ac-text: #0b1413; --ac-muted: #4a5856; --ac-subtle: #7c8987;
|
|
@@ -738,7 +738,7 @@ button.primary:hover:not(:disabled) { transform: translateY(-1px); background: v
|
|
|
738
738
|
button.primary:disabled { opacity: .55; cursor: not-allowed; }
|
|
739
739
|
kbd { font: 11px var(--ac-mono); color: var(--ac-subtle); }
|
|
740
740
|
button.primary kbd { color: inherit; opacity: .7; }
|
|
741
|
-
`;var Is=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Ds=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Yc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Is(n):Ds(n)}`}function Jc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Ds(n)],Is(n)].join(" ")}function Qc(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 Zc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var rn=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,ed=rn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),td=rn('<path d="m6 15 6-6 6 6"/>'),nd=rn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Cs(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Gc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=
|
|
741
|
+
`;var Is=t=>t.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"}),Ds=t=>`${t.getDate()} ${t.toLocaleDateString("en-US",{month:"short"})}`;function Yc(t,e){let n=new Date(t);return Number.isNaN(n.getTime())?"":`since ${n.toDateString()===new Date(e).toDateString()?Is(n):Ds(n)}`}function Jc(t,e){let n=new Date(t),r=n.getTime()-e<6*864e5;return[n.toLocaleDateString("en-US",{weekday:"short"}),...r?[]:[Ds(n)],Is(n)].join(" ")}function Qc(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 Zc(t){return t.origin?.kind==="request"?"Hand it back":t.draft?"Send":t.choices?.length?"Choose":"Yes"}var rn=t=>`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${t}</svg>`,ed=rn('<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/>'),td=rn('<path d="m6 15 6-6 6 6"/>'),nd=rn('<rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/>');function Cs(t,e={}){let n=e.now??Date.now(),r=e.from||t.raised_by,o=Gc(12).toString("base64"),s=t.choices??[],i=t.origin?.kind==="reminder",a=t.origin?.kind==="request",d=Hn(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:Bn,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
742
|
<html lang="en"><head><meta charset="utf-8">
|
|
743
743
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${o}'">
|
|
744
744
|
<title>AgentX</title>
|
|
@@ -930,7 +930,7 @@ function gone(why) { return JSON.stringify({ action: "dismiss", why: why }) }
|
|
|
930
930
|
function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
931
931
|
`;function dd(t,e){let n=t.trim().split(`
|
|
932
932
|
`).pop()??"",r;try{r=JSON.parse(n)}catch{return{action:"dismiss"}}if(r?.action==="no")return{action:"no"};if(r?.action==="dismiss"&&Ls.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>
|
|
933
|
+
`).trim():"",!i||i.length>jn.text)?{action:"dismiss"}:{action:"yes",...s?{choice:s}:{},...i?{text:i}:{}}}async function Os(t,e,n){let r=Math.max(10,Math.round(e.timeoutSeconds)),o=od(Ns(ad(),"agentx-card-"));try{let s=Ns(o,"card.html");id(s,Cs(t,{...e,still:!!e.capture}),{mode:384});let i=["-l","JavaScript","-e",cd,s,String(ld),String(r),...e.capture?[e.capture]:[]],a=await n("/usr/bin/osascript",i,(r+10)*1e3);return a.ok?dd(a.stdout,t):null}finally{sd(o,{recursive:!0,force:!0})}}var Ls=["not now","timed out","closed"],pd=(t,e,n)=>new Promise(r=>{try{ud(t,e,{timeout:n},(o,s)=>r({ok:!o,stdout:String(s??"")}))}catch{r({ok:!1,stdout:""})}}),Ps=160,on=15e3;function Ms(t){let e=(t.say||t.title).replace(/\s+/g," ").trim();return e.length>Ps?e.slice(0,Ps):e}async function gd(t,e,n,r,o){let s=e.sound==="chime"?r?"":"Glass":e.sound,i=s?Er(s):null;if(i&&await n("/usr/bin/afplay",["-v",String(Math.min(1,Math.max(0,e.volume))),i],on),!!e.speak)if(o){let a;await Promise.race([o(Ms(t)),new Promise(d=>{a=setTimeout(d,on)})]),clearTimeout(a)}else{let a=e.voice&&/^[\w .()-]+$/.test(e.voice)?["-v",e.voice]:[];await n("/usr/bin/say",[...a,"--",Ms(t)],on)}}function Ws(t,e){return[...t.flatMap(n=>["-e",n]),...e]}function md(t,e,n){return Ws(["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 Fs(t,e,n,r,o){return Ws(["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
934
|
`),n[n.length-1],String(r),...o!==void 0?[o]:[]])}function Us(t){let e=t.replace(/\n$/,"");if(!e)return null;let n=e.indexOf(`
|
|
935
935
|
`);return n<0?{button:e,text:""}:{button:e.slice(0,n),text:e.slice(n+1)}}function sn(t){return[t.ask,t.recommend?`Recommended: ${t.recommend}`:"",`From ${t.raised_by}`].filter(Boolean).join(`
|
|
936
936
|
|
|
@@ -938,14 +938,14 @@ function quoted(s) { return "'" + String(s).replace(/'/g, "'\\\\''") + "'" }
|
|
|
938
938
|
|
|
939
939
|
Message (edit it if you like):`:`${sn(t)}
|
|
940
940
|
|
|
941
|
-
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Fs(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,
|
|
941
|
+
Message (edit it if you like):`,p=await n("/usr/bin/osascript",Fs(s,l,i?["Cancel","Send"]:["Not now","No","Send"],r,qn(t.draft,i)),o),u=p.ok?Us(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",Fs(s,sn(t),["Not now","No","Yes"],r),o),d=a.ok?Us(a.stdout):null;return d?.button==="Yes"?{action:"yes"}:d?.button==="No"?{action:"no"}:{action:"dismiss"}}var cn=24*36e5,an=!1,hd=10*6e4,Bs=-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=Z(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)||Ir(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>cn&&!(g<=a)))return c}return null}function ln(t){try{return G(t)?.listByState("needs_attention")??[]}catch{return[]}}var Hs=new Map;function bd(t,e=()=>!0){let n=t.now??Date.now(),{popped:r={},snoozed:o}=N(t.root);return e({})?ln(t).find(s=>{let i=`request:${s.id}`,a=o[i];return Hs.get(s.id)===K(s,ot.title).headline?!1:!r[i]&&!(a&&Date.parse(a)>n)&&n-s.updatedAt<=cn})??null:null}function yd(t,e){return{id:t.id,title:K(t,ot.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+cn).toISOString(),raised_by:t.agentId,created_at:new Date(t.createdAt).toISOString(),status:"pending",origin:{kind:"request",id:t.id}}}async function Cf(t){let{ctx:e,settings:n,log:r}=t;if(!n.enabled||(t.platform??process.platform)!=="darwin")return"off";if(an)return"busy";let o=qs(e,t.reaches)?null:bd(e,t.reaches),s=o?yd(o,e.now??Date.now()):qs(e,t.reaches);if(!s)return"none";let i=(t.focus??gs)();if(i.active)return"held";let a=`${o?"request":"card"}:${s.id}`,d=(N(e.root).wanted??[]).includes(a)?null:Vn(s);if(d){if(o)Hs.set(o.id,s.title);else{let l=[...Z(e.root,"pending").map(c=>`card:${c.id}`),...ln(e).map(c=>`request:${c.id}`)];bt(e.root,a,l,e.now)}return r(`[approvals] popup: ${a} not shown, back to ${s.raised_by}: ${d}`),t.returnToAuthor?.(s,Xn(s,d)),"returned"}an=!0;try{let l=[...Z(e.root,"pending").map(w=>`card:${w.id}`),...ln(e).map(w=>`request:${w.id}`)];bt(e.root,a,l,e.now),r(`[approvals] popup: showing ${a} from ${s.raised_by}`);let c=e.now??Date.now(),p=!!o&&c-Bs<hd;o&&n.speak&&(Bs=c);let u=t.agentName?.(s.raised_by)??(s.node?`${s.raised_by} on ${s.node}`:void 0),g=await(t.show??js)(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"} (${or(i)} when shown)`),"shown";if(!(o?G(e)?.get(o.id)?.state==="needs_attention":ce(e.root,s.id)?.status==="pending"))return r(`[approvals] popup: ${a} was answered elsewhere; popup answer ignored`),"shown";let f=await yo(e,a,g.action,{by:"operator (popup)",popup:!0,...g.action==="yes"?{choice:g.choice,text:g.text}:{}});return r(f.ok?`[approvals] popup: ${f.message}`:`[approvals] popup: ${a} not recorded: ${f.error}`),"shown"}catch(l){return r(`[approvals] popup failed for ${a}: ${l?.message??l}`),"shown"}finally{an=!1}}function Nf(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:")?ce(t.root,e.slice(5)):null;return r?r.status!=="pending"?{ok:!1,error:`${e} is already ${r.status}`}:(jr(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 wd,mkdirSync as xd,readFileSync as kd,renameSync as vd,writeFileSync as Sd}from"fs";import{dirname as Ed,resolve as _d}from"path";var $d=["all","urgent","off"],Td=24*36e5,Vs=24*36e5,Ad=30*24*36e5,Xs=t=>$d.includes(t);function Mf(t){let e=t.desk?.phone,n=t.desk?.computer;return{phone:Xs(e)?e:"off",computer:Xs(n)?n:t.popupEnabled?"all":"off"}}function Ks(t,e){let n=t.expires?Date.parse(t.expires):NaN;return Number.isFinite(n)&&n-e<=Td}function zs(t,e,n){return t==="all"||t==="urgent"&&Ks(e,n)}function Gs(t){return _d(t,".agentx","desk-routed.json")}function Rd(t){let e=Gs(t);if(!wd(e))return null;try{let n=JSON.parse(kd(e,"utf-8"));return n&&typeof n.items=="object"?n:{items:{}}}catch{return null}}function dn(t,e){let n=Gs(t);xd(Ed(n),{recursive:!0});let r=`${n}.${process.pid}.tmp`;Sd(r,JSON.stringify(e,null,2)),vd(r,n)}async function Ff(t){let{root:e,now:n,list:r,routing:o,log:s}=t,i={primed:!1,phone:[],computer:[]},a=new Date(n).toISOString(),d=Rd(e);if(!d){let p={};for(let u of r.items)p[u.key]={at:a,seen:a};return dn(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)>Vs&&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<=Vs&&l.push(p)}for(let[p,u]of Object.entries(d.items))n-Date.parse(u.seen)>Ad&&delete d.items[p];dn(e,d);for(let p of l)if(zs(o.phone,p,n))try{await t.phone(p,Ks(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(!zs(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&&dn(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 Uf(t){let e=t.ask??t.need??t.facts??"It waits for you.";return{title:t.title,message:`${e}
|
|
942
942
|
Answer it on the Desk.`}}import{closeSync as ye,createReadStream as Id,fstatSync as Dd,openSync as Cd,realpathSync as Ys}from"fs";import{isAbsolute as Nd,resolve as Js,sep as Qs}from"path";var Vf="/app-files",Od=/^[A-Za-z0-9_.:-]{1,64}$/;function Ld(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 ${dt}/ first`};if(!ue(e))return{ok:!1,status:415,error:"this type of file is not served"};let r;try{r=Ys(Js(n,t))}catch{return{ok:!1,status:404,error:"the agent's workspace is missing"}}let o;try{o=Ys(Nd(e)?e:Js(r,e))}catch{return{ok:!1,status:404,error:"file not found"}}if(!o.startsWith(r+Qs))return{ok:!1,status:403,error:`the file is outside the agent's workspace: copy it into ${dt}/ first`};let s=ue(o);return s?{ok:!0,path:o,...s}:{ok:!1,status:415,error:"this type of file is not served"}}function Pd(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 Md(t,e,n){return{"Content-Type":t,"Content-Disposition":Pd(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 Fd(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 Xf(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(!Od.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=Ld(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=Cd(d.path,"r")}catch{return o(404,{error:"file not found"})}let c;try{let x=Dd(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(Qs).pop()||"file",u=Md(d.mime,p,d.kind),g=Fd(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=Id("",{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 Ud,writeFileSync as Wd}from"fs";import{tmpdir as jd}from"os";import{join as Bd}from"path";$n();var Zs=t=>t&&t!==1?Math.round(175*t):null,Ge=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=Ud(t,"utf8").trim();if(e)return e}catch{}return null}function th(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",...Ge(n.voice.rate)?{voice_settings:{speed:Ge(n.voice.rate)}}:{}}),signal:r});if(!o.ok)throw new Error(`ElevenLabs ${o.status}: ${(await o.text()).slice(0,160)}`);let s=Bd(jd(),`agentx-say-${process.pid}-${++e}.mp3`);return Wd(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 ei(t,e){let n=t.languages&&_e(e);return n&&t.languages&&n in t.languages?t.languages[n]:t.system}var Hd=(t,e="")=>{let n=ei(t,e),r=Zs(t.rate);return[...n&&!Io(n)?["-v",n]:[],...r?["-r",String(r)]:[]]};function Vd(t,e,n){if(!n)return["say",Hd(t,e)];let r=ei(t,e);return["/bin/sh",[n,...r?[r]:[]]]}function nh(t){let e=t.split(/\s+/).filter(Boolean).length;return Math.min(300,5+Math.floor(e*6/10))*1e3}function rh(t=un()){if(t)try{we("/bin/sh",[t,"--stop"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function oh(t=un()){if(t)try{we("/bin/sh",[t,"--restore"],{stdio:"ignore"}).on("error",()=>{})}catch{}}function un(t={},e){if(!At(t))return null;try{return No(e)}catch(n){return Y("siri-say",`[voice] could not write the Siri voice script (${String(n?.message??n).split(`
|
|
943
943
|
`)[0]}); Siri voices will not switch`),null}}var sh=(t,e)=>{if(!t){let[n,r]=Vd(e.voice,e.text,un()),o=Zs(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 ti}from"child_process";import{accessSync as Xd,constants as zd,readFileSync as ni}from"fs";import{homedir as Kd}from"os";import{basename as se,delimiter as ri,dirname as Gd,extname as Yd,join as pn}from"path";var z={ms:2*60*1e3,bitsPerSecond:64e3,bytes:2*1024*1024};function oi(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:mn()}:null}var mn=()=>`The recording is longer than ${z.ms/6e4} minutes.`,Jd={"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 si(t){let e=String(t||"").split(";")[0].trim().toLowerCase();return Jd[e]??null}function ii(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 fn(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 gn(t,e,n=process.env.PATH??""){let r=Kd(),o=[pn(r,".local","bin"),"/opt/homebrew/bin","/usr/local/bin",...n.split(ri).filter(Boolean)];for(let s of[e,...o.map(i=>pn(i,t))])if(s)try{return Xd(s,zd.X_OK),s}catch{}return null}function uh(t){return{key:t,mlx:gn("mlx_whisper",process.env.AGENTX_MLX_WHISPER),whisper:gn("whisper",process.env.AGENTX_WHISPER),ffmpeg:Qd()}}var Qd=()=>gn("ffmpeg",process.env.AGENTX_FFMPEG);async function ai(t,e){return e?Zd(t,e):null}async function Zd(t,e){let n=String(z.ms/1e3+5);try{let o=[...(await eu(e,["-nostdin","-hide_banner","-t",n,"-i",t,"-f","null","-"],3e4)).matchAll(/time=(\d+):(\d+):(\d+(?:\.\d+)?)/g)],s=o[o.length-1];return s?Number(s[1])*3600+Number(s[2])*60+Number(s[3]):null}catch{return null}}async function li(t,e,n,r){let o=new FormData;o.set("model_id",process.env.AGENTX_STT_MODEL||"scribe_v1"),o.set("file",new Blob([ni(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 ci(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:`${Gd(r)}${ri}${process.env.PATH??""}`};await tu(e,s,12e4,i);try{return ni(pn(o,se(n,Yd(n))+".txt"),"utf8").trim()}catch{throw new Error(`${t} wrote no transcript`)}}function eu(t,e,n){return new Promise((r,o)=>{let s=ti(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 tu(t,e,n,r=process.env){return new Promise((o,s)=>{let i=ti(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
944
|
`).pop()?.slice(0,160)??""}`))})})}import{mkdtemp as nu,rm as ru,writeFile as ou}from"fs/promises";import{tmpdir as su}from"os";import{join as di}from"path";vi();var iu=64*1024,au=2,hn=0;function vh(t){return t==="/voice/transcribe"||t==="/voice/speak"}async function Sh(t,e,n,r){return t.method!=="POST"?$(e,405,{error:"POST"}):n==="/voice/transcribe"?lu(t,e,r):uu(t,e,r)}async function lu(t,e,n){let r=String(t.headers["content-type"]||""),o=si(r);if(!o)return $(e,415,{error:"Send the recording as audio (webm, mp4, ogg, mp3 or wav)."});let s=oi(t.headers["x-audio-duration-ms"]);if(s)return t.resume(),$(e,s.status,{error:s.error});let i=await ui(t,z.bytes);if(!i)return $(e,413,{error:mu()});if(!i.length)return $(e,400,{error:"The recording is empty."});if(hn>=au)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=ii(a,d);if(!d.ffmpeg&&!n.allowUnmeasured?.()){let p=n.nodeName?`on ${n.nodeName}`:"on this computer",u=l.length?"":" "+fn(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:fn(a,d),setup:!1});hn++;let c;try{let p=await nu(di(su(),"agentx-phone-voice-"));try{c=await cu(p,`speech.${o}`,i,r,d,l,n)}finally{await ru(p,{recursive:!0,force:!0}).catch(()=>{})}}finally{hn--}$(e,c[0],c[1])}async function cu(t,e,n,r,o,s,i){let a=di(t,e);if(await ou(a,n,{mode:384}),o.ffmpeg){let l=await(i.measure??ai)(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:mn()}]}let d=[];for(let l of s)try{let c=await du(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
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 du(t,e,n,r,o,s){let i=s.engines?.[t];if(i)return i(e,n,r,o);if(t==="elevenlabs")return li(e,n,r.key);let a=t==="mlx-whisper"?r.mlx:r.whisper;return ci(t,a,e,r.ffmpeg,o)}async function uu(t,e,n){let r=await ui(t,iu);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=pu(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??gu)(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
946
|
`)[0].slice(0,160)}`),c("ElevenLabs could not speak this answer.",502)}}function pu(t,e){let n=Xe(Ae(t).text).cleanText.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"");return Tn(n,e)}async function gu(t,e,n){let r=Ge(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 mu=()=>`The recording is larger than ${z.bytes/1024/1024} MB, more than ${z.ms/6e4} minutes of speech.`;function Eh(t,e,n,r){if(e)return r.speakerOn(e,t,!1)?.voice??null;let o=n.agents??{};return o[t]?Ft(Lt(t,o,n.voice)):null}function ui(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 fu="[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.]",hu="operator",bu=50,pi=4,gi=500;function yu(t){let e={channel:"app",chatId:t.chatId,sender:hu,...t.spoken?{via:"voice"}:{}},n=t.call==="watch"?`${fu}
|
|
947
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 Rh(t,e,n,r){let{path:o,body:s}=yu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:
|
|
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 Rh(t,e,n,r){let{path:o,body:s}=yu(e),i="",a=!1,d=[],l=new Map,c=(p,u,g)=>{let m=p!=="done",f=a?{text:er(u,m),artifacts:[]}:Ae(u,W.perMessage,m),{cleanText:w,ui:x}=p==="done"?Xe(f.text):{cleanText:f.text,ui:void 0},b=a?void 0:xu(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 ku(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<bu){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,wu(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 wu(t){let e=String(t||"The agent could not answer.");return Gn(e)?"The agent is busy with other work. Send the message again when it is free.":e.slice(0,500)}function xu(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,pi).map(i=>i.slice(0,gi));o.length&&(n.quickReplies=o);let s=(t.replies??[]).slice(0,pi).map(i=>({label:i.label.slice(0,80),reply:i.reply.slice(0,gi)}));return s.length&&(n.replies=s),Object.keys(n).length?n:void 0}async function*ku(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
949
|
`);let i;for(;(i=r.indexOf(`
|
|
950
950
|
|
|
951
951
|
`))!==-1;){let a=r.slice(0,i);r=r.slice(i+2);let d="message",l=[];for(let c of a.split(`
|
|
@@ -966,4 +966,4 @@ Document the arguments, commands, or files the skill expects. Example:
|
|
|
966
966
|
claude-code ${Sn(t)} --arg value
|
|
967
967
|
\`\`\`
|
|
968
968
|
`}Mn();var yi={maxPixels:12e5,timeoutMs:5e3,intervalMs:100,changeThreshold:.015,stableMs:400,regions:{},buffer:{enabled:!1,seconds:10,fps:2,region:"screen",maxPixels:3e5}};function wi(t){return{...yi,...t??{},regions:{...t?.regions??{}},buffer:{...yi.buffer,...t?.buffer??{}}}}function zh(t){try{return wi(Pn(t).screen)}catch{return wi(void 0)}}var Ru=/^[a-z][\w-]*$/,xi=["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 Je=(t,e)=>ke(t,e,n=>Number.isInteger(n)&&n>0,"a whole number above 0");function ki(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 Kh(t,e){let n={...t??{}};if("maxPixels"in e&&(n.maxPixels=Je(e.maxPixels,"maxPixels")),"timeoutMs"in e&&(n.timeoutMs=Je(e.timeoutMs,"timeoutMs")),"intervalMs"in e&&(n.intervalMs=Je(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(!Ru.test(s))throw new Error(`region name "${s}" must be lowercase letters, digits, - or _`);i===null?delete o[s]:o[s]=ki(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=Je(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&&!xi.includes(r)&&!n.regions?.[r])try{ki(r)}catch{throw new Error(`buffer.region "${r}" is not a region \u2014 use ${[...xi,...Object.keys(n.regions??{})].join(", ")}, or x,y,w,h`)}return n}export{Dr as a,Cu as b,Yt as c,sc as d,ic as e,mm as f,fm as g,hm as h,wm as i,xm as j,km as k,ls as l,cs as m,vm as n,Xe as o,Em as p,$m as q,X as r,ds as s,A as t,Pu as u,gs as v,Cm as w,Lm as x,fs as y,Pm as z,hs as A,Mm as B,he as C,Nc as D,Fm as E,Um as F,ys as G,Ju as H,Zi as I,rp as J,Yr as K,N as L,ju as M,Bu as N,pp as O,Ne as P,gp as Q,Br as R,Ku as S,G as T,jp as U,fo as V,yo as W,Mc as X,jm as Y,Fc as Z,Bm as _,qm as $,Qt as aa,xs as ba,Xm as ca,en as da,jc as ea,Bc as fa,Ym as ga,Pa as ha,Ma as ia,Hp as ja,Vp as ka,Ha as la,Gp as ma,As as na,Zm as oa,Qp as pa,Zp as qa,os as ra,jt as sa,Ql as ta,R as ua,js as va,Cf as wa,Nf as xa,$d as ya,Mf as za,zs as Aa,Ff as Ba,Uf as Ca,Vf as Da,Ld as Ea,Md as Fa,Xf as Ga,tg as Ha,ng as Ia,rg as Ja,og as Ka,sg as La,ig as Ma,ag as Na,lg as Oa,dg as Pa,ug as Qa,mg as Ra,fg as Sa,hg as Ta,wg as Ua,xg as Va,kg as Wa,vg as Xa,Sg as Ya,Eg as Za,_g as _a,Og as $a,Dt as ab,Lg as bb,Pg as cb,me as db,fe as eb,qd as fb,th as gb,nh as hb,rh as ib,oh as jb,un as kb,sh as lb,Ot as mb,Lt as nb,Be as ob,xl as pb,vl as qb,jg as rb,Mt as sb,Ft as tb,Sl as ub,El as vb,qo as wb,zo as xb,Bg as yb,Tl as zb,qg as Ab,Ll as Bb,Fl as Cb,Ut as Db,Wl as Eb,Ko as Fb,z as Gb,oi as Hb,si as Ib,ii as Jb,gn as Kb,uh as Lb,Qd as Mb,li as Nb,ci as Ob,vh as Pb,Sh as Qb,mu as Rb,Eh as Sb,ui as Tb,Qo as Ub,Rh as Vb,xu as Wb,Dh as Xb,Ch as Yb,qe as Zb,om as _b,Kt as $b,um as ac,Ph as bc,Mh as cc,Fh as dc,Uh as ec,Wh as fc,jh as gc,Bh as hc,qh as ic,Hh as jc,yi as kc,wi as lc,zh as mc,xi as nc,Kh as oc};
|
|
969
|
-
//# sourceMappingURL=chunk-
|
|
969
|
+
//# sourceMappingURL=chunk-KSO2DLVR.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
var d=7,h=6;function c(l){let a=l.replace(/^---[\s\S]*?\n---\n/,""),n=[],o=/^##\s+([^\n]*)\n([\s\S]*?)(?=^##\s|(?![\s\S]))/gm;for(let t=o.exec(a);t;t=o.exec(a))n.push({head:t[1].trim(),text:t[2]});let r=t=>t.replace(/<!--[\s\S]*?-->/g,"").replace(/\n{3,}/g,`
|
|
2
|
+
|
|
3
|
+
`).trim(),e=n.filter(t=>/^(update|change|amend)/i.test(t.head)),s=n.find(t=>/^rule\b/i.test(t.head)&&!/superseded|earlier rule/i.test(t.head)),i;return e.length?(i=[...e].reverse().map(t=>`${t.head}:
|
|
4
|
+
${r(t.text)}`).join(`
|
|
5
|
+
|
|
6
|
+
`),s&&(i+=`
|
|
7
|
+
|
|
8
|
+
Older rule (the updates above win where they differ):
|
|
9
|
+
${r(s.text)}`)):i=r(s?s.text:a),i.length>1400?i.slice(0,1400-1)+"\u2026":i}function m(l,a,n={}){let o=a-(n.days??7)*864e5,r=l.filter(e=>e.meta.type==="decision"&&!e.path.includes("/_versions/")).map(e=>({a:e,at:Date.parse(e.meta.lastUpdated||e.meta.created||"")})).filter(e=>Number.isFinite(e.at)&&e.at>=o).sort((e,s)=>s.at-e.at).slice(0,n.max??6);return r.length===0?"":["[Owner decisions \u2014 the newest recorded rulings, from the wiki]","These outrank the chat history, the continuity memo and your own notes below. Where those say something else (an approval still needed, a step still waiting), they are out of date: follow these.",...r.map(({a:e})=>`
|
|
10
|
+
### ${e.meta.title} (updated ${e.meta.lastUpdated||e.meta.created})
|
|
11
|
+
${c(e.content)}`),"[End owner decisions]"].join(`
|
|
12
|
+
`)}export{d as a,h as b,c,m as d};
|
|
13
|
+
//# sourceMappingURL=chunk-KWWBDLE6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/owner-decisions.ts"],"sourcesContent":["// --- Owner decisions on a fresh session ---\n//\n// A fresh session (first turn, or after a rotation) is handed the chat's\n// recent history and a continuity memo from the session before it. Both\n// can be hours old. On 2026-11-07 a rotated session read its own earlier\n// reply in the history (\"needs your yes on Telegram for five steps\") and\n// repeated it to the owner, although the owner had removed those yeses an\n// hour before and the work had already merged. The wiki held the newer\n// decision, but a fresh session only sees the wiki's catalog of titles.\n//\n// This block puts the newest decision articles, with their rule text,\n// ahead of the history and the memo, and says they win where those\n// disagree. Fresh sessions only, like the catalog: a resumed session\n// already saw it.\n\nimport type { WikiArticle } from \"@/wiki/types\"\n\nexport const DECISION_DAYS = 7\nexport const MAX_DECISIONS = 6\nconst RULE_CLIP = 1400\n\n/** The rule of a decision article, newest first. Decision pages are often\n * appended to (\"## Update <date> ...\" below an older \"## Rule\"), so the\n * latest update comes first and the older rule last, marked as older.\n * With neither heading, the start of the body. */\nexport function ruleText(content: string): string {\n const body = content.replace(/^---[\\s\\S]*?\\n---\\n/, \"\")\n const sections: Array<{ head: string; text: string }> = []\n const re = /^##\\s+([^\\n]*)\\n([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))/gm\n for (let m = re.exec(body); m; m = re.exec(body)) sections.push({ head: m[1].trim(), text: m[2] })\n const clean = (t: string) => t.replace(/<!--[\\s\\S]*?-->/g, \"\").replace(/\\n{3,}/g, \"\\n\\n\").trim()\n const updates = sections.filter((x) => /^(update|change|amend)/i.test(x.head))\n const rule = sections.find((x) => /^rule\\b/i.test(x.head) && !/superseded|earlier rule/i.test(x.head))\n let text: string\n if (updates.length) {\n text = [...updates].reverse().map((u) => `${u.head}:\\n${clean(u.text)}`).join(\"\\n\\n\")\n if (rule) text += `\\n\\nOlder rule (the updates above win where they differ):\\n${clean(rule.text)}`\n } else {\n text = clean(rule ? rule.text : body)\n }\n return text.length > RULE_CLIP ? text.slice(0, RULE_CLIP - 1) + \"…\" : text\n}\n\nexport function buildOwnerDecisions(articles: WikiArticle[], now: number, opts: { days?: number; max?: number } = {}): string {\n const since = now - (opts.days ?? DECISION_DAYS) * 86_400_000\n const recent = articles\n .filter((a) => a.meta.type === \"decision\" && !a.path.includes(\"/_versions/\"))\n .map((a) => ({ a, at: Date.parse(a.meta.lastUpdated || a.meta.created || \"\") }))\n .filter((x) => Number.isFinite(x.at) && x.at >= since)\n .sort((x, y) => y.at - x.at)\n .slice(0, opts.max ?? MAX_DECISIONS)\n if (recent.length === 0) return \"\"\n return [\n \"[Owner decisions — the newest recorded rulings, from the wiki]\",\n \"These outrank the chat history, the continuity memo and your own notes below. Where those say something else (an approval still needed, a step still waiting), they are out of date: follow these.\",\n ...recent.map(({ a }) => `\\n### ${a.meta.title} (updated ${a.meta.lastUpdated || a.meta.created})\\n${ruleText(a.content)}`),\n \"[End owner decisions]\",\n ].join(\"\\n\")\n}\n"],"mappings":"AAiBO,IAAMA,EAAgB,EAChBC,EAAgB,EAOtB,SAASC,EAASC,EAAyB,CAChD,IAAMC,EAAOD,EAAQ,QAAQ,sBAAuB,EAAE,EAChDE,EAAkD,CAAC,EACnDC,EAAK,mDACX,QAASC,EAAID,EAAG,KAAKF,CAAI,EAAGG,EAAGA,EAAID,EAAG,KAAKF,CAAI,EAAGC,EAAS,KAAK,CAAE,KAAME,EAAE,CAAC,EAAE,KAAK,EAAG,KAAMA,EAAE,CAAC,CAAE,CAAC,EACjG,IAAMC,EAAS,GAAc,EAAE,QAAQ,mBAAoB,EAAE,EAAE,QAAQ,UAAW;AAAA;AAAA,CAAM,EAAE,KAAK,EACzFC,EAAUJ,EAAS,OAAQK,GAAM,0BAA0B,KAAKA,EAAE,IAAI,CAAC,EACvEC,EAAON,EAAS,KAAMK,GAAM,WAAW,KAAKA,EAAE,IAAI,GAAK,CAAC,2BAA2B,KAAKA,EAAE,IAAI,CAAC,EACjGE,EACJ,OAAIH,EAAQ,QACVG,EAAO,CAAC,GAAGH,CAAO,EAAE,QAAQ,EAAE,IAAKI,GAAM,GAAGA,EAAE;AAAA,EAAUL,EAAMK,EAAE,IAAI,GAAG,EAAE,KAAK;AAAA;AAAA,CAAM,EAChFF,IAAMC,GAAQ;AAAA;AAAA;AAAA,EAA8DJ,EAAMG,EAAK,IAAI,MAE/FC,EAAOJ,EAAMG,EAAOA,EAAK,KAAOP,CAAI,EAE/BQ,EAAK,OAAS,KAAYA,EAAK,MAAM,EAAG,KAAY,CAAC,EAAI,SAAMA,CACxE,CAEO,SAASE,EAAoBC,EAAyBC,EAAaC,EAAwC,CAAC,EAAW,CAC5H,IAAMC,EAAQF,GAAOC,EAAK,MAAQ,GAAiB,MAC7CE,EAASJ,EACZ,OAAQK,GAAMA,EAAE,KAAK,OAAS,YAAc,CAACA,EAAE,KAAK,SAAS,aAAa,CAAC,EAC3E,IAAKA,IAAO,CAAE,EAAAA,EAAG,GAAI,KAAK,MAAMA,EAAE,KAAK,aAAeA,EAAE,KAAK,SAAW,EAAE,CAAE,EAAE,EAC9E,OAAQV,GAAM,OAAO,SAASA,EAAE,EAAE,GAAKA,EAAE,IAAMQ,CAAK,EACpD,KAAK,CAACR,EAAGW,IAAMA,EAAE,GAAKX,EAAE,EAAE,EAC1B,MAAM,EAAGO,EAAK,KAAO,CAAa,EACrC,OAAIE,EAAO,SAAW,EAAU,GACzB,CACL,sEACA,qMACA,GAAGA,EAAO,IAAI,CAAC,CAAE,EAAAC,CAAE,IAAM;AAAA,MAASA,EAAE,KAAK,kBAAkBA,EAAE,KAAK,aAAeA,EAAE,KAAK;AAAA,EAAalB,EAASkB,EAAE,OAAO,GAAG,EAC1H,uBACF,EAAE,KAAK;AAAA,CAAI,CACb","names":["DECISION_DAYS","MAX_DECISIONS","ruleText","content","body","sections","re","m","clean","updates","x","rule","text","u","buildOwnerDecisions","articles","now","opts","since","recent","a","y"]}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{createHash as c}from"crypto";import{existsSync as l,mkdirSync as d,readFileSync as u,renameSync as f,writeFileSync as v}from"fs";import{dirname as g,resolve as A}from"path";function s(e){return A(e,"_decisions","approved.json")}function p(e){return c("sha256").update(`${e.meta.title??""}
|
|
2
|
+
${(e.content??"").trim()}`).digest("hex")}function i(e){let n=s(e);if(!l(n))return{};try{let t=JSON.parse(u(n,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}catch{return{}}}function a(e,n){let t=s(e);d(g(t),{recursive:!0});let r=`${t}.${process.pid}.tmp`;v(r,JSON.stringify(n,null,2)+`
|
|
3
|
+
`),f(r,t)}function m(e,n){let t=n[e.path];return t?t.hash===p(e)?"approved":"changed":"waiting"}function y(e,n){return e.filter(t=>t.meta.type!=="decision"||m(t,n)==="approved")}function S(e,n,t){return t?y(e,i(n)):e}function k(e=process.env){return e.AGENTX_AGENT_ID?.trim()||e.AGENTX_TASK_ID?.trim()?"decision pages are approved by the owner from a terminal, not from inside an agent's run":null}function w(e,n,t={}){if(n.meta.type!=="decision")throw new Error(`${n.path} is not a decision page (type: ${n.meta.type??"none"})`);let r=i(e),o={hash:p(n),approvedAt:new Date(t.now??Date.now()).toISOString(),by:t.by||"owner",lastUpdated:n.meta.lastUpdated||void 0,...t.note?{note:t.note}:{}};return r[n.path]=o,a(e,r),o}function b(e,n){let t=i(e);return t[n]?(delete t[n],a(e,t),!0):!1}export{s as a,p as b,i as c,m as d,y as e,S as f,k as g,w as h,b as i};
|
|
4
|
+
//# sourceMappingURL=chunk-LIY5CHUV.js.map
|